Skip to contentSkip to conversation

alloc_tag and module codetag section fixes

PATCH Superseded Hao Ge 2 participants 8 messages Sep 7

Subsystems (4)

v8 of 11 Superseded Latest is v11 →

lore
Share & tools
lore

Hao Ge

author reviewer
#0 lore raw

v8 cover alloc_tag and module codetag section fixes

I ran into an overflow problem in the module tag area. With profiling toggled off, the overflow check in reserve_module_tags() did not run, a module could load with more tags than the page flags can address, and re-enabling profiling then silently corrupted /proc/allocinfo. On overflow the fix shuts profiling down, releases the reservation and returns -EAGAIN, and the codetag section lands as regular module data in the same load, so the module loads without profiling.

Review of the earlier series by Sashiko turned up two more problems.

One is a race. layout_sections() and move_module() both asked codetag_needs_module_section() where a codetag section goes, and mem_profiling_support can change between the two calls, for instance when another module load overflows the tag index and shuts profiling down. move_module() then copied the codetag section to offset 0 of its regular destination and clobbered the first section placed in that region.

v7 reworks where codetag sections are allocated, on a prototype by Petr Pavlu [1]. The allocation runs before layout_sections() and the placement is decided in one step, so nothing re-asks the question and the race is gone. The retry is gone too, on -EAGAIN the section is laid out as regular module data right in the same load.

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

Following review feedback from Petr and Suren the series is now split into four patches.

Patch 1 moves release_module_tags() above reserve_module_tags(), since the failure paths now have to call it.

Patch 2 introduces SH_ENTSIZE_STANDALONE to mark sections with a separate allocation, per the ELF spec SHF_ALLOC means a section occupies memory during execution, and the percpu section does, only outside the regular module layout. It was previously excluded from the layout by clearing its SHF_ALLOC, overloading the flag with a loader-internal meaning. The mark lives in sh_entsize now, find_sec(".data..percpu") gives stable results again and apply_relocations() goes back to testing only SHF_ALLOC. The section becomes visible under /sys/module/*/sections/, reporting the boot CPU instance of the per-cpu area, and the interface is documented in the ABI docs.

Patch 3 moves the codetag allocation out of move_module() in front of layout_sections(). On overflow reserve_module_tags() shuts profiling down, releases the reservation and returns -EAGAIN, and the section is laid out as regular module data, so the module loads without profiling instead of failing. Any other error fails the load. The release and the fallback belong together, without the release rmmod hits the stale entry and panics.

Patch 4, split out per Suren's suggestion, releases the reservation when vm_module_tags_populate() fails, so that path stops leaking on its own.

Tested on an x86_64 virtual machine:

Booted without sysctl.vm.mem_profiling=1,compressed:

# cat /proc/allocinfo is fine

Booted with sysctl.vm.mem_profiling=1,compressed:

# cat /proc/allocinfo is fine
# insmod overflow_tag.ko
# dmesg
  With module overflow_tag there are too many tags to fit in 13 page
  flag bits. Memory allocation profiling is disabled!
# rmmod overflow_tag
The module loads without profiling and unloads cleanly.

Changes in v8:
- zero the separately allocated codetag memory for an SHT_NOBITS section, the tag area pages are not zeroed on allocation (Sashiko)
- .data..percpu is exported under /sys/module/*/sections/ with the boot CPU instance of the per-cpu area, and the interface is documented in the ABI docs (Petr Pavlu)
- keep a comment in apply_relocations() on how .data..percpu is relocated (Petr Pavlu)
- replace the "Based-on-a-patch-by:" tag with an in-body attribution and a numbered Link: (Andrew Morton)

Changes in v7:
- split the rework following review feedback (Petr Pavlu, Suren Baghdasaryan)
- new patch 2 marks separately allocated sections with SH_ENTSIZE_STANDALONE instead of clearing SHF_ALLOC (suggested by Petr Pavlu)
- split the populate failure release into its own patch (suggested by Suren Baghdasaryan)

Changes in v6:
- rework on Petr's prototype and allocate codetag sections before layout_sections(), the retry and its state resets are gone
- fix the layout_sections()/move_module() race (Found by Sashiko)
- release the reservation on populate failure as well (Found by Sashiko)
- only -EAGAIN keeps the fallback, other errors fail the load

Changes in v5:
- add Fixes: and Cc: stable to patch 1/2 as well, since 2/2 does not compile without it (Andrew Morton)
- restore frob-adjusted mem[type].size on retry instead of zeroing, as s390 and parisc add GOT/PLT space there in module_frob_arch_sections() (Reported by Sashiko)
- drop the load_module() mem_profiling_support check; the percpu counter leak is pre-existing and orthogonal to this fix

Changes in v4:
- add a new patch (1/2) to move release_module_tags() above reserve_module_tags(); the overflow fix is 2/2
- release the reservation on the -EAGAIN path
- return -EAGAIN instead of -ENOMEM so the module can still load without profiling (Suren)
- reset sh_addr, mem[type].size and sym/str SHF_ALLOC before retry
- skip percpu counters in load_module() when profiling is off

