bpf: introduce timeout hash map
Subsystems (6)
v5 cover bpf: introduce timeout hash map
From: Cong Wang <[email protected]>
This patchset introduces a new eBPF hash map whose elements have timeouts. Patch 1 is the implementation of timeout map, patch 2 adds some test cases for timeout map in test_maps, and patch 3 adds a test case in map ptr test. This patchset has been tested with the provided test cases for hours.
Please check each patch description for more details.
---
v5: add a lost piece of patch during rebase
fix the extra_elems corner case
add a stress test case
v4: merge gc_work into gc_idle_work to avoid a nasty race condition
fix a potential use-after-free
add one more test case
improve comments and update changelog
v3: move gc list from bucket to elem
reuse lru_node in struct htab_elem
drop patches which are no longer necessary
fix delete path
add a test case for delete path
add parallel test cases
change timeout to ms
drop batch ops
v2: fix hashmap ptr test
add a test case in map ptr test
factor out htab_timeout_map_alloc()
Cong Wang (3):
bpf: introduce timeout hash map selftests/bpf: add test cases for bpf timeout map selftests/bpf: add timeout map check in map_ptr tests
include/linux/bpf_types.h | 1 + include/uapi/linux/bpf.h | 5 +- kernel/bpf/hashtab.c | 274 +++++++++++++++++- kernel/bpf/syscall.c | 3 +- tools/include/uapi/linux/bpf.h | 1 + .../selftests/bpf/progs/map_ptr_kern.c | 20 ++ tools/testing/selftests/bpf/test_maps.c | 68 +++++ 7 files changed, 357 insertions(+), 15 deletions(-)
Signature · 1 line
2.25.1
PATCH v5 1/3 bpf: introduce timeout hash map
From: Cong Wang <[email protected]>
This borrows the idea from conntrack and will be used for conntrack in ebpf too. Each element in a timeout map has a user-specified timeout in msecs, after it expires it will be automatically removed from the map. Cilium already does the same thing, it uses a regular map or LRU map to track connections and has its own GC in user-space. This does not scale well when we have millions of connections, as each removal needs a syscall. Even if we could batch the operations, it still needs to copy a lot of data between kernel and user space.
There are two cases to consider here:
1. When the timeout map is idle, i.e. no one updates or accesses it, we rely on the delayed work to scan the whole hash table and remove these expired. The delayed work is scheduled every 1 sec when idle, which is also what conntrack uses. It is fine to scan the whole table as we do not actually remove elements during this scan, instead we simply queue them to the lockless list and defer all the removals to the next schedule.
2. When the timeout map is actively accessed, we could reach expired elements before the idle work automatically scans them, we can simply skip them and schedule the delayed work immediately to do the actual removals. We have to avoid taking locks on fast path.
The timeout of an element can be set or updated via bpf_map_update_elem() and we reuse the upper 32-bit of the 64-bit flag for the timeout value, as there are only a few bits are used currently. Note, a zero timeout means to expire immediately.
To avoid adding memory overhead to regular map, we have to reuse some field in struct htab_elem, that is, lru_node. Otherwise we would have to rewrite a lot of code.
For now, batch ops is not supported, we can add it later if needed.
--- include/linux/bpf_types.h | 1 + include/uapi/linux/bpf.h | 5 +- kernel/bpf/hashtab.c | 274 +++++++++++++++++++++++++++++++-- kernel/bpf/syscall.c | 3 +- tools/include/uapi/linux/bpf.h | 1 + 5 files changed, 269 insertions(+), 15 deletions(-)
include/linux/bpf_types.h +1 -0
@@ -125,6 +125,7 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_STACK, stack_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_STRUCT_OPS, bpf_struct_ops_map_ops)#endif BPF_MAP_TYPE(BPF_MAP_TYPE_RINGBUF, ringbuf_map_ops) +BPF_MAP_TYPE(BPF_MAP_TYPE_TIMEOUT_HASH, htab_timeout_map_ops) BPF_LINK_TYPE(BPF_LINK_TYPE_RAW_TRACEPOINT, raw_tracepoint)BPF_LINK_TYPE (BPF_LINK_TYPE_TRACING , tracing)
include/uapi/linux/bpf.h +4 -1
@@ -164,6 +164,7 @@ enum bpf_map_type {BPF_MAP_TYPE_RINGBUF ,BPF_MAP_TYPE_INODE_STORAGE ,BPF_MAP_TYPE_TASK_STORAGE , + BPF_MAP_TYPE_TIMEOUT_HASH, };/* Note that tracing related programs such as
@@ -399,7 +400,9 @@ enum bpf_link_type {*/ #define BPF_PSEUDO_CALL 1 -/* flags for BPF_MAP_UPDATE_ELEM command */ +/* flags for BPF_MAP_UPDATE_ELEM command, upper 32 bits are timeout for +* BPF_MAP_TYPE_TIMEOUT_HASH (in milliseconds). +*/ enum {BPF_ANY =0 ,/* create new element or update existing */ BPF_NOEXIST =1 ,/* create new element if it didn't exist */
kernel/bpf/hashtab.c +261 -13
421 lines not on this page · raw message
kernel/bpf/syscall.c +2 -1
@@ -777,7 +777,8 @@ static int map_check_btf(struct bpf_map *map, const struct btf *btf, map->map_type !=BPF_MAP_TYPE_CGROUP_STORAGE && map->map_type !=BPF_MAP_TYPE_SK_STORAGE && map->map_type !=BPF_MAP_TYPE_INODE_STORAGE && - map->map_type != BPF_MAP_TYPE_TASK_STORAGE) + map->map_type !=BPF_MAP_TYPE_TASK_STORAGE && + map->map_type != BPF_MAP_TYPE_TIMEOUT_HASH) return -ENOTSUPP;if (map->spin_lock_off +sizeof (struct bpf_spin_lock ) > map->value_size) {
tools/include/uapi/linux/bpf.h +1 -0
@@ -164,6 +164,7 @@ enum bpf_map_type {BPF_MAP_TYPE_RINGBUF ,BPF_MAP_TYPE_INODE_STORAGE ,BPF_MAP_TYPE_TASK_STORAGE , + BPF_MAP_TYPE_TIMEOUT_HASH, };/* Note that tracing related programs such as
Signature · 1 line
2.25.1
Daniel Borkmann
maintainerQuoted 31 lines · Cong Wang
From: Cong Wang <[email protected]>
This borrows the idea from conntrack and will be used for conntrack in ebpf too. Each element in a timeout map has a user-specified timeout in msecs, after it expires it will be automatically removed from the map. Cilium already does the same thing, it uses a regular map or LRU map to track connections and has its own GC in user-space. This does not scale well when we have millions of connections, as each removal needs a syscall. Even if we could batch the operations, it still needs to copy a lot of data between kernel and user space.
There are two cases to consider here:
1. When the timeout map is idle, i.e. no one updates or accesses it, we rely on the delayed work to scan the whole hash table and remove these expired. The delayed work is scheduled every 1 sec when idle, which is also what conntrack uses. It is fine to scan the whole table as we do not actually remove elements during this scan, instead we simply queue them to the lockless list and defer all the removals to the next schedule.
2. When the timeout map is actively accessed, we could reach expired elements before the idle work automatically scans them, we can simply skip them and schedule the delayed work immediately to do the actual removals. We have to avoid taking locks on fast path.
The timeout of an element can be set or updated via
bpf_map_update_elem()and we reuse the upper 32-bit of the 64-bit flag for the timeout value, as there are only a few bits are used currently. Note, a zero timeout means to expire immediately.
Quoted 5 lines
To avoid adding memory overhead to regular map, we have to reuse some field in struct
htab_elem, that is,lru_node. Otherwise we would have to rewrite a lot of code.For now, batch ops is not supported, we can add it later if needed.
Back in earlier conversation [0], I mentioned also LRU map flavors and to look into adding a flag, so we wouldn't need new BPF_MAP_TYPE_TIMEOUT_HASH/*LRU types that replicate existing types once again just with the timeout in addition, so UAPI wise new map type is not great.
Given you mention Cilium above, only for kernels where there is no LRU hash map, that is < 4.10, we rely on plain hash, everything else LRU + prealloc to mitigate ddos by refusing to add new entries when full whereas less active ones will be purged instead. Timeout /only/ for plain hash is less useful overall, did you sketch a more generic approach in the meantime that would work for all the htab/lru flavors (and ideally as non-delayed_work based)?
[0] https://lore.kernel.org/bpf/[email protected]/
[...]
Quoted 28 lines
kernel/bpf/hashtab.c +5
-0@@ -1012,6 +1081,8 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, l_old->key +round_up (key_size,8 ), value, false); +if (timeout_map) + l_old->expires =msecs_to_expire (timeout);return 0 ; }/* fall through, grab the bucket lock and lookup again. @@ -1020,6 +1091,7 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,*/ } +again: ret =htab_lock_bucket (htab, b, hash, &flags);if (ret)return ret;@@ -1040,26 +1112,41 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, l_old->key +round_up (key_size,8 ), value, false); +if (timeout_map) + l_old->expires =msecs_to_expire (timeout); ret =0 ; goto err; } l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false,
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 10 lines
kernel/bpf/hashtab.c +6
-2- l_old); + timeout_map, l_old);if (IS_ERR (l_new)) { -/* all pre-allocated elements are in use or memory exhausted */ ret =PTR_ERR (l_new); +if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;
Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for system_unbound_wq to kick in to make forward progress?
Quoted 8 lines
kernel/bpf/hashtab.c +5
-0+ } +/* all pre-allocated elements are in use or memory exhausted */ goto err; } +if (timeout_map) + l_new->expires =msecs_to_expire (timeout); +
Quoted 37 lines · Daniel Borkmann
Quoted 35 lines · Cong Wang
From: Cong Wang <[email protected]>
This borrows the idea from conntrack and will be used for conntrack in ebpf too. Each element in a timeout map has a user-specified timeout in msecs, after it expires it will be automatically removed from the map. Cilium already does the same thing, it uses a regular map or LRU map to track connections and has its own GC in user-space. This does not scale well when we have millions of connections, as each removal needs a syscall. Even if we could batch the operations, it still needs to copy a lot of data between kernel and user space.
There are two cases to consider here:
1. When the timeout map is idle, i.e. no one updates or accesses it, we rely on the delayed work to scan the whole hash table and remove these expired. The delayed work is scheduled every 1 sec when idle, which is also what conntrack uses. It is fine to scan the whole table as we do not actually remove elements during this scan, instead we simply queue them to the lockless list and defer all the removals to the next schedule.
2. When the timeout map is actively accessed, we could reach expired elements before the idle work automatically scans them, we can simply skip them and schedule the delayed work immediately to do the actual removals. We have to avoid taking locks on fast path.
The timeout of an element can be set or updated via
bpf_map_update_elem()and we reuse the upper 32-bit of the 64-bit flag for the timeout value, as there are only a few bits are used currently. Note, a zero timeout means to expire immediately.To avoid adding memory overhead to regular map, we have to reuse some field in struct
htab_elem, that is,lru_node. Otherwise we would have to rewrite a lot of code.
Quoted 6 lines
Quoted 1 line
For now, batch ops is not supported, we can add it later if needed.
Back in earlier conversation [0], I mentioned also LRU map flavors and to look into adding a flag, so we wouldn't need new BPF_MAP_TYPE_TIMEOUT_HASH/*LRU types that replicate existing types once again just with the timeout in addition, so UAPI wise new map type is not great.
Interestingly, Jamal also brought this flag up to me.
The reason why I don't use a flag is that I don't see any other maps need a timeout. Take the LRU map you mentioned as an example, it evicts elements based on size, not based on time, I can't think of a case where we need both time and size based eviction. Another example is array, there is no way to delete an element from an array, so we can't really expire an element.
Or do you have any use case for a non-regular hash map with timeout?
Quoted 5 lines
Given you mention Cilium above, only for kernels where there is no LRU hash map, that is < 4.10, we rely on plain hash, everything else LRU + prealloc to mitigate ddos by refusing to add new entries when full whereas less active ones will be purged instead. Timeout /only/ for plain hash is less useful overall, did you
The difference between LRU and a timeout map is whether we should drop the least recently used one too when it is full. For conntrack, this is not a good idea, because when we have a burst of connections, the least recently used might be just 1-s old, so evicting it out is not a good idea. With a timeout
map, we just drop all new connection when it is full and wait for some connect to timeout naturally, aligned with the definition of conntrack.
So it should be a good replacement for LRU map too in terms of conntrack.
Quoted 2 lines
sketch a more generic approach in the meantime that would work for all the htab/lru flavors (and ideally as non-delayed_work based)?
If you mean LRU maps may need timeout too, like I explained above, I can't think of any such use cases.
Quoted 31 lines
[0] https://lore.kernel.org/bpf/[email protected]/[...]
Quoted 27 lines
kernel/bpf/hashtab.c +5
-0@@ -1012,6 +1081,8 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, l_old->key +round_up (key_size,8 ), value, false); +if (timeout_map) + l_old->expires =msecs_to_expire (timeout);return 0 ; }/* fall through, grab the bucket lock and lookup again. @@ -1020,6 +1091,7 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,*/ } +again: ret =htab_lock_bucket (htab, b, hash, &flags);if (ret)return ret;@@ -1040,26 +1112,41 @@ static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, l_old->key +round_up (key_size,8 ), value, false); +if (timeout_map) + l_old->expires =msecs_to_expire (timeout); ret =0 ; goto err; }
Quoted 14 lines
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 11 lines
kernel/bpf/hashtab.c +6
-2l_new =alloc_htab_elem (htab, key, value, key_size, hash, false, false, - l_old); + timeout_map, l_old);if (IS_ERR (l_new)) { -/* all pre-allocated elements are in use or memory exhausted */ ret =PTR_ERR (l_new); +if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for
system_unbound_wqto kick in to make forward progress?
In this case, the old one is scheduled for removal in GC, we just wait for GC to finally remove it. It won't stall unless GC itself or the worker scheduler is wrong, both of which should be kernel bugs.
If we don't do this, users would get a -E2BIG when it is not too big. I don't know a better way to handle this sad situation, maybe returning -EBUSY to users and let them call again?
Thanks.
Quoted 10 lines · Cong Wang
Quoted 9 lines
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 6 lines
ret = PTR_ERR(l_new);kernel/bpf/hashtab.c +5
-0+if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for
system_unbound_wqto kick in to make forward progress?
Quoted 7 lines
In this case, the old one is scheduled for removal in GC, we just wait for GC to finally remove it. It won't stall unless GC itself or the worker scheduler is wrong, both of which should be kernel bugs.
If we don't do this, users would get a
-E2BIGwhen it is not too big. I don't know a better way to handle this sad situation, maybe returning-EBUSYto users and let them call again?
I think using wq for timers is a non-starter. Tying a hash/lru map with a timer is not a good idea either.
I think timers have to be done as independent objects similar to how the kernel uses them.
Then there will be no question whether lru or hash map needs it. The bpf prog author will be able to use timers with either. The prog will be able to use timers without hash maps too.
I'm proposing a timer map where each object will go through bpf_timer_setup(timer, callback, flags);
where "callback" is a bpf subprogram.
Corresponding bpf_del_timer and bpf_mod_timer would work the same way they are in the kernel.
The tricky part is kernel style of using from_timer() to access the object with additional info.
I think bpf timer map can model it the same way.
At map creation time the value_size will specify the amount of extra bytes necessary.
Another alternative is to pass an extra data argument to a callback.
Daniel Borkmann
maintainerQuoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Cong Wang
Quoted 9 lines
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 6 lines
ret = PTR_ERR(l_new);kernel/bpf/hashtab.c +5
-0+if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for
system_unbound_wqto kick in to make forward progress?In this case, the old one is scheduled for removal in GC, we just wait for GC to finally remove it. It won't stall unless GC itself or the worker scheduler is wrong, both of which should be kernel bugs.
Quoted 6 lines
Quoted 3 lines
If we don't do this, users would get a
-E2BIGwhen it is not too big. I don't know a better way to handle this sad situation, maybe returning-EBUSYto users and let them call again?I think using wq for timers is a non-starter. Tying a hash/lru map with a timer is not a good idea either.
Thinking some more, given we have jiffies64 helper and atomic ops for BPF by now, we would technically only need the ability to delete entries via bpf iter progs (d6c4503cc296 ("bpf: Implement bpf iterator for hash maps")) which could then be kicked off from user space at e.g. dynamic intervals which would be the equivalent for the wq in here. That patch could then be implemented this way. I presume the ability to delete map entries from bpf iter progs would be generic and useful enough anyway.
Quoted 6 lines
I think timers have to be done as independent objects similar to how the kernel uses them.
Then there will be no question whether lru or hash map needs it. The bpf prog author will be able to use timers with either. The prog will be able to use timers without hash maps too.
Quoted 7 lines
I'm proposing a timer map where each object will go through
bpf_timer_setup(timer, callback, flags);
where "callback" is a bpf subprogram.
Correspondingbpf_del_timerandbpf_mod_timerwould work the same way they are in the kernel.
The tricky part is kernel style of usingfrom_timer()to access the object with additional info.
Would this mean N timer objs for N map elems? I presume not given this could be racy and would have huge extra mem overhead. Either way, timer obj could work, but then at the same time you could probably also solve it with the above; it's not like you need the timer to kick in at some /exact/ time, but rather at some point to clean up stale entries before the map gets full and worst case refuses updates for new entries. (In the ideal case though we wouldn't need the extra effort to search deeply for elements w/o penalizing the fast-path lookup costs too much when walking the bucket.)
Quoted 4 lines
I think bpf timer map can model it the same way.
At map creation time thevalue_sizewill specify the amount of extra bytes necessary.
Another alternative is to pass an extra data argument to a callback.
Quoted 24 lines · Daniel Borkmann
Quoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Cong Wang
Quoted 9 lines
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 6 lines
ret = PTR_ERR(l_new);kernel/bpf/hashtab.c +5
-0+if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for
system_unbound_wqto kick in to make forward progress?In this case, the old one is scheduled for removal in GC, we just wait for GC to finally remove it. It won't stall unless GC itself or the worker scheduler is wrong, both of which should be kernel bugs.
Quoted 6 lines
Quoted 3 lines
If we don't do this, users would get a
-E2BIGwhen it is not too big. I don't know a better way to handle this sad situation, maybe returning-EBUSYto users and let them call again?I think using wq for timers is a non-starter. Tying a hash/lru map with a timer is not a good idea either.
Quoted 7 lines
Thinking some more, given we have jiffies64 helper and atomic ops for BPF by now, we would technically only need the ability to delete entries via bpf iter progs (
d6c4503cc296("bpf: Implement bpf iterator for hash maps")) which could then be kicked off from user space at e.g. dynamic intervals which would be the equivalent for the wq in here. That patch could then be implemented this way. I presume the ability to delete map entries from bpf iter progs would be generic and useful enough anyway.
I think bpf_iter for maps doesn't hold bucket lock anymore, so delete of the same element should be allowed already. Unless I've mistaken wip patches with landed ones.
Soon there will be support for bpf_map_for_each_elem() iterator running from the bpf program itself, so even more ways to do GC like work.
Quoted 14 lines
Quoted 6 lines
I think timers have to be done as independent objects similar to how the kernel uses them.
Then there will be no question whether lru or hash map needs it. The bpf prog author will be able to use timers with either. The prog will be able to use timers without hash maps too.Quoted 7 lines
I'm proposing a timer map where each object will go through
bpf_timer_setup(timer, callback, flags);
where "callback" is a bpf subprogram.
Correspondingbpf_del_timerandbpf_mod_timerwould work the same way they are in the kernel.
The tricky part is kernel style of usingfrom_timer()to access the object with additional info.
Quoted 2 lines
Would this mean N timer objs for N map elems? I presume not given this could be racy and would have huge extra mem overhead.
hmm. Not sure I got the point about overhead.sizeof(struct timer_list) == 40 bytes.
Not a lot of overhead even if there is a timer object per flow. When bpf_map_for_each_elem() lands the bpf prog could have one timer that will kick one a second (or whatever GC period the prog author wants) and does bpf_map_for_each_elem() once callback fires to delete elems older than whatever interval the prog needs.
imo that would be a true generic way to combinebpf_maps, bpf_iters and bpf_timers.
Quoted 7 lines
Either way, timer obj could work, but
then at the same time you could probably also solve it with the above; it's not like you need the timer to kick in at some /exact/ time, but rather at some point to clean up stale entries before the map gets full and worst case refuses updates for new entries. (In the ideal case though we wouldn't need the extra effort to search deeply for elements w/o penalizing the fast-path lookup costs too much when walking the bucket.)
Right. I wasn't suggesting to mess with the timer object at every lookup. My understanding that mod_timer() isn't that fast to call a million times a second.
bpf progs would have to be smart.
Instead of timer objects as a timer map (a collection of timers that bpf progs can manipulate)
we can introduce them similar to "struct bpf_spin_lock". Then "struct bpf_timer foo;" field can be embedded inside any map value (both hash and array). The verifier work would be a bit trickier than support for bpf_spin_lock,
but certainly doable.
My main point was that bpf should grow with small composable building blocks instead of single purpose constructs.
I view hashmap+GC as an example of something that should be split into smaller blocks.
Quoted 16 lines · Alexei Starovoitov
Quoted 14 lines · Cong Wang
Quoted 9 lines
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 6 lines
ret = PTR_ERR(l_new);kernel/bpf/hashtab.c +5
-0+if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for
system_unbound_wqto kick in to make forward progress?In this case, the old one is scheduled for removal in GC, we just wait for GC to finally remove it. It won't stall unless GC itself or the worker scheduler is wrong, both of which should be kernel bugs.
Quoted 6 lines
Quoted 3 lines
If we don't do this, users would get a
-E2BIGwhen it is not too big. I don't know a better way to handle this sad situation, maybe returning-EBUSYto users and let them call again?I think using wq for timers is a non-starter. Tying a hash/lru map with a timer is not a good idea either.
Both xt_hashlimit and nf_conntrack_core use delayed/deferrable works, probably since their beginnings. They seem to have started well. ;)
Quoted 4 lines
I think timers have to be done as independent objects similar to how the kernel uses them.
Then there will be no question whether lru or hash map needs it.
Yeah, this probably could make the code easier, but when we have millions of entries in a map, millions of timers would certainly bring a lot of CPU overhead (timer interrupt storm?).
Quoted 14 lines
The bpf prog author will be able to use timers with either. The prog will be able to use timers without hash maps too.
I'm proposing a timer map where each object will go through
bpf_timer_setup(timer, callback, flags);
where "callback" is a bpf subprogram.
Correspondingbpf_del_timerandbpf_mod_timerwould work the same way they are in the kernel.
The tricky part is kernel style of usingfrom_timer()to access the object with additional info.
I think bpf timer map can model it the same way.
At map creation time thevalue_sizewill specify the amount of extra bytes necessary.
Another alternative is to pass an extra data argument to a callback.
Hmm, this idea is very interesting. I still think arming a timer, whether a kernel timer or a bpf timer, for each entry is overkill, but we can arm one for each map, something like:
bpf_timer_run(interval, bpf_prog, &any_map);
so we run 'bpf_prog' on any map every 'interval', but the 'bpf_prog' would have to iterate the whole map during each interval to delete the expired ones. This is probably doable: the timestamps can be stored either as a part of key or value, and bpf_jiffies64() is already available, users would have to discard expired ones after lookup when they are faster than the timer GC.
Let me take a deeper look tomorrow.
Thanks.
Quoted 22 lines · Cong Wang
Quoted 20 lines · Alexei Starovoitov
Quoted 17 lines · Cong Wang
Quoted 9 lines
kernel/bpf/hashtab.c static int htab_map_update_elem(struct bpf_map *map, void *key, void *value, · line 1129
Quoted 6 lines
ret = PTR_ERR(l_new);kernel/bpf/hashtab.c +5
-0+if (ret == -EAGAIN ) { +htab_unlock_bucket (htab, b, hash, flags); +htab_gc_elem (htab, l_old); +mod_delayed_work (system_unbound_wq, &htab->gc_work,0 ); + goto again;Also this one looks rather worrying, so the BPF prog is stalled here, loop-waiting in (e.g. XDP) hot path for
system_unbound_wqto kick in to make forward progress?In this case, the old one is scheduled for removal in GC, we just wait for GC to finally remove it. It won't stall unless GC itself or the worker scheduler is wrong, both of which should be kernel bugs.
If we don't do this, users would get a
-E2BIGwhen it is not too big. I don't know a better way to handle this sad situation, maybe returning-EBUSYto users and let them call again?
Quoted 6 lines
Quoted 2 lines
I think using wq for timers is a non-starter. Tying a hash/lru map with a timer is not a good idea either.
Both
xt_hashlimitandnf_conntrack_coreuse delayed/deferrable works, probably since their beginnings. They seem to have started well. ;)
That code was written when network speed was in Mbits and DDoS abbreviation wasn't invented. Things are different now.
Quoted 16 lines
Quoted 11 lines
I'm proposing a timer map where each object will go through
bpf_timer_setup(timer, callback, flags);
where "callback" is a bpf subprogram.
Correspondingbpf_del_timerandbpf_mod_timerwould work the same way they are in the kernel.
The tricky part is kernel style of usingfrom_timer()to access the object with additional info.
I think bpf timer map can model it the same way.
At map creation time thevalue_sizewill specify the amount of extra bytes necessary.
Another alternative is to pass an extra data argument to a callback.Hmm, this idea is very interesting. I still think arming a timer, whether a kernel timer or a bpf timer, for each entry is overkill, but we can arm one for each map, something like:
Quoted 8 lines
bpf_timer_run(interval, bpf_prog, &any_map);so we run '
bpf_prog' on any map every 'interval', but the 'bpf_prog' would have to iterate the whole map during each interval to delete the expired ones. This is probably doable: the timestamps can be stored either as a part of key or value, andbpf_jiffies64()is already available, users would have to discard expired ones after lookup when they are faster than the timer GC.
I meant it would look like:
noinline per_elem_callback(map, key, value, ...)
{
if (value->foo > ...)
bpf_delete_map_elem(map, key); }
noinline timer_callback(timer, ctx)
{
map = ctx->map;
bpf_for_each_map_elem(map, per_elem_callback, ...);
}
int main_bpf_prog(skb)
{
bpf_timer_setup(my_timer, timer_callback, ...);
bpf_mod_timer(my_timer, HZ);
}
The bpf_for_each_map_elem() work is already in progress. Expect patches to hit mailing list soon.
If you can work on patches for bpf_timer_*() it would be awesome.
Quoted 15 lines · Alexei Starovoitov
I meant it would look like:
noinline
per_elem_callback(map, key, value, ...)
{
if (value->foo> ...)bpf_delete_map_elem(map, key); }noinline
timer_callback(timer, ctx)
{
map =ctx->map;
bpf_for_each_map_elem(map, per_elem_callback, ...);
}
Quoted 8 lines
int
main_bpf_prog(skb)
{
bpf_timer_setup(my_timer, timer_callback, ...);
bpf_mod_timer(my_timer, HZ);
}The
bpf_for_each_map_elem()work is already in progress. Expect patches to hit mailing list soon.
We don't want a per-element timer, we want a per-map timer but that requires a way to iterate the whole map. If you or other can provide bpf_for_each_map_elem(), we can certainly build our timeout map on top of it.
Quoted 1 line
If you can work on patches for bpf_timer_*() it would be awesome.
Yeah, I will work on this, not only for timeout map, but also possibly for the ebpf qdisc I plan to add soon.
Thanks.
Quoted 23 lines · Cong Wang
Quoted 21 lines · Alexei Starovoitov
I meant it would look like:
noinline
per_elem_callback(map, key, value, ...){ if (value->foo > ...) bpf_delete_map_elem(map, key); }noinline
timer_callback(timer, ctx){ map = ctx->map; bpf_for_each_map_elem(map, per_elem_callback, ...); }int
main_bpf_prog(skb){ bpf_timer_setup(my_timer, timer_callback, ...); bpf_mod_timer(my_timer, HZ); }
Quoted 7 lines
Quoted 2 lines
The
bpf_for_each_map_elem()work is already in progress. Expect patches to hit mailing list soon.We don't want a per-element timer, we want a per-map timer but that requires a way to iterate the whole map. If you or other can provide
bpf_for_each_map_elem(), we can certainly build our timeout map on top of it.
I am working on this. Still need a few weeks to post RFC. Will share as soon as it is in reasonable shape. Thanks!
Quoted 8 lines
Quoted 2 lines
If you can work on patches for bpf_timer_*() it would be awesome.
Yeah, I will work on this, not only for timeout map, but also possibly for the ebpf qdisc I plan to add soon.
Thanks.
A message that is not in the archive (sent off-list or not yet received): [email protected]
A message that is not in the archive (sent off-list or not yet received): [email protected]
Quoted 11 lines · Jamal Hadi Salim
Quoted 7 lines · Jamal Hadi Salim
Which leads to:
Why not extend the general feature so one can register for optional callbacks not just for expire but also add/del/update on specific entries or table?
add/del/update could be sourced from other kernel programs or user space and the callback would be invoked before an entry is added/deleted etc. (just like it is here for expiry).
Quoted 3 lines
Sorry - shouldve read the rest of the thread:
Agree with Cong that you want per-map but there are use cases where you want it per entry (eg the add/del/update case).
That was my point as well.bpf_timer api should be generic, so that users can do both.
The program could use bpf_timer one for each flow and bpf_timer for each map. And timers without maps.
Quoted 12 lines · Alexei Starovoitov
Quoted 11 lines · Jamal Hadi Salim
Quoted 7 lines · Jamal Hadi Salim
Which leads to:
Why not extend the general feature so one can register for optional callbacks not just for expire but also add/del/update on specific entries or table?
add/del/update could be sourced from other kernel programs or user space and the callback would be invoked before an entry is added/deleted etc. (just like it is here for expiry).
Quoted 8 lines
Quoted 3 lines
Sorry - shouldve read the rest of the thread:
Agree with Cong that you want per-map but there are use cases where you want it per entry (eg the add/del/update case).That was my point as well.
bpf_timerapi should be generic, so that users can do both.
The program could usebpf_timerone for each flow andbpf_timerfor each map. And timers without maps.
I like it. Sensible to also have callback invocations for map changes i.e entry create/update/delete (maybe map create/destroy).
cheers,
jamal
PATCH v5 2/3 selftests/bpf: add test cases for bpf timeout map
In reply to Cong WangFrom: Cong Wang <[email protected]>
Add some test cases in test_maps.c for timeout map, which focus on testing timeout. The parallel tests make sure to catch race conditions and the large map test stresses GC.
--- tools/testing/selftests/bpf/test_maps.c | 68 +++++++++++++++++++++++++ 1 file changed, 68 insertions(+)
tools/testing/selftests/bpf/test_maps.c +68 -0
@@ -639,6 +639,52 @@ static void test_stackmap(unsigned int task, void *data)close (fd); } +static void test_timeout_map (unsigned int task,void *data) +{ +int val1 =1 , val2 =2 , val3 =3 ; +int key1 =1 , key2 =2 , key3 =3 ; +int fd; + + fd =bpf_create_map (BPF_MAP_TYPE_TIMEOUT_HASH ,sizeof (int ),sizeof (int ), +3 , map_flags); +if (fd <0 ) { +printf ("Failed to create timeout map '%s'!\n" ,strerror (errno)); +exit (1 ); + } + +/* Timeout after 1 secs */ +assert (bpf_map_update_elem (fd, &key1, &val1, (u64 )1000 <<32 ) ==0 ); +/* Timeout after 2 secs */ +assert (bpf_map_update_elem (fd, &key2, &val2, (u64 )2000 <<32 ) ==0 ); +/* Timeout after 10 secs */ +assert (bpf_map_update_elem (fd, &key3, &val3, (u64 )10000 <<32 ) ==0 ); + +sleep (1 ); +assert (bpf_map_lookup_elem (fd, &key1, &val1) !=0 ); + val2 =0 ; +assert (bpf_map_lookup_elem (fd, &key2, &val2) ==0 && val2 ==2 ); + +sleep (1 ); +assert (bpf_map_lookup_elem (fd, &key1, &val1) !=0 ); +assert (bpf_map_lookup_elem (fd, &key2, &val2) !=0 ); + +/* Modify timeout to expire it earlier */ + val3 =0 ; +assert (bpf_map_lookup_elem (fd, &key3, &val3) ==0 && val3 ==3 ); +assert (bpf_map_update_elem (fd, &key3, &val3, (u64 )1000 <<32 ) ==0 ); +sleep (1 ); +assert (bpf_map_lookup_elem (fd, &key3, &val3) !=0 ); + +/* Add one elem expired immediately and try to delete this expired */ +assert (bpf_map_update_elem (fd, &key3, &val3,0 ) ==0 ); +assert (bpf_map_delete_elem (fd, &key3) ==-1 && errno ==ENOENT ); + +/* Add one elem and let the map removal clean up */ +assert (bpf_map_update_elem (fd, &key3, &val3, (u64 )10000 <<32 ) ==0 ); + +close (fd); +} +#include <sys/ioctl.h> #include <arpa/inet.h> #include <sys/select.h>
@@ -1305,6 +1351,7 @@ static void test_map_stress(void)run_parallel (100 , test_arraymap,NULL );run_parallel (100 , test_arraymap_percpu,NULL ); +run_parallel (100 , test_timeout_map,NULL ); }#define TASKS 1024
@@ -1759,6 +1806,25 @@ static void test_reuseport_array(void)close (map_fd); } +static void test_large_timeout_map (int nr_elems) +{ +int val, key; +int i, fd; + + fd =bpf_create_map (BPF_MAP_TYPE_TIMEOUT_HASH ,sizeof (int ),sizeof (int ), + nr_elems, map_flags); +if (fd <0 ) { +printf ("Failed to create a large timeout map '%s'!\n" ,strerror (errno)); +exit (1 ); + } +for (i =0 ; i < nr_elems; i++) { + key = val = i; +/* Timeout after 10 secs */ +assert (bpf_map_update_elem (fd, &key, &val, (u64 )10000 <<32 ) ==0 ); + } +close (fd); +} +static void run_all_tests (void ) {test_hashmap (0 ,NULL );
@@ -1788,6 +1854,8 @@ static void run_all_tests(void)test_stackmap (0 ,NULL );test_map_in_map (); + +test_large_timeout_map (1000000 ); }#define DEFINE_TEST (name) extern void test_##name(void);
Signature · 1 line
2.25.1
PATCH v5 3/3 selftests/bpf: add timeout map check in map_ptr tests
In reply to Cong WangFrom: Cong Wang <[email protected]>
Similar to regular hashmap test.
--- .../selftests/bpf/progs/map_ptr_kern.c | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+)
tools/testing/selftests/bpf/progs/map_ptr_kern.c +20 -0
@@ -648,6 +648,25 @@ static inline int check_ringbuf(void)return 1 ; } +struct { + __uint(type, BPF_MAP_TYPE_TIMEOUT_HASH); + __uint(max_entries, MAX_ENTRIES); + __type(key, __u32); + __type(value, __u32); +} m_timeout SEC(".maps"); + +static inline int check_timeout_hash (void ) +{ +struct bpf_htab *timeout_hash = (struct bpf_htab *)&m_timeout; +struct bpf_map *map = (struct bpf_map *)&m_timeout; + +VERIFY (check_default (&timeout_hash->map, map)); +VERIFY (timeout_hash->n_buckets ==MAX_ENTRIES ); +VERIFY (timeout_hash->elem_size ==64 ); + +return 1 ; +} + SEC("cgroup_skb/egress")int cg_skb (void *ctx) {
@@ -679,6 +698,7 @@ int cg_skb(void *ctx)VERIFY_TYPE (BPF_MAP_TYPE_SK_STORAGE , check_sk_storage);VERIFY_TYPE (BPF_MAP_TYPE_DEVMAP_HASH , check_devmap_hash);VERIFY_TYPE (BPF_MAP_TYPE_RINGBUF , check_ringbuf); +VERIFY_TYPE (BPF_MAP_TYPE_TIMEOUT_HASH , check_timeout_hash);return 1 ; }
Signature · 1 line
2.25.1