Skip to contentSkip to conversation

bpf: Move IPIs out of pack_mutex and reduce IBPB flushes

PATCH In review Xu Kuohai 3 participants 11 messages Dec 2 – Dec 3

Subsystems (2)
lore
Share & tools
lore
author
#4 lore raw

PATCH 2/3 bpf: Change dirty tracking from packs to chunks

In reply to Xu Kuohai

From: Xu Kuohai <[email protected]>

Currently, predictor dirty tracking in the pack allocator is per pack. Even if all chunks allocated for a cBPF program are clean, a flush is still triggered if they come from a dirty pack.

So switch dirty tracking from packs to chunks by maintaining a dirty bit for each chunk. The dirty bits are initialized to 1 when the pack is newly added, and cleared when memory is freed back to the pack while pack->arch_flush_needed is false.

The pack->arch_flush_needed flag is cleared at flush time, so dirty bits are not changed during the window between the flush and the next free. But the stale dirty bits in this window are harmless. Even if a cBPF filter is allocated a dirty chunk, no flush is triggered as long as pack->arch_flush_needed is false.

---
 kernel/bpf/core.c | 73 +++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 64 insertions(+), 9 deletions(-)
kernel/bpf/core.c +64 -9
index f43c512d3cc5..51818dd5ad50 100644
@@ -1153,6 +1153,7 @@ struct bpf_prog_pack {
 	struct list_head list;
 	void *ptr;
 	bool arch_flush_needed;
+	unsigned long *dirty_map;
 	unsigned long bitmap[];
 };
 
@@ -1201,16 +1202,19 @@ static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_ins
 	struct bpf_prog_pack *pack;
 	int err;
 
-	pack = kzalloc_flex(*pack, bitmap, BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT));
+	pack = kzalloc_flex(*pack, bitmap, 2 * BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT));
 	if (!pack)
 		return NULL;
+	pack->dirty_map = pack->bitmap + BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT);
 	pack->ptr = bpf_jit_alloc_exec(BPF_PROG_PACK_SIZE);
 	if (!pack->ptr)
 		goto out;
 	bitmap_zero(pack->bitmap, BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE);
 
-	if (static_branch_unlikely(&bpf_pred_flush_enabled))
+	if (static_branch_unlikely(&bpf_pred_flush_enabled)) {
 		pack->arch_flush_needed = true;
+		bitmap_fill(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
+	}
 	if (!bpf_jit_mem_is_rox()) {
 		bpf_fill_ill_insns(pack->ptr, BPF_PROG_PACK_SIZE);
 		set_vm_flush_reset_perms(pack->ptr);
@@ -1228,11 +1232,48 @@ static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_ins
 	return NULL;
 }
 
+static bool bpf_pack_chunks_are_dirty(struct bpf_prog_pack *pack, unsigned long pos,
+				      unsigned int nbits)
+{
+	return find_next_bit(pack->dirty_map, pos + nbits, pos) < pos + nbits;
+}
+
+static unsigned long
+bpf_pack_find_area(struct bpf_prog_pack *pack, unsigned long pos, u32 nbits, bool clean)
+{
+	unsigned long dirty_pos;
+
+	while (pos < BPF_PROG_CHUNK_COUNT) {
+		if (clean) {
+			/* Find the next window that starts at a clean chunk */
+			pos = find_next_zero_bit(pack->dirty_map, BPF_PROG_CHUNK_COUNT, pos);
+		} else {
+			/* Find the next window that holds a dirty chunk */
+			dirty_pos = find_next_bit(pack->dirty_map, BPF_PROG_CHUNK_COUNT, pos);
+			if (dirty_pos >= BPF_PROG_CHUNK_COUNT)
+				return BPF_PROG_CHUNK_COUNT;
+			pos = dirty_pos - nbits + 1;
+		}
+
+		pos = bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, pos, nbits, 0);
+		if (pos >= BPF_PROG_CHUNK_COUNT)
+			return BPF_PROG_CHUNK_COUNT;
+
+		dirty_pos = find_next_bit(pack->dirty_map, pos + nbits, pos);
+		if (clean == (dirty_pos >= pos + nbits))
+			return pos;
+
+		/* Resume at the first dirty chunk, or move to the following window */
+		pos = clean ? dirty_pos + 1 : pos + nbits;
+	}
+	return BPF_PROG_CHUNK_COUNT;
+}
+
 void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool was_classic)
 {
 	unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
 	struct bpf_prog_pack *pack, *fallback_pack = NULL;
-	unsigned long pos, fallback_pos = 0;
+	unsigned long pos, dirty_pos, fallback_pos = 0;
 	void *ptr = NULL;
 
 	mutex_lock(&pack_mutex);
@@ -1270,16 +1311,23 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 		if (!static_branch_unlikely(&bpf_pred_flush_enabled))
 			goto found_free_area;
 		/*
-		 * cBPF reuse of a dirty pack triggers a flush, so prefer a
-		 * clean pack for cBPF. eBPF never flushes, so steer it to a
-		 * dirty pack and keep clean packs free for cBPF.
+		 * cBPF reuse of a dirty chunk triggers a flush, so prefer
+		 * clean chunks for cBPF. eBPF never flushes, so steer it to
+		 * dirty chunks and keep clean chunks free for cBPF.
 		 */
-		if (was_classic ^ pack->arch_flush_needed)
+		dirty_pos = find_next_bit(pack->dirty_map, pos + nbits, pos);
+		if (was_classic ^ (dirty_pos < pos + nbits))
 			goto found_free_area;
+
 		if (!fallback_pack) {
 			fallback_pack = pack;
 			fallback_pos = pos;
 		}
+
+		/* Find clean chunks for cBPF or dirty chunks for eBPF */
+		pos = bpf_pack_find_area(pack, dirty_pos, nbits, was_classic);
+		if (pos < BPF_PROG_CHUNK_COUNT)
+			goto found_free_area;
 	}
 
 	/* No preferred pack found */
