BPF List
 help / color / mirror / Atom feed
* [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion
@ 2026-11-19  3:30 Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 1/6] bpf: Mark task work FREED before detaching it Yun Lu
                   ` (5 more replies)
  0 siblings, 6 replies; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

This series fixes a use-after-free when a BPF program schedules task
work, workqueue work or a timer through a value pointer retained across
map deletion. Review of the earlier task-work series [1] pointed out
that cancellation can leave the deleted value open to reinitialization.

The original reader keeps the element alive while it queues new work,
but the new callback can start outside the grace period that protects
the element and access the freed key or value. Patch 2 describes the
race and includes a KASAN report from an unmodified kernel.

Mark task work FREED or clear cb->map before detaching the context.
Following Alexei's suggestions [2, 3], check task-work membership after
claiming PENDING and check wq/timer membership in the shared setter.
The setter also rejects zero usercnt. An idle callback can survive in
an unlinked cached element past the last user reference and be reused
when the element is inserted again.

Patches 1-3 fix task work and add its regression test. Patches 4-6 fix
the shared wq/timer paths and cover both in the wq and rhash_timer
selftests.

Testing on x86-64 QEMU/KVM with KASAN, PROVE_LOCKING, PROVE_RCU and
DEBUG_ATOMIC_SLEEP:

- task_work_stress, wq, rhash_timer, timer and timer_mim pass.
- With the same test binary on v3, the new wq test fails as expected:
  the setter returns 0 instead of -EPERM.
- A reduced LKMM model rules out the stale usercnt result with the full
  barrier after the membership check.

Changes since v3:
- Reject zero usercnt in the shared setter (Sashiko), order the check
  after lookup with a full barrier, and add a wq regression for reuse.
- Consolidate the task-work return value documentation (bpf-ci).

v3: https://lore.kernel.org/all/20261111024333.228633-1-luyun_611@163.com/

Changes since v2:
- Use the existing map lookup and move the wq/timer check to the shared
  setter (Alexei).
- Give slot detachment to the first invalidator and reuse the existing
  task-work, wq and timer selftests.

v2: https://lore.kernel.org/all/20261106095747.471718-1-luyun_611@163.com/

Changes since v1:
- Replace slot poisoning and allocator hooks with lookup checks
  and split out cancellation ordering (Alexei).
- Extend the fix and regression coverage to wq and timers (Alexei,
  Mykyta).

v1: https://lore.kernel.org/all/20261028073525.1035605-1-luyun_611@163.com/

[1] https://lore.kernel.org/all/20261012061915.231254-1-luyun_611@163.com/
[2] https://lore.kernel.org/all/DMGN8VM2BAOR.28NRNN51MCI8I@gmail.com/
[3] https://lore.kernel.org/all/DMOAQI1S0JBS.3N3WETHD2L6KQ@gmail.com/

Yun Lu (6):
  bpf: Mark task work FREED before detaching it
  bpf: Check task work value membership before scheduling
  selftests/bpf: Test task work scheduling on a deleted value
  bpf: Invalidate async callbacks before detaching them
  bpf: Check async callback membership and user references
  selftests/bpf: Test wq callback setup after deletion and user release

 include/uapi/linux/bpf.h                      |   2 +
 kernel/bpf/helpers.c                          |  89 +++++++++++++--
 tools/include/uapi/linux/bpf.h                |   2 +
 .../selftests/bpf/prog_tests/rhash_timer.c    |  24 ++--
 .../bpf/prog_tests/task_work_stress.c         |  18 +++
 tools/testing/selftests/bpf/prog_tests/wq.c   | 103 +++++++++++++++++-
 .../testing/selftests/bpf/progs/rhash_timer.c |  26 ++---
 .../selftests/bpf/progs/task_work_stress.c    |  17 +++
 tools/testing/selftests/bpf/progs/wq.c        |  62 +++++++++++
 9 files changed, 299 insertions(+), 44 deletions(-)


base-commit: bd75869299f1d4ff6e9f45117cce28f8badee1cd
-- 
2.43.0


^ permalink raw reply	[flat|nested] 10+ messages in thread

* [PATCH bpf-next v4 1/6] bpf: Mark task work FREED before detaching it
  2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
@ 2026-11-19  3:30 ` Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 2/6] bpf: Check task work value membership before scheduling Yun Lu
                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

bpf_task_work_cancel_and_free() clears the value's context slot before
marking the context FREED. A concurrent deletion can observe the empty
slot and return while the detached context can still enter RUNNING:

  uref cleanup                 delete                  target task
  xchg(slot, NULL) gets C
                               unlink E
                               cancel sees NULL
                               return
                                                       C -> RUNNING
  xchg(C->state, FREED)

A preallocated HASH uref walk racing with deletion allows this missed
cancellation. This deletion does not itself free the element.

Mark FREED before clearing the slot. Only the first FREED transition
clears the slot and drops or transfers its map-owned context reference.
Until that canceller clears the slot, no replacement can be published,
so a plain slot store cannot overwrite a new context.

Reading the slot no longer acquires exclusive ownership of C. Protect
that access with regular RCU while another canceller can release C, and
preserve unlink-to-slot ordering with a full barrier, including when the
slot is NULL.

Fixes: 38aa7003e369 ("bpf: task work scheduling kfuncs")
Signed-off-by: Yun Lu <luyun@kylinos.cn>
---
 kernel/bpf/helpers.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 937a0d7d6839..b5674be41dab 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -5174,11 +5174,21 @@ void bpf_task_work_cancel_and_free(void *val)
 	struct bpf_task_work_ctx *ctx;
 	enum bpf_task_work_state state;
 
-	ctx = xchg(&twk->ctx, NULL);
+	/* Another canceller can release the map-owned context reference. */
+	guard(rcu)();
+	/* Order a preceding unlink before observing an empty slot. */
+	smp_mb();
+	ctx = READ_ONCE(twk->ctx);
 	if (!ctx)
 		return;
 
+	/* Prevent entry to RUNNING before clearing the slot. */
 	state = xchg(&ctx->state, BPF_TW_FREED);
