Re: [PATCH] crypto: af_alg - Fix data-race in af_alg_wait_for_data() and af_alg_wait_for_wmem()
From: Herbert Xu
Date: Thu Nov 26 2026 - 23:26:33 EST
On Wed, Nov 18, 2026 at 10:48:15AM -0500, Guicai Ma wrote:
> KCSAN reported a data-race between af_alg_sendmsg() and
> af_alg_wait_for_data():
>
> BUG: KCSAN: data-race in af_alg_sendmsg / af_alg_wait_for_data
>
> write to 0xffff8eec18118fa4 of 1 bytes by task 17152 on cpu 17:
> af_alg_sendmsg+0x1c7/0xfa0 crypto/af_alg.c:949
> skcipher_sendmsg+0x78/0x90 crypto/algif_skcipher.c:47
> ...
>
> read to 0xffff8eec18118fa4 of 1 bytes by task 17143 on cpu 1:
> af_alg_wait_for_data+0x1f9/0x3c0 crypto/af_alg.c:854
> _skcipher_recvmsg+0x52f/0x720 crypto/algif_skcipher.c:65
> ...
>
> value changed: 0x13 -> 0x1b
>
> Both af_alg_wait_for_data() and af_alg_wait_for_wmem() are called with
> the socket lock held and use sk_wait_event() to wait for the condition.
> However, sk_wait_event() calls release_sock() before evaluating the
> condition expression for the first time, which reads ctx->init,
> ctx->more, and ctx->used without the socket lock. Meanwhile,
> af_alg_sendmsg() acquires the socket lock and modifies ctx->write (which
> shares the same 1-byte bitfield as ctx->more and ctx->init), as well as
> ctx->init, ctx->more, and ctx->used.
>
> Unlike TCP/UDP sockets, af_alg updates these context fields only in
> process context under lock_sock(sk). Since add_wait_queue() with
> woken_wake_function is already done while holding the socket lock, check
> the wait condition under lock_sock(sk) before calling release_sock(sk)
> and wait_woken(), avoiding the lockless read entirely.
>
> Fixes: 2d97591ef43d ("crypto: af_alg - consolidation of duplicate code")
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Guicai Ma <maguicai@xxxxxxxxxx>
> ---
> Testing:
> Verified with a concurrent AF_ALG skcipher (ecb(aes)) send/recv stress
> test under CONFIG_KCSAN=y (QEMU arm64, 8 vCPUs, 60s per run, ~470k rounds):
> - Baseline (6.6.156): 51 af_alg KCSAN data-race reports (both the 1-byte
> bitfield race and the 8-byte ctx->used race).
> - Patched (6.6.156, 2 runs): 0 af_alg KCSAN reports; roundtrip
> functional check passed and unrelated KCSAN reports remained active.
> - Upstream (20eef29b7c84, arm64 defconfig + KCSAN): compile-tested
> crypto/af_alg.o, crypto/algif_skcipher.o, and crypto/algif_aead.o
> with W=1 cleanly (0 warnings/errors).
>
> crypto/af_alg.c | 22 ++++++++++++----------
> 1 file changed, 12 insertions(+), 10 deletions(-)
This looks like a false-positive because sk_wait_event evaluates
__condition twice, once without locks before the wait and once with
locks.
It's the evaluation within locks that is final so everything should
be correct.
Thanks,
--
Email: Herbert Xu <herbert@xxxxxxxxxxxxxxxxxxx>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt