Skip to contentSkip to conversation

x86/module: rework ROX cache to avoid writable copy

PATCH Superseded Mike Rapoport 12 participants 23 messages Dec 27, 2024 – Jan 14, 2025

Subsystems (15)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Mike Rapoport

author maintainer
#0 lore raw

cover x86/module: rework ROX cache to avoid writable copy

From: "Mike Rapoport (Microsoft)" <[email protected]>

Hi,

Following Peter's comments [1] these patches rework handling of ROX caches for module text allocations.

Instead of using a writable copy that really complicates alternatives patching, temporarily remap parts of a large ROX page as RW for the time of module formation and then restore it's ROX protections when the module is ready.

To keep the ROX memory mapped with large pages, make set_memory code capable of restoring large pages (more details are in patch 3).

The patches also available in git
https://git.kernel.org/rppt/h/execmem/x86-rox/v8

[1] https://lore.kernel.org/all/[email protected]

Kirill A. Shutemov (1):
x86/mm/pat: Restore large pages after fragmentation

Mike Rapoport (Microsoft) (7):
x86/mm/pat: cpa-test: fix length for CPA_ARRAY test x86/mm/pat: drop duplicate variable in cpa_flush()
execmem: add API for temporal remapping as RW and restoring ROX
afterwards
module: introduce MODULE_STATE_GONE
modules: switch to execmem API for remapping as RW and restoring ROX Revert "x86/module: prepare module loading for ROX allocations of
text"
module: drop unused module_writable_address()

 arch/um/kernel/um_arch.c                      |  11 +-
 arch/x86/entry/vdso/vma.c                     |   3 +-
 arch/x86/include/asm/alternative.h            |  14 +-
 arch/x86/include/asm/pgtable_types.h          |   2 +
 arch/x86/kernel/alternative.c                 | 181 ++++++---------
 arch/x86/kernel/ftrace.c                      |  30 ++-
 arch/x86/kernel/module.c                      |  45 ++--
 arch/x86/mm/pat/cpa-test.c                    |   2 +-
 arch/x86/mm/pat/set_memory.c                  | 216 +++++++++++++++++-
 include/linux/execmem.h                       |  31 +++
 include/linux/module.h                        |  21 +-
 include/linux/moduleloader.h                  |   4 -
 include/linux/vm_event_item.h                 |   2 +
 kernel/module/kallsyms.c                      |   8 +-
 kernel/module/kdb.c                           |   2 +-
 kernel/module/main.c                          |  86 ++-----
 kernel/module/procfs.c                        |   2 +-
 kernel/module/strict_rwx.c                    |   9 +-
 kernel/tracepoint.c                           |   2 +
 lib/kunit/test.c                              |   2 +
 mm/execmem.c                                  | 118 ++++++++--
 mm/vmstat.c                                   |   2 +
 samples/livepatch/livepatch-callbacks-demo.c  |   1 +
 .../test_modules/test_klp_callbacks_demo.c    |   1 +
 .../test_modules/test_klp_callbacks_demo2.c   |   1 +
 .../livepatch/test_modules/test_klp_state.c   |   1 +
 .../livepatch/test_modules/test_klp_state2.c  |   1 +
 27 files changed, 511 insertions(+), 287 deletions(-)
Signature · 1 line
2.45.2
author maintainer
#1 lore raw

PATCH 1/8 x86/mm/pat: cpa-test: fix length for CPA_ARRAY test

From: "Mike Rapoport (Microsoft)" <[email protected]>

The CPA_ARRAY test always uses len[1] as numpages argument to change_page_attr_set() although the addresses array is different each iteration of the test loop.

Replace len[1] with len[i] to have numpages matching the addresses array.

Fixes ecc729f1f471 ("x86/mm/cpa: Add ARRAY and PAGES_ARRAY selftests")
---
 arch/x86/mm/pat/cpa-test.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/mm/pat/cpa-test.c +1 -1
index 3d2f7f0a6ed1..ad3c1feec990 100644
@@ -183,7 +183,7 @@ static int pageattr_test(void)
 			break;
 
 		case 1:
-			err = change_page_attr_set(addrs, len[1], PAGE_CPA_TEST, 1);
+			err = change_page_attr_set(addrs, len[i], PAGE_CPA_TEST, 1);
 			break;
 
 		case 2:
Signature · 1 line
2.45.2
author maintainer
#3 lore raw

PATCH 2/8 x86/mm/pat: drop duplicate variable in cpa_flush()

In reply to Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

There is a 'struct cpa_data *data' parameter in cpa_flush() that is assigned to a local 'struct cpa_data *cpa' variable.

Rename the parameter from 'data' to 'cpa' and drop declaration of the local 'cpa' variable.

---
 arch/x86/mm/pat/set_memory.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
arch/x86/mm/pat/set_memory.c +1 -2
index 95bc50a8541c..d43b919b11ae 100644
@@ -396,9 +396,8 @@ static void __cpa_flush_tlb(void *data)
 		flush_tlb_one_kernel(fix_addr(__cpa_addr(cpa, i)));
 }
 