+	/* Only the first FREED transition detaches ctx and owns the map's ref. */
+	if (state == BPF_TW_FREED)
+		return;
+	WRITE_ONCE(twk->ctx, NULL);
+
 	if (state == BPF_TW_SCHEDULED) {
 		/* run in irq_work to avoid locks in NMI */
 		init_irq_work(&ctx->irq_work, bpf_task_work_cancel_scheduled);
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH bpf-next v4 2/6] bpf: Check task work value membership before scheduling
  2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 1/6] bpf: Mark task work FREED before detaching it Yun Lu
@ 2026-11-19  3:30 ` Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 3/6] selftests/bpf: Test task work scheduling on a deleted value Yun Lu
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

Cancellation clears the task-work slot, but a BPF program can retain the
deleted element's value pointer and publish a new context through it.
The context reference keeps C alive, not the element at C->map_val:

  1. A BPF program looks up E and retains its value pointer.
  2. Another task deletes E, cancels its task work and clears the slot.
  3. The original reader publishes C, queues task work and leaves its
     trace read-side section.
  4. C enters RUNNING outside the grace period's waiting set for E,
     before the final destructor marks C FREED.
  5. The destructor frees E while the callback can still access it.

A controlled reproducer on the unmodified kernel reported:

  BUG: KASAN: slab-use-after-free in array_map_update_elem+0x4b8/0x7f0
  Read of size 8 at addr ffff88800e61be98 by task uaf_repro/91
  Call Trace:
   __asan_memcpy+0x23/0x60
   array_map_update_elem+0x4b8/0x7f0
   bpf_prog_976f3fa6d36fbef6_cb_probe_step+0xaf/0xe5
   bpf_prog_ac7215eae4609044_process_work_cb+0x12c/0x234
   bpf_task_work_callback+0x351/0x970
   task_work_run+0x116/0x200

  Freed by task 9:
   kfree+0x1b8/0x550
   free_all.isra.0+0x5b/0x110
   __free_rcu+0x87/0x1b0
   srcu_invoke_callbacks+0x360/0x5c0

After obtaining C and claiming PENDING, require a lookup by key to return
the same value before queueing irq_work. If deletion races with a
successful lookup, the published context is visible to cancellation.

Membership is pointer equality: a value reinserted at the same address
is treated as the current value.

Return -ENOENT on mismatch. Conditionally roll PENDING back to STANDBY to
preserve a concurrent FREED, and drop this attempt's callback reference.
Leave the idle context for normal cancellation and reclamation.

Fixes: 38aa7003e369 ("bpf: task work scheduling kfuncs")
Suggested-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Yun Lu <luyun@kylinos.cn>
---
 kernel/bpf/helpers.c | 27 +++++++++++++++++++++++++--
 1 file changed, 25 insertions(+), 2 deletions(-)

diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index b5674be41dab..468486102073 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -1151,6 +1151,14 @@ static void *map_key_from_value(struct bpf_map *map, void *value, u32 *arr_idx)
 	return (void *)value - round_up(map->key_size, 8);
 }
 
+/* Is the element that holds this value still in the map? */
+static bool bpf_map_value_is_linked(struct bpf_map *map, void *value)
+{
+	u32 idx;
+
+	return map->ops->map_lookup_elem(map, map_key_from_value(map, value, &idx)) == value;
+}
+
 enum bpf_async_type {
 	BPF_ASYNC_TYPE_TIMER = 0,
 	BPF_ASYNC_TYPE_WQ,
@@ -4859,6 +4867,19 @@ static struct bpf_task_work_ctx *bpf_task_work_acquire_ctx(struct bpf_task_work
 		return ERR_PTR(-EBUSY);
 	}
 
+	/*
+	 * The prog can still hold a value of an element that was deleted from the map.
+	 * bpf_task_work_cancel_and_free() is done with it and nothing stops a new callback
+	 * when the element is freed. The ctx is published and PENDING at this point: either
+	 * the lookup doesn't find the element or bpf_task_work_cancel_and_free() finds the ctx.
+	 * An idle ctx stays in the element until the element is reused or freed.
+	 */
+	if (!bpf_map_value_is_linked(map, (void *)tw - map->record->task_work_off)) {
+		(void)cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_STANDBY);
+		bpf_task_work_ctx_put(ctx);
+		return ERR_PTR(-ENOENT);
+	}
+
 	/*
 	 * If no process or bpffs is holding a reference to the map, no new callbacks should be
 	 * scheduled. This does not address any race or correctness issue, but rather is a policy
@@ -4927,7 +4948,9 @@ release_prog:
  * @callback: pointer to BPF subprogram to call
  * @aux: pointer to bpf_prog_aux of the caller BPF program, implicitly set by the verifier
  *
- * Return: 0 if task work has been scheduled successfully, negative error code otherwise
+ * Return: 0 if the scheduling irq_work was queued, -ENOENT if the value is
+ * no longer the current map value at the membership check, -EBUSY for a busy
+ * context or zero usercnt, or another negative error code on failure.
  */
 __bpf_kfunc int bpf_task_work_schedule_signal(struct task_struct *task, struct bpf_task_work *tw,
 					      void *map__const_map, bpf_task_work_callback_t callback,
@@ -4945,7 +4968,7 @@ __bpf_kfunc int bpf_task_work_schedule_signal(struct task_struct *task, struct b
  * @callback: pointer to BPF subprogram to call
  * @aux: pointer to bpf_prog_aux of the caller BPF program, implicitly set by the verifier
  *
- * Return: 0 if task work has been scheduled successfully, negative error code otherwise
+ * Return: See bpf_task_work_schedule_signal().
  */
 __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct bpf_task_work *tw,
 					      void *map__const_map, bpf_task_work_callback_t callback,
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH bpf-next v4 3/6] selftests/bpf: Test task work scheduling on a deleted value
  2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 1/6] bpf: Mark task work FREED before detaching it Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 2/6] bpf: Check task work value membership before scheduling Yun Lu
@ 2026-11-19  3:30 ` Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 4/6] bpf: Invalidate async callbacks before detaching them Yun Lu
                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