Changes in v3:
- use pr_warn_once() instead of pr_warn()
- return -ENOMEM instead of -ENOSPC (Suren)
- expand the commit message to describe the /proc/allocinfo impact (Andrew)

Changes in v2:
- return an error after shutdown_mem_profiling() to skip vm_module_tags_populate()

v1: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v5: https://lore.kernel.org/all/[email protected]/
v6: https://lore.kernel.org/all/[email protected]/
v7: https://lore.kernel.org/all/[email protected]/

Hao Ge (4):
alloc_tag: move release_module_tags() above reserve_module_tags()
module: introduce SH_ENTSIZE_STANDALONE for separately allocated
sections
module: allocate codetag sections before the regular module layout
alloc_tag: release the reservation when populate fails

 Documentation/ABI/testing/sysfs-module |   8 ++
 include/linux/module.h                 |   2 +
 kernel/module/internal.h               |   8 ++
 kernel/module/kallsyms.c               |  13 +--
 kernel/module/main.c                   | 138 ++++++++++++++-----------
 mm/alloc_tag.c                         | 101 +++++++++---------
 6 files changed, 149 insertions(+), 121 deletions(-)
Signature · 1 line
2.25.1
author reviewer
#1 lore raw

PATCH v8 1/4 alloc_tag: move release_module_tags() above reserve_module_tags()

release_module_tags() is a cleanup helper. reserve_module_tags() can also fail after storing the reservation in the maple tree, in which case it should call release_module_tags() to undo it. Move the helper above reserve_module_tags() so no forward declaration is needed.

No functional change.

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")
Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")
---
 mm/alloc_tag.c | 92 +++++++++++++++++++++++++-------------------------
 1 file changed, 46 insertions(+), 46 deletions(-)
mm/alloc_tag.c +46 -46
index b1d48532a25a..e7a79116ad81 100644
@@ -843,6 +843,52 @@ static int vm_module_tags_populate(void)
 	return 0;
 }
 
+static void release_module_tags(struct module *mod, bool used)
+{
+	MA_STATE(mas, &mod_area_mt, module_tags.size, module_tags.size);
+	struct alloc_tag *start_tag;
+	struct alloc_tag *end_tag;
+	struct module *val;
+
+	mas_lock(&mas);
+	mas_for_each_rev(&mas, val, 0)
+		if (val == mod)
+			break;
+
+	if (!val) /* module not found */
+		goto out;
+
+	if (!used)
+		goto release_area;
+
+	start_tag = (struct alloc_tag *)(module_tags.start_addr + mas.index);
+	end_tag = (struct alloc_tag *)(module_tags.start_addr + mas.last);
+	if (!clean_unused_counters(start_tag, end_tag)) {
+		struct alloc_tag *tag;
+
+		for (tag = start_tag; tag <= end_tag; tag++) {
+			struct alloc_tag_counters counter;
+
+			if (!tag->counters)
+				continue;
+
+			counter = alloc_tag_read(tag);
+			pr_info("%s:%u module %s func:%s has %llu allocated at module unload\n",
+				tag->ct.filename, tag->ct.lineno, tag->ct.modname,
+				tag->ct.function, counter.bytes);
+		}
+	} else {
+		used = false;
+	}
+release_area:
+	mas_store(&mas, used ? &unloaded_mod : NULL);
+	val = mas_prev_range(&mas, 0);
+	if (val == &prepend_mod)
+		mas_store(&mas, NULL);
+out:
+	mas_unlock(&mas);
+}
+
 static void *reserve_module_tags(struct module *mod, unsigned long size,
 				 unsigned int prepend, unsigned long align)
 {
@@ -930,52 +976,6 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 	return (struct alloc_tag *)(module_tags.start_addr + offset);
 }
 