-static void cpa_flush(struct cpa_data *data, int cache)
+static void cpa_flush(struct cpa_data *cpa, int cache)
 {
-	struct cpa_data *cpa = data;
 	unsigned int i;
 
 	BUG_ON(irqs_disabled() && !early_boot_irqs_disabled);
Signature · 1 line
2.45.2
author maintainer
#4 lore raw

PATCH 3/8 x86/mm/pat: Restore large pages after fragmentation

In reply to Mike Rapoport

From: "Kirill A. Shutemov" <[email protected]>

Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result.

With current code it's one way road: kernel tries to avoid splitting large pages, but it doesn't restore them back even if page attributes got compatible again.

Any change to the mapping may potentially allow to restore large page.

Hook up into cpa_flush() path to check if there's any pages to be recovered in PUD_SIZE range around pages we've just touched.

CPUs don't like[1] to have to have TLB entries of different size for the same memory, but looks like it's okay as long as these entries have matching attributes[2]. Therefore it's critical to flush TLB before any following changes to the mapping.

Note that we already allow for multiple TLB entries of different sizes for the same memory now in split_large_page() path. It's not a new situation.

set_memory_4k() provides a way to use 4k pages on purpose. Kernel must not remap such pages as large. Re-use one of software PTE bits to indicate such pages.

[1] See Erratum 383 of AMD Family 10h Processors
[2] https://lore.kernel.org/linux-mm/[email protected]/

[[email protected]:
* s/restore/collapse/
* update formatting per peterz
* use 'struct ptdesc' instead of 'struct page' for list of page tables to be freed
* try to collapse PMD first and if it succeeds move on to PUD as peterz suggested
* flush TLB twice: for changes done in the original CPA call and after collapsing of large pages
]

---
 arch/x86/include/asm/pgtable_types.h |   2 +
 arch/x86/mm/pat/set_memory.c         | 213 ++++++++++++++++++++++++++-
 include/linux/vm_event_item.h        |   2 +
 mm/vmstat.c                          |   2 +
 4 files changed, 216 insertions(+), 3 deletions(-)
arch/x86/include/asm/pgtable_types.h +2 -0
index 4b804531b03c..c90e9c51edb7 100644
@@ -33,6 +33,7 @@
 #define _PAGE_BIT_CPA_TEST	_PAGE_BIT_SOFTW1
 #define _PAGE_BIT_UFFD_WP	_PAGE_BIT_SOFTW2 /* userfaultfd wrprotected */
 #define _PAGE_BIT_SOFT_DIRTY	_PAGE_BIT_SOFTW3 /* software dirty tracking */
+#define _PAGE_BIT_KERNEL_4K	_PAGE_BIT_SOFTW3 /* page must not be converted to large */
 #define _PAGE_BIT_DEVMAP	_PAGE_BIT_SOFTW4
 
 #ifdef CONFIG_X86_64
@@ -64,6 +65,7 @@
 #define _PAGE_PAT_LARGE (_AT(pteval_t, 1) << _PAGE_BIT_PAT_LARGE)
 #define _PAGE_SPECIAL	(_AT(pteval_t, 1) << _PAGE_BIT_SPECIAL)
 #define _PAGE_CPA_TEST	(_AT(pteval_t, 1) << _PAGE_BIT_CPA_TEST)
+#define _PAGE_KERNEL_4K	(_AT(pteval_t, 1) << _PAGE_BIT_KERNEL_4K)
 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
 #define _PAGE_PKEY_BIT0	(_AT(pteval_t, 1) << _PAGE_BIT_PKEY_BIT0)
 #define _PAGE_PKEY_BIT1	(_AT(pteval_t, 1) << _PAGE_BIT_PKEY_BIT1)
arch/x86/mm/pat/set_memory.c +210 -3

263 lines not on this page · raw message

include/linux/vm_event_item.h +2 -0
index f70d0958095c..5a37cb2b6f93 100644
@@ -151,6 +151,8 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,
 #ifdef CONFIG_X86
 		DIRECT_MAP_LEVEL2_SPLIT,
 		DIRECT_MAP_LEVEL3_SPLIT,
+		DIRECT_MAP_LEVEL2_COLLAPSE,
+		DIRECT_MAP_LEVEL3_COLLAPSE,
 #endif
 #ifdef CONFIG_PER_VMA_LOCK_STATS
 		VMA_LOCK_SUCCESS,
mm/vmstat.c +2 -0
index 4d016314a56c..d5e1d7f34f3c 100644
@@ -1435,6 +1435,8 @@ const char * const vmstat_text[] = {
 #ifdef CONFIG_X86
 	"direct_map_level2_splits",
 	"direct_map_level3_splits",
+	"direct_map_level2_collapses",
+	"direct_map_level3_collapses",
 #endif
 #ifdef CONFIG_PER_VMA_LOCK_STATS
 	"vma_lock_success",
Signature · 1 line
2.45.2
author maintainer
#10 lore raw

PATCH 4/8 execmem: add API for temporal remapping as RW and restoring ROX afterwards

In reply to Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

Using a writable copy for ROX memory is cumbersome and error prone.

Add API that allow temporarily remapping of ranges in the ROX cache as writable and then restoring their read-only-execute permissions.

This API will be later used in modules code and will allow removing nasty games with writable copy in alternatives patching on x86.

The restoring of the ROX permissions relies on the ability of architecture to reconstruct large pages in its set_memory_rox() method.

---
 include/linux/execmem.h |  31 +++++++++++
 mm/execmem.c            | 118 +++++++++++++++++++++++++++++++++-------
 2 files changed, 130 insertions(+), 19 deletions(-)
include/linux/execmem.h +31 -0
index 64130ae19690..65655a5d1be2 100644
@@ -65,6 +65,37 @@ enum execmem_range_flags {
  * Architectures that use EXECMEM_ROX_CACHE must implement this.
  */
 void execmem_fill_trapping_insns(void *ptr, size_t size, bool writable);
+
+/**
+ * execmem_make_temp_rw - temporarily remap region with read-write
+ *			  permissions
+ * @ptr:	address of the region to remap
+ * @size:	size of the region to remap
+ *
+ * Remaps a part of the cached large page in the ROX cache in the range
+ * [@ptr, @ptr + @size) as writable and not executable. The caller must
+ * have exclusive ownership of this range and ensure nothing will try to
+ * execute code in this range.
+ *
+ * Return: 0 on success or negative error code on failure.
+ */
+int execmem_make_temp_rw(void *ptr, size_t size);
+
+/**
+ * execmem_restore_rox - restore read-only-execute permissions
+ * @ptr:	address of the region to remap
+ * @size:	size of the region to remap
+ *
+ * Restores read-only-execute permissions on a range [@ptr, @ptr + @size)
+ * after it was temporarily remapped as writable. Relies on architecture
+ * implementation of set_memory_rox() to restore mapping using large pages.
+ *
+ * Return: 0 on success or negative error code on failure.
+ */
+int execmem_restore_rox(void *ptr, size_t size);
+#else
+static inline int execmem_make_temp_rw(void *ptr, size_t size) { return 0; }
+static inline int execmem_restore_rox(void *ptr, size_t size) { return 0; }
 #endif
 
 /**
mm/execmem.c +99 -19

235 lines not on this page · raw message

Signature · 1 line
2.45.2
author maintainer
#11 lore raw

PATCH 5/8 module: introduce MODULE_STATE_GONE

In reply to Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

In order to use execmem's API for temporal remapping of the memory allocated from ROX cache as writable, there is a need to distinguish between the state when the module is being formed and the state when it is deconstructed and freed so that when module_memory_free() is called from error paths during module loading it could restore ROX mappings.

Replace open coded checks for MODULE_STATE_UNFORMED with a helper function module_is_formed() and add a new MODULE_STATE_GONE that will be set when the module is deconstructed and freed.

---
 include/linux/module.h                        |  6 ++++++
 kernel/module/kallsyms.c                      |  8 ++++----
 kernel/module/kdb.c                           |  2 +-
 kernel/module/main.c                          | 19 +++++++++----------
 kernel/module/procfs.c                        |  2 +-
 kernel/tracepoint.c                           |  2 ++
 lib/kunit/test.c                              |  2 ++
 samples/livepatch/livepatch-callbacks-demo.c  |  1 +
 .../test_modules/test_klp_callbacks_demo.c    |  1 +
 .../test_modules/test_klp_callbacks_demo2.c   |  1 +
 .../livepatch/test_modules/test_klp_state.c   |  1 +
 .../livepatch/test_modules/test_klp_state2.c  |  1 +
 12 files changed, 30 insertions(+), 16 deletions(-)
include/linux/module.h +6 -0
index 94acbacdcdf1..bd8cf93d32c8 100644
@@ -320,6 +320,7 @@ enum module_state {
 	MODULE_STATE_COMING,	/* Full formed, running module_init. */
 	MODULE_STATE_GOING,	/* Going away. */
 	MODULE_STATE_UNFORMED,	/* Still setting it up. */
+	MODULE_STATE_GONE,	/* Deconstructing and freeing. */
 };
 
 struct mod_tree_node {
@@ -620,6 +621,11 @@ static inline bool module_is_coming(struct module *mod)
         return mod->state == MODULE_STATE_COMING;
 }
 
+static inline bool module_is_formed(struct module *mod)
+{
+	return mod->state < MODULE_STATE_UNFORMED;
+}
+
 struct module *__module_text_address(unsigned long addr);
 struct module *__module_address(unsigned long addr);
 bool is_module_address(unsigned long addr);
kernel/module/kallsyms.c +4 -4
index bf65e0c3c86f..daf9a9b3740f 100644
@@ -361,7 +361,7 @@ int lookup_module_symbol_name(unsigned long addr, char *symname)
 
 	preempt_disable();
 	list_for_each_entry_rcu(mod, &modules, list) {
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 		if (within_module(addr, mod)) {
 			const char *sym;
@@ -389,7 +389,7 @@ int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
 	list_for_each_entry_rcu(mod, &modules, list) {
 		struct mod_kallsyms *kallsyms;
 
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 		kallsyms = rcu_dereference_sched(mod->kallsyms);
 		if (symnum < kallsyms->num_symtab) {
@@ -441,7 +441,7 @@ static unsigned long __module_kallsyms_lookup_name(const char *name)
 	list_for_each_entry_rcu(mod, &modules, list) {
 		unsigned long ret;
 
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 		ret = __find_kallsyms_symbol_value(mod, name);
 		if (ret)
@@ -484,7 +484,7 @@ int module_kallsyms_on_each_symbol(const char *modname,
 	list_for_each_entry(mod, &modules, list) {
 		struct mod_kallsyms *kallsyms;
 
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 
 		if (modname && strcmp(modname, mod->name))
kernel/module/kdb.c +1 -1
index 995c32d3698f..14f14700ffc2 100644
@@ -23,7 +23,7 @@ int kdb_lsmod(int argc, const char **argv)
 
 	kdb_printf("Module                  Size  modstruct     Used by\n");
 	list_for_each_entry(mod, &modules, list) {
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 
 		kdb_printf("%-20s%8u", mod->name, mod->mem[MOD_TEXT].size);
kernel/module/main.c +9 -10
index 5399c182b3cb..ad8ef20c120f 100644
@@ -153,7 +153,7 @@ EXPORT_SYMBOL(unregister_module_notifier);
  */
 static inline int strong_try_module_get(struct module *mod)
 {
-	BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
+	BUG_ON(mod && !module_is_formed(mod));
 	if (mod && mod->state == MODULE_STATE_COMING)
 		return -EBUSY;
 	if (try_module_get(mod))
@@ -361,7 +361,7 @@ bool find_symbol(struct find_symbol_arg *fsa)
 			  GPL_ONLY },
 		};
 
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 
 		for (i = 0; i < ARRAY_SIZE(arr); i++)
@@ -386,7 +386,7 @@ struct module *find_module_all(const char *name, size_t len,
 
 	list_for_each_entry_rcu(mod, &modules, list,
 				lockdep_is_held(&module_mutex)) {
-		if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
+		if (!even_unformed && !module_is_formed(mod))
 			continue;
 		if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
 			return mod;
@@ -457,7 +457,7 @@ bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
 	preempt_disable();
 
 	list_for_each_entry_rcu(mod, &modules, list) {
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 		if (!mod->percpu_size)
 			continue;
@@ -1326,7 +1326,7 @@ static void free_module(struct module *mod)
 	 * that noone uses it while it's being deconstructed.
 	 */
 	mutex_lock(&module_mutex);
-	mod->state = MODULE_STATE_UNFORMED;
+	mod->state = MODULE_STATE_GONE;
 	mutex_unlock(&module_mutex);
 
 	/* Arch-specific cleanup. */
@@ -3048,8 +3048,7 @@ static int module_patient_check_exists(const char *name,
 	if (old == NULL)
 		return 0;
 
-	if (old->state == MODULE_STATE_COMING ||
-	    old->state == MODULE_STATE_UNFORMED) {
+	if (old->state == MODULE_STATE_COMING || !module_is_formed(old)) {
 		/* Wait in case it fails to load. */
 		mutex_unlock(&module_mutex);
 		err = wait_event_interruptible(module_wq,
@@ -3608,7 +3607,7 @@ char *module_flags(struct module *mod, char *buf, bool show_state)
 {
 	int bx = 0;
 
-	BUG_ON(mod->state == MODULE_STATE_UNFORMED);
+	BUG_ON(!module_is_formed(mod));
 	if (!mod->taints && !show_state)
 		goto out;
 	if (mod->taints ||
@@ -3702,7 +3701,7 @@ struct module *__module_address(unsigned long addr)
 	mod = mod_find(addr, &mod_tree);
 	if (mod) {
 		BUG_ON(!within_module(addr, mod));
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			mod = NULL;
 	}
 	return mod;
@@ -3756,7 +3755,7 @@ void print_modules(void)
 	/* Most callers should already have preempt disabled, but make sure */
 	preempt_disable();
 	list_for_each_entry_rcu(mod, &modules, list) {
-		if (mod->state == MODULE_STATE_UNFORMED)
+		if (!module_is_formed(mod))
 			continue;
 		pr_cont(" %s%s", mod->name, module_flags(mod, buf, true));
 	}
kernel/module/procfs.c +1 -1
index 0a4841e88adb..2c617e6f8bc0 100644
@@ -79,7 +79,7 @@ static int m_show(struct seq_file *m, void *p)
 	unsigned int size;
 
 	/* We always ignore unformed modules. */
-	if (mod->state == MODULE_STATE_UNFORMED)
+	if (!module_is_formed(mod))
 		return 0;
 
 	size = module_total_size(mod);
kernel/tracepoint.c +2 -0
index 1848ce7e2976..e94247afb2c6 100644
@@ -668,6 +668,8 @@ static int tracepoint_module_notify(struct notifier_block *self,
 		break;
 	case MODULE_STATE_UNFORMED:
 		break;
+	case MODULE_STATE_GONE:
+		break;
 	}
 	return notifier_from_errno(ret);
 }
lib/kunit/test.c +2 -0
index 089c832e3cdb..54eaed92a2d3 100644
@@ -836,6 +836,8 @@ static int kunit_module_notify(struct notifier_block *nb, unsigned long val,
 		break;
 	case MODULE_STATE_UNFORMED:
 		break;
+	case MODULE_STATE_GONE:
+		break;
 	}
 
 	return 0;
samples/livepatch/livepatch-callbacks-demo.c +1 -0
index 11c3f4357812..324bddaef9a6 100644
@@ -93,6 +93,7 @@ static const char *const module_state[] = {
 	[MODULE_STATE_COMING]	= "[MODULE_STATE_COMING] Full formed, running module_init",
 	[MODULE_STATE_GOING]	= "[MODULE_STATE_GOING] Going away",
 	[MODULE_STATE_UNFORMED]	= "[MODULE_STATE_UNFORMED] Still setting it up",
+	[MODULE_STATE_GONE]	= "[MODULE_STATE_GONE] Deconstructing and freeing",
 };
 
 static void callback_info(const char *callback, struct klp_object *obj)
tools/testing/selftests/livepatch/test_modules/test_klp_callbacks_demo.c +1 -0
index 3fd8fe1cd1cc..8435e3254f85 100644
@@ -16,6 +16,7 @@ static const char *const module_state[] = {
 	[MODULE_STATE_COMING]	= "[MODULE_STATE_COMING] Full formed, running module_init",
 	[MODULE_STATE_GOING]	= "[MODULE_STATE_GOING] Going away",
 	[MODULE_STATE_UNFORMED]	= "[MODULE_STATE_UNFORMED] Still setting it up",
+	[MODULE_STATE_GONE]	= "[MODULE_STATE_GONE] Deconstructing and freeing",
 };
 
 static void callback_info(const char *callback, struct klp_object *obj)
tools/testing/selftests/livepatch/test_modules/test_klp_callbacks_demo2.c +1 -0
index 5417573e80af..78c1fff5d977 100644
@@ -16,6 +16,7 @@ static const char *const module_state[] = {
 	[MODULE_STATE_COMING]	= "[MODULE_STATE_COMING] Full formed, running module_init",
 	[MODULE_STATE_GOING]	= "[MODULE_STATE_GOING] Going away",
 	[MODULE_STATE_UNFORMED]	= "[MODULE_STATE_UNFORMED] Still setting it up",
+	[MODULE_STATE_GONE]	= "[MODULE_STATE_GONE] Deconstructing and freeing",
 };
 
 static void callback_info(const char *callback, struct klp_object *obj)
tools/testing/selftests/livepatch/test_modules/test_klp_state.c +1 -0
index 57a4253acb01..bdebf1d24c98 100644
@@ -18,6 +18,7 @@ static const char *const module_state[] = {
 	[MODULE_STATE_COMING]	= "[MODULE_STATE_COMING] Full formed, running module_init",
 	[MODULE_STATE_GOING]	= "[MODULE_STATE_GOING] Going away",
 	[MODULE_STATE_UNFORMED]	= "[MODULE_STATE_UNFORMED] Still setting it up",
+	[MODULE_STATE_GONE]	= "[MODULE_STATE_GONE] Deconstructing and freeing",
 };
 
 static void callback_info(const char *callback, struct klp_object *obj)
tools/testing/selftests/livepatch/test_modules/test_klp_state2.c +1 -0
index c978ea4d5e67..1a55f84a8eb3 100644
@@ -18,6 +18,7 @@ static const char *const module_state[] = {
 	[MODULE_STATE_COMING]	= "[MODULE_STATE_COMING] Full formed, running module_init",
 	[MODULE_STATE_GOING]	= "[MODULE_STATE_GOING] Going away",
 	[MODULE_STATE_UNFORMED]	= "[MODULE_STATE_UNFORMED] Still setting it up",
+	[MODULE_STATE_GONE]	= "[MODULE_STATE_GONE] Deconstructing and freeing",
 };
 
 static void callback_info(const char *callback, struct klp_object *obj)
Signature · 1 line
2.45.2
author maintainer
#13 lore raw

PATCH 6/8 modules: switch to execmem API for remapping as RW and restoring ROX

In reply to Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

Instead of using writable copy for module text sections, temporarily remap the memory allocated from execmem's ROX cache as writable and restore its ROX permissions after the module is formed.

This will allow removing nasty games with writable copy in alternatives patching on x86.

---
 include/linux/module.h       |  7 +---
 include/linux/moduleloader.h |  4 ---
 kernel/module/main.c         | 67 ++++++------------------------------
 kernel/module/strict_rwx.c   |  9 ++---
 4 files changed, 17 insertions(+), 70 deletions(-)
include/linux/module.h +1 -6
index bd8cf93d32c8..e9fc9d1fa476 100644
@@ -368,7 +368,6 @@ enum mod_mem_type {
 
 struct module_memory {
 	void *base;
-	void *rw_copy;
 	bool is_rox;
 	unsigned int size;
 
@@ -775,13 +774,9 @@ static inline bool is_livepatch_module(struct module *mod)
 
 void set_module_sig_enforced(void);
 
-void *__module_writable_address(struct module *mod, void *loc);
-
 static inline void *module_writable_address(struct module *mod, void *loc)
 {
-	if (!IS_ENABLED(CONFIG_ARCH_HAS_EXECMEM_ROX) || !mod)
-		return loc;
-	return __module_writable_address(mod, loc);
+	return loc;
 }
 
 #else /* !CONFIG_MODULES... */
include/linux/moduleloader.h +0 -4
index 1f5507ba5a12..e395461d59e5 100644
@@ -108,10 +108,6 @@ int module_finalize(const Elf_Ehdr *hdr,
 		    const Elf_Shdr *sechdrs,
 		    struct module *mod);
 
-int module_post_finalize(const Elf_Ehdr *hdr,
-			 const Elf_Shdr *sechdrs,
-			 struct module *mod);
-
 #ifdef CONFIG_MODULES
 void flush_module_init_free_work(void);
 #else
kernel/module/main.c +11 -56

140 lines not on this page · raw message

kernel/module/strict_rwx.c +5 -4
index 239e5013359d..ce47b6346f27 100644
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/vmalloc.h>
 #include <linux/set_memory.h>
+#include <linux/execmem.h>
 #include "internal.h"
 
 static int module_set_memory(const struct module *mod, enum mod_mem_type type,
@@ -32,12 +33,12 @@ static int module_set_memory(const struct module *mod, enum mod_mem_type type,
 int module_enable_text_rox(const struct module *mod)
 {
 	for_class_mod_mem_type(type, text) {
+		const struct module_memory *mem = &mod->mem[type];
 		int ret;
 
-		if (mod->mem[type].is_rox)
-			continue;
-
-		if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
+		if (mem->is_rox)
+			ret = execmem_restore_rox(mem->base, mem->size);
+		else if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
 			ret = module_set_memory(mod, type, set_memory_rox);
 		else
 			ret = module_set_memory(mod, type, set_memory_x);
Signature · 1 line
2.45.2
author maintainer
#21 lore raw

PATCH 7/8 Revert "x86/module: prepare module loading for ROX allocations of text"

In reply to Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

The module code does not create a writable copy of the executable memory anymore so there is no need to handle it in module relocation and alternatives patching.

This reverts commit 9bfc4824fd4836c16bb44f922bfaffba5da3e4f3.

---
 arch/um/kernel/um_arch.c           |  11 +-
 arch/x86/entry/vdso/vma.c          |   3 +-
 arch/x86/include/asm/alternative.h |  14 +--
 arch/x86/kernel/alternative.c      | 181 ++++++++++++-----------------
 arch/x86/kernel/ftrace.c           |  30 +++--
 arch/x86/kernel/module.c           |  45 +++----
 6 files changed, 117 insertions(+), 167 deletions(-)
arch/um/kernel/um_arch.c +5 -6
index 8037a967225d..d2cc2c69a8c4 100644
@@ -440,25 +440,24 @@ void __init arch_cpu_finalize_init(void)
 	os_check_bugs();
 }
 
-void apply_seal_endbr(s32 *start, s32 *end, struct module *mod)
+void apply_seal_endbr(s32 *start, s32 *end)
 {
 }
 
-void apply_retpolines(s32 *start, s32 *end, struct module *mod)
+void apply_retpolines(s32 *start, s32 *end)
 {
 }
 
-void apply_returns(s32 *start, s32 *end, struct module *mod)
+void apply_returns(s32 *start, s32 *end)
 {
 }
 
 void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
-		   s32 *start_cfi, s32 *end_cfi, struct module *mod)
+		   s32 *start_cfi, s32 *end_cfi)
 {
 }
 
-void apply_alternatives(struct alt_instr *start, struct alt_instr *end,
-			struct module *mod)
+void apply_alternatives(struct alt_instr *start, struct alt_instr *end)
 {
 }
 
arch/x86/entry/vdso/vma.c +1 -2
index 39e6efc1a9ca..bfc7cabf4017 100644
@@ -48,8 +48,7 @@ int __init init_vdso_image(const struct vdso_image *image)
 
 	apply_alternatives((struct alt_instr *)(image->data + image->alt),
 			   (struct alt_instr *)(image->data + image->alt +
-						image->alt_len),
-			   NULL);
+						image->alt_len));
 
 	return 0;
 }
arch/x86/include/asm/alternative.h +7 -7
index dc03a647776d..ca9ae606aab9 100644
@@ -96,16 +96,16 @@ extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
  * instructions were patched in already:
  */
 extern int alternatives_patched;
-struct module;
 
 extern void alternative_instructions(void);
-extern void apply_alternatives(struct alt_instr *start, struct alt_instr *end,
-			       struct module *mod);
-extern void apply_retpolines(s32 *start, s32 *end, struct module *mod);
-extern void apply_returns(s32 *start, s32 *end, struct module *mod);
-extern void apply_seal_endbr(s32 *start, s32 *end, struct module *mod);
+extern void apply_alternatives(struct alt_instr *start, struct alt_instr *end);
+extern void apply_retpolines(s32 *start, s32 *end);
+extern void apply_returns(s32 *start, s32 *end);
+extern void apply_seal_endbr(s32 *start, s32 *end);
 extern void apply_fineibt(s32 *start_retpoline, s32 *end_retpoine,
-			  s32 *start_cfi, s32 *end_cfi, struct module *mod);
+			  s32 *start_cfi, s32 *end_cfi);
+
+struct module;
 
 struct callthunk_sites {
 	s32				*call_start, *call_end;
arch/x86/kernel/alternative.c +76 -105

535 lines not on this page · raw message

arch/x86/kernel/ftrace.c +14 -16
index 4dd0ad6c94d6..adb09f78edb2 100644
@@ -118,13 +118,10 @@ ftrace_modify_code_direct(unsigned long ip, const char *old_code,
 		return ret;
 
 	/* replace the text with the new text */
-	if (ftrace_poke_late) {
+	if (ftrace_poke_late)
 		text_poke_queue((void *)ip, new_code, MCOUNT_INSN_SIZE, NULL);
-	} else {
-		mutex_lock(&text_mutex);
-		text_poke((void *)ip, new_code, MCOUNT_INSN_SIZE);
-		mutex_unlock(&text_mutex);
-	}
+	else
+		text_poke_early((void *)ip, new_code, MCOUNT_INSN_SIZE);
 	return 0;
 }
 
@@ -321,7 +318,7 @@ create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size)
 	unsigned const char op_ref[] = { 0x48, 0x8b, 0x15 };
 	unsigned const char retq[] = { RET_INSN_OPCODE, INT3_INSN_OPCODE };
 	union ftrace_op_code_union op_ptr;
-	void *ret;
+	int ret;
 
 	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) {
 		start_offset = (unsigned long)ftrace_regs_caller;
@@ -352,15 +349,15 @@ create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size)
 	npages = DIV_ROUND_UP(*tramp_size, PAGE_SIZE);
 
 	/* Copy ftrace_caller onto the trampoline memory */
-	ret = text_poke_copy(trampoline, (void *)start_offset, size);
-	if (WARN_ON(!ret))
+	ret = copy_from_kernel_nofault(trampoline, (void *)start_offset, size);
+	if (WARN_ON(ret < 0))
 		goto fail;
 
 	ip = trampoline + size;
 	if (cpu_feature_enabled(X86_FEATURE_RETHUNK))
 		__text_gen_insn(ip, JMP32_INSN_OPCODE, ip, x86_return_thunk, JMP32_INSN_SIZE);
 	else
-		text_poke_copy(ip, retq, sizeof(retq));
+		memcpy(ip, retq, sizeof(retq));
 
 	/* No need to test direct calls on created trampolines */
 	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) {
@@ -368,7 +365,8 @@ create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size)
 		ip = trampoline + (jmp_offset - start_offset);
 		if (WARN_ON(*(char *)ip != 0x75))
 			goto fail;
-		if (!text_poke_copy(ip, x86_nops[2], 2))
+		ret = copy_from_kernel_nofault(ip, x86_nops[2], 2);
+		if (ret < 0)
 			goto fail;
 	}
 
@@ -381,7 +379,7 @@ create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size)
 	 */
 
 	ptr = (unsigned long *)(trampoline + size + RET_SIZE);
-	text_poke_copy(ptr, &ops, sizeof(unsigned long));
+	*ptr = (unsigned long)ops;
 
 	op_offset -= start_offset;
 	memcpy(&op_ptr, trampoline + op_offset, OP_REF_SIZE);
@@ -397,7 +395,7 @@ create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size)
 	op_ptr.offset = offset;
 
 	/* put in the new offset to the ftrace_ops */
-	text_poke_copy(trampoline + op_offset, &op_ptr, OP_REF_SIZE);
+	memcpy(trampoline + op_offset, &op_ptr, OP_REF_SIZE);
 
 	/* put in the call to the function */
 	mutex_lock(&text_mutex);
@@ -407,9 +405,9 @@ create_trampoline(struct ftrace_ops *ops, unsigned int *tramp_size)
 	 * the depth accounting before the call already.
 	 */
 	dest = ftrace_ops_get_func(ops);
-	text_poke_copy_locked(trampoline + call_offset,
-	      text_gen_insn(CALL_INSN_OPCODE, trampoline + call_offset, dest),
-	      CALL_INSN_SIZE, false);
+	memcpy(trampoline + call_offset,
+	       text_gen_insn(CALL_INSN_OPCODE, trampoline + call_offset, dest),
+	       CALL_INSN_SIZE);
 	mutex_unlock(&text_mutex);
 
 	/* ALLOC_TRAMP flags lets us know we created it */
arch/x86/kernel/module.c +14 -31

102 lines not on this page · raw message

Signature · 1 line
2.45.2
author maintainer
#22 lore raw

PATCH 8/8 module: drop unused module_writable_address()

In reply to Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

module_writable_address() is unused and can be removed.

---
 include/linux/module.h | 10 ----------
 1 file changed, 10 deletions(-)
include/linux/module.h +0 -10
index e9fc9d1fa476..222099bb07cf 100644
@@ -774,11 +774,6 @@ static inline bool is_livepatch_module(struct module *mod)
 
 void set_module_sig_enforced(void);
 
-static inline void *module_writable_address(struct module *mod, void *loc)
-{
-	return loc;
-}
-
 #else /* !CONFIG_MODULES... */
 
 static inline struct module *__module_address(unsigned long addr)
@@ -886,11 +881,6 @@ static inline bool module_is_coming(struct module *mod)
 {
 	return false;
 }
-
-static inline void *module_writable_address(struct module *mod, void *loc)
-{
-	return loc;
-}
 #endif /* CONFIG_MODULES */
 
 #ifdef CONFIG_SYSFS
Signature · 1 line
2.45.2
#14 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

In reply to Mike Rapoport

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

It seems to be having an unhandled kernel page fault on exec, so I guess not actually making it exec somehow?

It is a pretty standard intel machine (arch linux config, slightly scaled down via make localmodconfig to make it easier to quickly rebuild kernels). Can give more details if needed.

Here is the (vaguely annotated-ish) splat:

:: running early hook [udev]
Starting systemd-udevd version 257.1-1-arch
:: running hook [udev]
:: Triggering uevents...

[    4.231005] usb 1-11: new high-speed USB device number 3 using xhci_hcd
[    4.261646] kernel tried to execute NX-protected page - exploit attempt? (uid: 0)

Guessing the execmem didn't make it exec somehow?

[    4.269136] BUG: unable to handle page fault for address: ffffffffc0641010
[    4.276009] #PF: supervisor instruction fetch in kernel mode
[    4.281666] #PF: error_code(0x0011) - permissions violation
[    4.287241] PGD 3027067 P4D 3027067 PUD 3029067 PMD 12a29e063 PTE 8000000129441163
[    4.294818] Oops: Oops: 0011 [#1] PREEMPT SMP NOPTI
[    4.299695] CPU: 31 UID: 0 PID: 331 Comm: (udev-worker) Tainted: G        W          6.13.0-rc4-1-custom #1 5815a74228bcc318a2a967d947d4ca4aa132a5ed
[    4.312992] Tainted: [W]=WARN
[    4.315961] Hardware name: Gigabyte Technology Co., Ltd. Z790 AORUS ELITE X WIFI7/Z790 AORUS ELITE X WIFI7, BIOS F7 09/27/2024
[    4.327349] RIP: 0010:crc32c_intel_mod_init+0x0/0xff0 [crc32c_intel]

My addr2line suggests:

/home/lorenzo/kerndev/kernels/mm/./arch/x86/include/asm/processor.h:43

DECLARE_PER_CPU_FIRST(struct fixed_percpu_data, fixed_percpu_data) __visible;

Which seems... odd :)

[    4.333702] Code: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 <f3> 0f 1e fa 0f 1f 44 00 00 48 c7 c7 00 e0 8a c0 e8 1b aa a8 c0 48
[    4.352466] RSP: 0018:ffffc90004223a58 EFLAGS: 00010246
[    4.357693] RAX: 0000000000000000 RBX: ffffffffc0641010 RCX: 0000000000000000
[    4.364827] RDX: 0000000000000000 RSI: ffffffffc0641010 RDI: ffffc90004223a40
[    4.371963] RBP: 0000000000000000 R08: 0000000000000020 R09: ffff88811adeeb00
[    4.379097] R10: ffffc90004223ad0 R11: 0000000000000000 R12: ffff8881278c3600
[    4.385530] usb 1-11: New USB device found, idVendor=05e3, idProduct=0608, bcdDevice=60.90
[    4.386230] R13: ffffc90004223a60 R14: ffff88811ae3ac00 R15: ffff88811f251b80
[    4.394497] usb 1-11: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[    4.401628] FS:  00007f92de124880(0000) GS:ffff88afffd80000(0000) knlGS:0000000000000000
[    4.401630] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[    4.408850] usb 1-11: Product: USB2.0 Hub
[    4.416938] CR2: ffffffffc0641010 CR3: 00000001279f6006 CR4: 0000000000f70ef0
[    4.416939] PKRU: 55555554
[    4.423588] hub 1-11:1.0: USB hub found
[    4.426696] Call Trace:
[    4.426697]  <TASK>
[    4.426699]  ? __die_body.cold+0x19/0x27
[    4.434112] hub 1-11:1.0: 4 ports detected
[    4.436547]  ? __pfx_crc32c_intel_mod_init+0x10/0x10 [crc32c_intel 0c38f5da3bf5b6f9ab94fb009bb43215a1542e3a]
[    4.462776]  ? page_fault_oops+0x15a/0x2d0
[    4.466874]  ? disable_mmiotrace.cold+0x6a/0xaa
[    4.471404]  ? __pfx_crc32c_intel_mod_init+0x10/0x10 [crc32c_intel 0c38f5da3bf5b6f9ab94fb009bb43215a1542e3a]
[    4.481229]  ? exc_page_fault+0x18a/0x190
[    4.485240]  ? asm_exc_page_fault+0x26/0x30
[    4.489422]  ? __pfx_crc32c_intel_mod_init+0x10/0x10 [crc32c_intel 0c38f5da3bf5b6f9ab94fb009bb43215a1542e3a]
[    4.499248]  ? __pfx_crc32c_intel_mod_init+0x10/0x10 [crc32c_intel 0c38f5da3bf5b6f9ab94fb009bb43215a1542e3a]
[    4.509073]  ? __pfx_crc32c_intel_mod_init+0x10/0x10 [crc32c_intel 0c38f5da3bf5b6f9ab94fb009bb43215a1542e3a]
[    4.518900]  do_one_initcall+0x58/0x310
[    4.522736]  do_init_module+0x82/0x270
[    4.526483]  init_module_from_file+0x86/0xc0
[    4.530756]  idempotent_init_module+0x115/0x310
[    4.535286]  __x64_sys_finit_module+0x65/0xc0
[    4.539642]  do_syscall_64+0x82/0x190
[    4.543305]  ? do_syscall_64+0x8e/0x190
[    4.547142]  ? filemap_map_pages+0x51f/0x670
[    4.551412]  ? do_filp_open+0xd8/0x190
[    4.555163]  ? __pfx_page_put_link+0x10/0x10
[    4.559433]  ? do_sys_openat2+0x9c/0xe0
[    4.563268]  ? syscall_exit_to_user_mode+0x37/0x1c0
[    4.568147]  ? syscall_exit_to_user_mode+0x37/0x1c0
[    4.573024]  ? do_syscall_64+0x8e/0x190
[    4.576861]  entry_SYSCALL_64_after_hwframe+0x76/0x7e
[    4.581003] usb 1-12: new high-speed USB device number 4 using xhci_hcd
[    4.581914] RIP: 0033:0x7f92de91b1fd
[    4.592102] Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 90 f3 0f 1e fa 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 8b 0d e3 fa 0c 00 f7 d8 64 89 01 48
[    4.610867] RSP: 002b:00007ffcf33fa0b8 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
[    4.618434] RAX: ffffffffffffffda RBX: 0000555fbf68a870 RCX: 00007f92de91b1fd
[    4.625570] RDX: 0000000000000000 RSI: 00007f92de11e05d RDI: 0000000000000014
[    4.632704] RBP: 00007ffcf33fa170 R08: 0000000000000002 R09: 00007ffcf33fa120
[    4.639839] R10: 0000000000000007 R11: 0000000000000246 R12: 00007f92de11e05d
[    4.646973] R13: 0000000000020000 R14: 0000555fbf682a70 R15: 0000555fbf682fd0
[    4.654109]  </TASK>
[    4.656296] Modules linked in: crc32c_intel(+) spi_intel_pci drm_display_helper spi_intel nvme_auth cec video wmi

If I revert _just this_ commit it breaks the boot by not being able to find the disk (!) so guess you need to revert everything after it too which kinda makes sense :)

Quoted 245 lines · Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

Instead of using writable copy for module text sections, temporarily remap the memory allocated from execmem's ROX cache as writable and restore its ROX permissions after the module is formed.

This will allow removing nasty games with writable copy in alternatives patching on x86.

---
 include/linux/module.h       |  7 +---
 include/linux/moduleloader.h |  4 ---
 kernel/module/main.c         | 67 ++++++------------------------------
 kernel/module/strict_rwx.c   |  9 ++---
 4 files changed, 17 insertions(+), 70 deletions(-)
include/linux/module.h +1 -6
index bd8cf93d32c8..e9fc9d1fa476 100644
@@ -368,7 +368,6 @@ enum mod_mem_type {
 
 struct module_memory {
 	void *base;
-	void *rw_copy;
 	bool is_rox;
 	unsigned int size;
 
@@ -775,13 +774,9 @@ static inline bool is_livepatch_module(struct module *mod)
 
 void set_module_sig_enforced(void);
 
-void *__module_writable_address(struct module *mod, void *loc);
-
 static inline void *module_writable_address(struct module *mod, void *loc)
 {
-	if (!IS_ENABLED(CONFIG_ARCH_HAS_EXECMEM_ROX) || !mod)
-		return loc;
-	return __module_writable_address(mod, loc);
+	return loc;
 }
 
 #else /* !CONFIG_MODULES... */
include/linux/moduleloader.h +0 -4
index 1f5507ba5a12..e395461d59e5 100644
@@ -108,10 +108,6 @@ int module_finalize(const Elf_Ehdr *hdr,
 		    const Elf_Shdr *sechdrs,
 		    struct module *mod);
 
-int module_post_finalize(const Elf_Ehdr *hdr,
-			 const Elf_Shdr *sechdrs,
-			 struct module *mod);
-
 #ifdef CONFIG_MODULES
 void flush_module_init_free_work(void);
 #else
kernel/module/main.c +11 -56
index ad8ef20c120f..ee6b46e753a0 100644
@@ -1221,18 +1221,6 @@ void __weak module_arch_freeing_init(struct module *mod)
 {
 }
 
-void *__module_writable_address(struct module *mod, void *loc)
-{
-	for_class_mod_mem_type(type, text) {
-		struct module_memory *mem = &mod->mem[type];
-
-		if (loc >= mem->base && loc < mem->base + mem->size)
-			return loc + (mem->rw_copy - mem->base);
-	}
-
-	return loc;
-}
-
 static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
 {
 	unsigned int size = PAGE_ALIGN(mod->mem[type].size);
@@ -1250,21 +1238,15 @@ static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
 	if (!ptr)
 		return -ENOMEM;
 
-	mod->mem[type].base = ptr;
-
 	if (execmem_is_rox(execmem_type)) {
-		ptr = vzalloc(size);
+		int err = execmem_make_temp_rw(ptr, size);
 
-		if (!ptr) {
-			execmem_free(mod->mem[type].base);
+		if (err) {
+			execmem_free(ptr);
 			return -ENOMEM;
 		}
 
-		mod->mem[type].rw_copy = ptr;
 		mod->mem[type].is_rox = true;
-	} else {
-		mod->mem[type].rw_copy = mod->mem[type].base;
-		memset(mod->mem[type].base, 0, size);
 	}
 
 	/*
@@ -1280,6 +1262,9 @@ static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
 	 */
 	kmemleak_not_leak(ptr);
 
+	memset(ptr, 0, size);
+	mod->mem[type].base = ptr;
+
 	return 0;
 }
 
@@ -1287,8 +1272,8 @@ static void module_memory_free(struct module *mod, enum mod_mem_type type)
 {
 	struct module_memory *mem = &mod->mem[type];
 
-	if (mem->is_rox)
-		vfree(mem->rw_copy);
+	if (mod->state == MODULE_STATE_UNFORMED && mem->is_rox)
+		execmem_restore_rox(mem->base, mem->size);
 
 	execmem_free(mem->base);
 }
@@ -2561,7 +2546,6 @@ static int move_module(struct module *mod, struct load_info *info)
 	for_each_mod_mem_type(type) {
 		if (!mod->mem[type].size) {
 			mod->mem[type].base = NULL;
-			mod->mem[type].rw_copy = NULL;
 			continue;
 		}
 
@@ -2578,7 +2562,6 @@ static int move_module(struct module *mod, struct load_info *info)
 		void *dest;
 		Elf_Shdr *shdr = &info->sechdrs[i];
 		const char *sname;
-		unsigned long addr;
 
 		if (!(shdr->sh_flags & SHF_ALLOC))
 			continue;
@@ -2599,14 +2582,12 @@ static int move_module(struct module *mod, struct load_info *info)
 				ret = PTR_ERR(dest);
 				goto out_err;
 			}
-			addr = (unsigned long)dest;
 			codetag_section_found = true;
 		} else {
 			enum mod_mem_type type = shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT;
 			unsigned long offset = shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK;
 
-			addr = (unsigned long)mod->mem[type].base + offset;
-			dest = mod->mem[type].rw_copy + offset;
+			dest = mod->mem[type].base + offset;
 		}
 
 		if (shdr->sh_type != SHT_NOBITS) {
@@ -2629,7 +2610,7 @@ static int move_module(struct module *mod, struct load_info *info)
 		 * users of info can keep taking advantage and using the newly
 		 * minted official memory area.
 		 */
-		shdr->sh_addr = addr;
+		shdr->sh_addr = (unsigned long)dest;
 		pr_debug("\t0x%lx 0x%.8lx %s\n", (long)shdr->sh_addr,
 			 (long)shdr->sh_size, info->secstrings + shdr->sh_name);
 	}
@@ -2782,17 +2763,8 @@ int __weak module_finalize(const Elf_Ehdr *hdr,
 	return 0;
 }
 
-int __weak module_post_finalize(const Elf_Ehdr *hdr,
-				const Elf_Shdr *sechdrs,
-				struct module *me)
-{
-	return 0;
-}
-
 static int post_relocation(struct module *mod, const struct load_info *info)
 {
-	int ret;
-
 	/* Sort exception table now relocations are done. */
 	sort_extable(mod->extable, mod->extable + mod->num_exentries);
 
@@ -2804,24 +2776,7 @@ static int post_relocation(struct module *mod, const struct load_info *info)
 	add_kallsyms(mod, info);
 
 	/* Arch-specific module finalizing. */
-	ret = module_finalize(info->hdr, info->sechdrs, mod);
-	if (ret)
-		return ret;
-
-	for_each_mod_mem_type(type) {
-		struct module_memory *mem = &mod->mem[type];
-
-		if (mem->is_rox) {
-			if (!execmem_update_copy(mem->base, mem->rw_copy,
-						 mem->size))
-				return -ENOMEM;
-
-			vfree(mem->rw_copy);
-			mem->rw_copy = NULL;
-		}
-	}
-
-	return module_post_finalize(info->hdr, info->sechdrs, mod);
+	return module_finalize(info->hdr, info->sechdrs, mod);
 }
 
 /* Call module constructors. */
kernel/module/strict_rwx.c +5 -5
index 239e5013359d..ce47b6346f27 100644
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/vmalloc.h>
 #include <linux/set_memory.h>
+#include <linux/execmem.h>
 #include "internal.h"
 
 static int module_set_memory(const struct module *mod, enum mod_mem_type type,
@@ -32,12 +33,12 @@ static int module_set_memory(const struct module *mod, enum mod_mem_type type,
 int module_enable_text_rox(const struct module *mod)
 {
 	for_class_mod_mem_type(type, text) {
+		const struct module_memory *mem = &mod->mem[type];
 		int ret;
 
-		if (mod->mem[type].is_rox)
-			continue;
-
-		if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
+		if (mem->is_rox)
+			ret = execmem_restore_rox(mem->base, mem->size);
+		else if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
 			ret = module_set_memory(mod, type, set_memory_rox);
 		else
 			ret = module_set_memory(mod, type, set_memory_x);
--

2.45.2

#15 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

Quoted 4 lines

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

For what it's worth, we've found the same under Xen too.

There's one concrete bug in the series, failing to cope with the absence of superpages (fix in
https://lore.kernel.org/xen-devel/[email protected]/
but not formally posted yet AFAICT).

The rest of the thread then found a crash looking to be the same as reported here, but you've made better progress narrowing it down than we have.

~Andrew

maintainer
#16 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

Quoted 7 lines · On Fri, 3 Jan 2025 02:06:10 +0000 Andrew Cooper <[email protected]>…
Quoted 4 lines

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

For what it's worth, we've found the same under Xen too.

Quoted 9 lines

There's one concrete bug in the series, failing to cope with the absence of superpages (fix in
https://lore.kernel.org/xen-devel/[email protected]/
but not formally posted yet AFAICT).

The rest of the thread then found a crash looking to be the same as reported here, but you've made better progress narrowing it down than we have.

Thanks. I removed this series from mm.git while this is worked on.

#18 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

In reply to Andrew Cooper
Quoted 11 lines · Andrew Cooper
Quoted 4 lines

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

For what it's worth, we've found the same under Xen too.

There's one concrete bug in the series, failing to cope with the absence of superpages (fix in
https://lore.kernel.org/xen-devel/[email protected]/
but not formally posted yet AFAICT).

Now sent out:

https://lore.kernel.org/lkml/[email protected]/T/#u

Juergen

#17 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

In reply to Andrew Morton

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

Quoted 14 lines · Andrew Morton
Quoted 12 lines · On Fri, 3 Jan 2025 02:06:10 +0000 Andrew Cooper <[email protected]>…
Quoted 4 lines

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

For what it's worth, we've found the same under Xen too.

There's one concrete bug in the series, failing to cope with the absence of superpages (fix in
https://lore.kernel.org/xen-devel/[email protected]/
but not formally posted yet AFAICT).

Quoted 6 lines
Quoted 4 lines

The rest of the thread then found a crash looking to be the same as reported here, but you've made better progress narrowing it down than we have.

Thanks. I removed this series from mm.git while this is worked on.

The issue under Xen that Andrew linked happens on 6.13-rc5 which AFAICT doesn't this series yet. So, it's probably a different issue.

- --
Best Regards,
Marek Marczykowski-Górecki
Invisible Things Lab
-----BEGIN PGP SIGNATURE-----

iQEzBAEBCAAdFiEEhrpukzGPukRmQqkK24/THMrX1ywFAmd3wpUACgkQ24/THMrX 1yzmigf/XurIB/pN9J44SKwSeCWCQMVu3ZjFfeQ7XiAl3IpiALExuGFtEiAX8sY/ BqA3MWs9AKpBz7qfUQGU3+tRUbEVQz/rHh8FBo3OBwZQJuxntlT291E4/FzIHUzN JZ0b6AAgU9MaSdOC0A0XGwFDbhTPbbqbHanyaVyCf+2QVCEW4OFcgnlUVBdIs6sW tXzKWNr70Jkq/XguvrWVBHgg5C3E/SfXZzoRIFCKfMuXfpqVVpa35X/Zf3+V8my/ n0Di7xZXQaXMSv72tQayI+/y2dT4PbLqTE+lhLf2UCXDn15WBHpmyppX9Nn3huEG L0NRHVLneeo25kRQuzGj04vWFem6MQ==
=0Iqv
-----END PGP SIGNATURE-----

maintainer
#2 lore raw

Re: [PATCH 1/8] x86/mm/pat: cpa-test: fix length for CPA_ARRAY test

In reply to Mike Rapoport
Quoted 7 lines · Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

The CPA_ARRAY test always uses len[1] as numpages argument to change_page_attr_set() although the addresses array is different each iteration of the test loop.

Replace len[1] with len[i] to have numpages matching the addresses array.

D'oh..

maintainer
#19 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

In reply to Jürgen Groß
Quoted 8 lines · Jürgen Groß
Quoted 7 lines · Andrew Cooper
Quoted 4 lines

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

For what it's worth, we've found the same under Xen too.

Quoted 8 lines
Quoted 4 lines

There's one concrete bug in the series, failing to cope with the absence of superpages (fix in
https://lore.kernel.org/xen-devel/[email protected]/
but not formally posted yet AFAICT).

Now sent out:

https://lore.kernel.org/lkml/[email protected]/T/#u

Thanks,

Marek, Adam, can you try this patch? Although the reply here is for another future series being worked on the fix is for commit 2e45474ab14f ("execmem: add support for cache of large ROX pages").

Luis

#20 lore raw

Re: [PATCH 6/8] modules: switch to execmem API for remapping as RW and restoring ROX

Quoted 19 lines · Luis Chamberlain
Quoted 8 lines · Jürgen Groß
Quoted 7 lines · Andrew Cooper
Quoted 4 lines

Hi Mike,

This commit is making my intel box not boot in mm-unstable :>) I bisected it to this commit.

For what it's worth, we've found the same under Xen too.

Quoted 8 lines
Quoted 4 lines

There's one concrete bug in the series, failing to cope with the absence of superpages (fix in
https://lore.kernel.org/xen-devel/[email protected]/
but not formally posted yet AFAICT).

Now sent out:

https://lore.kernel.org/lkml/[email protected]/T/#u

Quoted 7 lines

Thanks,

Marek, Adam, can you try this patch? Although the reply here is for another future series being worked on the fix is for commit 2e45474ab14f ("execmem: add support for cache of large ROX pages").

Luis

Hi Luis,

I suppose you're referring to the issue described here
https://lore.kernel.org/linux-mm/CAGcaFA2hdThQV6mjD_1_U+GNHThv84+MQvMWLgEuX+LVbAyDxg@mail.gmail.com/T/
Unfortnuetly this patch didn't help.

Best,
Marek

maintainer Acked-by on v1 5/8
#12 lore raw

Re: [PATCH 5/8] module: introduce MODULE_STATE_GONE

In reply to Mike Rapoport
Quoted 8 lines · Mike Rapoport

From: "Mike Rapoport (Microsoft)" <[email protected]>

In order to use execmem's API for temporal remapping of the memory allocated from ROX cache as writable, there is a need to distinguish between the state when the module is being formed and the state when it is deconstructed and freed so that when module_memory_free() is called from error paths during module loading it could restore ROX mappings.

Quoted 5 lines

Replace open coded checks for MODULE_STATE_UNFORMED with a helper function module_is_formed() and add a new MODULE_STATE_GONE that will be set when the module is deconstructed and freed.

I've seen the rest of the discussion about this patch... but in case I forget, and from an extremely myopic kgdb/kdb point of view:

Daniel.

#5 lore raw

Re: [PATCH 3/8] x86/mm/pat: Restore large pages after fragmentation

In reply to Mike Rapoport
Quoted 41 lines · Mike Rapoport

From: "Kirill A. Shutemov" <[email protected]>

Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result.

With current code it's one way road: kernel tries to avoid splitting large pages, but it doesn't restore them back even if page attributes got compatible again.

Any change to the mapping may potentially allow to restore large page.

Hook up into cpa_flush() path to check if there's any pages to be recovered in PUD_SIZE range around pages we've just touched.

CPUs don't like[1] to have to have TLB entries of different size for the same memory, but looks like it's okay as long as these entries have matching attributes[2]. Therefore it's critical to flush TLB before any following changes to the mapping.

Note that we already allow for multiple TLB entries of different sizes for the same memory now in split_large_page() path. It's not a new situation.

set_memory_4k() provides a way to use 4k pages on purpose. Kernel must not remap such pages as large. Re-use one of software PTE bits to indicate such pages.

[1] See Erratum 383 of AMD Family 10h Processors
[2] https://lore.kernel.org/linux-mm/[email protected]/

[[email protected]:
* s/restore/collapse/
* update formatting per peterz
* use 'struct ptdesc' instead of 'struct page' for list of page tables to be freed
* try to collapse PMD first and if it succeeds move on to PUD as peterz suggested
* flush TLB twice: for changes done in the original CPA call and after collapsing of large pages
]

Quoted 4 lines

When I originally attempted this, the patch was dropped because of performance regressions. Was it addressed somehow?

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
maintainer
#6 lore raw

Re: [PATCH 3/8] x86/mm/pat: Restore large pages after fragmentation

Quoted 42 lines · Kirill A. Shutemov
Quoted 41 lines · Mike Rapoport

From: "Kirill A. Shutemov" <[email protected]>

Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result.

With current code it's one way road: kernel tries to avoid splitting large pages, but it doesn't restore them back even if page attributes got compatible again.

Any change to the mapping may potentially allow to restore large page.

Hook up into cpa_flush() path to check if there's any pages to be recovered in PUD_SIZE range around pages we've just touched.

CPUs don't like[1] to have to have TLB entries of different size for the same memory, but looks like it's okay as long as these entries have matching attributes[2]. Therefore it's critical to flush TLB before any following changes to the mapping.

Note that we already allow for multiple TLB entries of different sizes for the same memory now in split_large_page() path. It's not a new situation.

set_memory_4k() provides a way to use 4k pages on purpose. Kernel must not remap such pages as large. Re-use one of software PTE bits to indicate such pages.

[1] See Erratum 383 of AMD Family 10h Processors
[2] https://lore.kernel.org/linux-mm/[email protected]/

[[email protected]:
* s/restore/collapse/
* update formatting per peterz
* use 'struct ptdesc' instead of 'struct page' for list of page tables to be freed
* try to collapse PMD first and if it succeeds move on to PUD as peterz suggested
* flush TLB twice: for changes done in the original CPA call and after collapsing of large pages
]

Quoted 8 lines
Quoted 4 lines

When I originally attempted this, the patch was dropped because of performance regressions. Was it addressed somehow?

Also, the statement:

"Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result. "

Seems to contradict the findings reported at LSFMM by Mike before that direct map fragmentation does not incur performance penalty, so I don't see a point in contradicing those findings and confusing people further.

Luis

author maintainer
#7 lore raw

Re: [PATCH 3/8] x86/mm/pat: Restore large pages after fragmentation

In reply to Kirill A. Shutemov

Hi Kirill,

Quoted 42 lines · Kirill A. Shutemov
Quoted 41 lines · Mike Rapoport

From: "Kirill A. Shutemov" <[email protected]>

Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result.

With current code it's one way road: kernel tries to avoid splitting large pages, but it doesn't restore them back even if page attributes got compatible again.

Any change to the mapping may potentially allow to restore large page.

Hook up into cpa_flush() path to check if there's any pages to be recovered in PUD_SIZE range around pages we've just touched.

CPUs don't like[1] to have to have TLB entries of different size for the same memory, but looks like it's okay as long as these entries have matching attributes[2]. Therefore it's critical to flush TLB before any following changes to the mapping.

Note that we already allow for multiple TLB entries of different sizes for the same memory now in split_large_page() path. It's not a new situation.

set_memory_4k() provides a way to use 4k pages on purpose. Kernel must not remap such pages as large. Re-use one of software PTE bits to indicate such pages.

[1] See Erratum 383 of AMD Family 10h Processors
[2] https://lore.kernel.org/linux-mm/[email protected]/

[[email protected]:
* s/restore/collapse/
* update formatting per peterz
* use 'struct ptdesc' instead of 'struct page' for list of page tables to be freed
* try to collapse PMD first and if it succeeds move on to PUD as peterz suggested
* flush TLB twice: for changes done in the original CPA call and after collapsing of large pages
]

Quoted 7 lines
Quoted 4 lines

When I originally attempted this, the patch was dropped because of performance regressions. Was it addressed somehow?

I didn't realize the patch was dropped because of performance regressions, so I didn't address it.

Do you remember where did the regressions show up?

Quoted 3 lines
Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
Signature · 2 lines
Sincerely yours,
Mike.
#8 lore raw

Re: [PATCH 3/8] x86/mm/pat: Restore large pages after fragmentation

Quoted 50 lines · Mike Rapoport

Hi Kirill,

Quoted 47 lines · Kirill A. Shutemov
Quoted 45 lines · Mike Rapoport

From: "Kirill A. Shutemov" <[email protected]>

Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result.

With current code it's one way road: kernel tries to avoid splitting large pages, but it doesn't restore them back even if page attributes got compatible again.

Any change to the mapping may potentially allow to restore large page.

Hook up into cpa_flush() path to check if there's any pages to be recovered in PUD_SIZE range around pages we've just touched.

CPUs don't like[1] to have to have TLB entries of different size for the same memory, but looks like it's okay as long as these entries have matching attributes[2]. Therefore it's critical to flush TLB before any following changes to the mapping.

Note that we already allow for multiple TLB entries of different sizes for the same memory now in split_large_page() path. It's not a new situation.

set_memory_4k() provides a way to use 4k pages on purpose. Kernel must not remap such pages as large. Re-use one of software PTE bits to indicate such pages.

[1] See Erratum 383 of AMD Family 10h Processors
[2] https://lore.kernel.org/linux-mm/[email protected]/

[[email protected]:
* s/restore/collapse/
* update formatting per peterz
* use 'struct ptdesc' instead of 'struct page' for list of page tables to be freed
* try to collapse PMD first and if it succeeds move on to PUD as peterz suggested
* flush TLB twice: for changes done in the original CPA call and after collapsing of large pages
]

Quoted 7 lines
Quoted 2 lines

When I originally attempted this, the patch was dropped because of performance regressions. Was it addressed somehow?

I didn't realize the patch was dropped because of performance regressions, so I didn't address it.

Do you remember where did the regressions show up?

https://github.com/zen-kernel/zen-kernel/issues/169

My understanding is if userspace somewhat frequently triggers set_memory_* codepath we will get a performance hit.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
author maintainer
#9 lore raw

Re: [PATCH 3/8] x86/mm/pat: Restore large pages after fragmentation

Quoted 57 lines · Kirill A. Shutemov
Quoted 56 lines · Mike Rapoport

Hi Kirill,

Quoted 42 lines · Kirill A. Shutemov
Quoted 41 lines · Mike Rapoport

From: "Kirill A. Shutemov" <[email protected]>

Change of attributes of the pages may lead to fragmentation of direct mapping over time and performance degradation as result.

With current code it's one way road: kernel tries to avoid splitting large pages, but it doesn't restore them back even if page attributes got compatible again.

Any change to the mapping may potentially allow to restore large page.

Hook up into cpa_flush() path to check if there's any pages to be recovered in PUD_SIZE range around pages we've just touched.

CPUs don't like[1] to have to have TLB entries of different size for the same memory, but looks like it's okay as long as these entries have matching attributes[2]. Therefore it's critical to flush TLB before any following changes to the mapping.

Note that we already allow for multiple TLB entries of different sizes for the same memory now in split_large_page() path. It's not a new situation.

set_memory_4k() provides a way to use 4k pages on purpose. Kernel must not remap such pages as large. Re-use one of software PTE bits to indicate such pages.

[1] See Erratum 383 of AMD Family 10h Processors
[2] https://lore.kernel.org/linux-mm/[email protected]/

[[email protected]:
* s/restore/collapse/
* update formatting per peterz
* use 'struct ptdesc' instead of 'struct page' for list of page tables to be freed
* try to collapse PMD first and if it succeeds move on to PUD as peterz suggested
* flush TLB twice: for changes done in the original CPA call and after collapsing of large pages
]

Quoted 7 lines
Quoted 4 lines

When I originally attempted this, the patch was dropped because of performance regressions. Was it addressed somehow?

I didn't realize the patch was dropped because of performance regressions, so I didn't address it.

Quoted 6 lines
Quoted 1 line

Do you remember where did the regressions show up?

https://github.com/zen-kernel/zen-kernel/issues/169

My understanding is if userspace somewhat frequently triggers set_memory_* codepath we will get a performance hit.

This version of the patch will cause smaller performance hit because it does not scan an entire PUD every time collapse_large_pages() is called.

Still, when I tweaked cpa-test to take some time measurements I see about 60% increase in the time it takes to perform set_memory operations.

Since we only really care about restoring large pages for ROX mapping, I'm going to update the patch so that we'll try to collapse large pages only from set_memory_rox().

Quoted 2 lines
Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
Signature · 2 lines
Sincerely yours,
Mike.