[PATCH] mm: optimize the implementation of WARN_ON_ONCE_GFP()

From: Xie Yuanbin

Date: Mon Mar 09 2026 - 11:44:25 EST


As shown in the commit message of commit 242b872239f6a7deacbc
("include/linux/once_lite.h: fix judgment in WARN_ONCE with clang"),
the code "unlikely(a && b)" may generate poor assembly code if it is
actually "unlikely(a) && unlikely(b)" or "unlikely(a) && b".

WARN_ON_ONCE_GFP() may be used in the hot path code:
1. The argument cond shoud be unlikely.
2. When "1." is true, !(gfp & __GFP_NOWARN) is unlikely, otherwise, a
WARN may be triggered, which is a very unlikely case.
3. When "1. && 2." is true, just like the implementation of WARN_ONCE(),
!__warned can be unlikely.

Reorder __ret_warn_once judgement to first and split out the unlikely()
in WARN_ON_ONCE_GFP() to optimize performance.

Cc: Mike Rapoport <rppt@xxxxxxxxxx>
Cc: David Laight <david.laight.linux@xxxxxxxxx>
Cc: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx>
Signed-off-by: Xie Yuanbin <qq570070308@xxxxxxxxx>
---
mm/internal.h | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/mm/internal.h b/mm/internal.h
index 6e1162e13289..49d2b7a270d3 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -93,7 +93,8 @@ struct pagetable_move_control {
static bool __section(".data..once") __warned; \
int __ret_warn_once = !!(cond); \
\
- if (unlikely(!(gfp & __GFP_NOWARN) && __ret_warn_once && !__warned)) { \
+ if (unlikely(__ret_warn_once) && \
+ unlikely(!(gfp & __GFP_NOWARN)) && unlikely(!__warned)) { \
__warned = true; \
WARN_ON(1); \
} \
--
2.53.0