Introduce a classic BPF filter cache for seccomp
Subsystems (10)
cover Introduce a classic BPF filter cache for seccomp
Sandboxes like Firecracker use seccomp filters to restrict allowed syscalls. Hundreds to thousands of Firecracker VM instances can run from a single template. Each instance loads identical seccomp filters. The kernel repeatedly translates and JIT-compiles these same cBPF programs, wasting CPU cycles and slowing down bulk startup of identically sandboxed workloads. cBPF lacks dynamic instruction patching features like tail calls or tracing. Its JITed instructions remain immutable at runtime. This makes it possible to share the same cBPF filter between different processes.
This series introduces a classic BPF filter cache. It is implemented as a hash table that maps user-space filter instructions to the prepared bpf prog.
The cache lookup occurs before filter preparation:
- cache hit: Returns the shared bpf prog directly.
- cache miss: Reserves an entry. Concurrent tasks loading the same filter wait on a wait queue until preparation completes.
The cache is instantiated per subsystem. Currently, seccomp is the only user.
This series ends with a benchmark test. Every producer spawns one worker thread at a time, the worker installs a batch of filters and exits, the benchmark reports the number of filters installed per second. The table below benchmarks the batch size and the instruction length in one round, running the command below with different option values. The base column runs the same command on a kernel without this series. All data was measured on a local test setup with 32 producers.
$ ./bench --producers 32 --duration 10 seccomp-install \
--sync-mode yes --filter-len 128 --batch 4 --same-filter yesbatch filter-len base cache hit cache miss
(--same-filter yes) (--same-filter no)
1 32 0.044M/s 0.064M/s(1.5x) 0.040M/s(0.9x)
1 128 0.043M/s 0.062M/s(1.4x) 0.039M/s(0.9x)
1 512 0.037M/s 0.052M/s(1.4x) 0.034M/s(0.9x)
1 2048 0.023M/s 0.037M/s(1.6x) 0.023M/s(1.0x)
4 32 0.065M/s 0.187M/s(2.9x) 0.059M/s(0.9x)
4 128 0.062M/s 0.190M/s(3.1x) 0.055M/s(0.9x)
4 512 0.052M/s 0.167M/s(3.2x) 0.046M/s(0.9x)
4 2048 0.030M/s 0.119M/s(4.0x) 0.028M/s(0.9x)On cache hits, the cache delivers 1.4x to 4.0x throughput. Hits bypass the translation and JIT compilation pipeline entirely, so gains grow with filter length. The worker thread setup hides the win at one install per worker, a larger batch amortizes it. On cache misses, a miss costs a hash lookup and an entry allocation, the throughput degradation stays within about 10%.
Xu Kuohai (3):
bpf: Introduce classic BPF filter cache
seccomp: Use the classic BPF filter cache selftests/bpf: Add benchmark for seccomp filter install
include/linux/filter.h | 25 +- io_uring/bpf_filter.c | 3 +- kernel/seccomp.c | 12 +- net/core/filter.c | 318 +++++++++++++++++- net/packet/af_packet.c | 2 +- tools/testing/selftests/bpf/bench.c | 4 + .../bpf/benchs/bench_seccomp_install.c | 249 ++++++++++++++ 7 files changed, 604 insertions(+), 9 deletions(-) create mode 100644 tools/testing/selftests/bpf/benchs/bench_seccomp_install.c
Signature · 1 line
2.43.0
RFC PATCH 1/3 bpf: Introduce classic BPF filter cache
From: Xu Kuohai <[email protected]>
Introduce a cache for prepared classic BPF filters. It is implemented as a hash table that maps user-space filter instructions to the prepared bpf prog. The cache key consists of the raw instructions (stored as orig_prog) and a snapshot of the constant blinding and JIT policy read at load time. This ensures that sysctl changes produce different keys even for identical instructions.
Lookup occurs before filter preparation:
- cache hit: Returns the shared bpf prog directly.
- cache miss: Reserves an entry. Concurrent tasks loading the same filter wait on a wait queue until preparation completes.
--- include/linux/filter.h | 25 +++- io_uring/bpf_filter.c | 3 +- kernel/seccomp.c | 3 +- net/core/filter.c | 318 ++++++++++++++++++++++++++++++++++++++++- net/packet/af_packet.c | 2 +- 5 files changed, 343 insertions(+), 8 deletions(-)
include/linux/filter.h +24 -1
@@ -794,9 +794,30 @@ struct compat_sock_fprog {compat_uptr_t filter;/* struct sock_filter * */ }; +#define CBPF_CACHE_BITS 8 +#define CBPF_CACHE_SIZE BIT(CBPF_CACHE_BITS) + +/* cache of classic bpf filters. Identical filters share same prog */ +struct cbpf_cache { +struct hlist_head hash[CBPF_CACHE_SIZE ]; +spinlock_t lock[CBPF_CACHE_SIZE ];/* per-bucket */ +}; + +/* define a classic BPF filter cache */ +#define DEFINE_CBPF_CACHE (name) \ + struct cbpf_cache name = { \ + .lock = { \ + [0 ... (CBPF_CACHE_SIZE - 1)] = \ + __SPIN_LOCK_UNLOCKED(name.lock), \ + }, \ + } + +struct cbpf_cache_entry ; +struct sock_fprog_kern {u16 len;struct sock_filter *filter; +struct cbpf_cache_entry *cache_entry; };/* Some arches need doubleword alignment for their instructions and/or data */
@@ -1360,7 +1381,9 @@ typedef int (*bpf_aux_classic_check_t)(struct sock_filter *filter,int bpf_prog_create (struct bpf_prog **pfp,struct sock_fprog_kern *fprog);int bpf_prog_create_from_user (struct bpf_prog **pfp,struct sock_fprog *fprog, -bpf_aux_classic_check_t trans,bool save_orig); +bpf_aux_classic_check_t trans,bool save_orig, +struct cbpf_cache *cache); +void cbpf_cache_put_prog (struct bpf_prog *prog);void bpf_prog_destroy (struct bpf_prog *fp);int sk_attach_filter (struct sock_fprog *fprog,struct sock *sk);
io_uring/bpf_filter.c +2 -1
@@ -375,7 +375,8 @@ int io_register_bpf_filter(struct io_restriction *res, fprog.filter =u64_to_user_ptr (reg.filter.filter_ptr); ret =bpf_prog_create_from_user (&prog, &fprog, - io_uring_check_cbpf_filter, false); + io_uring_check_cbpf_filter, false, +NULL );if (ret)return ret;
kernel/seccomp.c +2 -1
@@ -701,7 +701,8 @@ static struct seccomp_filter *seccomp_prepare_filter(struct sock_fprog *fprog)mutex_init (&sfilter->notify_lock); ret =bpf_prog_create_from_user (&sfilter->prog, fprog, - seccomp_check_filter, save_orig); + seccomp_check_filter, save_orig, +NULL );if (ret <0 ) {kfree (sfilter);return ERR_PTR (ret);
net/core/filter.c +314 -4
372 lines not on this page · raw message
net/packet/af_packet.c +1 -1
@@ -1617,7 +1617,7 @@ static int fanout_set_data_cbpf(struct packet_sock *po, sockptr_t data,if (ret)return ret; - ret =bpf_prog_create_from_user (&new, &fprog,NULL , false); + ret =bpf_prog_create_from_user (&new, &fprog,NULL , false,NULL );if (ret)return ret;
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [RFC PATCH 1/3] bpf: Introduce classic BPF filter cache
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] bpf: write to read-only bpf_prog in cbpf_cache_complete() - [Low] bpf: unsnapshotted bpf_jit_enable…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] bpf: write to read-only bpf_prog in cbpf_cache_complete()
- [Low] bpf: unsnapshotted bpf_jit_enable read in cbpf_cache_tag() --
commit 150cca79ed8acc9b4ba7fe54a3257e050436741a
Author: Xu Kuohai <[email protected]>
bpf: Introduce classic BPF filter cache
This commit introduces a hash table cache for prepared classic BPF filters so identical user-space filter programs share the same prepared bpf_prog.
Quoted 4 lines
net/core/filter.c +0
-0
[ ... ]
Quoted 4 lines
net/core/filter.c +0
-0@@ -1187,6 +1193,282 @@ static void bpf_release_orig_filter(struct bpf_prog *fp) } }
[ ... ]
Quoted 24 lines
net/core/filter.c +24
-0+/* +* calculate tag from the allocation-time JIT and blinding states, so sysctl +* changes produce a different tag. +*/ +static u32 cbpf_cache_tag (const struct bpf_prog *prog) +{ +u32 tag =0 ; + + tag |= (prog->jit_requested <<1 ); + tag |= (prog->blinding_requested <<2 ); +#ifdef CONFIG_BPF_JIT + tag |= (bpf_jit_enable <<3 ); +#endif + +return tag; +} + +static u32 cbpf_cache_bucket (const struct bpf_prog *prog) +{ +const struct sock_fprog_kern *orig = prog->orig_prog; + +return jhash (orig->filter, orig->len *sizeof (struct sock_filter ), +cbpf_cache_tag (prog)) %CBPF_CACHE_SIZE ; +}
[ ... ]
Quoted 4 lines
net/core/filter.c +4
-0+static int cbpf_cache_insert (struct cbpf_cache *cache,struct bpf_prog *prog, +struct cbpf_cache_entry **pentry) +{ +struct cbpf_cache_entry *entry, *hit, *cur;
net/core/filter.c static void bpf_release_orig_filter(struct bpf_prog *fp) · line 1352
Quoted 10 lines
net/core/filter.c +10
-0+u32 bucket =cbpf_cache_bucket (prog); + + entry =kzalloc_obj (*entry,GFP_KERNEL | __GFP_NOWARN); +if (!entry) +return -ENOMEM ; + + entry->orig = prog->orig_prog; + entry->cache = cache; + entry->tag =cbpf_cache_tag (prog); + entry->bucket = bucket;
[Severity: Low]
Can entry->bucket and entry->tag disagree if bpf_jit_enable changes via sysctl while cbpf_cache_insert() sleeps in kzalloc_obj()?
Unlike prog->jit_requested and prog->blinding_requested, bpf_jit_enable is read live from the global variable on each cbpf_cache_tag() call rather than from an allocation-time snapshot. If bpf_jit_enable changes between cbpf_cache_bucket() and cbpf_cache_tag(), the entry is inserted into the bucket hashed with the old tag while storing the new tag in entry->tag, so future lookups in either bucket will not match it.
[ ... ]
net/core/filter.c static void bpf_release_orig_filter(struct bpf_prog *fp) · line 1438
Quoted 6 lines
net/core/filter.c +6
-0+/* publish the prepared result, and wake up waiters */ +static void cbpf_cache_complete (struct cbpf_cache_entry *entry, +struct bpf_prog *fp) +{ + fp->orig_prog = entry->orig; + fp->orig_prog->cache_entry = entry;
[Severity: High]
Does assigning fp->orig_prog here fault on read-only memory when the filter is not JIT-compiled on a !CONFIG_BPF_JIT_ALWAYS_ON kernel?
In bpf_prog_create_from_user(), cbpf_cache_insert() clears prog->orig_prog before calling bpf_prepare_filter(), and cbpf_cache_complete() restores fp->orig_prog afterwards. However, bpf_prepare_filter() -> bpf_migrate_filter() -> bpf_prog_select_runtime() -> __bpf_prog_select_runtime() calls bpf_prog_lock_ro(fp), which marks all pages of struct bpf_prog read-only via set_memory_ro() when !fp->jited and !CONFIG_BPF_JIT_ALWAYS_ON. Writing to fp->orig_prog in cbpf_cache_complete() then triggers a supervisor write page fault.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
RFC PATCH 2/3 seccomp: Use the classic BPF filter cache
In reply to Xu KuohaiFrom: Xu Kuohai <[email protected]>
Define a classic BPF filter cache in seccomp. This allows identical seccomp filters to share a single prepared program instead of each paying the cost of the check, rewrite, migration, and JIT compilation pipeline.
--- kernel/seccomp.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/seccomp.c +9 -2
@@ -465,6 +465,9 @@ static inline void seccomp_assign_mode(struct task_struct *task, }#ifdef CONFIG_SECCOMP_FILTER + +static DEFINE_CBPF_CACHE (seccomp_cbpf_cache); +/* Returns 1 if the parent is an ancestor of the child. */ static int is_ancestor (struct seccomp_filter *parent,struct seccomp_filter *child)
@@ -526,7 +529,11 @@ static inline pid_t seccomp_can_sync_threads(void)static inline void seccomp_filter_free (struct seccomp_filter *filter) {if (filter) { -bpf_prog_destroy (filter->prog); +if (filter->prog->orig_prog && + filter->prog->orig_prog->cache_entry) +cbpf_cache_put_prog (filter->prog); +else +bpf_prog_destroy (filter->prog);kfree (filter); } }
@@ -702,7 +709,7 @@ static struct seccomp_filter *seccomp_prepare_filter(struct sock_fprog *fprog)mutex_init (&sfilter->notify_lock); ret =bpf_prog_create_from_user (&sfilter->prog, fprog, seccomp_check_filter, save_orig, -NULL ); + &seccomp_cbpf_cache);if (ret <0 ) {kfree (sfilter);return ERR_PTR (ret);
Signature · 1 line
2.43.0
RFC PATCH 3/3 selftests/bpf: Add benchmark for seccomp filter install
In reply to Xu KuohaiFrom: Xu Kuohai <[email protected]>
Add a benchmark to measure the cost of installing seccomp filter. Each producer spawns one worker thread per burst. The worker installs a batch of filters and exits. The benchmark reports the number of filters installed per second.
--- tools/testing/selftests/bpf/bench.c | 4 + .../bpf/benchs/bench_seccomp_install.c | 249 ++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 tools/testing/selftests/bpf/benchs/bench_seccomp_install.c
tools/testing/selftests/bpf/bench.c +4 -0
@@ -289,6 +289,7 @@ extern struct argp bench_sockmap_argp;extern struct argp bench_lpm_trie_map_argp;extern struct argp bench_xdp_lb_argp;extern struct argp bench_libarena_argp; +extern struct argp bench_seccomp_install_argp;static const struct argp_child bench_parsers[] = { { &bench_ringbufs_argp,0 ,"Ring buffers benchmark" ,0 },
@@ -308,6 +309,7 @@ static const struct argp_child bench_parsers[] = { { &bench_lpm_trie_map_argp, 0, "LPM trie map benchmark", 0 }, { &bench_xdp_lb_argp, 0, "XDP load-balancer benchmark", 0 }, { &bench_libarena_argp, 0, "libarena allocator benchmark", 0 }, + { &bench_seccomp_install_argp, 0, "seccomp install benchmark", 0 }, {}, };
@@ -578,6 +580,7 @@ extern const struct bench bench_rhtab_mem;extern const struct bench bench_crypto_encrypt;extern const struct bench bench_crypto_decrypt;extern const struct bench bench_sockmap; +extern const struct bench bench_seccomp_install;extern const struct bench bench_lpm_trie_noop;extern const struct bench bench_lpm_trie_baseline;extern const struct bench bench_lpm_trie_lookup;
@@ -666,6 +669,7 @@ static const struct bench *benchs[] = { &bench_crypto_encrypt, &bench_crypto_decrypt, &bench_sockmap, + &bench_seccomp_install, &bench_lpm_trie_noop, &bench_lpm_trie_baseline, &bench_lpm_trie_lookup,
tools/testing/selftests/bpf/benchs/bench_seccomp_install.c new file +249 -0
249 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [RFC PATCH 3/3] selftests/bpf: Add benchmark for seccomp filter install
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] selftests/bpf: seccomp insn budget undercount and overflow in setup() - [Low] selftests/bpf: barrier…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] selftests/bpf: seccomp insn budget undercount and overflow in setup()
- [Low] selftests/bpf: barrier hang on malloc() failure in producer() --
commit e23b8e529406f7cf306411e18be355c8be76105c
Author: Xu Kuohai <[email protected]>
selftests/bpf: Add benchmark for seccomp filter install
This commit adds a benchmark to measure the throughput of installing seccomp filters in batches from worker threads.
Quoted 6 lines
tools/testing/selftests/bpf/benchs/bench_seccomp_install.c new file +0
-0@@ -0,0 +1,249 @@
[ ... ]
tools/testing/selftests/bpf/benchs/bench_seccomp_install.c line 192
Quoted 11 lines
tools/testing/selftests/bpf/benchs/bench_seccomp_install.c new file +11
-0+static void *producer (void *input) +{ +struct sock_filter *insns; +pthread_t thread; +void *ret; + + insns =malloc (ctx.filter_len *sizeof (*insns)); +if (!insns) { +atomic_inc (&ctx.drops.value); +return NULL ; + }
[Severity: Low]
Can a malloc() failure in one producer thread hang the remaining workers on ctx.barrier?
When ctx.sync is enabled, setup() initializes ctx.barrier with env.producer_cnt threads. If malloc() fails here, this producer exits without spawning worker threads, so the workers created by the remaining producers block in install_batch() at pthread_barrier_wait(&ctx.barrier) for the rest of the benchmark run.
[ ... ]
tools/testing/selftests/bpf/benchs/bench_seccomp_install.c line 230
Quoted 11 lines
tools/testing/selftests/bpf/benchs/bench_seccomp_install.c new file +11
-0+static void setup (void ) +{ +if (prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )) { +fprintf (stderr,"PR_SET_NO_NEW_PRIVS failed: %d\n" , -errno); +exit (1 ); + } + +if ((args.filter_len +4 ) * args.batch >SECCOMP_MAX_INSNS_PER_PATH ) { +fprintf (stderr,"the batch exceeds the seccomp insns budget of one task\n" ); +exit (1 ); + }
[Severity: Low]
Does this budget check undercount the kernel's per-task seccomp instruction calculation and risk 32-bit overflow?
bpf_convert_filter() expands the cBPF filter built by fill_filter() from args.filter_len to args.filter_len + 4 eBPF instructions (3-insn prologue and 2 insns for BPF_RET | BPF_K). seccomp_attach_filter() then charges prog->len for the new filter plus walker->prog->len + 4 for each existing filter on the task, reaching (args.filter_len + 8) * args.batch - 4 on the final install of a batch. Because setup() checks (args.filter_len + 4) * args.batch (and does so in 32-bit unsigned arithmetic, which can wrap on large --batch values), combinations such as --filter-len 4090 with default --batch 8 pass setup() and fail every seccomp() call in install_batch() with ENOMEM.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Quoted 3 lines · Xu Kuohai
The kernel repeatedly translates and JIT-compiles these same cBPF programs, wasting CPU cycles and slowing down bulk startup of identically sandboxed workloads. cBPF lacks dynamic instruction patching
There is no VM startup number in the series
which makes me question the whole thing.
Quoted 3 lines
features like tail calls or tracing. Its JITed instructions remain immutable at runtime. This makes it possible to share the same cBPF filter between different processes.
Immutable is not enough. The image depends on the caps of the task that loads the filter.
Also any task can time seccomp() and learn that somebody has this filter. seccomp_get_filter() needs CAP_SYS_ADMIN for that today.
fork() shares the filter already, see copy_seccomp(). A launcher can install the common filter once and fork the VMs.
I don't think we need this.
pw-bot: cr
Quoted 8 lines · Alexei Starovoitov
Quoted 3 lines · Xu Kuohai
The kernel repeatedly translates and JIT-compiles these same cBPF programs, wasting CPU cycles and slowing down bulk startup of identically sandboxed workloads. cBPF lacks dynamic instruction patching
There is no VM startup number in the series
which makes me question the whole thing.
The problem comes from an agent sandbox deployment, where sandboxes are snapshotted to disk and resumed on demand for each new request.
Below are the Firecracker microVM startup latencies I measured on a local server at different VM request rates. Parentheses show the improvement over the base kernel.
VM req/s base p50 series p50 (gain) base p95 series p95 (gain) base p99 series p99 (gain) 400 20.2 ms 19.7 ms (+2%) 29.2 ms 27.9 ms (+5%) 34.7 ms 33.3 ms (+4%) 500 28.2 ms 27.1 ms (+4%) 96.8 ms 69.4 ms (+28%) 164.0 ms 107.9 ms (+34%) 600 56.6 ms 45.0 ms (+21%) 602 ms 154.5 ms (+74%) 831.8 ms 223.6 ms (+73%) 700 65.5 ms 41.1 ms (+37%) 1.63 s 134.1 ms (+92%) 2.43 s 194.1 ms (+92%) 800 65.4 ms 39.4 ms (+40%) 2.97 s 113.8 ms (+96%) 4.60 s 167.3 ms (+96%) 900 61.9 ms 35.7 ms (+42%) 3.04 s 95.2 ms (+97%) 5.13 s 147.3 ms (+97%) 1000 53.2 ms 32.2 ms (+39%) 3.38 s 80.0 ms (+98%) 5.78 s 125.1 ms (+98%)
At 400 VM/s, the two kernels perform similarly. At higher rates, the base kernel suffers severe tail latency collapse, while this series keeps p99 below 225 ms, reducing it by up to 98% at 1000 VM/s.
After further profiling, I found that this collapse is mainly caused by Firecracker instances queuing on the global pack_mutex in bpf_prog_pack_alloc(). So a better approach is to replace the global mutex to per-pack locks. I will work on that instead.
Quoted 15 lines
Quoted 3 lines
features like tail calls or tracing. Its JITed instructions remain immutable at runtime. This makes it possible to share the same cBPF filter between different processes.
Immutable is not enough. The image depends on the caps of the task that loads the filter.
Also any task can timeseccomp()and learn that somebody has this filter.seccomp_get_filter()needsCAP_SYS_ADMINfor that today.
fork()shares the filter already, seecopy_seccomp(). A launcher can install the common filter once and fork the VMs.I don't think we need this.
pw-bot: cr
Quoted 5 lines · Xu Kuohai
After further profiling, I found that this collapse is mainly caused by Firecracker instances queuing on the global
pack_mutexinbpf_prog_pack_alloc(). So a better approach is to replace the global mutex to per-pack locks. I will work on that instead.
Makes sense to fix it there. Every prog load benefits.
But I doubt that per-pack locks help.bpf_prog_pack_alloc() walks pack_list from the head and takes the first pack that has room. All loaders pick the same pack and queue on its lock.
I suspect the hold time comes from these:
path under pack_mutex what it does ----- -------------------------- -------------------------------- alloc bpf_arch_pred_flush() x86: IBPB via on_each_cpu() free bpf_arch_text_invalidate() x86: text_poke_set(), text_mutex free bpf_arch_text_invalidate() arm64: kick_all_cpus_sync()
Every free marks its pack dirty. A cBPF alloc from a dirty pack flushes. The log of commit a9b1f19a6a67 ("bpf: Prefer packs that won't trigger an IBPB flush on allocation") has ideas how to flush less.
bpf_arch_text_invalidate() doesn't need pack_mutex. The bits of the chunks are still set in pack->bitmap at that point, so nobody can take the chunks or free the pack.
What do you see in your profile?
Quoted 24 lines · Alexei Starovoitov
Quoted 5 lines · Xu Kuohai
After further profiling, I found that this collapse is mainly caused by Firecracker instances queuing on the global
pack_mutexinbpf_prog_pack_alloc(). So a better approach is to replace the global mutex to per-pack locks. I will work on that instead.Makes sense to fix it there. Every prog load benefits.
But I doubt that per-pack locks help.bpf_prog_pack_alloc()walkspack_listfrom the head and takes the first pack that has room. All loaders pick the same pack and queue on its lock.I suspect the hold time comes from these:
path under pack_mutex what it does ----- -------------------------- -------------------------------- alloc bpf_arch_pred_flush() x86: IBPB via on_each_cpu() free bpf_arch_text_invalidate() x86: text_poke_set(), text_mutex free bpf_arch_text_invalidate() arm64: kick_all_cpus_sync()Every free marks its pack dirty. A cBPF alloc from a dirty pack flushes. The log of commit
a9b1f19a6a67("bpf: Prefer packs that won't trigger an IBPB flush on allocation") has ideas how to flush less.
Quoted 5 lines
bpf_arch_text_invalidate()doesn't needpack_mutex. The bits of the chunks are still set inpack->bitmapat that point, so nobody can take the chunks or free the pack.What do you see in your profile?
Hi Alexei,
You are correct.
The benchmark server is arm64. The lock hold times in bpf_prog_pack_alloc() and bpf_prog_pack_free() are typically 8–16 us and 256–512 us, respectively.
The free path is dominated by bpf_arch_text_invalidate(), which sends IPIs to all CPUs and waits for completion. The wait happens after put_cpu(), so the task is preemptible. If the task is preempted, other lock waiters remain blocked until it is scheduled back and releases the lock. This can extend the lock hold time to seconds.
Below is a sample of the captured preemption stack:
-> bpf_prog_pack_free
-> bpf_arch_text_invalidate
-> aarch64_insn_set
-> __text_poke
-> kick_all_cpus_sync
-> smp_call_function_many_cond
-> el1h_64_irq
-> el1h_64_irq_handler
-> el1_interrupt
-> arm64_exit_to_kernel_mode_preempt
-> irqentry_exit_cond_resched
-> preempt_schedule_irq
-> __scheduleAfter moving bpf_arch_text_invalidate() out of pack_mutex, the p99 VM startup latency drops from 2.79 s to 170 ms under the same workload.
I will post the patch once it is ready.
Quoted 8 lines · Xu Kuohai
The free path is dominated by
bpf_arch_text_invalidate(), which sends IPIs to all CPUs and waits for completion. The wait happens afterput_cpu(), so the task is preemptible. If the task is preempted, other lock waiters remain blocked until it is scheduled back and releases the lock. This can extend the lock hold time to seconds.After moving
bpf_arch_text_invalidate()out ofpack_mutex, the p99 VM startup latency drops from 2.79 s to 170 ms under the same workload.
Awesome!
btw every free still sends these IPIs.
We can probably remove them.
aarch64_insn_set() can do caches_clean_inval_pou() only like aarch64_insn_patch_text_nosync(). bpf_arch_text_invalidate() is its only caller and nothing runs in the freed chunks.
It can be a separate patch, of course.
Quoted 15 lines · Alexei Starovoitov
Quoted 8 lines · Xu Kuohai
The free path is dominated by
bpf_arch_text_invalidate(), which sends IPIs to all CPUs and waits for completion. The wait happens afterput_cpu(), so the task is preemptible. If the task is preempted, other lock waiters remain blocked until it is scheduled back and releases the lock. This can extend the lock hold time to seconds.After moving
bpf_arch_text_invalidate()out ofpack_mutex, the p99 VM startup latency drops from 2.79 s to 170 ms under the same workload.Awesome!
btw every free still sends these IPIs.
We can probably remove them.
Quoted 6 lines
aarch64_insn_set()can docaches_clean_inval_pou()only likeaarch64_insn_patch_text_nosync().bpf_arch_text_invalidate()is its only caller and nothing runs in the freed chunks.It can be a separate patch, of course.
Yeah, I'll look into it.
Kees Cook
maintainerQuoted 22 lines · Xu Kuohai
Sandboxes like Firecracker use seccomp filters to restrict allowed syscalls. Hundreds to thousands of Firecracker VM instances can run from a single template. Each instance loads identical seccomp filters. The kernel repeatedly translates and JIT-compiles these same cBPF programs, wasting CPU cycles and slowing down bulk startup of identically sandboxed workloads. cBPF lacks dynamic instruction patching features like tail calls or tracing. Its JITed instructions remain immutable at runtime. This makes it possible to share the same cBPF filter between different processes.
This series introduces a classic BPF filter cache. It is implemented as a hash table that maps user-space filter instructions to the prepared bpf prog.
The cache lookup occurs before filter preparation:
- cache hit: Returns the shared bpf prog directly.
- cache miss: Reserves an entry. Concurrent tasks loading the same filter wait on a wait queue until preparation completes.The cache is instantiated per subsystem. Currently, seccomp is the only user.
Quoted 7 lines
This series ends with a benchmark test. Every producer spawns one worker thread at a time, the worker installs a batch of filters and exits, the benchmark reports the number of filters installed per second. The table below benchmarks the batch size and the instruction length in one round, running the command below with different option values. The base column runs the same command on a kernel without this series. All data was measured on a local test setup with 32 producers.
I would expect either memory usage or launch benchmarks, not just filter install timings.
Is there a workload where there is a problem? It is hinted at in the opening paragraph, but I'd want to better understand the actual constraints before jumping to a solution. E.g. it's already possible to share filters by way of process hierarchy, so perhaps the issue is lack of hierarchy?
I've seen proposals in the past about having handles to pre-constructed filters, which could be applied (i.e. much of the existing caching and lifetime management remained unchanged).
-Kees
Signature · 1 line
Kees Cook