From: Yun Lu __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 --- 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 a08b2af56ee6..716be7a852b5 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