Add a deleted-value case to task_work_stress. A syscall program looks up
a HASH value, deletes it and schedules task work through the retained
pointer. Assert that scheduling returns -ENOENT; positive step codes
distinguish setup failures from the unfixed kernel's return value of 0.

Reuse process_work(), which only counts callbacks and does not dereference
the old key or value.

Signed-off-by: Yun Lu <luyun@kylinos.cn>
---
 .../bpf/prog_tests/task_work_stress.c          | 18 ++++++++++++++++++
 .../selftests/bpf/progs/task_work_stress.c     | 17 +++++++++++++++++
 2 files changed, 35 insertions(+)

diff --git a/tools/testing/selftests/bpf/prog_tests/task_work_stress.c b/tools/testing/selftests/bpf/prog_tests/task_work_stress.c
index 450d17d91a56..90d6d696537d 100644
--- a/tools/testing/selftests/bpf/prog_tests/task_work_stress.c
+++ b/tools/testing/selftests/bpf/prog_tests/task_work_stress.c
@@ -121,8 +121,26 @@ cleanup:
 	task_work_stress__destroy(skel);
 }
 
+static void task_work_deleted(void)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct task_work_stress *skel;
+	int err;
+
+	skel = task_work_stress__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "open_and_load"))
+		return;
+	err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.schedule_deleted_task_work),
+				     &opts);
+	if (ASSERT_OK(err, "schedule_deleted_task_work"))
+		ASSERT_EQ((int)opts.retval, -ENOENT, "deleted schedule rejected");
+	task_work_stress__destroy(skel);
+}
+
 void test_task_work_stress(void)
 {
+	if (test__start_subtest("deleted"))
+		task_work_deleted();
 	if (test__start_subtest("no_delete"))
 		task_work_run(false);
 	if (test__start_subtest("with_delete"))
diff --git a/tools/testing/selftests/bpf/progs/task_work_stress.c b/tools/testing/selftests/bpf/progs/task_work_stress.c
index 1d4378f351ef..5f47133ad308 100644
--- a/tools/testing/selftests/bpf/progs/task_work_stress.c
+++ b/tools/testing/selftests/bpf/progs/task_work_stress.c
@@ -71,3 +71,20 @@ int delete_task_work(void *ctx)
 		__sync_fetch_and_add(&delete_success, 1);
 	return 0;
 }
+
+SEC("syscall")
+int schedule_deleted_task_work(void *ctx)
+{
+	struct elem empty = {}, *value;
+	int key = 0;
+
+	if (bpf_map_update_elem(&hmap, &key, &empty, BPF_NOEXIST))
+		return 1;
+	value = bpf_map_lookup_elem(&hmap, &key);
+	if (!value)
+		return 2;
+	if (bpf_map_delete_elem(&hmap, &key))
+		return 3;
+	return bpf_task_work_schedule_signal(bpf_get_current_task_btf(),
+					     &value->tw, &hmap, process_work);
+}
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH bpf-next v4 4/6] bpf: Invalidate async callbacks before detaching them
  2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
                   ` (2 preceding siblings ...)
  2026-11-19  3:30 ` [PATCH bpf-next v4 3/6] selftests/bpf: Test task work scheduling on a deleted value Yun Lu