@@ -1299,6 +1347,7 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 	/* Flush only for cBPF as it may contain a crafted gadget */
 	if (static_branch_unlikely(&bpf_pred_flush_enabled) &&
 	    pack->arch_flush_needed &&
+	    bpf_pack_chunks_are_dirty(pack, pos, nbits) &&
 	    was_classic) {
 		struct bpf_prog_pack *p;
 
@@ -1351,8 +1400,14 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 
 	bitmap_clear(pack->bitmap, pos, nbits);
 
-	if (static_branch_unlikely(&bpf_pred_flush_enabled))
-		pack->arch_flush_needed = true;
+	if (static_branch_unlikely(&bpf_pred_flush_enabled)) {
+		if (!pack->arch_flush_needed) {
+			/* Clean the stale dirty_map if the pack is clean */
+			bitmap_zero(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
+			pack->arch_flush_needed = true;
+		}
+		bitmap_set(pack->dirty_map, pos, nbits);
+	}
 	if (bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0,
 				       BPF_PROG_CHUNK_COUNT, 0) == 0) {
 		list_del(&pack->list);
Signature · 1 line
2.47.3

Xu Kuohai

author
#0 lore raw

cover bpf: Move IPIs out of pack_mutex and reduce IBPB flushes

From: Xu Kuohai <[email protected]>

BPF JIT memory is allocated through the BPF program pack allocator, which uses a global pack_mutex to protect its packs. While holding this lock, the allocator currently sends IPI to all CPUs on two paths: IBPB flush on the x86 alloc path and CPU pipeline flush on the arm64 free path. Because the caller can be preempted while waiting for the IPI completion, the lock can be held for a long time, causing heavy lock contention on busy systems.

This series moves both IPI out of pack_mutex and tracks dirty state per chunk instead of per pack to reduce IBPB flushes.

Xu Kuohai (3):
bpf: Move bpf_arch_text_invalidate() out of pack_mutex
bpf: Change dirty tracking from packs to chunks
bpf: Move branch predictor flush out of pack_mutex

 kernel/bpf/core.c | 153 ++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 133 insertions(+), 20 deletions(-)
Signature · 1 line
2.47.3
author
#1 lore raw

PATCH 1/3 bpf: Move bpf_arch_text_invalidate() out of pack_mutex

From: Xu Kuohai <[email protected]>

bpf_prog_pack_free() holds pack_mutex across bpf_arch_text_invalidate(). On arm64 the invalidation sends an IPI to every CPU, and waits for each of them to complete. The wait is preemptible. When the freeing task is preempted there, it keeps the lock, and the waiters, in either the free or the alloc path, wait until it is scheduled back and releases the mutex. This can cause a significant lock convoy on busy systems.

Since the bits of the chunk are still set at invalidation time, nobody can take the chunk, so it is safe to move the invalidation out of the mutex.

On an arm64 host busy loading seccomp filters for Firecracker sandboxes, moving the invalidation outside the lock reduced the p99 startup latency from 2.79 s to 170 ms.

---
 kernel/bpf/core.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
kernel/bpf/core.c +10 -3
index 32a267656c0e..f43c512d3cc5 100644
@@ -1335,13 +1335,20 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 
 	if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
 		goto out;
+	mutex_unlock(&pack_mutex);
 
-	nbits = BPF_PROG_SIZE_TO_NBITS(size);
-	pos = ((unsigned long)ptr - (unsigned long)pack->ptr) >> BPF_PROG_CHUNK_SHIFT;
-
+	/*
+	 * The bits of this chunk are still set, so nobody can take the chunk
+	 * or free the pack, no need to hold the mutex.
+	 */
 	WARN_ONCE(bpf_arch_text_invalidate(ptr, size),
 		  "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n");
 
+	mutex_lock(&pack_mutex);
+
+	nbits = BPF_PROG_SIZE_TO_NBITS(size);
+	pos = ((unsigned long)ptr - (unsigned long)pack->ptr) >> BPF_PROG_CHUNK_SHIFT;
+
 	bitmap_clear(pack->bitmap, pos, nbits);
 
 	if (static_branch_unlikely(&bpf_pred_flush_enabled))
Signature · 1 line
2.47.3
author
#7 lore raw

PATCH 3/3 bpf: Move branch predictor flush out of pack_mutex

In reply to Xu Kuohai

From: Xu Kuohai <[email protected]>

bpf_prog_pack_alloc() flushes the branch predictors under pack_mutex. On x86 the flush sends IPI to all CPUs to do IBPB, and waits for each CPU to complete. This is a heavy operation inside a mutex, so move it out of the pack_mutex.

With the flush moved out, packs can become dirty while it runs unlocked. A flush therefore cannot blindly clear dirty flags. Instead, track a global dirty and flush generation pair:

- Each time a pack is marked dirty, increment the dirty generation and assign it to the pack.

- When a flush is done, set the flush generation to the dirty generation observed before the flush.

This removes the need for the flag arch_flush_needed. A pack is dirty if its dirty generation is greater than the flush generation.

---
 kernel/bpf/core.c | 71 ++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 61 insertions(+), 10 deletions(-)
kernel/bpf/core.c +61 -10
index 51818dd5ad50..07864d56e050 100644
@@ -1152,7 +1152,7 @@ int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
 struct bpf_prog_pack {
 	struct list_head list;
 	void *ptr;
-	bool arch_flush_needed;
+	u64 dirty_seq;
 	unsigned long *dirty_map;
 	unsigned long bitmap[];
 };
@@ -1176,6 +1176,23 @@ DEFINE_STATIC_KEY_FALSE(bpf_pred_flush_enabled);
 static DEFINE_MUTEX(pack_mutex);
 static LIST_HEAD(pack_list);
 
+/*
+ * The dirty generation counter. Every event that makes a pack dirty counts
+ * itself here.
+ */
+static atomic64_t pack_dirty_seq;
+
+/*
+ * The flush generation counter, published without a lock. It is set at
+ * flush time, to the dirty generation right before the flush.
+ */
+static atomic64_t pack_flush_seq;
+
+static bool bpf_prog_pack_is_dirty(const struct bpf_prog_pack *pack)
+{
+	return (s64)(pack->dirty_seq - atomic64_read(&pack_flush_seq)) > 0;
+}
+
 /* PMD_SIZE is not available in some special config, e.g. ARCH=arm with
  * CONFIG_MMU=n. Use PAGE_SIZE in these cases.
  */
@@ -1212,7 +1229,7 @@ static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_ins
 	bitmap_zero(pack->bitmap, BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE);
 
 	if (static_branch_unlikely(&bpf_pred_flush_enabled)) {
-		pack->arch_flush_needed = true;
+		pack->dirty_seq = atomic64_inc_return(&pack_dirty_seq);
 		bitmap_fill(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
 	}
 	if (!bpf_jit_mem_is_rox()) {
@@ -1232,6 +1249,40 @@ static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_ins
 	return NULL;
 }
 
+static DEFINE_MUTEX(pack_flush_mutex);
+
+static void bpf_prog_pack_flush(u64 count)
+{
+	u64 seq;
+
+	/*
+	 * Before getting the lock, check if someone else already performed
+	 * the flush. The acquire pairs with the xchg barrier of the publish.
+	 */
+	if ((s64)(atomic64_read(&pack_flush_seq) - count) >= 0) {
+		smp_acquire__after_ctrl_dep();
+		return;
+	}
+
+	mutex_lock(&pack_flush_mutex);
+
+	/* A flush may have run before we got the mutex */
+	if ((s64)(atomic64_read(&pack_flush_seq) - count) >= 0)
+		goto out;
+
+	seq = atomic64_read(&pack_dirty_seq);
+
+	/* Read the dirty generation before the broadcast starts */
+	smp_mb();
+
+	static_call_cond(bpf_arch_pred_flush)();
+
+	/* xchg is a full barrier. It orders the flush before the publish. */
+	atomic64_xchg(&pack_flush_seq, seq);
+out:
+	mutex_unlock(&pack_flush_mutex);
+}
+
 static bool bpf_pack_chunks_are_dirty(struct bpf_prog_pack *pack, unsigned long pos,
 				      unsigned int nbits)
 {
@@ -1274,6 +1325,8 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 	unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
 	struct bpf_prog_pack *pack, *fallback_pack = NULL;
 	unsigned long pos, dirty_pos, fallback_pos = 0;
+	bool flush = false;
+	u64 count = 0;
 	void *ptr = NULL;
 
 	mutex_lock(&pack_mutex);
@@ -1346,20 +1399,18 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 found_free_area:
 	/* Flush only for cBPF as it may contain a crafted gadget */
 	if (static_branch_unlikely(&bpf_pred_flush_enabled) &&
-	    pack->arch_flush_needed &&
 	    bpf_pack_chunks_are_dirty(pack, pos, nbits) &&
 	    was_classic) {
-		struct bpf_prog_pack *p;
-
-		static_call_cond(bpf_arch_pred_flush)();
-		list_for_each_entry(p, &pack_list, list)
-			p->arch_flush_needed = false;
+		flush = true;
+		count = pack->dirty_seq;
 	}
 	bitmap_set(pack->bitmap, pos, nbits);
 	ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
 
 out:
 	mutex_unlock(&pack_mutex);
+	if (flush)
+		bpf_prog_pack_flush(count);
 	return ptr;
 }
 
@@ -1401,12 +1452,12 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 	bitmap_clear(pack->bitmap, pos, nbits);
 
 	if (static_branch_unlikely(&bpf_pred_flush_enabled)) {
-		if (!pack->arch_flush_needed) {
+		if (!bpf_prog_pack_is_dirty(pack)) {
 			/* Clean the stale dirty_map if the pack is clean */
 			bitmap_zero(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
-			pack->arch_flush_needed = true;
 		}
 		bitmap_set(pack->dirty_map, pos, nbits);
+		pack->dirty_seq = atomic64_inc_return(&pack_dirty_seq);
 	}
 	if (bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0,
 				       BPF_PROG_CHUNK_COUNT, 0) == 0) {
Signature · 1 line
2.47.3
#5 lore raw

Re: [PATCH bpf-next 2/3] bpf: Change dirty tracking from packs to chunks

In reply to Xu Kuohai
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: stale dirty_map read when !arch_flush_needed in bpf_prog_pack_alloc() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: stale dirty_map read when !arch_flush_needed in bpf_prog_pack_alloc()
--

commit 811051fe76077420fa826110b71c4df5c0c494fd
Author: Xu Kuohai <[email protected]>

bpf: Change dirty tracking from packs to chunks

This commit switches predictor dirty tracking in the BPF prog pack allocator from per-pack to per-chunk using a dirty_map bitmap on each pack.

Quoted 4 lines
kernel/bpf/core.c +0 -0
index 63bc7e7b95409..920c8cdaf2679 100644

[ ... ]

Quoted 16 lines
kernel/bpf/core.c +6 -4
@@ -1304,16 +1345,23 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 		if (!static_branch_unlikely(&bpf_pred_flush_enabled))
 			goto found_free_area;
 		/*
-		 * cBPF reuse of a dirty pack triggers a flush, so prefer a
-		 * clean pack for cBPF. eBPF never flushes, so steer it to a
-		 * dirty pack and keep clean packs free for cBPF.
+		 * cBPF reuse of a dirty chunk triggers a flush, so prefer
+		 * clean chunks for cBPF. eBPF never flushes, so steer it to
+		 * dirty chunks and keep clean chunks free for cBPF.
 		 */
-		if (was_classic ^ pack->arch_flush_needed)
+		dirty_pos = find_next_bit(pack->dirty_map, pos + nbits, pos);
+		if (was_classic ^ (dirty_pos < pos + nbits))
 			goto found_free_area;
+

kernel/bpf/core.c void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool · line 1365

Quoted 10 lines
kernel/bpf/core.c +5 -0
 		if (!fallback_pack) {
 			fallback_pack = pack;
 			fallback_pos = pos;
 		}
+
+		/* Find clean chunks for cBPF or dirty chunks for eBPF */
+		pos = bpf_pack_find_area(pack, dirty_pos, nbits, was_classic);
+		if (pos < BPF_PROG_CHUNK_COUNT)
+			goto found_free_area;
 	}

[Severity: Medium]
Does consulting pack->dirty_map here without checking pack->arch_flush_needed misclassify clean packs that still hold stale dirty bits?

When a flush runs, it sets p->arch_flush_needed = false across pack_list without clearing p->dirty_map, deferring bitmap_zero() until the next bpf_prog_pack_free() on each pack. Until a free happens in that pack, pack->dirty_map retains stale 1 bits (including all bits set to 1 from alloc_new_pack()).

If an earlier pack in pack_list has only dirty free chunks and becomes fallback_pack, while a later pack has arch_flush_needed == false with stale bits in dirty_map, a cBPF allocation treats the clean pack as dirty, skips it, falls back to the dirty fallback_pack, and triggers an unnecessary bpf_arch_pred_flush(). For eBPF, the stale bits make the clean pack look dirty, steering eBPF allocations into clean packs instead of saving them for cBPF. Checking pack->arch_flush_needed before inspecting pack->dirty_map (treating all chunks in the pack as clean when !pack->arch_flush_needed) would avoid acting on the stale bitmap.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#8 lore raw

Re: [PATCH bpf-next 3/3] bpf: Move branch predictor flush out of pack_mutex

In reply to Xu Kuohai
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: stale dirty_map read in bpf_prog_pack_alloc() on clean packs --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: stale dirty_map read in bpf_prog_pack_alloc() on clean packs
--

commit 34ea7e29e7698a27be8a5df803db4e9f53918487
Author: Xu Kuohai <[email protected]>

bpf: Move branch predictor flush out of pack_mutex

This commit moves branch predictor flushing out of pack_mutex by replacing pack->arch_flush_needed with pack_dirty_seq and pack_flush_seq generation counters, serializing flushes under pack_flush_mutex.

Quoted 4 lines
kernel/bpf/core.c +0 -0
index 920c8cdaf2679..1ecf39885bfb0 100644

[ ... ]

Quoted 28 lines
kernel/bpf/core.c +4 -6
@@ -1380,20 +1433,18 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 found_free_area:
 	/* Flush only for cBPF as it may contain a crafted gadget */
 	if (static_branch_unlikely(&bpf_pred_flush_enabled) &&
-	    pack->arch_flush_needed &&
 	    bpf_pack_chunks_are_dirty(pack, pos, nbits) &&
 	    was_classic) {
-		struct bpf_prog_pack *p;
-
-		static_call_cond(bpf_arch_pred_flush)();
-		list_for_each_entry(p, &pack_list, list)
-			p->arch_flush_needed = false;
+		flush = true;
+		count = pack->dirty_seq;
 	}
 	bitmap_set(pack->bitmap, pos, nbits);
 	ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
 
 out:
 	mutex_unlock(&pack_mutex);
+	if (flush)
+		bpf_prog_pack_flush(count);
 	return ptr;
 }
 
@@ -1435,12 +1486,12 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 	bitmap_clear(pack->bitmap, pos, nbits);
 

kernel/bpf/core.c void bpf_prog_pack_free(void *ptr, u32 size) · line 1495

Quoted 10 lines
kernel/bpf/core.c +2 -2
 	if (static_branch_unlikely(&bpf_pred_flush_enabled)) {
-		if (!pack->arch_flush_needed) {
+		if (!bpf_prog_pack_is_dirty(pack)) {
 			/* Clean the stale dirty_map if the pack is clean */
 			bitmap_zero(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
-			pack->arch_flush_needed = true;
 		}
 		bitmap_set(pack->dirty_map, pos, nbits);
+		pack->dirty_seq = atomic64_inc_return(&pack_dirty_seq);
 	}

[Severity: Medium]
Does bpf_prog_pack_alloc() read stale bits from pack->dirty_map when a pack has already been flushed?

bpf_prog_pack_flush() advances pack_flush_seq without clearing pack->dirty_map, and stale bits are only zeroed lazily in bpf_prog_pack_free() when a program is later freed from that pack while !bpf_prog_pack_is_dirty(pack). Until then, the pack search loop in bpf_prog_pack_alloc() inspects pack->dirty_map without checking bpf_prog_pack_is_dirty(pack):

kernel/bpf/core.c:bpf_prog_pack_alloc() {
    ...
		dirty_pos = find_next_bit(pack->dirty_map, pos + nbits, pos);
		if (was_classic ^ (dirty_pos < pos + nbits))
			goto found_free_area;

		if (!fallback_pack) {
			fallback_pack = pack;
			fallback_pos = pos;
		}

		/* Find clean chunks for cBPF or dirty chunks for eBPF */
		pos = bpf_pack_find_area(pack, dirty_pos, nbits, was_classic);
		if (pos < BPF_PROG_CHUNK_COUNT)
			goto found_free_area;
    ...
}

For example, alloc_new_pack() sets all bits in pack->dirty_map to 1. Once the first cBPF allocation from a new pack triggers a flush, that pack is clean (!bpf_prog_pack_is_dirty(pack)), yet its dirty_map remains all 1s until a program in that pack is freed. If an older pack earlier in pack_list has a chunk freed in the meantime (making it genuinely dirty), a subsequent cBPF allocation records the dirty older pack as fallback_pack, scans all 32,768 stale bits of the clean pack's dirty_map without finding a 0 bit, falls back to the dirty pack, and triggers an unnecessary broadcast IBPB flush. Similarly, eBPF allocations mistake stale dirty_map bits in clean packs for dirty chunks and place eBPF programs into clean packs.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#2 lore raw

Re: [PATCH bpf-next 1/3] bpf: Move bpf_arch_text_invalidate() out of pack_mutex

In reply to Xu Kuohai

Review

Quoted 5 lines · Xu Kuohai
(quoted diff) +2 -0
 	if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
 		goto out;
+	mutex_unlock(&pack_mutex);
 
+	mutex_lock(&pack_mutex);

can we invalidate before the first mutex_lock() ?
Then a free takes pack_mutex once.
Puranjay posted the same fix in that form, but it slipped through the cracks :(
https://lore.kernel.org/bpf/[email protected]/

On top of the series, core.c compiles on x86-64, but I didn't run it:

kernel/bpf/core.c +6 -12
index 1ecf398..2a21470 100644
@@ -1454,12 +1454,16 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 	unsigned int nbits;
 	unsigned long pos;
 
-	mutex_lock(&pack_mutex);
 	if (size > BPF_PROG_PACK_SIZE) {
 		bpf_jit_free_exec(ptr);
-		goto out;
+		return;
 	}
 
+	/* The caller owns the chunks until bitmap_clear() */
+	WARN_ONCE(bpf_arch_text_invalidate(ptr, size),
+		  "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n");
+
+	mutex_lock(&pack_mutex);
 	list_for_each_entry(tmp, &pack_list, list) {
 		if (ptr >= tmp->ptr && (tmp->ptr + BPF_PROG_PACK_SIZE) > ptr) {
 			pack = tmp;
@@ -1469,16 +1473,6 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 
 	if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
 		goto out;
-	mutex_unlock(&pack_mutex);
-
-	/*
-	 * The bits of this chunk are still set, so nobody can take the chunk
-	 * or free the pack, no need to hold the mutex.
-	 */
-	WARN_ONCE(bpf_arch_text_invalidate(ptr, size),
-		  "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n");
-
-	mutex_lock(&pack_mutex);
 
 	nbits = BPF_PROG_SIZE_TO_NBITS(size);
 	pos = ((unsigned long)ptr - (unsigned long)pack->ptr) >> BPF_PROG_CHUNK_SHIFT;

This fix doesn't depend on patches 2 and 3.

#10 lore raw

Re: [PATCH bpf-next 3/3] bpf: Move branch predictor flush out of pack_mutex

In reply to Xu Kuohai

Review

Quoted 8 lines · Xu Kuohai

With the flush moved out, packs can become dirty while it runs unlocked. A flush therefore cannot blindly clear dirty flags. Instead, track a global dirty and flush generation pair:

(quoted diff) +1 -1
-		if (!pack->arch_flush_needed) {
+		if (!bpf_prog_pack_is_dirty(pack)) {
 			/* Clean the stale dirty_map if the pack is clean */
 			bitmap_zero(pack->dirty_map, BPF_PROG_CHUNK_COUNT);

This is quite heavy and it takes back what patch 2 gains. One free during the flush keeps the whole dirty_map of the pack. Say pack_flush_seq is 4:

cBPF alloc free in the same pack
count = pack->dirty_seq = 5
seq = pack_dirty_seq = 5
IBPB on all CPUs is_dirty: 5 > 4, no bitmap_zero()

                                 pack->dirty_seq = 6
  pack_flush_seq = 5
                                 is_dirty: 6 > 5, no bitmap_zero()
                                 pack->dirty_seq = 7

next alloc, no clean area
count = 7, IBPB again

The wait for IPIs is preemptible, so the window can be long.

can we set dirty bits in alloc and clear them before IBPB ? cBPF allocs hold pack_flush_mutex, so they see clean bits only after IBPB. Frees and eBPF allocs don't wait for it.
No need for generations, barriers, bpf_pack_find_area(), fallback_pack. A small cBPF alloc has to wait for a flush in flight though. eBPF is back to first fit, as before commit b72e29e0f7ee.

Against bpf-next, in place of patches 2 and 3. core.c builds, not booted:

kernel/bpf/core.c +39 -39
index 3653a2e..27cf96c 100644
@@ -1186,7 +1186,8 @@ int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
 struct bpf_prog_pack {
 	struct list_head list;
 	void *ptr;
-	bool arch_flush_needed;
+	/* chunks that were in use since the last predictor flush */
+	unsigned long *dirty_map;
 	unsigned long bitmap[];
 };
 
@@ -1209,6 +1210,12 @@ DEFINE_STATIC_KEY_FALSE(bpf_pred_flush_enabled);
 static DEFINE_MUTEX(pack_mutex);
 static LIST_HEAD(pack_list);
 
+/*
+ * Held by the readers of dirty_map. The map is cleaned before the flush,
+ * so they have to wait until the flush is done. Nests outside of pack_mutex.
+ */
+static DEFINE_MUTEX(pack_flush_mutex);
+
 /* PMD_SIZE is not available in some special config, e.g. ARCH=arm with
  * CONFIG_MMU=n. Use PAGE_SIZE in these cases.
  */
@@ -1235,16 +1242,16 @@ static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_ins
 	struct bpf_prog_pack *pack;
 	int err;
 
-	pack = kzalloc_flex(*pack, bitmap, BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT));
+	pack = kzalloc_flex(*pack, bitmap, 2 * BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT));
 	if (!pack)
 		return NULL;
+	pack->dirty_map = pack->bitmap + BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT);
 	pack->ptr = bpf_jit_alloc_exec(BPF_PROG_PACK_SIZE);
 	if (!pack->ptr)
 		goto out;
 	bitmap_zero(pack->bitmap, BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE);
+	bitmap_fill(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
 
-	if (static_branch_unlikely(&bpf_pred_flush_enabled))
-		pack->arch_flush_needed = true;
 	if (!bpf_jit_mem_is_rox()) {
 		bpf_fill_ill_insns(pack->ptr, BPF_PROG_PACK_SIZE);
 		set_vm_flush_reset_perms(pack->ptr);
@@ -1264,11 +1271,16 @@ out:
 
 void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool was_classic)
 {
+	/* Flush only for cBPF as it may contain a crafted gadget */
+	bool need_clean = was_classic && static_branch_unlikely(&bpf_pred_flush_enabled);
 	unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
-	struct bpf_prog_pack *pack, *fallback_pack = NULL;
-	unsigned long pos, fallback_pos = 0;
+	struct bpf_prog_pack *pack, *p;
+	bool flush = false;
+	unsigned long pos;
 	void *ptr = NULL;
 
+	if (need_clean)
+		mutex_lock(&pack_flush_mutex);
 	mutex_lock(&pack_mutex);
 	if (size > BPF_PROG_PACK_SIZE) {
 		/*
@@ -1277,7 +1289,7 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 		 * safe because cBPF programs (the unprivileged attack surface)
 		 * are bounded well below a pack size.
 		 */
-		if (was_classic && static_branch_unlikely(&bpf_pred_flush_enabled))
+		if (need_clean)
 			pr_warn_once("BPF: Predictors not flushed for allocations greater than BPF_PROG_PACK_SIZE\n");
 		size = round_up(size, PAGE_SIZE);
 		ptr = bpf_jit_alloc_exec(size);
@@ -1295,32 +1307,20 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 		}
 		goto out;
 	}
+	if (need_clean) {
+		list_for_each_entry(pack, &pack_list, list) {
+			pos = bitmap_find_next_zero_area(pack->dirty_map, BPF_PROG_CHUNK_COUNT,
+							 0, nbits, 0);
+			if (pos < BPF_PROG_CHUNK_COUNT)
+				goto found_clean_area;
+		}
+	}
+
 	list_for_each_entry(pack, &pack_list, list) {
 		pos = bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0,
 						 nbits, 0);
-		if (pos >= BPF_PROG_CHUNK_COUNT)
-			continue;
-		/* Flush not enabled, use any pack */
-		if (!static_branch_unlikely(&bpf_pred_flush_enabled))
+		if (pos < BPF_PROG_CHUNK_COUNT)
 			goto found_free_area;
-		/*
-		 * cBPF reuse of a dirty pack triggers a flush, so prefer a
-		 * clean pack for cBPF. eBPF never flushes, so steer it to a
-		 * dirty pack and keep clean packs free for cBPF.
-		 */
-		if (was_classic ^ pack->arch_flush_needed)
-			goto found_free_area;
-		if (!fallback_pack) {
-			fallback_pack = pack;
-			fallback_pos = pos;
-		}
-	}
-
-	/* No preferred pack found */
-	if (fallback_pack) {
-		pack = fallback_pack;
-		pos = fallback_pos;
-		goto found_free_area;
 	}
 
 	pack = alloc_new_pack(bpf_fill_ill_insns);
@@ -1330,21 +1330,23 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
 	pos = 0;
 
 found_free_area:
-	/* Flush only for cBPF as it may contain a crafted gadget */
-	if (static_branch_unlikely(&bpf_pred_flush_enabled) &&
-	    pack->arch_flush_needed &&
-	    was_classic) {
-		struct bpf_prog_pack *p;
-
-		static_call_cond(bpf_arch_pred_flush)();
+	if (need_clean) {
+		/* The flush below covers all chunks that are free now */
 		list_for_each_entry(p, &pack_list, list)
-			p->arch_flush_needed = false;
+			bitmap_copy(p->dirty_map, p->bitmap, BPF_PROG_CHUNK_COUNT);
+		flush = true;
 	}
+found_clean_area:
+	bitmap_set(pack->dirty_map, pos, nbits);
 	bitmap_set(pack->bitmap, pos, nbits);
 	ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
 
 out:
 	mutex_unlock(&pack_mutex);
+	if (flush)
+		static_call_cond(bpf_arch_pred_flush)();
+	if (need_clean)
+		mutex_unlock(&pack_flush_mutex);
 	return ptr;
 }
 
@@ -1378,8 +1380,6 @@ void bpf_prog_pack_free(void *ptr, u32 size)
 
 	bitmap_clear(pack->bitmap, pos, nbits);
 
-	if (static_branch_unlikely(&bpf_pred_flush_enabled))
-		pack->arch_flush_needed = true;
 	if (bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0,
 				       BPF_PROG_CHUNK_COUNT, 0) == 0) {
 		list_del(&pack->list);

pw-bot: cr

author
#3 lore raw

Re: [PATCH bpf-next 1/3] bpf: Move bpf_arch_text_invalidate() out of pack_mutex

In reply to Alexei Starovoitov
Quoted 11 lines · Alexei Starovoitov

kernel/bpf/core.c void bpf_prog_pack_free(void *ptr, u32 size) · line 1466

Quoted 5 lines · Xu Kuohai

if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
goto out;

kernel/bpf/core.c +2 -0
+	mutex_unlock(&pack_mutex);
 
+	mutex_lock(&pack_mutex);

can we invalidate before the first mutex_lock() ?
Then a free takes pack_mutex once.
Puranjay posted the same fix in that form, but it slipped through the cracks :(
https://lore.kernel.org/bpf/[email protected]/

Yes, that's much cleaner. I will pick up Puranjay's patch in v2.

author
#6 lore raw

Re: [PATCH bpf-next 2/3] bpf: Change dirty tracking from packs to chunks

In reply to [email protected]
Quoted 60 lines · On 12/2/2026 11:55 PM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: stale dirty_map read when !arch_flush_needed in bpf_prog_pack_alloc()
--

commit 811051fe76077420fa826110b71c4df5c0c494fd
Author: Xu Kuohai <[email protected]>

bpf: Change dirty tracking from packs to chunks

This commit switches predictor dirty tracking in the BPF prog pack allocator from per-pack to per-chunk using a dirty_map bitmap on each pack.

Quoted 4 lines
kernel/bpf/core.c +0 -0
index 63bc7e7b95409..920c8cdaf2679 100644

[ ... ]

Quoted 16 lines
kernel/bpf/core.c +6 -4
@@ -1304,16 +1345,23 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
  		if (!static_branch_unlikely(&bpf_pred_flush_enabled))
  			goto found_free_area;
  		/*
-		 * cBPF reuse of a dirty pack triggers a flush, so prefer a
-		 * clean pack for cBPF. eBPF never flushes, so steer it to a
-		 * dirty pack and keep clean packs free for cBPF.
+		 * cBPF reuse of a dirty chunk triggers a flush, so prefer
+		 * clean chunks for cBPF. eBPF never flushes, so steer it to
+		 * dirty chunks and keep clean chunks free for cBPF.
  		 */
-		if (was_classic ^ pack->arch_flush_needed)
+		dirty_pos = find_next_bit(pack->dirty_map, pos + nbits, pos);
+		if (was_classic ^ (dirty_pos < pos + nbits))
  			goto found_free_area;
+

kernel/bpf/core.c void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool · line 1365

Quoted 10 lines
kernel/bpf/core.c +5 -0
  		if (!fallback_pack) {
  			fallback_pack = pack;
  			fallback_pos = pos;
  		}
+
+		/* Find clean chunks for cBPF or dirty chunks for eBPF */
+		pos = bpf_pack_find_area(pack, dirty_pos, nbits, was_classic);
+		if (pos < BPF_PROG_CHUNK_COUNT)
+			goto found_free_area;
  	}

[Severity: Medium]
Does consulting pack->dirty_map here without checking pack->arch_flush_needed misclassify clean packs that still hold stale dirty bits?

When a flush runs, it sets p->arch_flush_needed = false across pack_list without clearing p->dirty_map, deferring bitmap_zero() until the next bpf_prog_pack_free() on each pack. Until a free happens in that pack, pack->dirty_map retains stale 1 bits (including all bits set to 1 from alloc_new_pack()).

Quoted 7 lines

If an earlier pack in pack_list has only dirty free chunks and becomes fallback_pack, while a later pack has arch_flush_needed == false with stale bits in dirty_map, a cBPF allocation treats the clean pack as dirty, skips it, falls back to the dirty fallback_pack, and triggers an unnecessary bpf_arch_pred_flush(). For eBPF, the stale bits make the clean pack look dirty, steering eBPF allocations into clean packs instead of saving them for cBPF.

That is true.

Quoted 4 lines

Checking pack->arch_flush_needed before
inspecting pack->dirty_map (treating all chunks in the pack as clean when !pack->arch_flush_needed) would avoid acting on the stale bitmap.

Makes sense. I will add this check in the next version.

author
#9 lore raw

Re: [PATCH bpf-next 3/3] bpf: Move branch predictor flush out of pack_mutex

In reply to [email protected]
Quoted 88 lines · On 12/2/2026 11:57 PM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: stale dirty_map read in bpf_prog_pack_alloc() on clean packs
--

commit 34ea7e29e7698a27be8a5df803db4e9f53918487
Author: Xu Kuohai <[email protected]>

bpf: Move branch predictor flush out of pack_mutex

This commit moves branch predictor flushing out of pack_mutex by replacing pack->arch_flush_needed with pack_dirty_seq and pack_flush_seq generation counters, serializing flushes under pack_flush_mutex.

Quoted 4 lines
kernel/bpf/core.c +0 -0
index 920c8cdaf2679..1ecf39885bfb0 100644

[ ... ]

Quoted 28 lines
kernel/bpf/core.c +4 -6
@@ -1380,20 +1433,18 @@ void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool
  found_free_area:
  	/* Flush only for cBPF as it may contain a crafted gadget */
  	if (static_branch_unlikely(&bpf_pred_flush_enabled) &&
-	    pack->arch_flush_needed &&
  	    bpf_pack_chunks_are_dirty(pack, pos, nbits) &&
  	    was_classic) {
-		struct bpf_prog_pack *p;
-
-		static_call_cond(bpf_arch_pred_flush)();
-		list_for_each_entry(p, &pack_list, list)
-			p->arch_flush_needed = false;
+		flush = true;
+		count = pack->dirty_seq;
  	}
  	bitmap_set(pack->bitmap, pos, nbits);
  	ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
 
  out:
  	mutex_unlock(&pack_mutex);
+	if (flush)
+		bpf_prog_pack_flush(count);
  	return ptr;
  }
 
@@ -1435,12 +1486,12 @@ void bpf_prog_pack_free(void *ptr, u32 size)
  	bitmap_clear(pack->bitmap, pos, nbits);
 

kernel/bpf/core.c void bpf_prog_pack_free(void *ptr, u32 size) · line 1495

Quoted 10 lines
kernel/bpf/core.c +2 -2
  	if (static_branch_unlikely(&bpf_pred_flush_enabled)) {
-		if (!pack->arch_flush_needed) {
+		if (!bpf_prog_pack_is_dirty(pack)) {
  			/* Clean the stale dirty_map if the pack is clean */
  			bitmap_zero(pack->dirty_map, BPF_PROG_CHUNK_COUNT);
-			pack->arch_flush_needed = true;
  		}
  		bitmap_set(pack->dirty_map, pos, nbits);
+		pack->dirty_seq = atomic64_inc_return(&pack_dirty_seq);
  	}

[Severity: Medium]
Does bpf_prog_pack_alloc() read stale bits from pack->dirty_map when a pack has already been flushed?

bpf_prog_pack_flush() advances pack_flush_seq without clearing pack->dirty_map, and stale bits are only zeroed lazily in bpf_prog_pack_free() when a program is later freed from that pack while !bpf_prog_pack_is_dirty(pack). Until then, the pack search loop in bpf_prog_pack_alloc() inspects pack->dirty_map without checking bpf_prog_pack_is_dirty(pack):

kernel/bpf/core.c:bpf_prog_pack_alloc() {
     ...
		dirty_pos = find_next_bit(pack->dirty_map, pos + nbits, pos);
		if (was_classic ^ (dirty_pos < pos + nbits))
			goto found_free_area;

		if (!fallback_pack) {
			fallback_pack = pack;
			fallback_pos = pos;
		}

		/* Find clean chunks for cBPF or dirty chunks for eBPF */
		pos = bpf_pack_find_area(pack, dirty_pos, nbits, was_classic);
		if (pos < BPF_PROG_CHUNK_COUNT)
			goto found_free_area;
     ...
}
Quoted 11 lines

For example, alloc_new_pack() sets all bits in pack->dirty_map to 1. Once the first cBPF allocation from a new pack triggers a flush, that pack is clean (!bpf_prog_pack_is_dirty(pack)), yet its dirty_map remains all 1s until a program in that pack is freed. If an older pack earlier in pack_list has a chunk freed in the meantime (making it genuinely dirty), a subsequent cBPF allocation records the dirty older pack as fallback_pack, scans all 32,768 stale bits of the clean pack's dirty_map without finding a 0 bit, falls back to the dirty pack, and triggers an unnecessary broadcast IBPB flush. Similarly, eBPF allocations mistake stale dirty_map bits in clean packs for dirty chunks and place eBPF programs into clean packs.

This is the same issue as reported in patch 2, will fix it in v2.