-static void release_module_tags(struct module *mod, bool used)
-{
-	MA_STATE(mas, &mod_area_mt, module_tags.size, module_tags.size);
-	struct alloc_tag *start_tag;
-	struct alloc_tag *end_tag;
-	struct module *val;
-
-	mas_lock(&mas);
-	mas_for_each_rev(&mas, val, 0)
-		if (val == mod)
-			break;
-
-	if (!val) /* module not found */
-		goto out;
-
-	if (!used)
-		goto release_area;
-
-	start_tag = (struct alloc_tag *)(module_tags.start_addr + mas.index);
-	end_tag = (struct alloc_tag *)(module_tags.start_addr + mas.last);
-	if (!clean_unused_counters(start_tag, end_tag)) {
-		struct alloc_tag *tag;
-
-		for (tag = start_tag; tag <= end_tag; tag++) {
-			struct alloc_tag_counters counter;
-
-			if (!tag->counters)
-				continue;
-
-			counter = alloc_tag_read(tag);
-			pr_info("%s:%u module %s func:%s has %llu allocated at module unload\n",
-				tag->ct.filename, tag->ct.lineno, tag->ct.modname,
-				tag->ct.function, counter.bytes);
-		}
-	} else {
-		used = false;
-	}
-release_area:
-	mas_store(&mas, used ? &unloaded_mod : NULL);
-	val = mas_prev_range(&mas, 0);
-	if (val == &prepend_mod)
-		mas_store(&mas, NULL);
-out:
-	mas_unlock(&mas);
-}
-
 static int load_module(struct module *mod, struct codetag *start, struct codetag *stop)
 {
 	/* Allocate module alloc_tag percpu counters */
Signature · 1 line
2.25.1
author reviewer
#2 lore raw

PATCH v8 2/4 module: introduce SH_ENTSIZE_STANDALONE for separately allocated sections

In reply to Hao Ge

SHF_ALLOC means, per the ELF spec, that a section occupies memory during process execution. Some module sections occupy memory outside the regular module layout, for example the percpu section with its per-CPU allocations. The loader currently excludes such a section from the layout by clearing its SHF_ALLOC, which overloads the flag with a loader-internal meaning. apply_relocations() needs a special case for the section, and find_sec(".data..percpu") returns different results before and after layout_and_allocate().

Introduce SH_ENTSIZE_STANDALONE to mark sections with a separate allocation. The percpu section is its first user. layout_sections() and move_module() skip marked sections, and apply_relocations() goes back to testing only SHF_ALLOC. Based on a patch by Petr Pavlu [1].

.data..percpu keeps SHF_ALLOC, so it is now exported under /sys/module/*/sections/. Report the boot CPU instance of the module's per-CPU area there, as __is_module_percpu_address() does. No functional change otherwise.

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")
---
 Documentation/ABI/testing/sysfs-module |  8 ++++++
 include/linux/module.h                 |  2 ++
 kernel/module/internal.h               |  8 ++++++
 kernel/module/kallsyms.c               | 13 +++------
 kernel/module/main.c                   | 37 +++++++++++++++-----------
 5 files changed, 43 insertions(+), 25 deletions(-)
Documentation/ABI/testing/sysfs-module +8 -0
index d5b7d19bd310..65e152c6fa58 100644
@@ -57,6 +57,14 @@ Description:	List of symbol namespaces imported by this module via
 		This file only exists for modules that import at least one
 		namespace.
 
+What:		/sys/module/*/sections/<section>
+Date:		June 2005
+KernelVersion:	2.6.12
+Contact:	[email protected]
+Description:	The memory address of the given loaded section of the
+		module. .data..percpu has one instance per CPU; the
+		address reported is the instance of the boot CPU.
+
 What:		/sys/module/*/taint
 Date:		Jan 2012
 KernelVersion:	3.3
include/linux/module.h +2 -0
index 7566815fabbe..33548daa31a3 100644
@@ -325,6 +325,8 @@ enum mod_mem_type {
 	MOD_INIT_RODATA,
 
 	MOD_MEM_NUM_TYPES,
+
+	MOD_STANDALONE = -2,
 	MOD_INVALID = -1,
 };
 
kernel/module/internal.h +8 -0
index 061161cc79d9..4c738074a27b 100644
@@ -29,6 +29,14 @@
 #define SH_ENTSIZE_TYPE_MASK	((1UL << SH_ENTSIZE_TYPE_BITS) - 1)
 #define SH_ENTSIZE_OFFSET_MASK	((1UL << (BITS_PER_LONG - SH_ENTSIZE_TYPE_BITS)) - 1)
 
+/*
+ * Marker for sections with a separate allocation, which are not placed
+ * into mod->mem[].
+ */
+#define SH_ENTSIZE_STANDALONE					\
+	(((unsigned long)MOD_STANDALONE & SH_ENTSIZE_TYPE_MASK)	\
+	 << SH_ENTSIZE_TYPE_SHIFT)
+
 /* Maximum number of characters written by module_flags() */
 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
 
kernel/module/kallsyms.c +3 -10
index 0fc11e45df9b..49190deae61e 100644
@@ -76,7 +76,7 @@ static char elf_type(const Elf_Sym *sym, const struct load_info *info)
 }
 
 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
-			   unsigned int shnum, unsigned int pcpundx)
+			   unsigned int shnum)
 {
 	const Elf_Shdr *sec;
 	enum mod_mem_type type;
@@ -86,11 +86,6 @@ static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
 	    !src->st_name)
 		return false;
 