@ 2026-11-19  3:30 ` Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 5/6] bpf: Check async callback membership and user references Yun Lu
  2026-11-19  3:30 ` [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release Yun Lu
  5 siblings, 0 replies; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

__bpf_async_init() publishes a callback object C before checking usercnt.
On a non-preallocated HASH map, a syscall BPF program can pause after
publication while another CPU configures and queues C on the live value.
If usercnt then drops to zero, init's failure cleanup can race with uref
cleanup and deletion. The old code permits this interleaving:

  1. Init's cleanup detaches C and pauses before clearing C->map.
  2. Uref cleanup and deletion see an empty slot; deletion retires the
     element for reclamation.
  3. C's queued WQ callback enters outside the freeing GP's waiting set
     and reads a valid map, program and callback function.
  4. Init's cleanup resumes and invalidates C, but cancel_work() does not
     wait for the running callback.
  5. The element is freed while the callback can still access its value.

Invalidate C before detaching it. Use xchg() on cb->map to select the only
canceller that clears the slot and consumes the map-owned reference.
Until it clears the slot, init cannot publish a replacement, so a plain
slot store cannot overwrite a new callback object.

Protect the initial access to C with regular RCU. Order unlink before the
slot load, and acquire prior invalidation when the slot is already empty.

Fixes: 1bfbc267ec91 ("bpf: Enable bpf_timer and bpf_wq in any context")
Signed-off-by: Yun Lu <luyun@kylinos.cn>
---
 kernel/bpf/helpers.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 468486102073..fa7e514ffd19 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -1747,15 +1747,18 @@ static void bpf_async_cancel_and_free(struct bpf_async_kern *async)
 {
 	struct bpf_async_cb *cb;
 
-	if (!READ_ONCE(async->cb))
+	/* Another canceller can release the map-owned cb reference. */
+	guard(rcu)();
+	/* Order unlink before reading async->cb, including an empty slot. */
+	smp_mb();
+	/* Acquire any invalidation published before the slot was cleared. */
+	cb = smp_load_acquire(&async->cb);
+	/* Only the first invalidator detaches cb and drops the map's reference. */
+	if (!cb || !xchg(&cb->map, NULL))
 		return;
 
-	cb = xchg(&async->cb, NULL);
-	if (!cb)
-		return;
+	WRITE_ONCE(async->cb, NULL);
 
-	/* Callbacks that run after this see NULL and return. */
-	WRITE_ONCE(cb->map, NULL);
 	bpf_async_update_prog_callback(cb, NULL, NULL);
 	/*
 	 * No refcount_inc_not_zero(&cb->refcnt) here. Dropping the last
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH bpf-next v4 5/6] bpf: Check async callback membership and user references
  2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
                   ` (3 preceding siblings ...)
  2026-11-19  3:30 ` [PATCH bpf-next v4 4/6] bpf: Invalidate async callbacks before detaching them Yun Lu
@ 2026-11-19  3:30 ` Yun Lu
  2026-11-19  4:20   ` bot+bpf-ci
  2026-11-19  3:30 ` [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release Yun Lu
  5 siblings, 1 reply; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

A BPF program can retain a value pointer across deletion, initialize a
new timer or workqueue object on it, and configure and start a callback.
That callback can run outside the grace period freeing the element and
access its freed key or value. Keeping the callback object alive does not
keep the element alive.

Check membership in __bpf_async_set_callback(), which installs cb->prog
and cb->callback_fn. Order the slot load before the lookup with a full
barrier. Return -ENOENT if the object was invalidated or the lookup no
longer returns cb->value.

An idle callback object can survive in an unlinked, cached element when
the last map user reference is released. A later insertion can reuse the
element and its callback object, so membership succeeds with usercnt at
zero. If the program holds a reference to the map, installing cb->prog
would form a reference cycle. The init-time usercnt check does not cover
this reuse. Reject it with -EPERM before taking a program reference.

The first smp_mb() orders the callback slot load before the lookup.
The second provides cumulative ordering between the observed insertion
and the usercnt read. A read barrier does not provide the cumulative
ordering needed here.

Leave __bpf_async_init() unchanged. An unconfigured object cannot start a
BPF callback. Document the setter errors and adjust rhash_timer to expect
-ENOENT while retaining its recycled timer-field check.

Fixes: 1bfbc267ec91 ("bpf: Enable bpf_timer and bpf_wq in any context")
Suggested-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Yun Lu <luyun@kylinos.cn>
---
 include/uapi/linux/bpf.h                      |  2 ++
 kernel/bpf/helpers.c                          | 35 +++++++++++++++++++
 tools/include/uapi/linux/bpf.h                |  2 ++
 .../selftests/bpf/prog_tests/rhash_timer.c    | 24 +++++--------
 .../testing/selftests/bpf/progs/rhash_timer.c | 26 ++++----------
 5 files changed, 55 insertions(+), 34 deletions(-)

diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h
index 62de0919db72..0d0d56f87e09 100644
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -5478,6 +5478,8 @@ union bpf_attr {
  *	Return
  *		0 on success.
  *		**-EINVAL** if *timer* was not initialized with bpf_timer_init() earlier.
+ *		**-ENOENT** if the containing map element is no longer in the map
+ *		or the timer was invalidated by map cleanup.
  *		**-EPERM** if *timer* is in a map that doesn't have any user references.
  *		The user space should either hold a file descriptor to a map with timers
  *		or pin such map in bpffs. When map is unpinned or file descriptor is
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index fa7e514ffd19..029f60b9e3df 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -1552,11 +1552,34 @@ static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback
 				    struct bpf_prog *prog)
 {
 	struct bpf_async_cb *cb;
+	struct bpf_map *map;
 
 	cb = READ_ONCE(async->cb);
 	if (!cb)
 		return -EINVAL;
 
+	/*
+	 * The prog can still hold a value of an element that was deleted from the map.
+	 * bpf_async_cancel_and_free() is done with it and nothing stops a new callback
+	 * when the element is freed. cb is published at this point: either the lookup
+	 * doesn't find the element or bpf_async_cancel_and_free() finds cb.
+	 * Nothing runs without callback_fn. An idle cb stays in the element until the
+	 * element is reused or freed.
+	 */
+	smp_mb();
+	map = READ_ONCE(cb->map);
+	if (!map || !bpf_map_value_is_linked(map, cb->value))
+		return -ENOENT;
+	/*
+	 * Dropping the last user reference sets usercnt to zero before the cleanup walk.
+	 * The walk can miss a cached element that another CPU later reinserts. If our
+	 * lookup finds that element, the usercnt check must not see the old nonzero
+	 * count and allow a callback to be installed after cleanup.
+	 */
+	smp_mb();
+	if (!atomic64_read(&map->usercnt))
+		return -EPERM;
+
 	return bpf_async_update_prog_callback(cb, prog, callback_fn);
 }
 
@@ -3530,6 +3553,18 @@ __bpf_kfunc int bpf_wq_start(struct bpf_wq *wq, unsigned int flags)
 	}
 }
 
