Skip to contentSkip to conversation

mm/rodata_test: Use READ_ONCE() to read const variable

PATCH Superseded Petr Tesarik 1 participant 2 messages Nov 19, 2024

Subsystems (2)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 mm/rodata_test: Use READ_ONCE() to read const variable

The C compiler may optimize away the memory read of a const variable if its value is known at compile time.

In particular, GCC14 with -O2 generates no code at all for test 1, and it generates the following x86_64 instructions for test 3:

	cmpl	$195, 4(%rsp)
	je	.L14

That is, it replaces the read of rodata_test_data with an immediate value and compares it to the value of the local variable "zero".

Use READ_ONCE() to undo any such compiler optimizations and enforce a memory read.

Fixes 2959a5f726f6 ("mm: add arch-independent testcases for RODATA")
---
 mm/rodata_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/rodata_test.c +2 -2
index 6d783436951f..3b60425d80fe 100644
@@ -20,7 +20,7 @@ void rodata_test(void)
 
 	/* test 1: read the value */
 	/* If this test fails, some previous testrun has clobbered the state */
-	if (!rodata_test_data) {
+	if (!READ_ONCE(rodata_test_data)) {
 		pr_err("test 1 fails (start data)\n");
 		return;
 	}
@@ -33,7 +33,7 @@ void rodata_test(void)
 	}
 
 	/* test 3: check the value hasn't changed */
-	if (rodata_test_data == zero) {
+	if (READ_ONCE(rodata_test_data) == zero) {
 		pr_err("test data was changed\n");
 		return;
 	}
Signature · 1 line
2.46.1
#1 lore raw

Oops, this should have been a two-patch series. Will resend in a minute. Sorry.

Petr T

Quoted 43 lines · On Tue, 19 Nov 2024 12:20:09 +0100 Petr Tesarik <[email protected]> wrote:

The C compiler may optimize away the memory read of a const variable if its value is known at compile time.

In particular, GCC14 with -O2 generates no code at all for test 1, and it generates the following x86_64 instructions for test 3:

	cmpl	$195, 4(%rsp)
	je	.L14

That is, it replaces the read of rodata_test_data with an immediate value and compares it to the value of the local variable "zero".

Use READ_ONCE() to undo any such compiler optimizations and enforce a memory read.

Fixes 2959a5f726f6 ("mm: add arch-independent testcases for RODATA")
---
 mm/rodata_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/rodata_test.c +2 -2
index 6d783436951f..3b60425d80fe 100644
@@ -20,7 +20,7 @@ void rodata_test(void)
 
 	/* test 1: read the value */
 	/* If this test fails, some previous testrun has clobbered the state */
-	if (!rodata_test_data) {
+	if (!READ_ONCE(rodata_test_data)) {
 		pr_err("test 1 fails (start data)\n");
 		return;
 	}
@@ -33,7 +33,7 @@ void rodata_test(void)
 	}
 
 	/* test 3: check the value hasn't changed */
-	if (rodata_test_data == zero) {
+	if (READ_ONCE(rodata_test_data) == zero) {
 		pr_err("test data was changed\n");
 		return;
 	}