git: 640ddf857129 - main - libc: Enforce lock-free atomic_flag and C23-safe initialisation

From: Warner Losh <imp_at_FreeBSD.org>
Date: Sat, 20 Jun 2026 00:24:55 UTC
The branch main has been updated by imp:

URL: https://cgit.FreeBSD.org/src/commit/?id=640ddf8571291ab2965de85f67e6065a4d7efbf8

commit 640ddf8571291ab2965de85f67e6065a4d7efbf8
Author:     Faraz Vahedi <kfv@kfv.io>
AuthorDate: 2026-05-07 10:25:56 +0000
Commit:     Warner Losh <imp@FreeBSD.org>
CommitDate: 2026-06-20 00:23:29 +0000

    libc: Enforce lock-free atomic_flag and C23-safe initialisation
    
    Select the `atomic_flag` backing type according to the C standard
    requirements that `atomic_flag` operations be lock-free.
    
    C11 §7.17.1.5 defines `atomic_flag` as:
    
    > a structure type representing a lock-free, primitive atomic flag
    
    and §7.17.8.2 further requires:
    
    > Operations on an object of type atomic_flag shall be lock free
    
    Therefore:
    
    - Prefer `atomic_bool` when `ATOMIC_BOOL_LOCK_FREE == 2`
    - Fall back to `atomic_uchar` when `ATOMIC_CHAR_LOCK_FREE == 2`
    - Trigger a translation failure if neither type is lock-free
    
    Adjust `ATOMIC_FLAG_INIT` for C23 initialisation rules:
    
    - Use `{ ATOMIC_VAR_INIT(0) }` in pre-C23 modes
    - Use `{ 0 }` in C23 and later
    
    Preserve `atomic_flag_test_and_set_explicit()` semantics by
    normalising the exchanged value with `!= 0`, ensuring consistent
    boolean results regardless of whether the underlying
    representation is `atomic_bool` or `atomic_uchar`.
    
    Signed-off-by: Faraz Vahedi <kfv@kfv.io>
    Reviewed by: imp
    Pull Request: https://github.com/freebsd/freebsd-src/pull/2185
---
 sys/sys/stdatomic.h | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/sys/sys/stdatomic.h b/sys/sys/stdatomic.h
index bbdd196515e0..3e4bdd505418 100644
--- a/sys/sys/stdatomic.h
+++ b/sys/sys/stdatomic.h
@@ -377,21 +377,29 @@ __extension__ ({							\
 
 /*
  * 7.17.8 Atomic flag type and operations.
- *
- * XXX: Assume atomic_bool can be used as an atomic_flag. Is there some
- * kind of compiler built-in type we could use?
  */
 
 typedef struct {
+#if ATOMIC_BOOL_LOCK_FREE == 2
 	atomic_bool	__flag;
+#elif ATOMIC_CHAR_LOCK_FREE == 2
+	atomic_uchar	__flag;
+#else
+#error "atomic_flag is required to be lock-free"
+#endif
 } atomic_flag;
+#if __ISO_C_VISIBLE < 2023
 #define	ATOMIC_FLAG_INIT		{ ATOMIC_VAR_INIT(0) }
+#else
+#define	ATOMIC_FLAG_INIT		{ 0 }
+#endif
 
 static __inline _Bool
 atomic_flag_test_and_set_explicit(volatile atomic_flag *__object,
     memory_order __order)
 {
-	return (atomic_exchange_explicit(&__object->__flag, 1, __order));
+
+	return (atomic_exchange_explicit(&__object->__flag, 1, __order) != 0);
 }
 
 static __inline void