-#ifdef CONFIG_KALLSYMS_ALL
-	if (src->st_shndx == pcpundx)
-		return true;
-#endif
-
 	sec = sechdrs + src->st_shndx;
 	type = sec->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT;
 	if (!(sec->sh_flags & SHF_ALLOC)
@@ -131,8 +126,7 @@ void layout_symtab(struct module *mod, struct load_info *info)
 	/* Compute total space required for the core symbols' strtab. */
 	for (ndst = i = 0; i < nsrc; i++) {
 		if (i == 0 || is_livepatch_module(mod) ||
-		    is_core_symbol(src + i, info->sechdrs, info->hdr->e_shnum,
-				   info->index.pcpu)) {
+		    is_core_symbol(src + i, info->sechdrs, info->hdr->e_shnum)) {
 			strtab_size += strlen(&info->strtab[src[i].st_name]) + 1;
 			ndst++;
 		}
@@ -199,8 +193,7 @@ void add_kallsyms(struct module *mod, const struct load_info *info)
 	for (ndst = i = 0; i < kallsyms->num_symtab; i++) {
 		kallsyms->typetab[i] = elf_type(src + i, info);
 		if (i == 0 || is_livepatch_module(mod) ||
-		    is_core_symbol(src + i, info->sechdrs, info->hdr->e_shnum,
-				   info->index.pcpu)) {
+		    is_core_symbol(src + i, info->sechdrs, info->hdr->e_shnum)) {
 			ssize_t ret;
 
 			mod->core_kallsyms.typetab[ndst] =
kernel/module/main.c +22 -15
index c32f1d370b73..20b85148ad72 100644
@@ -1620,12 +1620,13 @@ static int apply_relocations(struct module *mod, const struct load_info *info)
 
 		/*
 		 * Don't bother with non-allocated sections.
-		 * An exception is the percpu section, which has separate allocations
-		 * for individual CPUs. We relocate the percpu section in the initial
-		 * ELF template and subsequently copy it to the per-CPU destinations.
+		 *
+		 * Note that .data..percpu has separate allocations for
+		 * individual CPUs. We relocate the section in the
+		 * initial ELF template and subsequently copy it to the
+		 * per-CPU destinations.
 		 */
-		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC) &&
-		    (!infosec || infosec != info->index.pcpu))
+		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
 			continue;
 
 		if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
@@ -1716,7 +1717,7 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool i
 
 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
 			    || (s->sh_flags & masks[m][1])
-			    || s->sh_entsize != ~0UL
+			    || s->sh_entsize != ~0UL /* offset or standalone */
 			    || is_init != module_init_layout_section(sname))
 				continue;
 
@@ -1746,16 +1747,10 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool i
 /*
  * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
  * might -- code, read-only data, read-write data, small data.  Tally
- * sizes, and place the offsets into sh_entsize fields: high bit means it
- * belongs in init.
+ * sizes, and place the offsets into sh_entsize fields.
  */
 static void layout_sections(struct module *mod, struct load_info *info)
 {
-	unsigned int i;
-
-	for (i = 0; i < info->hdr->e_shnum; i++)
-		info->sechdrs[i].sh_entsize = ~0UL;
-
 	pr_debug("Core section allocation order for %s:\n", mod->name);
 	__layout_sections(mod, info, false);
 
@@ -2811,7 +2806,8 @@ static int move_module(struct module *mod, struct load_info *info)
 		Elf_Shdr *shdr = &info->sechdrs[i];
 		const char *sname;
 
-		if (!(shdr->sh_flags & SHF_ALLOC))
+		if (!(shdr->sh_flags & SHF_ALLOC)
+		    || shdr->sh_entsize == SH_ENTSIZE_STANDALONE)
 			continue;
 
 		sname = info->secstrings + shdr->sh_name;
@@ -2943,6 +2939,7 @@ core_param(module_blacklist, module_blacklist, charp, 0400);
 static struct module *layout_and_allocate(struct load_info *info, int flags)
 {
 	struct module *mod;
+	unsigned int i;
 	int err;
 
 	/* Allow arches to frob section contents and sizes.  */
@@ -2956,8 +2953,13 @@ static struct module *layout_and_allocate(struct load_info *info, int flags)
 	if (err < 0)
 		return ERR_PTR(err);
 
+	/* Repurpose sh_entsize to track where each section is allocated. */
+	for (i = 0; i < info->hdr->e_shnum; i++)
+		info->sechdrs[i].sh_entsize = ~0UL;
+
 	/* We will do a special allocation for per-cpu sections later. */
-	info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
+	if (info->index.pcpu)
+		info->sechdrs[info->index.pcpu].sh_entsize = SH_ENTSIZE_STANDALONE;
 
 	/*
 	 * Mark relevant sections as SHF_RO_AFTER_INIT so layout_sections() can
@@ -3520,6 +3522,11 @@ static int load_module(struct load_info *info, const char __user *uargs,
 	if (err < 0)
 		goto free_modinfo;
 
+	/* The percpu ELF section is a template; report the boot CPU instance. */
+	if (info->index.pcpu)
+		info->sechdrs[info->index.pcpu].sh_addr =
+			(unsigned long)per_cpu_ptr(mod->percpu, get_boot_cpu_id());
+
 	flush_module_icache(mod);
 
 	/* Now copy in args */
Signature · 1 line
2.25.1
author reviewer
#3 lore raw

PATCH v8 3/4 module: allocate codetag sections before the regular module layout

In reply to Hao Ge

Whether a codetag section goes to the codetag region is decided by layout_sections() and asked again in move_module(). A concurrent load can shut profiling down in between, and move_module() then copies the section to offset 0 of its regular destination, overwriting whatever is there.

Decide and allocate in one pass, before the layout. Allocation errors fail the load. On a tag area overflow profiling is already disabled, so -EAGAIN makes the section fall back to regular module data and the module still loads.

When profiling was toggled off the overflow check did not run, a module could load with more tags than the page flags can address, and re-enabling profiling then silently corrupted /proc/allocinfo. The check no longer depends on mem_alloc_profiling_enabled().

Based on a patch by Petr Pavlu [1].

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")
---
 kernel/module/main.c | 101 +++++++++++++++++++++++--------------------
 mm/alloc_tag.c       |   8 ++--
 2 files changed, 59 insertions(+), 50 deletions(-)
kernel/module/main.c +54 -47
index 20b85148ad72..612facc51214 100644
@@ -1724,20 +1724,6 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool i
 			if (WARN_ON_ONCE(type == MOD_INVALID))
 				continue;
 
-			/*
-			 * Do not allocate codetag memory as we load it into
-			 * preallocated contiguous memory.
-			 */
-			if (codetag_needs_module_section(mod, sname, s->sh_size)) {
-				/*
-				 * s->sh_entsize won't be used but populate the
-				 * type field to avoid confusion.
-				 */
-				s->sh_entsize = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK)
-						<< SH_ENTSIZE_TYPE_SHIFT;
-				continue;
-			}
-
 			s->sh_entsize = module_get_offset_and_type(mod, type, s, i);
 			pr_debug("\t%s\n", sname);
 		}
@@ -2784,7 +2770,6 @@ static int move_module(struct module *mod, struct load_info *info)
 {
 	int i, ret;
 	enum mod_mem_type t = MOD_MEM_NUM_TYPES;
-	bool codetag_section_found = false;
 
 	for_each_mod_mem_type(type) {
 		if (!mod->mem[type].size) {
@@ -2804,35 +2789,13 @@ static int move_module(struct module *mod, struct load_info *info)
 	for (i = 0; i < info->hdr->e_shnum; i++) {
 		void *dest;
 		Elf_Shdr *shdr = &info->sechdrs[i];
-		const char *sname;
 
 		if (!(shdr->sh_flags & SHF_ALLOC)
 		    || shdr->sh_entsize == SH_ENTSIZE_STANDALONE)
 			continue;
 
-		sname = info->secstrings + shdr->sh_name;
-		/*
-		 * Load codetag sections separately as they might still be used
-		 * after module unload.
-		 */
-		if (codetag_needs_module_section(mod, sname, shdr->sh_size)) {
-			dest = codetag_alloc_module_section(mod, sname, shdr->sh_size,
-					arch_mod_section_prepend(mod, i), shdr->sh_addralign);
-			if (WARN_ON(!dest)) {
-				ret = -EINVAL;
-				goto out_err;
-			}
-			if (IS_ERR(dest)) {
-				ret = PTR_ERR(dest);
-				goto out_err;
-			}
-			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;
-
-			dest = mod->mem[type].base + offset;
-		}
+		dest = mod->mem[shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT].base +
+		       (shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK);
 
 		if (shdr->sh_type != SHT_NOBITS) {
 			/*
@@ -2864,8 +2827,6 @@ static int move_module(struct module *mod, struct load_info *info)
 	module_memory_restore_rox(mod);
 	while (t--)
 		module_memory_free(mod, t);
-	if (codetag_section_found)
-		codetag_free_module_sections(mod);
 
 	return ret;
 }
@@ -2936,6 +2897,49 @@ static bool blacklisted(const char *module_name)
 }
 core_param(module_blacklist, module_blacklist, charp, 0400);
 
+/*
+ * Allocate codetag sections separately. They are loaded into preallocated
+ * contiguous memory because they may still be used after the module is
+ * unloaded.
+ *
+ * If the separate allocation overflows, allocate the section normally
+ * so that the module can still be loaded.
+ */
+static int allocate_codetag_sections(struct load_info *info)
+{
+	for (unsigned int i = 1; i < info->hdr->e_shnum; i++) {
+		Elf_Shdr *shdr = &info->sechdrs[i];
+		const char *sname = info->secstrings + shdr->sh_name;
+		void *dest;
+
+		if (!codetag_needs_module_section(info->mod, sname, shdr->sh_size))
+			continue;
+
+		dest = codetag_alloc_module_section(info->mod, sname, shdr->sh_size,
+				arch_mod_section_prepend(info->mod, i), shdr->sh_addralign);
+		if (WARN_ON(!dest)) {
+			codetag_free_module_sections(info->mod);
+			return -EINVAL;
+		}
+		if (dest == ERR_PTR(-EAGAIN))
+			/* Allocate the section as a regular section. */
+			continue;
+		if (IS_ERR(dest)) {
+			codetag_free_module_sections(info->mod);
+			return PTR_ERR(dest);
+		}
+
+		if (shdr->sh_type != SHT_NOBITS)
+			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
+		else
+			memset(dest, 0, shdr->sh_size);
+		shdr->sh_addr = (unsigned long)dest;
+		shdr->sh_entsize = SH_ENTSIZE_STANDALONE;
+	}
+
+	return 0;
+}
+
 static struct module *layout_and_allocate(struct load_info *info, int flags)
 {
 	struct module *mod;
@@ -2968,18 +2972,21 @@ static struct module *layout_and_allocate(struct load_info *info, int flags)
 	 */
 	module_mark_ro_after_init(info->hdr, info->sechdrs, info->secstrings);
 
-	/*
-	 * Determine total sizes, and put offsets in sh_entsize.  For now
-	 * this is done generically; there doesn't appear to be any
-	 * special cases for the architectures.
-	 */
+	/* Allow codetag sections to be allocated separately first. */
+	err = allocate_codetag_sections(info);
+	if (err)
+		return ERR_PTR(err);
+
+	/* Determine total sizes and put offsets in sh_entsize. */
 	layout_sections(info->mod, info);
 	layout_symtab(info->mod, info);
 
 	/* Allocate and move to the final place */
 	err = move_module(info->mod, info);
-	if (err)
+	if (err) {
+		codetag_free_module_sections(info->mod);
 		return ERR_PTR(err);
+	}
 
 	/* Module has been copied to its final place now: return it. */
 	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
mm/alloc_tag.c +5 -3
index e7a79116ad81..248496470904 100644
@@ -958,10 +958,12 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 		int grow_res;
 
 		module_tags.size = offset + size;
-		if (mem_alloc_profiling_enabled() && !tags_addressable()) {
+		if (!tags_addressable()) {
 			shutdown_mem_profiling(true);
-			pr_warn("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
-				mod->name, NR_UNUSED_PAGEFLAG_BITS);
+			pr_warn_once("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
+				     mod->name, NR_UNUSED_PAGEFLAG_BITS);
+			release_module_tags(mod, false);
+			return ERR_PTR(-EAGAIN);
 		}
 
 		grow_res = vm_module_tags_populate();
Signature · 1 line
2.25.1
author reviewer
#5 lore raw

PATCH v8 4/4 alloc_tag: release the reservation when populate fails

In reply to Hao Ge

vm_module_tags_populate() can fail after the reservation was stored in the maple tree, and the error return leaks the entry, since a failed load never unloads the module. Release it.

Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")
---
 mm/alloc_tag.c | 1 +
 1 file changed, 1 insertion(+)
mm/alloc_tag.c +1 -0
index 248496470904..3c25475becbc 100644
@@ -971,6 +971,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 			shutdown_mem_profiling(true);
 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
 			       mod->name);
+			release_module_tags(mod, false);
 			return ERR_PTR(grow_res);
 		}
 	}
Signature · 1 line
2.25.1
#6 lore raw

Re: [PATCH v8 4/4] alloc_tag: release the reservation when populate fails

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

New issues:
- [Critical] The patch introduces a kernel crash by freeing the maple tree entry without rolling back module_tags.size on failure.

Pre-existing issues:
- [High] vmap_pages_range() failure in vm_module_tags_populate() leaves physical pages mapped while freeing them, leading to Use-After-Free.
- [High] AB-BA Deadlock between procfs read and module loading via shutdown_mem_profiling().
- [Medium] Memory leak of percpu counters when module falls back to standard section allocation.
--

commit 09d0b9820f6ab861e4c9680b44a685c8658fb571
Author: Hao Ge <[email protected]>

alloc_tag: release the reservation when populate fails

vm_module_tags_populate() can fail after a reservation is stored in the maple tree. The error return previously leaked the entry because a failed load never unloads the module. This patch calls release_module_tags() on failure to free the reservation.

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 963

Quoted 6 lines
mm/alloc_tag.c +0 -0
index 112a014d4b890..c11813cd9e153 100644
@@ -963,6 +963,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 			shutdown_mem_profiling(true);

[Severity: High]
This isn't a bug introduced by this patch, but could calling shutdown_mem_profiling(true) here risk an AB-BA deadlock?

A read to /proc/allocinfo enters proc_reg_read_iter(), taking an 'in_use' reference on the proc entry, then calls allocinfo_start() which waits for down_read(&alloc_tag_cttype->mod_lock).

Concurrently, module loading calls codetag_alloc_module_section(), holding down_write(&alloc_tag_cttype->mod_lock).

If reserve_module_tags() encounters an error, it calls shutdown_mem_profiling(true), which invokes remove_proc_entry().

Since remove_proc_entry() blocks waiting for the 'in_use' reference count to drop to zero, and the procfs reader blocks on the mod_lock held by the writer, doesn't this create a system hang during a module load failure?

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 974

Quoted 3 lines
mm/alloc_tag.c +1 -0
 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
 			       mod->name);
+			release_module_tags(mod, false);

[Severity: Critical]
Will this new call to release_module_tags() cause a kernel crash on a subsequent module load?

In reserve_module_tags(), module_tags.size is optimistically updated (module_tags.size = offset + size;) before attempting to allocate physical memory via vm_module_tags_populate().

If population fails, this patch frees the maple tree entry, but module_tags.size is left artificially inflated.

A subsequent module load will search the maple tree and reuse this freed gap. Because module_tags.size is already inflated, the allocation check bypasses vm_module_tags_populate(), returning an unmapped virtual address. Can copying section data into this address then trigger a fatal page fault?

[Severity: Medium]
This is a pre-existing issue, but might the use of release_module_tags() when falling back to a standard section allocation leak percpu counters?

If tags are not addressable, reserve_module_tags() calls release_module_tags(mod, false) to remove the module from the maple tree and returns -EAGAIN.

The module loader catches -EAGAIN and falls back to a normal section allocation. Later, load_module() successfully allocates percpu counters for the tags.

On unload, release_module_tags(mod, true) is called to free the counters. However, because the module is no longer in the maple tree, the search fails and exits early:

mm/alloc_tag.c:release_module_tags() {
    ...
    if (!val) /* module not found */
        goto out;
    ...
}

Are the percpu counters allocated during load_module() permanently leaked in this scenario?

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 975

Quoted 1 line
mm/alloc_tag.c +0 -0
 			return ERR_PTR(grow_res);

[Severity: High]
This is a pre-existing issue, but is there a risk that the failure path of vm_module_tags_populate() leaves dangling PTEs causing a Use-After-Free?

In vm_module_tags_populate(), vmap_pages_range() maps allocated pages into the kernel virtual address space.

If it fails, it returns an error but may leave successfully mapped PTEs active in the page tables. The error path calls release_pages() to free the physical pages back to the allocator, but fails to call vunmap_range():

mm/alloc_tag.c:vm_module_tags_populate() {
    ...
    if (nr < more_pages || vmap_pages_range(...) < 0) {
        release_pages(arg, nr);
        return -ENOMEM;
    }
    ...
}

Could this leave dangling PTEs with PAGE_KERNEL permissions pointing to freed pages, risking data corruption when the pages are reallocated?

Quoted 2 lines
mm/alloc_tag.c +0 -0
 		}
 	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#4 lore raw

Re: [PATCH v8 3/4] module: allocate codetag sections before the regular module layout

In reply to Hao Ge
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Per-cpu counters for allocation tags are permanently leaked on module unload if the tag area…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Per-cpu counters for allocation tags are permanently leaked on module unload if the tag area overflows during module load. --

commit 2a544bb32bf3bb065ea63ecd36207973b4aa45cd
Author: Hao Ge <[email protected]>

module: allocate codetag sections before the regular module layout

This commit modifies the module loader to decide and allocate codetag sections in one pass before the regular module layout. If the separate allocation overflows, it returns -EAGAIN so the section can fall back to being a regular module section, allowing the module to still load.

Quoted 4 lines
kernel/module/main.c +0 -0
index 9b495571d8074..c3ea72e1e412f 100644

[ ... ]

Quoted 10 lines
kernel/module/main.c +9 -0
@@ -2947,6 +2908,49 @@ static bool blacklisted(const char *module_name)
+static int allocate_codetag_sections(struct load_info *info)
+{
+	for (unsigned int i = 1; i < info->hdr->e_shnum; i++) {
+		Elf_Shdr *shdr = &info->sechdrs[i];
+		const char *sname = info->secstrings + shdr->sh_name;
+		void *dest;
+
+		if (!codetag_needs_module_section(info->mod, sname, shdr->sh_size))
+			continue;

kernel/module/main.c static bool blacklisted(const char *module_name) · line 2926

Quoted 10 lines
kernel/module/main.c +10 -0
+
+		dest = codetag_alloc_module_section(info->mod, sname, shdr->sh_size,
+				arch_mod_section_prepend(info->mod, i), shdr->sh_addralign);
+		if (WARN_ON(!dest)) {
+			codetag_free_module_sections(info->mod);
+			return -EINVAL;
+		}
+		if (dest == ERR_PTR(-EAGAIN))
+			/* Allocate the section as a regular section. */
+			continue;

[Severity: Medium]
Could this fallback mechanism cause a permanent leak of per-cpu counters when the module is unloaded?

When the module tag area overflows, reserve_module_tags() returns -EAGAIN, and this code catches it to allow the section to load normally. Later in the load process, the tags are still processed, and per-cpu counters are unconditionally allocated for each tag:

mm/alloc_tag.c:load_module() {
    ...
    tag->counters = alloc_percpu(struct alloc_tag_counters);
    ...
}

However, on module unload, release_module_tags() searches the mod_area_mt maple tree to find the module. Since the codetag section fell back to standard memory and was never added to the maple tree, the search fails:

mm/alloc_tag.c:release_module_tags() {
    ...
    if (!val) /* module not found */
        goto out;
    ...
}

This early exit completely bypasses clean_unused_counters(), leaving all those per-cpu counters allocated during load permanently leaked. Is there a way to ensure the counters are cleaned up even when the codetag section falls back to standard memory?

Quoted 15 lines
kernel/module/main.c +15 -0
+		if (IS_ERR(dest)) {
+			codetag_free_module_sections(info->mod);
+			return PTR_ERR(dest);
+		}
+
+		if (shdr->sh_type != SHT_NOBITS)
+			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
+		else
+			memset(dest, 0, shdr->sh_size);
+		shdr->sh_addr = (unsigned long)dest;
+		shdr->sh_entsize = SH_ENTSIZE_STANDALONE;
+	}
+
+	return 0;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author reviewer
#7 lore raw

Re: [PATCH v8 4/4] alloc_tag: release the reservation when populate fails

In reply to [email protected]
Quoted 58 lines · On 2026/9/7 14:43, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

New issues:
- [Critical] The patch introduces a kernel crash by freeing the maple tree entry without rolling back module_tags.size on failure.

Pre-existing issues:
- [High] vmap_pages_range() failure in vm_module_tags_populate() leaves physical pages mapped while freeing them, leading to Use-After-Free.
- [High] AB-BA Deadlock between procfs read and module loading via shutdown_mem_profiling().
- [Medium] Memory leak of percpu counters when module falls back to standard section allocation.
--

commit 09d0b9820f6ab861e4c9680b44a685c8658fb571
Author: Hao Ge <[email protected]>

alloc_tag: release the reservation when populate fails

vm_module_tags_populate() can fail after a reservation is stored in the maple tree. The error return previously leaked the entry because a failed load never unloads the module. This patch calls release_module_tags() on failure to free the reservation.

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 963

Quoted 6 lines
mm/alloc_tag.c +0 -0
index 112a014d4b890..c11813cd9e153 100644
@@ -963,6 +963,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 			shutdown_mem_profiling(true);

[Severity: High]
This isn't a bug introduced by this patch, but could calling shutdown_mem_profiling(true) here risk an AB-BA deadlock?

A read to /proc/allocinfo enters proc_reg_read_iter(), taking an 'in_use' reference on the proc entry, then calls allocinfo_start() which waits for down_read(&alloc_tag_cttype->mod_lock).

Concurrently, module loading calls codetag_alloc_module_section(), holding down_write(&alloc_tag_cttype->mod_lock).

If reserve_module_tags() encounters an error, it calls shutdown_mem_profiling(true), which invokes remove_proc_entry().

Since remove_proc_entry() blocks waiting for the 'in_use' reference count to drop to zero, and the procfs reader blocks on the mod_lock held by the writer, doesn't this create a system hang during a module load failure?

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 974

Quoted 3 lines
mm/alloc_tag.c +1 -0
 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
 			       mod->name);
+			release_module_tags(mod, false);

[Severity: Critical]
Will this new call to release_module_tags() cause a kernel crash on a subsequent module load?

In reserve_module_tags(), module_tags.size is optimistically updated (module_tags.size = offset + size;) before attempting to allocate physical memory via vm_module_tags_populate().

Quoted 8 lines

If population fails, this patch frees the maple tree entry, but module_tags.size is left artificially inflated.

A subsequent module load will search the maple tree and reuse this freed gap. Because module_tags.size is already inflated, the allocation check bypasses vm_module_tags_populate(), returning an unmapped virtual address. Can copying section data into this address then trigger a fatal page fault?

I see.

No, not for a subsequent load. The failure path shuts profiling down before returning:

grow_res = vm_module_tags_populate();

if (grow_res) {
	shutdown_mem_profiling(true); /* mem_profiling_support = false */
	...
	release_module_tags(mod, false);
	 return ERR_PTR(grow_res);
}

and any later load bails out in needs_section_mem() long before it reaches reserve_module_tags():

	if (!mem_profiling_support)
		return false;          

so no new reservation is made and the unmapped address is never handed out.

But this reminds me of another race condition:

CPU0: failing load CPU1: concurrent load
---------------------- ---------------------------
needs_section_mem(): true needs_section_mem(): true
reserve_module_tags(): reserve the gap,
module_tags.size = end
populate() fails, gap released
reserve_module_tags(): reuse the gap, end <= size -> skip populate memcpy() -> page fault

I have a fix for this, but I'd like to wait for Petr and Suren to review the remaining parts before sending it out.

Thanks
Best Regards
Hao

Quoted 54 lines

[Severity: Medium]
This is a pre-existing issue, but might the use of release_module_tags() when falling back to a standard section allocation leak percpu counters?

If tags are not addressable, reserve_module_tags() calls release_module_tags(mod, false) to remove the module from the maple tree and returns -EAGAIN.

The module loader catches -EAGAIN and falls back to a normal section allocation. Later, load_module() successfully allocates percpu counters for the tags.

On unload, release_module_tags(mod, true) is called to free the counters. However, because the module is no longer in the maple tree, the search fails and exits early:

mm/alloc_tag.c:release_module_tags() {
    ...
    if (!val) /* module not found */
        goto out;
    ...
}

Are the percpu counters allocated during load_module() permanently leaked in this scenario?

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 975

Quoted 1 line
mm/alloc_tag.c +0 -0
 			return ERR_PTR(grow_res);

[Severity: High]
This is a pre-existing issue, but is there a risk that the failure path of vm_module_tags_populate() leaves dangling PTEs causing a Use-After-Free?

In vm_module_tags_populate(), vmap_pages_range() maps allocated pages into the kernel virtual address space.

If it fails, it returns an error but may leave successfully mapped PTEs active in the page tables. The error path calls release_pages() to free the physical pages back to the allocator, but fails to call vunmap_range():

mm/alloc_tag.c:vm_module_tags_populate() {
    ...
    if (nr < more_pages || vmap_pages_range(...) < 0) {
        release_pages(arg, nr);
        return -ENOMEM;
    }
    ...
}

Could this leave dangling PTEs with PAGE_KERNEL permissions pointing to freed pages, risking data corruption when the pages are reallocated?

Quoted 2 lines
mm/alloc_tag.c +0 -0
 		}
 	}