[tip: x86/urgent] x86/boot: Add volatile, clobbers and zero-length test in memcmp()

From: tip-bot2 for Mauricio Faria de Oliveira

Date: Tue Jul 28 2026 - 21:37:44 EST


The following commit has been merged into the x86/urgent branch of tip:

Commit-ID: a8c171c107c0b61a5e7e10cedab0fb72aeaf640d
Gitweb: https://git.kernel.org/tip/a8c171c107c0b61a5e7e10cedab0fb72aeaf640d
Author: Mauricio Faria de Oliveira <mfo@xxxxxxxxxx>
AuthorDate: Thu, 23 Jul 2026 20:08:04 -03:00
Committer: Borislav Petkov (AMD) <bp@xxxxxxxxx>
CommitterDate: Tue, 28 Jul 2026 16:32:44 -07:00

x86/boot: Add volatile, clobbers and zero-length test in memcmp()

Add the volatile qualifier and clobbers parameter to prevent bugs with
instruction reordering and optimization.

Also add TEST for the zero-length case to set ZF, as, if the count register
is zero, the REPE prefix does not run the CMPSB instruction, leaving the ZF
flag undetermined.

[ bp: Add a comment about the len==0 case. ]

Fixes: 62bd0337d0c4 ("Top header file for new x86 setup code")
Closes: https://sashiko.dev/#/patchset/20260701-pvh-kasan-inline-v6-0-ba99045dfa9f%40igalia.com
Suggested-by: Borislav Petkov <bp@xxxxxxxxx>
Signed-off-by: Mauricio Faria de Oliveira <mfo@xxxxxxxxxx>
Signed-off-by: Borislav Petkov (AMD) <bp@xxxxxxxxx>
Link: https://lore.kernel.org/all/20260721-pvh-kasan-inline-v7-2-38979a50cef0@xxxxxxxxxx
---
arch/x86/boot/string.c | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/arch/x86/boot/string.c b/arch/x86/boot/string.c
index ac0f900..1632d40 100644
--- a/arch/x86/boot/string.c
+++ b/arch/x86/boot/string.c
@@ -32,8 +32,15 @@
int memcmp(const void *s1, const void *s2, size_t len)
{
bool diff;
- asm("repe cmpsb"
- : "=@ccnz" (diff), "+D" (s1), "+S" (s2), "+c" (len));
+
+ /*
+ * Make sure ZF is properly set in the len==0 case because in it,
+ * RCX==0 and the REPE; CMPSB won't get executed.
+ */
+ asm volatile("test %3, %3\n\t"
+ "repe cmpsb"
+ : "=@ccnz" (diff), "+D" (s1), "+S" (s2), "+c" (len)
+ : : "cc", "memory");
return diff;
}