[PATCH 2/9] x86/mm: don't set kernel_set_to_readonly when write protecting fails

From: Mike Rapoport (Microsoft)

Date: Thu Nov 12 2026 - 11:47:00 EST


mark_rodata_ro() ignores the result of write protecting the kernel text
and rodata. It can fail when CPA cannot allocate a page table to split a
large page, and then a part of the text and rodata stays writable.

kernel_set_to_readonly is set anyway, and CPA enforces the static
protections of rodata from then on. On 64-bit the next call,
set_memory_nx() for the data, may find the writable rodata and warn
about a conflict with the static protections, which does not say what
actually went wrong.

Report the failure and set kernel_set_to_readonly only when write
protecting succeeds.

Signed-off-by: Mike Rapoport (Microsoft) <rppt@xxxxxxxxxx>
---
arch/x86/mm/init_32.c | 8 ++++++--
arch/x86/mm/init_64.c | 8 ++++++--
2 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/arch/x86/mm/init_32.c b/arch/x86/mm/init_32.c
index 0908c44d51e6f..8323c1f599f25 100644
--- a/arch/x86/mm/init_32.c
+++ b/arch/x86/mm/init_32.c
@@ -741,12 +741,16 @@ void mark_rodata_ro(void)
{
unsigned long start = PFN_ALIGN(_text);
unsigned long size = (unsigned long)__end_rodata - start;
+ int err;

- set_pages_ro(virt_to_page(start), size >> PAGE_SHIFT);
+ err = set_pages_ro(virt_to_page(start), size >> PAGE_SHIFT);
pr_info("Write protecting kernel text and read-only data: %luk\n",
size >> 10);
+ if (err)
+ pr_err("Failed to write protect kernel text and read-only data: %d\n",
+ err);

- kernel_set_to_readonly = 1;
+ kernel_set_to_readonly = !err;

#ifdef CONFIG_CPA_DEBUG
pr_info("Testing CPA: Reverting %lx-%lx\n", start, start + size);
diff --git a/arch/x86/mm/init_64.c b/arch/x86/mm/init_64.c
index 8b6d86fb5a42e..a68998f359bf3 100644
--- a/arch/x86/mm/init_64.c
+++ b/arch/x86/mm/init_64.c
@@ -1365,12 +1365,16 @@ void mark_rodata_ro(void)
unsigned long text_end = PFN_ALIGN(_etext);
unsigned long rodata_end = PFN_ALIGN(__end_rodata);
unsigned long all_end;
+ int err;

printk(KERN_INFO "Write protecting the kernel read-only data: %luk\n",
(end - start) >> 10);
- set_memory_ro(start, (end - start) >> PAGE_SHIFT);
+ err = set_memory_ro(start, (end - start) >> PAGE_SHIFT);
+ if (err)
+ pr_err("Failed to write protect the kernel read-only data: %d\n",
+ err);

- kernel_set_to_readonly = 1;
+ kernel_set_to_readonly = !err;

/*
* The rodata/data/bss/brk section (but not the kernel text!)

--
2.53.0