+/**
+ * bpf_wq_set_callback - Set the callback of a BPF workqueue
+ * @wq: pointer to the bpf_wq field
+ * @callback_fn: callback function
+ * @flags: must be zero
+ * @aux: implicit program metadata
+ *
+ * Return: 0 on success, -EINVAL for invalid flags or an uninitialized @wq,
+ * -ENOENT if the containing map element is no longer in the map or the
+ * workqueue was invalidated by map cleanup, -EPERM if the map has no user
+ * references, or another negative error.
+ */
 __bpf_kfunc int bpf_wq_set_callback(struct bpf_wq *wq,
 				    int (callback_fn)(void *map, int *key, void *value),
 				    unsigned int flags,
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 62de0919db72..0d0d56f87e09 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -5478,6 +5478,8 @@ union bpf_attr {
  *	Return
  *		0 on success.
  *		**-EINVAL** if *timer* was not initialized with bpf_timer_init() earlier.
+ *		**-ENOENT** if the containing map element is no longer in the map
+ *		or the timer was invalidated by map cleanup.
  *		**-EPERM** if *timer* is in a map that doesn't have any user references.
  *		The user space should either hold a file descriptor to a map with timers
  *		or pin such map in bpffs. When map is unpinned or file descriptor is
diff --git a/tools/testing/selftests/bpf/prog_tests/rhash_timer.c b/tools/testing/selftests/bpf/prog_tests/rhash_timer.c
index 3aad9fc02e06..87287e038a98 100644
--- a/tools/testing/selftests/bpf/prog_tests/rhash_timer.c
+++ b/tools/testing/selftests/bpf/prog_tests/rhash_timer.c
@@ -52,7 +52,7 @@ void test_rhash_timer(void)
 	LIBBPF_OPTS(bpf_test_run_opts, opts);
 	struct rhash_timer *skel = NULL;
 	cpu_set_t old_mask;
-	int map_fd = -1, arm_fd, cancel_fd;
+	int map_fd = -1, init_fd, cancel_fd;
 	bool affinity_set = false;
 	__u64 key = 1;
 	int attempt, err;
@@ -69,8 +69,8 @@ void test_rhash_timer(void)
 	map_fd = bpf_map__fd(skel->maps.timer_map);
 	if (!ASSERT_GE(map_fd, 0, "timer_map fd"))
 		goto out;
-	arm_fd = bpf_program__fd(skel->progs.arm_deleted_timer);
-	if (!ASSERT_GE(arm_fd, 0, "arm_deleted_timer fd"))
+	init_fd = bpf_program__fd(skel->progs.init_deleted_timer);
+	if (!ASSERT_GE(init_fd, 0, "init_deleted_timer fd"))
 		goto out;
 	cancel_fd = bpf_program__fd(skel->progs.cancel_recycled_timer);
 	if (!ASSERT_GE(cancel_fd, 0, "cancel_recycled_timer fd"))
@@ -81,28 +81,22 @@ void test_rhash_timer(void)
 		goto out;
 
 	for (attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
-		err = run_prog(arm_fd, &opts);
+		err = run_prog(init_fd, &opts);
 		if (err) {
-			ASSERT_OK(err, "arm_deleted_timer");
+			ASSERT_OK(err, "init_deleted_timer");
 			goto out;
 		}
-		if (skel->bss->armed != attempt + 1) {
-			ASSERT_EQ(skel->bss->armed, attempt + 1, "armed");
+		if (skel->bss->initialized != attempt + 1) {
+			ASSERT_EQ(skel->bss->initialized, attempt + 1, "initialized");
 			goto out;
 		}
 		if (skel->bss->timer_init_err) {
 			ASSERT_OK(skel->bss->timer_init_err, "timer_init_err");
 			goto out;
 		}
-		if (skel->bss->timer_set_callback_err) {
-			ASSERT_OK(skel->bss->timer_set_callback_err,
-				  "timer_set_callback_err");
+		if (!ASSERT_EQ(skel->bss->timer_set_callback_err, -ENOENT,
+			       "deleted setter rejected"))
 			goto out;
-		}
-		if (skel->bss->timer_start_err) {
-			ASSERT_OK(skel->bss->timer_start_err, "timer_start_err");
-			goto out;
-		}
 
 		if ((attempt + 1) % RCU_SYNC_INTERVAL == 0) {
 			err = kern_sync_rcu();
diff --git a/tools/testing/selftests/bpf/progs/rhash_timer.c b/tools/testing/selftests/bpf/progs/rhash_timer.c
index 2e06a463c605..49bc3602fa12 100644
--- a/tools/testing/selftests/bpf/progs/rhash_timer.c
+++ b/tools/testing/selftests/bpf/progs/rhash_timer.c
@@ -5,7 +5,6 @@
 #include <bpf/bpf_helpers.h>
 
 #define CLOCK_MONOTONIC 1
-#define TIMER_NSEC (60ULL * 1000 * 1000 * 1000)
 
 struct timer_value {
 	struct bpf_timer timer;
@@ -20,11 +19,10 @@ struct {
 	__type(value, struct timer_value);
 } timer_map SEC(".maps");
 
-u64 armed;
+u64 initialized;
 u64 cancelled;
 long timer_init_err;
 long timer_set_callback_err;
-long timer_start_err;
 long timer_cancel_err;
 
 static int timer_cb(void *map, u64 *key, struct timer_value *value)
@@ -32,8 +30,8 @@ static int timer_cb(void *map, u64 *key, struct timer_value *value)
 	return 0;
 }
 
-static long arm_timer_cb(struct bpf_map *map, u64 *key,
-			 struct timer_value *value, void *ctx)
+static long init_timer_cb(struct bpf_map *map, u64 *key,
+			  struct timer_value *value, void *ctx)
 {
 	u64 key_copy = *key;
 	long err;
@@ -48,19 +46,9 @@ static long arm_timer_cb(struct bpf_map *map, u64 *key,
 		return 1;
 	}
 
-	err = bpf_timer_set_callback(&value->timer, timer_cb);
-	if (err) {
-		timer_set_callback_err = err;
-		return 1;
-	}
-
-	err = bpf_timer_start(&value->timer, TIMER_NSEC, BPF_F_TIMER_CPU_PIN);
-	if (err) {
-		timer_start_err = err;
-		return 1;
-	}
+	timer_set_callback_err = bpf_timer_set_callback(&value->timer, timer_cb);
 
-	__sync_fetch_and_add(&armed, 1);
+	__sync_fetch_and_add(&initialized, 1);
 	return 1;
 }
 
@@ -82,9 +70,9 @@ static long cancel_timer_cb(struct bpf_map *map, u64 *key,
 }
 
 SEC("syscall")
-int arm_deleted_timer(void *ctx)
+int init_deleted_timer(void *ctx)
 {
-	bpf_for_each_map_elem(&timer_map, arm_timer_cb, NULL, 0);
+	bpf_for_each_map_elem(&timer_map, init_timer_cb, NULL, 0);
 	return 0;
 }
 
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release
  2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
                   ` (4 preceding siblings ...)
  2026-11-19  3:30 ` [PATCH bpf-next v4 5/6] bpf: Check async callback membership and user references Yun Lu
@ 2026-11-19  3:30 ` Yun Lu
  2026-11-19  3:43   ` sashiko-bot
  2026-11-19  4:05   ` bot+bpf-ci
  5 siblings, 2 replies; 10+ messages in thread
From: Yun Lu @ 2026-11-19  3:30 UTC (permalink / raw)
  To: ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf

From: Yun Lu <luyun@kylinos.cn>

Use the existing NO_PREALLOC HASH map and callback to test that
bpf_wq_set_callback() rejects a deleted value with -ENOENT.

Keep the map alive through a program fd after dropping its last user
reference. When bpf_wq_init() returns -EBUSY on a reinserted element,
the idle callback survived reuse. Check that the setter returns -EPERM.
On v3 the same test gets 0. Retry only a cache miss and report cleanup
failures separately after attempting to delete each inserted element.

Signed-off-by: Yun Lu <luyun@kylinos.cn>
---
 tools/testing/selftests/bpf/prog_tests/wq.c | 103 +++++++++++++++++++-
 tools/testing/selftests/bpf/progs/wq.c      |  62 ++++++++++++
 2 files changed, 164 insertions(+), 1 deletion(-)

diff --git a/tools/testing/selftests/bpf/prog_tests/wq.c b/tools/testing/selftests/bpf/prog_tests/wq.c
index a4f71bc34fa6..f783a91417e0 100644
--- a/tools/testing/selftests/bpf/prog_tests/wq.c
+++ b/tools/testing/selftests/bpf/prog_tests/wq.c
@@ -1,11 +1,109 @@
 // SPDX-License-Identifier: GPL-2.0
 /* Copyright (c) 2024 Benjamin Tissoires */
+#include <errno.h>
+#include <sched.h>
+#include <unistd.h>
 #include <test_progs.h>
 #include "wq.skel.h"
 #include "wq_failures.skel.h"
 
 #define CALLBACK_WAIT_RETRIES 10000
 #define CALLBACK_WAIT_US 1000
+#define WQ_USERCNT_MAX_ATTEMPTS 256
+#define WQ_USERCNT_RETRY EAGAIN
+
+static int pin_to_first_cpu(cpu_set_t *old_mask)
+{
+	cpu_set_t new_mask;
+	int cpu;
+
+	if (sched_getaffinity(0, sizeof(*old_mask), old_mask))
+		return -errno;
+
+	for (cpu = 0; cpu < CPU_SETSIZE; cpu++)
+		if (CPU_ISSET(cpu, old_mask))
+			break;
+	if (cpu == CPU_SETSIZE)
+		return -EINVAL;
+
+	CPU_ZERO(&new_mask);
+	CPU_SET(cpu, &new_mask);
+	if (sched_setaffinity(0, sizeof(new_mask), &new_mask))
+		return -errno;
+	return 0;
+}
+
+static int run_wq_prog(int prog_fd, __s32 *retval)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	int err;
+
+	err = bpf_prog_test_run_opts(prog_fd, &opts);
+	if (err)
+		return err;
+	*retval = (__s32)opts.retval;
+	return 0;
+}
+
+/* Check callback setup after reusing an idle object with no map uref. */
+static void test_wq_usercnt_reuse(void)
+{
+	struct wq *skel = NULL;
+	cpu_set_t old_mask;
+	__s32 retval = 0;
+	int stage_b_fd = -1;
+	int err, attempt;
+
+	if (!ASSERT_OK(pin_to_first_cpu(&old_mask), "pin"))
+		return;
+
+	for (attempt = 0; attempt < WQ_USERCNT_MAX_ATTEMPTS; attempt++) {
+		skel = wq__open_and_load();
+		if (!ASSERT_OK_PTR(skel, "wq__open_and_load"))
+			break;
+
+		err = run_wq_prog(bpf_program__fd(skel->progs.test_deleted_wq),
+				  &retval);
+		if (!ASSERT_OK(err, "test_deleted_wq_run") ||
+		    !ASSERT_EQ(retval, (__s32)-ENOENT, "test_deleted_wq_ret"))
+			break;
+
+		stage_b_fd = dup(bpf_program__fd(skel->progs.test_wq_usercnt_reuse));
+		if (!ASSERT_GE(stage_b_fd, 0, "dup_stage_b"))
+			break;
+
+		/* Drop all target-map user FDs; the retained program FD keeps
+		 * the map alive through used_maps, but usercnt becomes zero.
+		 */
+		wq__destroy(skel);
+		skel = NULL;
+
+		err = run_wq_prog(stage_b_fd, &retval);
+		close(stage_b_fd);
+		if (!ASSERT_OK(err, "stage_b_run"))
+			break;
+
+		if (retval == WQ_USERCNT_RETRY) {
+			/* The cached element was not reused; try again. */
+			continue;
+		}
+		if (retval > 0) {
+			ASSERT_FAIL("usercnt stage error %d", retval);
+			break;
+		}
+
+		ASSERT_EQ(retval, (__s32)-EPERM, "usercnt_setter_ret");
+		break;
+	}
+
+	if (attempt == WQ_USERCNT_MAX_ATTEMPTS)
+		ASSERT_FAIL("usercnt reuse not hit after %d attempts",
+			    WQ_USERCNT_MAX_ATTEMPTS);
+
+	if (skel)
+		wq__destroy(skel);
+	sched_setaffinity(0, sizeof(old_mask), &old_mask);
+}
 
 void serial_test_wq(void)
 {
@@ -20,7 +118,7 @@ void serial_test_wq(void)
 
 	wq_skel = wq__open_and_load();
 	if (!ASSERT_OK_PTR(wq_skel, "wq__open_and_load"))
-		return;
+		goto clean_up;
 
 	err = wq__attach(wq_skel);
 	if (!ASSERT_OK(err, "wq_attach"))
@@ -37,6 +135,9 @@ void serial_test_wq(void)
 	ASSERT_EQ(wq_skel->bss->ok_sleepable, (1 << 1), "ok_sleepable");
 clean_up:
 	wq__destroy(wq_skel);
+
+	if (test__start_subtest("usercnt_reuse"))
+		test_wq_usercnt_reuse();
 }
 
 void serial_test_failures_wq(void)
diff --git a/tools/testing/selftests/bpf/progs/wq.c b/tools/testing/selftests/bpf/progs/wq.c
index 25be2cd9d42c..1543eeb7165f 100644
--- a/tools/testing/selftests/bpf/progs/wq.c
+++ b/tools/testing/selftests/bpf/progs/wq.c
@@ -3,6 +3,7 @@
  */
 
 #include "bpf_experimental.h"
+#include <errno.h>
 #include <bpf/bpf_helpers.h>
 #include "bpf_misc.h"
 #include "../test_kmods/bpf_testmod_kfunc.h"
@@ -138,6 +139,67 @@ static int wq_cb_sleepable(void *map, int *key, void *value)
 	return 0;
 }
 
+SEC("syscall")
+__retval(-ENOENT)
+long test_deleted_wq(void *ctx)
+{
+	struct hmap_elem empty = {}, *value;
+	int key = 0;
+
+	if (bpf_map_update_elem(&hmap_malloc, &key, &empty, BPF_NOEXIST))
+		return 1;
+	value = bpf_map_lookup_elem(&hmap_malloc, &key);
+	if (!value)
+		return 2;
+	if (bpf_map_delete_elem(&hmap_malloc, &key))
+		return 3;
+	if (bpf_wq_init(&value->work, &hmap_malloc, 0))
+		return 4;
+	return bpf_wq_set_callback(&value->work, wq_callback, 0);
+}
+
+#define WQ_USERCNT_RETRY EAGAIN
+#define WQ_USERCNT_SETUP_FAIL 1
+#define WQ_USERCNT_CLEANUP_FAIL 2
+
+/*
+ * The host runs this after dropping all user references to hmap_malloc.
+ * Use positive EAGAIN for a reuse miss. Return the setter result only
+ * after deleting the inserted element.
+ */
+SEC("syscall")
+long test_wq_usercnt_reuse(void *ctx)
+{
+	struct hmap_elem empty = {}, *value;
+	long init_ret, result;
+	int key = 0;
+
+	if (bpf_map_update_elem(&hmap_malloc, &key, &empty, BPF_NOEXIST))
+		return WQ_USERCNT_SETUP_FAIL;
+
+	value = bpf_map_lookup_elem(&hmap_malloc, &key);
+	if (!value) {
+		result = WQ_USERCNT_SETUP_FAIL;
+		goto delete;
+	}
+
+	init_ret = bpf_wq_init(&value->work, &hmap_malloc, 0);
+	if (init_ret == -EBUSY) {
+		result = bpf_wq_set_callback(&value->work, wq_callback, 0);
+	} else if (init_ret == -EPERM) {
+		/* The retained idle callback was not reused. */
+		result = WQ_USERCNT_RETRY;
+	} else {
+		/* init 0 or another error is a setup failure, not a miss. */
+		result = WQ_USERCNT_SETUP_FAIL;
+	}
+
+delete:
+	if (bpf_map_delete_elem(&hmap_malloc, &key))
+		return WQ_USERCNT_CLEANUP_FAIL;
+	return result;
+}
+
 SEC("tc")
 /* test that workqueues can be used from an array */
 __retval(0)
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* Re: [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release
  2026-11-19  3:30 ` [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release Yun Lu
@ 2026-11-19  3:43   ` sashiko-bot
  2026-11-19  4:05   ` bot+bpf-ci
  1 sibling, 0 replies; 10+ messages in thread
From: sashiko-bot @ 2026-11-19  3:43 UTC (permalink / raw)
  To: Yun Lu; +Cc: bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] selftests/bpf: multi-line comment style in
  test_wq_usercnt_reuse()
--

commit c499c2c6b9f5e1ec7aa72bc0571ecd4ff2c11fb1
Author: Yun Lu <luyun@kylinos.cn>

selftests/bpf: Test wq callback setup after deletion and user release

This commit adds BPF selftests covering bpf_wq_set_callback() on deleted
hash map elements and on reused elements after the last map user reference
is dropped.

> diff --git a/tools/testing/selftests/bpf/prog_tests/wq.c b/tools/testing/selftests/bpf/prog_tests/wq.c
> index a4f71bc34fa6c..f783a91417e00 100644
> --- a/tools/testing/selftests/bpf/prog_tests/wq.c
> +++ b/tools/testing/selftests/bpf/prog_tests/wq.c
> @@ -1,11 +1,109 @@

[ ... ]

> +/* Check callback setup after reusing an idle object with no map uref. */
> +static void test_wq_usercnt_reuse(void)
> +{

[ ... ]

> +		/* Drop all target-map user FDs; the retained program FD keeps
> +		 * the map alive through used_maps, but usercnt becomes zero.
> +		 */
> +		wq__destroy(skel);

[Severity: Low]
This isn't a bug, but BPF multi-line comment style puts the opening /* on
its own line with the comment text starting on the next line.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261119033051.196177-1-luyun_611@163.com?part=6

^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release
  2026-11-19  3:30 ` [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release Yun Lu
  2026-11-19  3:43   ` sashiko-bot
@ 2026-11-19  4:05   ` bot+bpf-ci
  1 sibling, 0 replies; 10+ messages in thread
From: bot+bpf-ci @ 2026-11-19  4:05 UTC (permalink / raw)
  To: luyun_611, ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3425 bytes --]

> selftests/bpf: Test wq callback setup after deletion and user release

TL;DR: Test issue: ASSERT_FAIL() in the new wq usercnt selftest may not record
failures, so setup, cleanup or never-reused cases could pass silently. Commit
message wording is a minor nit.

> selftests/bpf: Test wq callback setup after deletion and user release
>
> Use the existing NO_PREALLOC HASH map and callback to test that
> bpf_wq_set_callback() rejects a deleted value with -ENOENT.
>
> Keep the map alive through a program fd after dropping its last user
> reference. When bpf_wq_init() returns -EBUSY on a reinserted element,
> the idle callback survived reuse. Check that the setter returns -EPERM.
> On v3 the same test gets 0. Retry only a cache miss and report cleanup
> failures separately after attempting to delete each inserted element.
>
> Signed-off-by: Yun Lu <luyun@kylinos.cn>

This isn't a bug, but could "On v3 the same test gets 0" be reworded to say
which kernel behaviour returns 0 (for example, without "bpf: Check async
callback membership and user references"), with patch-revision notes moved
below the --- line?

> diff --git a/tools/testing/selftests/bpf/prog_tests/wq.c b/tools/testing/selftests/bpf/prog_tests/wq.c
> --- a/tools/testing/selftests/bpf/prog_tests/wq.c
> +++ b/tools/testing/selftests/bpf/prog_tests/wq.c

[ ... ]

> +		if (retval == WQ_USERCNT_RETRY) {
> +			/* The cached element was not reused; try again. */
> +			continue;
> +		}
> +		if (retval > 0) {
> +			ASSERT_FAIL("usercnt stage error %d", retval);
> +			break;
> +		}

Can this ASSERT_FAIL() mark the subtest as failed?  In test_progs.h it
expands to CHECK(false, "", ...), and _CHECK() only calls test__fail() when
its condition is true:

    #define ASSERT_FAIL(fmt, args...) ({ static int duration = 0; CHECK(false, "", fmt"\n", ##args); false; })

With a false condition it takes the pass branch, so the message is not
printed and the failure is not recorded.

If the BPF program returns WQ_USERCNT_SETUP_FAIL or WQ_USERCNT_CLEANUP_FAIL
(failed update, NULL lookup, bpf_wq_init() returning 0 or -ENOMEM, failed
bpf_map_delete_elem()), the code reaches this ASSERT_FAIL() and breaks out.
Since attempt is below WQ_USERCNT_MAX_ATTEMPTS, nothing else fails and the
subtest reports OK.

> +
> +		ASSERT_EQ(retval, (__s32)-EPERM, "usercnt_setter_ret");
> +		break;
> +	}
> +
> +	if (attempt == WQ_USERCNT_MAX_ATTEMPTS)
> +		ASSERT_FAIL("usercnt reuse not hit after %d attempts",
> +			    WQ_USERCNT_MAX_ATTEMPTS);

The same applies here.  If all 256 attempts see bpf_wq_init() return
-EPERM because the cached element is never reused, the loop ends and this
ASSERT_FAIL() also passes silently.  The subtest then goes green without
ever reaching the bpf_wq_set_callback() -EPERM check it was added for.

The commit message says the test will "report cleanup failures separately",
but these failures, the setup failures and the never-reused case all end up
as a passing usercnt_reuse subtest.

Would PRINT_FAIL() (which calls test__fail() unconditionally) work here, or
checks such as ASSERT_LE(retval, 0, "usercnt_stage_error") and
ASSERT_LT(attempt, WQ_USERCNT_MAX_ATTEMPTS, "usercnt_reuse_hit")?


---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44453425101

^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH bpf-next v4 5/6] bpf: Check async callback membership and user references
  2026-11-19  3:30 ` [PATCH bpf-next v4 5/6] bpf: Check async callback membership and user references Yun Lu
@ 2026-11-19  4:20   ` bot+bpf-ci
  0 siblings, 0 replies; 10+ messages in thread
From: bot+bpf-ci @ 2026-11-19  4:20 UTC (permalink / raw)
  To: luyun_611, ast, daniel, andrii, eddyz87, memxor, martin.lau, song,
	yonghong.song, jolsa, emil, ihor.solodrai
  Cc: yatsenko, bpf, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 2250 bytes --]

> bpf: Check async callback membership and user references

TL;DR: The new membership check in __bpf_async_set_callback() may mark LRU
hash elements as referenced on every timer/wq set_callback, perturbing LRU
eviction order; a lookup that avoids marking is suggested.

> diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
> --- a/kernel/bpf/helpers.c
> +++ b/kernel/bpf/helpers.c

[ ... ]

> @@ -1552,11 +1552,34 @@ static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback
>  				    struct bpf_prog *prog)
>  {
>  	struct bpf_async_cb *cb;
> +	struct bpf_map *map;
>  
>  	cb = READ_ONCE(async->cb);
>  	if (!cb)
>  		return -EINVAL;
>  
> +	/*
[ ... ]
> +	 */
> +	smp_mb();
> +	map = READ_ONCE(cb->map);
> +	if (!map || !bpf_map_value_is_linked(map, cb->value))
> +		return -ENOENT;

bpf_map_value_is_linked() goes through the program-facing
map->ops->map_lookup_elem().  For BPF_MAP_TYPE_LRU_HASH that is
htab_lru_map_lookup_elem() -> __htab_lru_map_lookup_elem(map, key, true),
which does:

    if (l) {
        if (mark)
            bpf_lru_node_set_ref(htab_elem_lru_node(l));

Does this mean every bpf_timer_set_callback() and bpf_wq_set_callback() on an
LRU element now marks it as referenced as a side effect of the membership
check?

A timer or wq callback gets its value pointer directly from bpf_timer_cb() or
bpf_wq_work() and can re-set its callback with no lookup beforehand, for
example when alternating callbacks.  An element that only its own timer
touches would then be kept alive in the LRU, and an element used by real
traffic could be evicted in its place.

The syscall path avoids this by using htab_lru_map_lookup_elem_sys()
(mark == false) through .map_lookup_elem_sys_only, which
bpf_map_copy_value() prefers.  Could bpf_map_value_is_linked() use
map_lookup_elem_sys_only when the map provides one, so the membership probe
does not change LRU eviction order?

The same helper is also used by bpf_task_work_acquire_ctx() earlier in the
series.

[ ... ]


---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/44453425101

^ permalink raw reply	[flat|nested] 10+ messages in thread

end of thread, other threads:[~2026-11-19  4:20 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-19  3:30 [PATCH bpf-next v4 0/6] bpf: Fix async callback use-after-free on map deletion Yun Lu
2026-11-19  3:30 ` [PATCH bpf-next v4 1/6] bpf: Mark task work FREED before detaching it Yun Lu
2026-11-19  3:30 ` [PATCH bpf-next v4 2/6] bpf: Check task work value membership before scheduling Yun Lu
2026-11-19  3:30 ` [PATCH bpf-next v4 3/6] selftests/bpf: Test task work scheduling on a deleted value Yun Lu
2026-11-19  3:30 ` [PATCH bpf-next v4 4/6] bpf: Invalidate async callbacks before detaching them Yun Lu
2026-11-19  3:30 ` [PATCH bpf-next v4 5/6] bpf: Check async callback membership and user references Yun Lu
2026-11-19  4:20   ` bot+bpf-ci
2026-11-19  3:30 ` [PATCH bpf-next v4 6/6] selftests/bpf: Test wq callback setup after deletion and user release Yun Lu
2026-11-19  3:43   ` sashiko-bot
2026-11-19  4:05   ` bot+bpf-ci

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox