alloc_tag and module codetag section fixes
Subsystems (6)
Hao Ge
reviewerv10 cover alloc_tag and module codetag section fixes
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 six patches. The two alloc_tag fixes from [2] are folded in as patches 5 and 6 and replace the versions currently in the mm tree. Sashiko keeps flagging the percpu counter leak [3], patch 5 fixes it, and now the whole set goes through review again.
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
Patch 1 moves release_module_tags() above reserve_module_tags(), since the failure paths now have to call it.
Patch 2 cleans up the populate failure path: the reservation is released, module_tags.size rolled back and the PTEs a failed vmap_pages_range() left behind unmapped, so a later populate of the same range is safe. It carries both Fixes tags so it backports wherever patch 4 goes, which uses its prev_size.
Patch 3 introduces SH_ENTSIZE_STANDALONE to mark sections with a separate allocation. The percpu section was previously excluded from the layout by clearing its SHF_ALLOC, which per the ELF spec says the section occupies memory during execution, and percpu does, only outside the regular module layout. 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 would show up under /sys/module/*/sections/, but it has one instance per CPU and no single address, and the entry never existed, so add_sect_attrs() and add_notes_attrs() skip it.
Patch 4 moves the codetag allocation out of move_module() in front of layout_sections(), so the placement is decided in one step and the race is gone. On overflow profiling is shut down, the reservation released, module_tags.size rolled back and -EAGAIN returned, the section is laid out as regular module data and 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 5 skips the percpu counter allocation when profiling is off. After the shutdown modules load their codetag section as regular data, load_module() still allocated counters for every tag and release_module_tags() cannot find them on unload, so they leaked (Suggested by Suren).
Patch 6 defers the /proc/allocinfo removal to a workqueue. shutdown_mem_profiling() runs under mod_lock, and the synchronous remove_proc_entry() deadlocks with a reader taking mod_lock for read in allocinfo_start(). The file is also created at the end of alloc_tag_init(), a leftover file after a failed init would panic its readers (Found by Sashiko).
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.
Also ran continuous LTP stress for a few days, nothing abnormal so far.
Changes in v10:
- fold in the two alloc_tag fixes from [2] as patches 5 and 6, they replace the versions in the mm tree and fix the percpu leak Sashiko keeps flagging [3]
- create /proc/allocinfo at the end of alloc_tag_init(), a leftover file after a failed init would panic its readers (Found by Sashiko)
- count note sections with sect_visible() in add_notes_attrs() too, the count has to match the fill loop
Changes in v9:
- do not export .data..percpu under /sys/module/*/sections/ (Petr Pavlu).
- move the populate failure cleanup in front of the rework, v8 patch 4 is patch 2 now. It declares prev_size itself, which the overflow path of the rework also uses, so it carries both Fixes tags and the two patches backport together
Changes in v8:
- roll back module_tags.size when the reservation is released, so a concurrent load which already passed needs_section_mem() does not skip populate for the freed gap (Sashiko)
- unmap the PTEs a failed vmap_pages_range() installed, a retry to populate the same range would BUG on them
- 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]/
v8: https://lore.kernel.org/all/[email protected]/
v9: https://lore.kernel.org/all/[email protected]/
Hao Ge (6):
alloc_tag: move release_module_tags() above reserve_module_tags()
alloc_tag: clean up the populate failure path
module: introduce SH_ENTSIZE_STANDALONE for separately allocated
sections
module: allocate codetag sections before the regular module layout
alloc_tag: skip percpu counter allocation when profiling is disabled
alloc_tag: Defer /proc/allocinfo removal to a workqueue
include/linux/module.h | 2 + kernel/module/internal.h | 8 +++ kernel/module/kallsyms.c | 13 +--- kernel/module/main.c | 133 +++++++++++++++++++----------------- kernel/module/sysfs.c | 17 +++-- lib/codetag.c | 10 ++- mm/alloc_tag.c | 141 +++++++++++++++++++++++---------------- 7 files changed, 188 insertions(+), 136 deletions(-)
Signature · 1 line
2.25.1
Hao Ge
reviewerPATCH v10 1/6 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.
--- mm/alloc_tag.c | 92 +++++++++++++++++++++++++------------------------- 1 file changed, 46 insertions(+), 46 deletions(-)
mm/alloc_tag.c +46 -46
@@ -835,6 +835,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) {
@@ -922,52 +968,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
Hao Ge
reviewerPATCH v10 2/6 alloc_tag: clean up the populate failure path
In reply to Hao GeThe reservation is already stored in the maple tree when vm_module_tags_populate() fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passed needs_section_mem() can reuse the freed gap, skip vm_module_tags_populate() and write to unmapped memory.
vmap_pages_range() may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
mm/alloc_tag.c +10 -0
@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page }; +/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. +*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;
@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;
@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;return ERR_PTR (grow_res); } }
Signature · 1 line
2.25.1
Suren Baghdasaryan
maintainerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 8 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
Quoted 6 lines
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")
If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Quoted 12 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 7 lines
mm/alloc_tag.c +4
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page }; +/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them.
If vmap_pages_range() failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue that vmap_pages_range() should be undoing these partial mappings itself before returning the error.
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;
mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;
Yes, this one is a valid fix. It fixes 0f9b685626da commit.
Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
Hao Ge
reviewerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.
Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls vm_module_tags_populate() again, and that retry would trip over the PTEs the failed vmap left behind.
Without the rollback a load that already passed needs_section_mem() just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.
Quoted 15 lines
Quoted 15 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };
Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.
Yeah it does - none of the paths under vmap_pages_range() undo themselves on error. pcpu_map_pages does perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.
If we really want vmap_pages_range() to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.
Thanks
Best Regards
Hao
Quoted 29 lines
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;Yes, this one is a valid fix. It fixes
0f9b685626dacommit.Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
Suren Baghdasaryan
maintainerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 29 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
Quoted 8 lines
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.
Yeah, that's why I think vmap_pages_range() cleanup should be a completely separate patch with vmap_pages_range() doing cleanup itself.
Quoted 26 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.
Quoted 1 line
Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you guys think? Shouldn't vmap_pages_range() undo its possible partial mapping when it fails?
Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Quoted 34 lines
Thanks
Best Regards
HaoQuoted 29 lines
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;Yes, this one is a valid fix. It fixes
0f9b685626dacommit.Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
Suren Baghdasaryan
maintainerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 70 lines · Suren Baghdasaryan
Quoted 29 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
Quoted 8 lines
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.Quoted 26 lines
Quoted 26 lines
Quoted 13 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 7 lines
mm/alloc_tag.c +4
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page }; +/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.
Quoted 7 lines
Quoted 1 line
Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
Quoted 50 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Quoted 34 lines
Thanks
Best Regards
HaoQuoted 29 lines
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;Yes, this one is a valid fix. It fixes
0f9b685626dacommit.Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
Hao Ge
reviewerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.
I think I get where you're coming from now.
Thanks for taking the time to explain.
Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.
Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 8 lines
Quoted 8 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 4 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Thanks
Best Regards
Hao
Quoted 34 lines
Quoted 34 lines
Quoted 34 lines
Thanks
Best Regards
HaoQuoted 29 lines
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;Yes, this one is a valid fix. It fixes
0f9b685626dacommit.Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
Hao Ge
reviewerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.
Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
I just looked into the call sites for __vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
When gfp_mask has __GFP_NOFAIL, the code keeps retrying __vmap_pages_range. If there are leftover PTE mappings,
this can trigger a BUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]
Quoted 38 lines
Thanks
Best Regards
HaoQuoted 34 lines
Quoted 34 lines
Quoted 34 lines
Thanks
Best Regards
HaoQuoted 29 lines
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;Yes, this one is a valid fix. It fixes
0f9b685626dacommit.Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
Re: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Looping in Ulad who is best placed to respond on this.
Ulad could you look at the below? Thanks! :)
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 7 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]
I think best person to look at this is Ulad as vmalloc is his baby :)
Ulad, what do you think?
Thread is at
https://lore.kernel.org/all/[email protected]/ for context.
Quoted 33 lines
Quoted 33 lines
Thanks
Best Regards
HaoQuoted 28 lines
Quoted 28 lines
Quoted 28 lines
Thanks
Best Regards
HaoQuoted 23 lines
Quoted 15 lines
mm/alloc_tag.c +4
-0+*/ +if (nr == more_pages) +vunmap_range (phys_end, phys_end + (nr <<PAGE_SHIFT ));/* Clean up and error out */ release_pages (arg, nr);return -ENOMEM ;@@ -947,6 +954,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,return ret;if (module_tags.size < offset + size) { +unsigned long prev_size = module_tags.size;int grow_res; module_tags.size = offset + size;mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 973
Quoted 5 lines
mm/alloc_tag.c +2
-0@@ -961,6 +969,8 @@ 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); + module_tags.size = prev_size;Yes, this one is a valid fix. It fixes
0f9b685626dacommit.
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
mm/alloc_tag.c +0
-1return ERR_PTR (grow_res); } } --2.25.1
--
Cheers, Lorenzo
Re: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 127 lines · Lorenzo Stoakes (ARM)
Looping in Ulad who is best placed to respond on this.
Ulad could you look at the below? Thanks! :)
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 7 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]
Quoted 8 lines
I think best person to look at this is Ulad as vmalloc is his baby :)
Ulad, what do you think?
Thread is at
https://lore.kernel.org/all/[email protected]/ for context.
Uh.. I missed this. Let me check!
--
Uladzislau Rezki
Re: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 4 lines · Uladzislau Rezki
Quoted 3 lines · Lorenzo Stoakes (ARM)
Looping in Ulad who is best placed to respond on this.
Ulad could you look at the below? Thanks! :)
...
Quoted 9 lines
Quoted 8 lines
I think best person to look at this is Ulad as vmalloc is his baby :)
Ulad, what do you think?
Thread is at
https://lore.kernel.org/all/[email protected]/ for context.Uh.. I missed this. Let me check!
Thanks! :)
Quoted 3 lines
--
Uladzislau Rezki
--
Cheers, Lorenzo
Re: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
In reply to Hao GeQuoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 8 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]
Indeed the below code is incomplete:
<snip>
/*
* page tables allocations ignore external gfp mask, enforce it
* by the scope API
*/
flags = memalloc_apply_gfp_scope(gfp_mask);
do {
ret = __vmap_pages_range(addr, addr + size, prot, area->pages,
page_shift, nested_gfp);
if (nofail && (ret < 0))
schedule_timeout_uninterruptible(1);
} while (nofail && (ret < 0));
memalloc_restore_scope(flags);<snip>
and it should be fixed. As the __vmap_pages_range() can actually fail and leave some installed mappings, we have to perform some cleanups on failure or on repeat(if nofail is true).
Below code:
+ /*
+ * vmap_pages_range() only runs once all pages were
+ * allocated, and it may have installed some mappings
+ * before failing. Undo them.
+ */
+ if (nr == more_pages)
+ vunmap_range(phys_end, phys_end + (nr << PAGE_SHIFT));
we can use but we need to check if partially mapped space is not an issue for the vunmap_range(). And it looks like it is not.
<snip>
@@ -3953,8 +3990,15 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
do {
ret = __vmap_pages_range(addr, addr + size, prot, area->pages,
page_shift, nested_gfp);- if (nofail && (ret < 0))
- schedule_timeout_uninterruptible(1);
+ if (ret < 0) {
+ /*
+ * __vmap_pages_range() may have installed some mappings + * before failing. Undo them before returning or retrying. + */
+ vunmap_range(addr, addr + size);
+ if (nofail)
+ schedule_timeout_uninterruptible(1);
+ }
} while (nofail && (ret < 0));
memalloc_restore_scope(flags);<snip>
--
Uladzislau Rezki
Re: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 167 lines · Uladzislau Rezki
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 8 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]Indeed the below code is incomplete:
<snip>
/* * page tables allocations ignore external gfp mask, enforce it * by the scope API */ flags = memalloc_apply_gfp_scope(gfp_mask); do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); if (nofail && (ret < 0)) schedule_timeout_uninterruptible(1); } while (nofail && (ret < 0)); memalloc_restore_scope(flags);<snip>
and it should be fixed. As the
__vmap_pages_range()can actually fail and leave some installed mappings, we have to perform some cleanups on failure or on repeat(if nofail is true).Below code:
(quoted diff) +7
-0+ /* + * vmap_pages_range() only runs once all pages were + * allocated, and it may have installed some mappings + * before failing. Undo them. + */ + if (nr == more_pages) + vunmap_range(phys_end, phys_end + (nr << PAGE_SHIFT));we can use but we need to check if partially mapped space is not an issue for the
vunmap_range(). And it looks like it is not.<snip>
(quoted diff) +2
-2@@ -3953,8 +3990,15 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); - if (nofail && (ret < 0)) - schedule_timeout_uninterruptible(1); + if (ret < 0) { + /*
Review static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, · line 4003
Quoted 10 lines
(quoted diff) +7
-0+ * __vmap_pages_range() may have installed some mappings + * before failing. Undo them before returning or retrying. + */ + vunmap_range(addr, addr + size); + if (nofail) + schedule_timeout_uninterruptible(1); + } } while (nofail && (ret < 0)); memalloc_restore_scope(flags);
And looking further. If the __vmap_pages_range()/__vmap_pages_range_noflush() and friends fail, a proper cleanups should be done inside, IMO.
But i am checking callers and see that some do some not:
<snip hooks.c>
__vunmap_range_noflush( vmalloc_shadow(start), vmalloc_shadow(start + clean * PAGE_SIZE)); __vunmap_range_noflush( vmalloc_origin(start), vmalloc_origin(start + clean * PAGE_SIZE));
<snip hooks.c>
kmsan_ioremap_page_range() it does clean ups; kmsan_vmap_pages_range_noflush() looks like does not care in shadow.c; __vmalloc_area_node() as noted, it is broken as there is a BUG() on next try if nofail; pcpu_map_pages() it does cleanups.
...
and so on.
--
Uladzislau Rezki
Suren Baghdasaryan
maintainerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 173 lines · Uladzislau Rezki
Quoted 171 lines · Uladzislau Rezki
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 8 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]Indeed the below code is incomplete:
<snip>
/* * page tables allocations ignore external gfp mask, enforce it * by the scope API */ flags = memalloc_apply_gfp_scope(gfp_mask); do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); if (nofail && (ret < 0)) schedule_timeout_uninterruptible(1); } while (nofail && (ret < 0)); memalloc_restore_scope(flags);<snip>
and it should be fixed. As the
__vmap_pages_range()can actually fail and leave some installed mappings, we have to perform some cleanups on failure or on repeat(if nofail is true).Below code:
(quoted diff) +7
-0+ /* + * vmap_pages_range() only runs once all pages were + * allocated, and it may have installed some mappings + * before failing. Undo them. + */ + if (nr == more_pages) + vunmap_range(phys_end, phys_end + (nr << PAGE_SHIFT));we can use but we need to check if partially mapped space is not an issue for the
vunmap_range(). And it looks like it is not.<snip>
(quoted diff) +7
-2@@ -3953,8 +3990,15 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); - if (nofail && (ret < 0)) - schedule_timeout_uninterruptible(1); + if (ret < 0) { + /* + * __vmap_pages_range() may have installed some mappings + * before failing. Undo them before returning or retrying. + */ + vunmap_range(addr, addr + size); + if (nofail)
Quoted 8 lines
Review static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, · line 4003
Quoted 6 lines
(quoted diff) +2
-0+ schedule_timeout_uninterruptible(1); + } } while (nofail && (ret < 0)); memalloc_restore_scope(flags);And looking further. If the __vmap_pages_range()/__vmap_pages_range_noflush() and friends fail, a proper cleanups should be done inside, IMO.
Sounds like we are in agreement.
Quoted 12 lines
But i am checking callers and see that some do some not:
<snip
hooks.c>__vunmap_range_noflush( vmalloc_shadow(start), vmalloc_shadow(start + clean * PAGE_SIZE)); __vunmap_range_noflush( vmalloc_origin(start), vmalloc_origin(start + clean * PAGE_SIZE));<snip
hooks.c>
Quoted 7 lines
kmsan_ioremap_page_range()it does clean ups;kmsan_vmap_pages_range_noflush()looks like does not care inshadow.c;__vmalloc_area_node()as noted, it is broken as there is aBUG()on next try if nofail;pcpu_map_pages()it does cleanups.
...and so on.
Yeah, the callers that do the cleanup should stop doing that once the vmap functions handle it themselves. I expect an overall reduction in code size.
Quoted 3 lines
--
Uladzislau Rezki
Re: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 203 lines · Suren Baghdasaryan
Quoted 173 lines · Uladzislau Rezki
Quoted 171 lines · Uladzislau Rezki
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 8 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]Indeed the below code is incomplete:
<snip>
/* * page tables allocations ignore external gfp mask, enforce it * by the scope API */ flags = memalloc_apply_gfp_scope(gfp_mask); do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); if (nofail && (ret < 0)) schedule_timeout_uninterruptible(1); } while (nofail && (ret < 0)); memalloc_restore_scope(flags);<snip>
and it should be fixed. As the
__vmap_pages_range()can actually fail and leave some installed mappings, we have to perform some cleanups on failure or on repeat(if nofail is true).Below code:
(quoted diff) +7
-0+ /* + * vmap_pages_range() only runs once all pages were + * allocated, and it may have installed some mappings + * before failing. Undo them. + */ + if (nr == more_pages) + vunmap_range(phys_end, phys_end + (nr << PAGE_SHIFT));we can use but we need to check if partially mapped space is not an issue for the
vunmap_range(). And it looks like it is not.<snip>
(quoted diff) +7
-2@@ -3953,8 +3990,15 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); - if (nofail && (ret < 0)) - schedule_timeout_uninterruptible(1); + if (ret < 0) { + /* + * __vmap_pages_range() may have installed some mappings + * before failing. Undo them before returning or retrying. + */ + vunmap_range(addr, addr + size); + if (nofail)Quoted 8 lines
Review static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, · line 4003
Quoted 6 lines
(quoted diff) +2
-0+ schedule_timeout_uninterruptible(1); + } } while (nofail && (ret < 0)); memalloc_restore_scope(flags);And looking further. If the __vmap_pages_range()/__vmap_pages_range_noflush() and friends fail, a proper cleanups should be done inside, IMO.
Sounds like we are in agreement.
Quoted 18 lines
But i am checking callers and see that some do some not:
<snip
hooks.c>__vunmap_range_noflush( vmalloc_shadow(start), vmalloc_shadow(start + clean * PAGE_SIZE)); __vunmap_range_noflush( vmalloc_origin(start), vmalloc_origin(start + clean * PAGE_SIZE));<snip
hooks.c>
kmsan_ioremap_page_range()it does clean ups;kmsan_vmap_pages_range_noflush()looks like does not care inshadow.c;__vmalloc_area_node()as noted, it is broken as there is aBUG()on next try if nofail;pcpu_map_pages()it does cleanups.
...
Quoted 6 lines
Quoted 1 line
and so on.
Yeah, the callers that do the cleanup should stop doing that once the vmap functions handle it themselves. I expect an overall reduction in code size.
Agree. If mapping API is called and it fails the caller should expect the state as it was before calling that API function, IMO.
--
Uladzislau Rezki
Suren Baghdasaryan
maintainerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Quoted 205 lines · Uladzislau Rezki
Quoted 203 lines · Suren Baghdasaryan
Quoted 173 lines · Uladzislau Rezki
Quoted 171 lines · Uladzislau Rezki
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 8 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]Indeed the below code is incomplete:
<snip>
/* * page tables allocations ignore external gfp mask, enforce it * by the scope API */ flags = memalloc_apply_gfp_scope(gfp_mask); do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); if (nofail && (ret < 0)) schedule_timeout_uninterruptible(1); } while (nofail && (ret < 0)); memalloc_restore_scope(flags);<snip>
and it should be fixed. As the
__vmap_pages_range()can actually fail and leave some installed mappings, we have to perform some cleanups on failure or on repeat(if nofail is true).Below code:
(quoted diff) +7
-0+ /* + * vmap_pages_range() only runs once all pages were + * allocated, and it may have installed some mappings + * before failing. Undo them. + */ + if (nr == more_pages) + vunmap_range(phys_end, phys_end + (nr << PAGE_SHIFT));we can use but we need to check if partially mapped space is not an issue for the
vunmap_range(). And it looks like it is not.<snip>
(quoted diff) +7
-2@@ -3953,8 +3990,15 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); - if (nofail && (ret < 0)) - schedule_timeout_uninterruptible(1); + if (ret < 0) { + /* + * __vmap_pages_range() may have installed some mappings + * before failing. Undo them before returning or retrying. + */ + vunmap_range(addr, addr + size); + if (nofail)Quoted 8 lines
Review static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, · line 4003
Quoted 6 lines
(quoted diff) +2
-0+ schedule_timeout_uninterruptible(1); + } } while (nofail && (ret < 0)); memalloc_restore_scope(flags);And looking further. If the __vmap_pages_range()/__vmap_pages_range_noflush() and friends fail, a proper cleanups should be done inside, IMO.
Sounds like we are in agreement.
Quoted 18 lines
But i am checking callers and see that some do some not:
<snip
hooks.c>__vunmap_range_noflush( vmalloc_shadow(start), vmalloc_shadow(start + clean * PAGE_SIZE)); __vunmap_range_noflush( vmalloc_origin(start), vmalloc_origin(start + clean * PAGE_SIZE));<snip
hooks.c>
kmsan_ioremap_page_range()it does clean ups;kmsan_vmap_pages_range_noflush()looks like does not care inshadow.c;__vmalloc_area_node()as noted, it is broken as there is aBUG()on next try if nofail;pcpu_map_pages()it does cleanups.
...
Quoted 8 lines
Quoted 6 lines
Quoted 1 line
and so on.
Yeah, the callers that do the cleanup should stop doing that once the vmap functions handle it themselves. I expect an overall reduction in code size.
Agree. If mapping API is called and it fails the caller should expect the state as it was before calling that API function, IMO.
Thanks for confirmation!
Hao, do you need help with making the change in vmap functions to cleanup upon a failure?
Quoted 3 lines
--
Uladzislau Rezki
Hao Ge
reviewerRe: [PATCH v10 2/6] alloc_tag: clean up the populate failure path
Hi Suren and Uladzislau
Quoted 212 lines · Suren Baghdasaryan
Quoted 211 lines · Uladzislau Rezki
Quoted 209 lines · Suren Baghdasaryan
Quoted 173 lines · Uladzislau Rezki
Quoted 171 lines · Uladzislau Rezki
Quoted 114 lines · Hao Ge
Hi Suren、David、Lorenzo
Quoted 103 lines · Hao Ge
Hi Suren
Quoted 37 lines · Suren Baghdasaryan
Quoted 36 lines · Suren Baghdasaryan
Quoted 34 lines · Hao Ge
Hi Suren
Thanks for you review.
Quoted 13 lines · Suren Baghdasaryan
Quoted 12 lines · Hao Ge
The reservation is already stored in the maple tree when
vm_module_tags_populate()fails. A failed load never unloads the module, so nothing releases the entry. Release it and roll module_tags.size back. Without the rollback a concurrent load that already passedneeds_section_mem()can reuse the freed gap, skipvm_module_tags_populate()and write to unmapped memory.
vmap_pages_range()may have installed some PTEs before failing. A retry to populate the same range would BUG on them, so undo them, but only if vmap actually ran.Quoted 7 lines
Quoted 2 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Fixes 0f9b685626da ("alloc_tag: populate memory for module tags as needed")If a patch fixes two other patches, it likely needs to be split so that each part fixes one patch only. But read on please. I'm not sure if one of the fixes is correct.
Kept them in one patch because they only make sense together.
After a failed populate the reservation is released and the size rolled back, so the next load takes the same gap and calls
vm_module_tags_populate()again, and that retry would trip over the PTEs the failed vmap left behind.Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Without the rollback a load that already passed
needs_section_mem()just reuses the gap, skips populate and writes to unmapped memory. So splitting them leaves each half broken.Yeah, that's why I think
vmap_pages_range()cleanup should be a completely separate patch withvmap_pages_range()doing cleanup itself.I think I get where you're coming from now.
Thanks for taking the time to explain.Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 16 lines
Quoted 16 lines
--- mm/alloc_tag.c | 10 ++++++++++ 1 file changed, 10 insertions(+)mm/alloc_tag.c +0
-0@@ -804,6 +804,13 @@ static int vm_module_tags_populate(void) next_page, PAGE_SHIFT) < 0) {release_pages_arg arg = { .pages = next_page };Quoted 10 lines
mm/alloc_tag.c static int vm_module_tags_populate(void) · line 810
Quoted 4 lines
mm/alloc_tag.c +4
-0+/* +* vmap_pages_range() only runs once all pages were +* allocated, and it may have installed some mappings +* before failing. Undo them. If
vmap_pages_range()failed to map the range, why should we need to undo it? If it indeed leaves some partial mapping when failing then I would argue thatvmap_pages_range()should be undoing these partial mappings itself before returning the error.Yeah it does - none of the paths under
vmap_pages_range()undo themselves on error.Quoted 8 lines
Quoted 5 lines
Hmm. I wonder if this behavior is intentional or requires a fix. The only possible reason I can think of is performance but I can't imagine a failure to map is a performance-critical case.
+David Hildenbrand (Red Hat), +Lorenzo Stoakes (Oracle) what do you
Huh, my gmail thinks you are still at your previous companies :)
I manually fixed it on the mailing list for this thread.
Quoted 12 lines
Quoted 12 lines
guys think? Shouldn't
vmap_pages_range()undo its possible partial mapping when it fails?Quoted 7 lines
pcpu_map_pagesdoes perform cleanup on its own as well. There may be other similar sites.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/percpu-vm.c#L255
so I did the same here.If we really want
vmap_pages_range()to handle this cleanup internally, I believe that would be a relatively large change, and we would need to consider many more cases. So I think we keep the current behaviour for now.Quoted 7 lines
Quoted 4 lines
Quoted 4 lines
Yeah, I understand it would require a deeper cut but if that's the right way to handle this we might as well do that. Let's see what MM folks think.
Sounds good to me. Let's wait and hear what the MM folks say.
Quoted 8 lines
I just looked into the call sites for
__vmap_pages_range. And I found there's a bug in one vmalloc caller [1].
Whengfp_maskhas__GFP_NOFAIL, the code keeps retrying__vmap_pages_range. If there are leftover PTE mappings,
this can trigger aBUG(); [2]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L3946 [1]
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/vmalloc.c#L121 [2]Indeed the below code is incomplete:
<snip>
/* * page tables allocations ignore external gfp mask, enforce it * by the scope API */ flags = memalloc_apply_gfp_scope(gfp_mask); do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); if (nofail && (ret < 0)) schedule_timeout_uninterruptible(1); } while (nofail && (ret < 0)); memalloc_restore_scope(flags);<snip>
and it should be fixed. As the
__vmap_pages_range()can actually fail and leave some installed mappings, we have to perform some cleanups on failure or on repeat(if nofail is true).Below code:
(quoted diff) +7
-0+ /* + * vmap_pages_range() only runs once all pages were + * allocated, and it may have installed some mappings + * before failing. Undo them. + */ + if (nr == more_pages) + vunmap_range(phys_end, phys_end + (nr << PAGE_SHIFT));we can use but we need to check if partially mapped space is not an issue for the
vunmap_range(). And it looks like it is not.<snip>
(quoted diff) +7
-2@@ -3953,8 +3990,15 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, do { ret = __vmap_pages_range(addr, addr + size, prot, area->pages, page_shift, nested_gfp); - if (nofail && (ret < 0)) - schedule_timeout_uninterruptible(1); + if (ret < 0) { + /* + * __vmap_pages_range() may have installed some mappings + * before failing. Undo them before returning or retrying. + */ + vunmap_range(addr, addr + size); + if (nofail)Quoted 8 lines
Review static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, · line 4003
Quoted 6 lines
(quoted diff) +2
-0+ schedule_timeout_uninterruptible(1); + } } while (nofail && (ret < 0)); memalloc_restore_scope(flags);And looking further. If the __vmap_pages_range()/__vmap_pages_range_noflush() and friends fail, a proper cleanups should be done inside, IMO.
Sounds like we are in agreement.
Quoted 12 lines
But i am checking callers and see that some do some not:
<snip
hooks.c>__vunmap_range_noflush( vmalloc_shadow(start), vmalloc_shadow(start + clean * PAGE_SIZE)); __vunmap_range_noflush( vmalloc_origin(start), vmalloc_origin(start + clean * PAGE_SIZE));<snip
hooks.c>Quoted 7 lines
kmsan_ioremap_page_range()it does clean ups;kmsan_vmap_pages_range_noflush()looks like does not care inshadow.c;__vmalloc_area_node()as noted, it is broken as there is aBUG()on next try if nofail;pcpu_map_pages()it does cleanups.
...and so on.
Yeah, the callers that do the cleanup should stop doing that once the vmap functions handle it themselves. I expect an overall reduction in code size.
Quoted 8 lines
Quoted 2 lines
Agree. If mapping API is called and it fails the caller should expect the state as it was before calling that API function, IMO.
Thanks for confirmation!
Hao, do you need help with making the change in vmap functions to cleanup upon a failure?
Thanks everyone for your help. I think we have reached a consensus. I spent a day sorting out the logic and generated the patches below:
https://lore.kernel.org/all/[email protected]/
Some edge cases might still be missing, please kindly review.
Thanks
Best Regards
Hao
Quoted 3 lines
Quoted 3 lines
--
Uladzislau Rezki
Hao Ge
reviewerPATCH v10 3/6 module: introduce SH_ENTSIZE_STANDALONE for separately allocated sections
In reply to Hao GeSHF_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 would now show up under /sys/module/*/sections/. The section has one instance per CPU and no single address to report, and the entry never existed before, so skip it in add_sect_attrs(). add_notes_attrs() indexes its attrs[] array and skips it too. No functional change otherwise.
--- include/linux/module.h | 2 ++ kernel/module/internal.h | 8 ++++++++ kernel/module/kallsyms.c | 13 +++---------- kernel/module/main.c | 32 +++++++++++++++++--------------- kernel/module/sysfs.c | 17 +++++++++++++---- 5 files changed, 43 insertions(+), 29 deletions(-)
include/linux/module.h +2 -0
@@ -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
@@ -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
@@ -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 +17 -15
@@ -1619,12 +1619,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 )
@@ -1715,7 +1716,7 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool iif ((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 ;
@@ -1745,16 +1746,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);
@@ -2822,7 +2817,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;
@@ -2954,6 +2950,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. */
@@ -2967,8 +2964,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
kernel/module/sysfs.c +13 -4
@@ -62,6 +62,15 @@ static void free_sect_attrs(struct module_sect_attrs *sect_attrs)kfree (sect_attrs); } +/* +* .data..percpu has a separate allocation per CPU and no single +* address to report. +*/ +static bool sect_visible (const struct load_info *info,unsigned int i) +{ +return !sect_empty (&info->sechdrs[i]) && i != info->index.pcpu; +} +static int add_sect_attrs (struct module *mod,const struct load_info *info) {struct module_sect_attrs *sect_attrs;
@@ -72,7 +81,7 @@ static int add_sect_attrs(struct module *mod, const struct load_info *info)/* Count loaded sections and allocate structures */ for (i =0 ; i < info->hdr->e_shnum; i++) -if (!sect_empty (&info->sechdrs[i])) +if (sect_visible (info, i)) nloaded++; sect_attrs =kzalloc_flex (*sect_attrs, attrs, nloaded);if (!sect_attrs)
@@ -92,7 +101,7 @@ static int add_sect_attrs(struct module *mod, const struct load_info *info)for (i =0 ; i < info->hdr->e_shnum; i++) {Elf_Shdr *sec = &info->sechdrs[i]; -if (sect_empty (sec)) +if (!sect_visible (info, i))continue ;sysfs_bin_attr_init (sattr); sattr->attr.name =
@@ -159,7 +168,7 @@ static int add_notes_attrs(struct module *mod, const struct load_info *info)/* Count notes sections and allocate structures. */ notes =0 ;for (i =0 ; i < info->hdr->e_shnum; i++) -if (!sect_empty (&info->sechdrs[i]) && +if (sect_visible (info, i) && info->sechdrs[i].sh_type ==SHT_NOTE ) ++notes;
@@ -181,7 +190,7 @@ static int add_notes_attrs(struct module *mod, const struct load_info *info) nattr = ¬es_attrs->attrs[0 ];for (loaded = i =0 ; i < info->hdr->e_shnum; ++i) { -if (sect_empty (&info->sechdrs[i])) +if (!sect_visible (info, i))continue ;if (info->sechdrs[i].sh_type ==SHT_NOTE ) {sysfs_bin_attr_init (nattr);
Signature · 1 line
2.25.1
Re: [PATCH v10 3/6] module: introduce SH_ENTSIZE_STANDALONE for separately allocated sections
Quoted 16 lines · Hao Ge
SHF_ALLOCmeans, 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 itsSHF_ALLOC, which overloads the flag with a loader-internal meaning.apply_relocations()needs a special case for the section, andfind_sec(".data..percpu")returns different results before and afterlayout_and_allocate().Introduce
SH_ENTSIZE_STANDALONEto mark sections with a separate allocation. The percpu section is its first user.layout_sections()andmove_module()skip marked sections, andapply_relocations()goes back to testing onlySHF_ALLOC. Based on a patch by Petr Pavlu [1].
Quoted 5 lines
.data..percpu keeps
SHF_ALLOC, so it would now show up under/sys/module/*/sections/. The section has one instance per CPU and no single address to report, and the entry never existed before, so skip it inadd_sect_attrs().add_notes_attrs()indexes its attrs[] array and skips it too. No functional change otherwise.
And IIUC no userspace-visible changes too, right?
Quoted 8 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Reported-by Sashiko <[email protected]>Suggested-by Petr Pavlu <[email protected]>Reviewed-by Petr Pavlu <[email protected]>Signed-off-by Hao Ge <[email protected]>
Quoted 227 lines
--- include/linux/module.h | 2 ++ kernel/module/internal.h | 8 ++++++++ kernel/module/kallsyms.c | 13 +++---------- kernel/module/main.c | 32 +++++++++++++++++--------------- kernel/module/sysfs.c | 17 +++++++++++++---- 5 files changed, 43 insertions(+), 29 deletions(-)include/linux/module.h +2
-0@@ -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@@ -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@@ -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 +17
-15@@ -1619,12 +1619,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 )@@ -1715,7 +1716,7 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool iif ((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 ;@@ -1745,16 +1746,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);@@ -2822,7 +2817,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;@@ -2954,6 +2950,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. */ @@ -2967,8 +2964,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 kernel/module/sysfs.c +13
-5@@ -62,6 +62,15 @@ static void free_sect_attrs(struct module_sect_attrs *sect_attrs)kfree (sect_attrs); } +/* +* .data..percpu has a separate allocation per CPU and no single +* address to report. +*/ +static bool sect_visible (const struct load_info *info,unsigned int i) +{ +return !sect_empty (&info->sechdrs[i]) && i != info->index.pcpu; +} +static int add_sect_attrs (struct module *mod,const struct load_info *info) {struct module_sect_attrs *sect_attrs;@@ -72,7 +81,7 @@ static int add_sect_attrs(struct module *mod, const struct load_info *info)/* Count loaded sections and allocate structures */ for (i =0 ; i < info->hdr->e_shnum; i++) -if (!sect_empty (&info->sechdrs[i])) +if (sect_visible (info, i)) nloaded++; sect_attrs =kzalloc_flex (*sect_attrs, attrs, nloaded);if (!sect_attrs)@@ -92,7 +101,7 @@ static int add_sect_attrs(struct module *mod, const struct load_info *info)for (i =0 ; i < info->hdr->e_shnum; i++) {Elf_Shdr *sec = &info->sechdrs[i]; -if (sect_empty (sec)) +if (!sect_visible (info, i))continue ;sysfs_bin_attr_init (sattr); sattr->attr.name =@@ -159,7 +168,7 @@ static int add_notes_attrs(struct module *mod, const struct load_info *info)/* Count notes sections and allocate structures. */ notes =0 ;for (i =0 ; i < info->hdr->e_shnum; i++) -if (!sect_empty (&info->sechdrs[i]) && +if (sect_visible (info, i) && info->sechdrs[i].sh_type ==SHT_NOTE ) ++notes;@@ -181,7 +190,7 @@ static int add_notes_attrs(struct module *mod, const struct load_info *info) nattr = ¬es_attrs->attrs[0 ];for (loaded = i =0 ; i < info->hdr->e_shnum; ++i) { -if (sect_empty (&info->sechdrs[i])) +if (!sect_visible (info, i))continue ;if (info->sechdrs[i].sh_type ==SHT_NOTE ) {sysfs_bin_attr_init (nattr); --2.25.1
Hao Ge
reviewerRe: [PATCH v10 3/6] module: introduce SH_ENTSIZE_STANDALONE for separately allocated sections
Hi Suren
Quoted 17 lines · Suren Baghdasaryan
Quoted 16 lines · Hao Ge
SHF_ALLOCmeans, 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 itsSHF_ALLOC, which overloads the flag with a loader-internal meaning.apply_relocations()needs a special case for the section, andfind_sec(".data..percpu")returns different results before and afterlayout_and_allocate().Introduce
SH_ENTSIZE_STANDALONEto mark sections with a separate allocation. The percpu section is its first user.layout_sections()andmove_module()skip marked sections, andapply_relocations()goes back to testing onlySHF_ALLOC. Based on a patch by Petr Pavlu [1].
Quoted 8 lines
Quoted 5 lines
.data..percpu keeps
SHF_ALLOC, so it would now show up under/sys/module/*/sections/. The section has one instance per CPU and no single address to report, and the entry never existed before, so skip it inadd_sect_attrs().add_notes_attrs()indexes its attrs[] array and skips it too. No functional change otherwise.And IIUC no userspace-visible changes too, right?
Right, I'll fold this into the commit message for the next version:
"No functional or userspace-visible changes otherwise."
Quoted 11 lines
Quoted 8 lines
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Reported-by Sashiko <[email protected]>Suggested-by Petr Pavlu <[email protected]>Reviewed-by Petr Pavlu <[email protected]>Signed-off-by Hao Ge <[email protected]>Reviewed-by Suren Baghdasaryan <[email protected]>
Thanks.
Best Regards
Hao
Quoted 227 lines
Quoted 227 lines
--- include/linux/module.h | 2 ++ kernel/module/internal.h | 8 ++++++++ kernel/module/kallsyms.c | 13 +++---------- kernel/module/main.c | 32 +++++++++++++++++--------------- kernel/module/sysfs.c | 17 +++++++++++++---- 5 files changed, 43 insertions(+), 29 deletions(-)include/linux/module.h +2
-0@@ -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@@ -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@@ -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 +17
-15@@ -1619,12 +1619,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 )@@ -1715,7 +1716,7 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool iif ((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 ;@@ -1745,16 +1746,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);@@ -2822,7 +2817,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;@@ -2954,6 +2950,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. */ @@ -2967,8 +2964,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 kernel/module/sysfs.c +13
-5@@ -62,6 +62,15 @@ static void free_sect_attrs(struct module_sect_attrs *sect_attrs)kfree (sect_attrs); } +/* +* .data..percpu has a separate allocation per CPU and no single +* address to report. +*/ +static bool sect_visible (const struct load_info *info,unsigned int i) +{ +return !sect_empty (&info->sechdrs[i]) && i != info->index.pcpu; +} +static int add_sect_attrs (struct module *mod,const struct load_info *info) {struct module_sect_attrs *sect_attrs;@@ -72,7 +81,7 @@ static int add_sect_attrs(struct module *mod, const struct load_info *info)/* Count loaded sections and allocate structures */ for (i =0 ; i < info->hdr->e_shnum; i++) -if (!sect_empty (&info->sechdrs[i])) +if (sect_visible (info, i)) nloaded++; sect_attrs =kzalloc_flex (*sect_attrs, attrs, nloaded);if (!sect_attrs)@@ -92,7 +101,7 @@ static int add_sect_attrs(struct module *mod, const struct load_info *info)for (i =0 ; i < info->hdr->e_shnum; i++) {Elf_Shdr *sec = &info->sechdrs[i]; -if (sect_empty (sec)) +if (!sect_visible (info, i))continue ;sysfs_bin_attr_init (sattr); sattr->attr.name =@@ -159,7 +168,7 @@ static int add_notes_attrs(struct module *mod, const struct load_info *info)/* Count notes sections and allocate structures. */ notes =0 ;for (i =0 ; i < info->hdr->e_shnum; i++) -if (!sect_empty (&info->sechdrs[i]) && +if (sect_visible (info, i) && info->sechdrs[i].sh_type ==SHT_NOTE ) ++notes;@@ -181,7 +190,7 @@ static int add_notes_attrs(struct module *mod, const struct load_info *info) nattr = ¬es_attrs->attrs[0 ];for (loaded = i =0 ; i < info->hdr->e_shnum; ++i) { -if (sect_empty (&info->sechdrs[i])) +if (!sect_visible (info, i))continue ;if (info->sechdrs[i].sh_type ==SHT_NOTE ) {sysfs_bin_attr_init (nattr); --2.25.1
Hao Ge
reviewerPATCH v10 4/6 module: allocate codetag sections before the regular module layout
In reply to Hao GeWhether 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. The reservation is released and module_tags.size rolled back, so a concurrent load which already passed needs_section_mem() does not skip vm_module_tags_populate().
An SHT_NOBITS codetag section is zeroed explicitly, the tag area pages are not zeroed on allocation.
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].
--- kernel/module/main.c | 101 +++++++++++++++++++++++-------------------- mm/alloc_tag.c | 9 ++-- 2 files changed, 60 insertions(+), 50 deletions(-)
kernel/module/main.c +54 -47
@@ -1723,20 +1723,6 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool iif (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); }
@@ -2795,7 +2781,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) {
@@ -2815,35 +2800,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 ) {/*
@@ -2875,8 +2838,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; }
@@ -2947,6 +2908,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;
@@ -2979,18 +2983,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 +6 -3
@@ -958,10 +958,13 @@ 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); + module_tags.size = prev_size; +return ERR_PTR (-EAGAIN ); } grow_res =vm_module_tags_populate ();
Signature · 1 line
2.25.1
Re: [PATCH v10 4/6] module: allocate codetag sections before the regular module layout
Quoted 22 lines · Hao Ge
Whether a codetag section goes to the codetag region is decided by
layout_sections()and asked again inmove_module(). A concurrent load can shut profiling down in between, andmove_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
-EAGAINmakes the section fall back to regular module data and the module still loads. The reservation is released and module_tags.size rolled back, so a concurrent load which already passedneeds_section_mem()does not skipvm_module_tags_populate().An
SHT_NOBITScodetag section is zeroed explicitly, the tag area pages are not zeroed on allocation.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 onmem_alloc_profiling_enabled().
Quoted 8 lines
Based on a patch by Petr Pavlu [1].
Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Reported-by Sashiko <[email protected]>Reviewed-by Petr Pavlu <[email protected]>Signed-off-by Hao Ge <[email protected]>
Makes the logic much simpler. Thanks!
Quoted 187 lines
--- kernel/module/main.c | 101 +++++++++++++++++++++++-------------------- mm/alloc_tag.c | 9 ++-- 2 files changed, 60 insertions(+), 50 deletions(-)kernel/module/main.c +54
-47@@ -1723,20 +1723,6 @@ static void __layout_sections(struct module *mod, struct load_info *info, bool iif (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); }@@ -2795,7 +2781,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) {@@ -2815,35 +2800,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 ) {/* @@ -2875,8 +2838,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; }@@ -2947,6 +2908,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;@@ -2979,18 +2983,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 +6
-4@@ -958,10 +958,13 @@ 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); + module_tags.size = prev_size; +return ERR_PTR (-EAGAIN ); } grow_res =vm_module_tags_populate (); --2.25.1
Hao Ge
reviewerPATCH v10 5/6 alloc_tag: skip percpu counter allocation when profiling is disabled
In reply to Hao GeAfter shutdown_mem_profiling() clears mem_profiling_support, needs_section_mem() returns false, so later modules have their codetag section placed as regular data and never enter the alloc_tag maple tree. codetag_load_module() still called load_module(), which allocated a percpu counter for every tag; release_module_tags() could not find these modules on unload, so the counters leaked.
Return -EOPNOTSUPP from load_module() when profiling is off:codetag_module_init() drops the module's cmod, no counters are allocated and the module loads without its tags. codetag_unload_module() now always calls free_section_mem(), since a module whose module_load() returned -EOPNOTSUPP is not in the idr but may still hold a reserved section.
--- lib/codetag.c | 10 ++++++++-- mm/alloc_tag.c | 4 ++++ 2 files changed, 12 insertions(+), 2 deletions(-)
lib/codetag.c +8 -2
@@ -240,7 +240,9 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)if (err <0 ) {kfree (cmod); -return err; +/* -EOPNOTSUPP means we can load the module without its tag. */ +if (err != -EOPNOTSUPP ) +return err; }return 0 ;
@@ -388,7 +390,11 @@ void codetag_unload_module(struct module *mod) ++cttype->content_id; }up_write (&cttype->mod_lock); -if (found && cttype->desc.free_section_mem) +/* +* A module whose module_load() returned -EOPNOTSUPP is not +* in the idr but may still hold reserved section memory. +*/ +if (cttype->desc.free_section_mem) cttype->desc.free_section_mem (mod, true); }mutex_unlock (&codetag_lock);
mm/alloc_tag.c +4 -0
@@ -988,6 +988,10 @@ static int load_module(struct module *mod, struct codetag *start, struct codetagstruct alloc_tag *stop_tag;struct alloc_tag *tag; +/* Profiling disabled: load the module without its tags. */ +if (!mem_profiling_support) +return -EOPNOTSUPP ; +/* percpu counters for core allocations are already statically allocated */ if (!mod)return 0 ;
Signature · 1 line
2.25.1
Suren Baghdasaryan
maintainerRe: [PATCH v10 5/6] alloc_tag: skip percpu counter allocation when profiling is disabled
Quoted 14 lines · Hao Ge
After
shutdown_mem_profiling()clearsmem_profiling_support,needs_section_mem()returns false, so later modules have their codetag section placed as regular data and never enter thealloc_tagmaple tree.codetag_load_module()still calledload_module(), which allocated a percpu counter for every tag;release_module_tags()could not find these modules on unload, so the counters leaked.Return
-EOPNOTSUPPfromload_module()when profiling is off:codetag_module_init()drops the module's cmod, no counters are allocated and the module loads without its tags.codetag_unload_module()now always callsfree_section_mem(), since a module whosemodule_load()returned-EOPNOTSUPPis not in the idr but may still hold a reserved section.
Quoted 5 lines
Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Suggested-by Suren Baghdasaryan <[email protected]>
Yeah, I guess I didn't think about alternatives...
When mem_profiling_support=false, why can't load_module() skip allocating percpu counters, zero out the whole area between start_tag and stop_tag and return 0 as success (mem_profiling_support is not enabled, so we acted accordingly)?
Module will be added into maple tree and later codetag_unload_module() will find the module, call release_module_tags() (which is a NOOP because tag->counter==NULL) and finally call free_section_mem(). This seems more natural than special-casing with EOPNOTSUPP. WDYT?
Quoted 52 lines
Signed-off-by Hao Ge <[email protected]>--- lib/codetag.c | 10 ++++++++-- mm/alloc_tag.c | 4 ++++ 2 files changed, 12 insertions(+), 2 deletions(-)lib/codetag.c +8
-2@@ -240,7 +240,9 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)if (err <0 ) {kfree (cmod); -return err; +/* -EOPNOTSUPP means we can load the module without its tag. */ +if (err != -EOPNOTSUPP ) +return err; }return 0 ;@@ -388,7 +390,11 @@ void codetag_unload_module(struct module *mod) ++cttype->content_id; }up_write (&cttype->mod_lock); -if (found && cttype->desc.free_section_mem) +/* +* A module whose module_load() returned -EOPNOTSUPP is not +* in the idr but may still hold reserved section memory. +*/ +if (cttype->desc.free_section_mem) cttype->desc.free_section_mem (mod, true); }mutex_unlock (&codetag_lock);mm/alloc_tag.c +4
-1@@ -988,6 +988,10 @@ static int load_module(struct module *mod, struct codetag *start, struct codetagstruct alloc_tag *stop_tag;struct alloc_tag *tag; +/* Profiling disabled: load the module without its tags. */ +if (!mem_profiling_support) +return -EOPNOTSUPP ; +/* percpu counters for core allocations are already statically allocated */ if (!mod)return 0 ; --2.25.1
Hao Ge
reviewerRe: [PATCH v10 5/6] alloc_tag: skip percpu counter allocation when profiling is disabled
Hi Suren
Quoted 23 lines · Suren Baghdasaryan
Quoted 14 lines · Hao Ge
After
shutdown_mem_profiling()clearsmem_profiling_support,needs_section_mem()returns false, so later modules have their codetag section placed as regular data and never enter thealloc_tagmaple tree.codetag_load_module()still calledload_module(), which allocated a percpu counter for every tag;release_module_tags()could not find these modules on unload, so the counters leaked.Return
-EOPNOTSUPPfromload_module()when profiling is off:codetag_module_init()drops the module's cmod, no counters are allocated and the module loads without its tags.codetag_unload_module()now always callsfree_section_mem(), since a module whosemodule_load()returned-EOPNOTSUPPis not in the idr but may still hold a reserved section.Quoted 5 lines
Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Suggested-by Suren Baghdasaryan <[email protected]>Yeah, I guess I didn't think about alternatives...
Quoted 9 lines
When mem_profiling_support=false, why can't
load_module()skip allocating percpu counters, zero out the whole area betweenstart_tagandstop_tagand return 0 as success (mem_profiling_supportis not enabled, so we acted accordingly)?
Module will be added into maple tree and latercodetag_unload_module()will find the module, callrelease_module_tags()(which is a NOOP because tag->counter==NULL) and finally callfree_section_mem(). This seems more natural than special-casing with EOPNOTSUPP. WDYT?
I see, but the module would then sit in the idr with NULL-counter tags that become visible to readers which today never expect that state.
alloc_tag_top_users calls codetag_next_ct() to find the next codetag and alloc_tag_read() would do per_cpu_ptr(NULL) for each cpu - plain pointer arithmetic onto a wild address, an oops straight out of the OOM report.
https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/alloc_tag.c#L503
So if the codetag section within this codetag_type ends up meaningless, is there a reason we still return success? We will still maintain cttype->count and allocate a slot for this module inside mod_idr.
I'd rather keep the -EOPNOTSUPP version (your original suggestion), also because the comments in load_module() and codetag_module_init() already document this scenario.
WDYT?
Thanks
Best Regards
Hao
Quoted 52 lines
Quoted 52 lines
Signed-off-by Hao Ge <[email protected]>--- lib/codetag.c | 10 ++++++++-- mm/alloc_tag.c | 4 ++++ 2 files changed, 12 insertions(+), 2 deletions(-)lib/codetag.c +8
-2@@ -240,7 +240,9 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)if (err <0 ) {kfree (cmod); -return err; +/* -EOPNOTSUPP means we can load the module without its tag. */ +if (err != -EOPNOTSUPP ) +return err; }return 0 ;@@ -388,7 +390,11 @@ void codetag_unload_module(struct module *mod) ++cttype->content_id; }up_write (&cttype->mod_lock); -if (found && cttype->desc.free_section_mem) +/* +* A module whose module_load() returned -EOPNOTSUPP is not +* in the idr but may still hold reserved section memory. +*/ +if (cttype->desc.free_section_mem) cttype->desc.free_section_mem (mod, true); }mutex_unlock (&codetag_lock);mm/alloc_tag.c +4
-1@@ -988,6 +988,10 @@ static int load_module(struct module *mod, struct codetag *start, struct codetagstruct alloc_tag *stop_tag;struct alloc_tag *tag; +/* Profiling disabled: load the module without its tags. */ +if (!mem_profiling_support) +return -EOPNOTSUPP ; +/* percpu counters for core allocations are already statically allocated */ if (!mod)return 0 ; --2.25.1
Re: [PATCH v10 5/6] alloc_tag: skip percpu counter allocation when profiling is disabled
Quoted 51 lines · Hao Ge
Hi Suren
Quoted 23 lines · Suren Baghdasaryan
Quoted 14 lines · Hao Ge
After
shutdown_mem_profiling()clearsmem_profiling_support,needs_section_mem()returns false, so later modules have their codetag section placed as regular data and never enter thealloc_tagmaple tree.codetag_load_module()still calledload_module(), which allocated a percpu counter for every tag;release_module_tags()could not find these modules on unload, so the counters leaked.Return
-EOPNOTSUPPfromload_module()when profiling is off:codetag_module_init()drops the module's cmod, no counters are allocated and the module loads without its tags.codetag_unload_module()now always callsfree_section_mem(), since a module whosemodule_load()returned-EOPNOTSUPPis not in the idr but may still hold a reserved section.Quoted 5 lines
Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Suggested-by Suren Baghdasaryan <[email protected]>Yeah, I guess I didn't think about alternatives...
Quoted 9 lines
When mem_profiling_support=false, why can't
load_module()skip allocating percpu counters, zero out the whole area betweenstart_tagandstop_tagand return 0 as success (mem_profiling_supportis not enabled, so we acted accordingly)?
Module will be added into maple tree and latercodetag_unload_module()will find the module, callrelease_module_tags()(which is a NOOP because tag->counter==NULL) and finally callfree_section_mem(). This seems more natural than special-casing with EOPNOTSUPP. WDYT?I see, but the module would then sit in the idr with NULL-counter tags that become visible to readers which today never expect that state.
alloc_tag_top_userscallscodetag_next_ct()to find the next codetag andalloc_tag_read()would doper_cpu_ptr(NULL)for each cpu - plain pointer arithmetic onto a wild address, an oops straight out of the OOM report.https://elixir.bootlin.com/linux/v7.3-rc3/source/mm/alloc_tag.c#L503
So if the codetag section within this
codetag_typeends up meaningless, is there a reason we still return success? We will still maintaincttype->countand allocate a slot for this module insidemod_idr.
Quoted 5 lines
I'd rather keep the
-EOPNOTSUPPversion (your original suggestion), also because the comments inload_module()andcodetag_module_init()already document this scenario.WDYT?
Ok, fair enough. I think your current fix is the simplest way to resolve this issue, so let's keep it simple.
Quoted 57 lines
Thanks
Best Regards
HaoQuoted 52 lines
Quoted 52 lines
Signed-off-by Hao Ge <[email protected]>--- lib/codetag.c | 10 ++++++++-- mm/alloc_tag.c | 4 ++++ 2 files changed, 12 insertions(+), 2 deletions(-)lib/codetag.c +8
-2@@ -240,7 +240,9 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)if (err <0 ) {kfree (cmod); -return err; +/* -EOPNOTSUPP means we can load the module without its tag. */ +if (err != -EOPNOTSUPP ) +return err; }return 0 ;@@ -388,7 +390,11 @@ void codetag_unload_module(struct module *mod) ++cttype->content_id; }up_write (&cttype->mod_lock); -if (found && cttype->desc.free_section_mem) +/* +* A module whose module_load() returned -EOPNOTSUPP is not +* in the idr but may still hold reserved section memory. +*/ +if (cttype->desc.free_section_mem) cttype->desc.free_section_mem (mod, true); }mutex_unlock (&codetag_lock);mm/alloc_tag.c +4
-1@@ -988,6 +988,10 @@ static int load_module(struct module *mod, struct codetag *start, struct codetagstruct alloc_tag *stop_tag;struct alloc_tag *tag; +/* Profiling disabled: load the module without its tags. */ +if (!mem_profiling_support) +return -EOPNOTSUPP ; +/* percpu counters for core allocations are already statically allocated */ if (!mod)return 0 ; --2.25.1
Hao Ge
reviewerPATCH v10 6/6 alloc_tag: Defer /proc/allocinfo removal to a workqueue
In reply to Hao Geshutdown_mem_profiling() calls remove_proc_entry() from reserve_module_tags(), which runs under mod_lock held for write. remove_proc_entry() waits for readers, and a reader takes mod_lock for read in allocinfo_start():
CPU0 (insmod) CPU1 (read /proc/allocinfo)
---------------- ----------------------------
reserve_module_tags()
down_write(&mod_lock) [held]
use_pde() [in_use++]
allocinfo_start()
down_read(&mod_lock) <- blocks
shutdown_mem_profiling()
remove_proc_entry()
wait for in_use == 0 <- blocksMove remove_proc_entry() to a workqueue.
The file creation is moved to the end of alloc_tag_init() as well. If alloc_tag_init() fails with alloc_tag_cttype still NULL or an error pointer, a concurrent reader of the leftover file would dereference it in allocinfo_start() and panic.
--- mm/alloc_tag.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)
mm/alloc_tag.c +17 -9
@@ -15,6 +15,7 @@#include <linux/seq_file.h> #include <linux/string_choices.h> #include <linux/vmalloc.h> +#include <linux/workqueue.h> #include <linux/kmemleak.h> #include <uapi/linux/alloc_tag.h>
@@ -591,6 +592,13 @@ void pgalloc_tag_swap(struct folio *new, struct folio *old)put_page_tag_ref (handle_new); } +static void remove_allocinfo_file (struct work_struct *work) +{ +remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +} + +static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file); +static void shutdown_mem_profiling (bool remove_file) {if (mem_alloc_profiling_enabled ())
@@ -600,7 +608,7 @@ static void shutdown_mem_profiling(bool remove_file)return ;if (remove_file) -remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +schedule_work (&remove_allocinfo_work); mem_profiling_support = false; }
@@ -1358,16 +1366,10 @@ static int __init alloc_tag_init(void)return 0 ; } -if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { -pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); -shutdown_mem_profiling (false); -return -ENOMEM ; - } - res =alloc_mod_tags_mem ();if (res) {pr_err ("Failed to reserve address space for module tags, errno = %d\n" , res); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return res; }
@@ -1375,10 +1377,16 @@ static int __init alloc_tag_init(void)if (IS_ERR (alloc_tag_cttype)) {pr_err ("Allocation tags registration failed, errno = %pe\n" , alloc_tag_cttype);free_mod_tags_mem (); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return PTR_ERR (alloc_tag_cttype); } +if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { +pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); +shutdown_mem_profiling (false); +return -ENOMEM ; + } +return 0 ; }module_init (alloc_tag_init);
Signature · 1 line
2.25.1
[email protected]
AI reviewRe: [PATCH v10 6/6] alloc_tag: Defer /proc/allocinfo removal to a workqueue
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm: memory leak in alloc_tag_init() when proc_create() fails --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm: memory leak in alloc_tag_init() when proc_create() fails
--
commit 4e566e12e21d0ae73ee9a25235cceeeff9cef087
Author: Hao Ge <[email protected]>
alloc_tag: Defer /proc/allocinfo removal to a workqueue
shutdown_mem_profiling() calls remove_proc_entry() from reserve_module_tags(), which runs under mod_lock held for write. remove_proc_entry() waits for readers, and a reader takes mod_lock for read in allocinfo_start(). This commit moves remove_proc_entry() to a workqueue and relocates file creation to avoid panics.
Quoted 4 lines
mm/alloc_tag.c +0
-0
[ ... ]
Quoted 21 lines
mm/alloc_tag.c +1
-7@@ -1358,16 +1366,10 @@ static int __init alloc_tag_init(void)return 0 ; } -if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { -pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); -shutdown_mem_profiling (false); -return -ENOMEM ; - } - res =alloc_mod_tags_mem ();if (res) {pr_err ("Failed to reserve address space for module tags, errno = %d\n" , res); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return res; }@@ -1375,10 +1377,16 @@ static int __init alloc_tag_init(void)if (IS_ERR (alloc_tag_cttype)) {pr_err ("Allocation tags registration failed, errno = %pe\n" , alloc_tag_cttype);
mm/alloc_tag.c static int __init alloc_tag_init(void) · line 1387
Quoted 10 lines
mm/alloc_tag.c +5
-1free_mod_tags_mem (); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return PTR_ERR (alloc_tag_cttype); } +if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { +pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); +shutdown_mem_profiling (false); +return -ENOMEM ;
[Severity: Medium]
Does this code leak the memory allocated by alloc_mod_tags_mem()?
Since the proc_create() call was relocated to execute after alloc_mod_tags_mem(), this error path seems to exit without unwinding the previous allocation by calling free_mod_tags_mem(), directly introducing a memory leak when procfs creation fails in mm/alloc_tag.c:alloc_tag_init().
Quoted 5 lines
mm/alloc_tag.c +2
-0+ } +return 0 ; }module_init (alloc_tag_init);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Suren Baghdasaryan
maintainerRe: [PATCH v10 6/6] alloc_tag: Defer /proc/allocinfo removal to a workqueue
In reply to Hao GeQuoted 87 lines · Hao Ge
shutdown_mem_profiling()callsremove_proc_entry()fromreserve_module_tags(), which runs undermod_lockheld for write.remove_proc_entry()waits for readers, and a reader takesmod_lockfor read inallocinfo_start():CPU0 (insmod) CPU1 (read
/proc/allocinfo)
---------------- ----------------------------
reserve_module_tags()down_write(&mod_lock) [held] use_pde() [in_use++] allocinfo_start() down_read(&mod_lock) <- blocks shutdown_mem_profiling() remove_proc_entry() wait for in_use == 0 <- blocksMove
remove_proc_entry()to a workqueue.The file creation is moved to the end of
alloc_tag_init()as well. Ifalloc_tag_init()fails withalloc_tag_cttypestill NULL or an error pointer, a concurrent reader of the leftover file would dereference it inallocinfo_start()and panic.Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Signed-off-by Hao Ge <[email protected]>--- mm/alloc_tag.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)mm/alloc_tag.c +10
-8@@ -15,6 +15,7 @@#include <linux/seq_file.h> #include <linux/string_choices.h> #include <linux/vmalloc.h> +#include <linux/workqueue.h> #include <linux/kmemleak.h> #include <uapi/linux/alloc_tag.h> @@ -591,6 +592,13 @@ void pgalloc_tag_swap(struct folio *new, struct folio *old)put_page_tag_ref (handle_new); } +static void remove_allocinfo_file (struct work_struct *work) +{ +remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +} + +static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file); +static void shutdown_mem_profiling (bool remove_file) {if (mem_alloc_profiling_enabled ())@@ -600,7 +608,7 @@ static void shutdown_mem_profiling(bool remove_file)return ;if (remove_file) -remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +schedule_work (&remove_allocinfo_work); mem_profiling_support = false; }@@ -1358,16 +1366,10 @@ static int __init alloc_tag_init(void)return 0 ; } -if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { -pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); -shutdown_mem_profiling (false); -return -ENOMEM ; - } - res =alloc_mod_tags_mem ();if (res) {pr_err ("Failed to reserve address space for module tags, errno = %d\n" , res); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return res; }@@ -1375,10 +1377,16 @@ static int __init alloc_tag_init(void)if (IS_ERR (alloc_tag_cttype)) {
mm/alloc_tag.c static int __init alloc_tag_init(void) · line 1386
Quoted 10 lines
mm/alloc_tag.c +4
-1pr_err ("Allocation tags registration failed, errno = %pe\n" , alloc_tag_cttype);free_mod_tags_mem (); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return PTR_ERR (alloc_tag_cttype); } +if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { +pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); +shutdown_mem_profiling (false);
You need free_mod_tags_mem() here.
Quoted 9 lines
mm/alloc_tag.c +3
-1+return -ENOMEM ; + } +return 0 ; }module_init (alloc_tag_init); --2.25.1
Hao Ge
reviewerRe: [PATCH v10 6/6] alloc_tag: Defer /proc/allocinfo removal to a workqueue
Hi Suren
Quoted 95 lines · Suren Baghdasaryan
Quoted 94 lines · Hao Ge
shutdown_mem_profiling()callsremove_proc_entry()fromreserve_module_tags(), which runs undermod_lockheld for write.remove_proc_entry()waits for readers, and a reader takesmod_lockfor read inallocinfo_start():CPU0 (insmod) CPU1 (read
/proc/allocinfo)
---------------- ----------------------------
reserve_module_tags()down_write(&mod_lock) [held] use_pde() [in_use++] allocinfo_start() down_read(&mod_lock) <- blocks shutdown_mem_profiling() remove_proc_entry() wait for in_use == 0 <- blocksMove
remove_proc_entry()to a workqueue.The file creation is moved to the end of
alloc_tag_init()as well. Ifalloc_tag_init()fails withalloc_tag_cttypestill NULL or an error pointer, a concurrent reader of the leftover file would dereference it inallocinfo_start()and panic.Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Signed-off-by Hao Ge <[email protected]>--- mm/alloc_tag.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)mm/alloc_tag.c +11
-9@@ -15,6 +15,7 @@#include <linux/seq_file.h> #include <linux/string_choices.h> #include <linux/vmalloc.h> +#include <linux/workqueue.h> #include <linux/kmemleak.h> #include <uapi/linux/alloc_tag.h> @@ -591,6 +592,13 @@ void pgalloc_tag_swap(struct folio *new, struct folio *old)put_page_tag_ref (handle_new); } +static void remove_allocinfo_file (struct work_struct *work) +{ +remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +} + +static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file); +static void shutdown_mem_profiling (bool remove_file) {if (mem_alloc_profiling_enabled ())@@ -600,7 +608,7 @@ static void shutdown_mem_profiling(bool remove_file)return ;if (remove_file) -remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +schedule_work (&remove_allocinfo_work); mem_profiling_support = false; }@@ -1358,16 +1366,10 @@ static int __init alloc_tag_init(void)return 0 ; } -if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { -pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); -shutdown_mem_profiling (false); -return -ENOMEM ; - } - res =alloc_mod_tags_mem ();if (res) {pr_err ("Failed to reserve address space for module tags, errno = %d\n" , res); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return res; }@@ -1375,10 +1377,16 @@ static int __init alloc_tag_init(void)if (IS_ERR (alloc_tag_cttype)) {pr_err ("Allocation tags registration failed, errno = %pe\n" , alloc_tag_cttype);free_mod_tags_mem (); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return PTR_ERR (alloc_tag_cttype); }
Quoted 6 lines
mm/alloc_tag.c static int __init alloc_tag_init(void) · line 1386
Quoted 3 lines
mm/alloc_tag.c +3
-0+if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { +pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); +shutdown_mem_profiling (false);You need
free_mod_tags_mem()here.
Right. Another problem is exposed here: moving proc_create() to the end implies successful return from codetag_register_type(),
so alloc_tag is already added into codetag_types.
That looks a bit odd to me. Because all places inside codetag that access this linked list will access this incompletely‑initialized codetag_type. There is currently no matching unregister interface to tear it down. So I drafted one previously:
void codetag_unregister_type(struct codetag_type *cttype)
{
struct codetag_module *cmod;
unsigned long id, tmp;
mutex_lock(&codetag_lock);
list_del(&cttype->link);
mutex_unlock(&codetag_lock);
codetag_lock_module_list(cttype);
idr_for_each_entry_ul(&cttype->mod_idr, cmod, tmp, id)
kfree(cmod);
idr_destroy(&cttype->mod_idr);
codetag_unlock_module_list(cttype);
kfree(cttype);
}But looking back, do we really need to do this? I'm not so sure.
I previously thought the issue reported by Sashiko was a false positive, and I laid out my thoughts back then:
https://lore.kernel.org/all/[email protected]/
and I thought the change would be straightforward, and defensive programming felt acceptable to me, but it turns out to be a little more complex than I expected.
Suren, could you help me analyze this? Thank you very much for your valuable feedback
Thanks
Best Regards
Hao
Quoted 9 lines
Quoted 9 lines
mm/alloc_tag.c +3
-1+return -ENOMEM ; + } +return 0 ; }module_init (alloc_tag_init); --2.25.1
Suren Baghdasaryan
maintainerRe: [PATCH v10 6/6] alloc_tag: Defer /proc/allocinfo removal to a workqueue
Quoted 132 lines · Hao Ge
Hi Suren
Quoted 95 lines · Suren Baghdasaryan
Quoted 94 lines · Hao Ge
shutdown_mem_profiling()callsremove_proc_entry()fromreserve_module_tags(), which runs undermod_lockheld for write.remove_proc_entry()waits for readers, and a reader takesmod_lockfor read inallocinfo_start():CPU0 (insmod) CPU1 (read
/proc/allocinfo)
---------------- ----------------------------
reserve_module_tags()down_write(&mod_lock) [held] use_pde() [in_use++] allocinfo_start() down_read(&mod_lock) <- blocks shutdown_mem_profiling() remove_proc_entry() wait for in_use == 0 <- blocksMove
remove_proc_entry()to a workqueue.The file creation is moved to the end of
alloc_tag_init()as well. Ifalloc_tag_init()fails withalloc_tag_cttypestill NULL or an error pointer, a concurrent reader of the leftover file would dereference it inallocinfo_start()and panic.Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Signed-off-by Hao Ge <[email protected]>--- mm/alloc_tag.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)mm/alloc_tag.c +11
-9@@ -15,6 +15,7 @@#include <linux/seq_file.h> #include <linux/string_choices.h> #include <linux/vmalloc.h> +#include <linux/workqueue.h> #include <linux/kmemleak.h> #include <uapi/linux/alloc_tag.h> @@ -591,6 +592,13 @@ void pgalloc_tag_swap(struct folio *new, struct folio *old)put_page_tag_ref (handle_new); } +static void remove_allocinfo_file (struct work_struct *work) +{ +remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +} + +static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file); +static void shutdown_mem_profiling (bool remove_file) {if (mem_alloc_profiling_enabled ())@@ -600,7 +608,7 @@ static void shutdown_mem_profiling(bool remove_file)return ;if (remove_file) -remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +schedule_work (&remove_allocinfo_work); mem_profiling_support = false; }@@ -1358,16 +1366,10 @@ static int __init alloc_tag_init(void)return 0 ; } -if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { -pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); -shutdown_mem_profiling (false); -return -ENOMEM ; - } - res =alloc_mod_tags_mem ();if (res) {pr_err ("Failed to reserve address space for module tags, errno = %d\n" , res); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return res; }@@ -1375,10 +1377,16 @@ static int __init alloc_tag_init(void)if (IS_ERR (alloc_tag_cttype)) {pr_err ("Allocation tags registration failed, errno = %pe\n" , alloc_tag_cttype);free_mod_tags_mem (); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return PTR_ERR (alloc_tag_cttype); }Quoted 6 lines
mm/alloc_tag.c static int __init alloc_tag_init(void) · line 1386
Quoted 3 lines
mm/alloc_tag.c +3
-0+if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { +pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); +shutdown_mem_profiling (false);You need
free_mod_tags_mem()here.Right. Another problem is exposed here: moving
proc_create()to the end implies successful return fromcodetag_register_type(),
soalloc_tagis already added intocodetag_types.
That looks a bit odd to me. Because all places inside codetag that access this linked list will access this incompletely‑initializedcodetag_type. There is currently no matching unregister interface to tear it down. So I drafted one previously:
voidcodetag_unregister_type(struct codetag_type *cttype){ struct codetag_module *cmod; unsigned long id, tmp; mutex_lock(&codetag_lock); list_del(&cttype->link); mutex_unlock(&codetag_lock); codetag_lock_module_list(cttype); idr_for_each_entry_ul(&cttype->mod_idr, cmod, tmp, id) kfree(cmod); idr_destroy(&cttype->mod_idr); codetag_unlock_module_list(cttype); kfree(cttype); }
Quoted 1 line
But looking back, do we really need to do this? I'm not so sure.
I think having codetag_unregister_type() would be a good idea. For now it's used only in this failure case, so we can make it an __init function and not waste any memory at all.
Quoted 21 lines
I previously thought the issue reported by Sashiko was a false positive, and I laid out my thoughts back then:
https://lore.kernel.org/all/[email protected]/
and I thought the change would be straightforward, and defensive programming felt acceptable to me, but it turns out to be a little more complex than I expected.Suren, could you help me analyze this? Thank you very much for your valuable feedback
Thanks
Best Regards
HaoQuoted 9 lines
Quoted 9 lines
mm/alloc_tag.c +3
-1+return -ENOMEM ; + } +return 0 ; }module_init (alloc_tag_init); --2.25.1
Hao Ge
reviewerRe: [PATCH v10 6/6] alloc_tag: Defer /proc/allocinfo removal to a workqueue
Hi Suren
Quoted 130 lines · Suren Baghdasaryan
Quoted 129 lines · Hao Ge
Hi Suren
Quoted 95 lines · Suren Baghdasaryan
Quoted 94 lines · Hao Ge
shutdown_mem_profiling()callsremove_proc_entry()fromreserve_module_tags(), which runs undermod_lockheld for write.remove_proc_entry()waits for readers, and a reader takesmod_lockfor read inallocinfo_start():CPU0 (insmod) CPU1 (read
/proc/allocinfo)
---------------- ----------------------------
reserve_module_tags()down_write(&mod_lock) [held] use_pde() [in_use++] allocinfo_start() down_read(&mod_lock) <- blocks shutdown_mem_profiling() remove_proc_entry() wait for in_use == 0 <- blocksMove
remove_proc_entry()to a workqueue.The file creation is moved to the end of
alloc_tag_init()as well. Ifalloc_tag_init()fails withalloc_tag_cttypestill NULL or an error pointer, a concurrent reader of the leftover file would dereference it inallocinfo_start()and panic.Reported-by Sashiko <[email protected]>Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")Signed-off-by Hao Ge <[email protected]>--- mm/alloc_tag.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)mm/alloc_tag.c +11
-9@@ -15,6 +15,7 @@#include <linux/seq_file.h> #include <linux/string_choices.h> #include <linux/vmalloc.h> +#include <linux/workqueue.h> #include <linux/kmemleak.h> #include <uapi/linux/alloc_tag.h> @@ -591,6 +592,13 @@ void pgalloc_tag_swap(struct folio *new, struct folio *old)put_page_tag_ref (handle_new); } +static void remove_allocinfo_file (struct work_struct *work) +{ +remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +} + +static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file); +static void shutdown_mem_profiling (bool remove_file) {if (mem_alloc_profiling_enabled ())@@ -600,7 +608,7 @@ static void shutdown_mem_profiling(bool remove_file)return ;if (remove_file) -remove_proc_entry (ALLOCINFO_FILE_NAME ,NULL ); +schedule_work (&remove_allocinfo_work); mem_profiling_support = false; }@@ -1358,16 +1366,10 @@ static int __init alloc_tag_init(void)return 0 ; } -if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { -pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); -shutdown_mem_profiling (false); -return -ENOMEM ; - } - res =alloc_mod_tags_mem ();if (res) {pr_err ("Failed to reserve address space for module tags, errno = %d\n" , res); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return res; }@@ -1375,10 +1377,16 @@ static int __init alloc_tag_init(void)if (IS_ERR (alloc_tag_cttype)) {pr_err ("Allocation tags registration failed, errno = %pe\n" , alloc_tag_cttype);free_mod_tags_mem (); -shutdown_mem_profiling (true); +shutdown_mem_profiling (false);return PTR_ERR (alloc_tag_cttype); }Quoted 6 lines
mm/alloc_tag.c static int __init alloc_tag_init(void) · line 1386
Quoted 3 lines
mm/alloc_tag.c +3
-0+if (!proc_create (ALLOCINFO_FILE_NAME ,0400 ,NULL , &allocinfo_proc_ops)) { +pr_err ("Failed to create %s file\n" ,ALLOCINFO_FILE_NAME ); +shutdown_mem_profiling (false);You need
free_mod_tags_mem()here.Right. Another problem is exposed here: moving
proc_create()to the end implies successful return fromcodetag_register_type(),
soalloc_tagis already added intocodetag_types.
That looks a bit odd to me. Because all places inside codetag that access this linked list will access this incompletely‑initializedcodetag_type. There is currently no matching unregister interface to tear it down. So I drafted one previously:
voidcodetag_unregister_type(struct codetag_type *cttype){ struct codetag_module *cmod; unsigned long id, tmp; mutex_lock(&codetag_lock); list_del(&cttype->link); mutex_unlock(&codetag_lock); codetag_lock_module_list(cttype); idr_for_each_entry_ul(&cttype->mod_idr, cmod, tmp, id) kfree(cmod); idr_destroy(&cttype->mod_idr); codetag_unlock_module_list(cttype);
Quoted 9 lines
Quoted 4 lines
kfree(cttype); }But looking back, do we really need to do this? I'm not so sure.
I think having
codetag_unregister_type()would be a good idea. For now it's used only in this failure case, so we can make it an__initfunction and not waste any memory at all.
Thank you for the valuable suggestion, I will take this approach. I've found there could be a race condition with alloc_tag_top_users. I'll analyze it.
Thanks
Best Regards
Hao
Quoted 21 lines
Quoted 21 lines
I previously thought the issue reported by Sashiko was a false positive, and I laid out my thoughts back then:
https://lore.kernel.org/all/[email protected]/
and I thought the change would be straightforward, and defensive programming felt acceptable to me, but it turns out to be a little more complex than I expected.Suren, could you help me analyze this? Thank you very much for your valuable feedback
Thanks
Best Regards
HaoQuoted 9 lines
Quoted 9 lines
mm/alloc_tag.c +3
-1+return -ENOMEM ; + } +return 0 ; }module_init (alloc_tag_init); --2.25.1
Suren Baghdasaryan
maintainerQuoted 81 lines · Hao Ge
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()andmove_module()both askedcodetag_needs_module_section()where a codetag section goes, andmem_profiling_supportcan 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-EAGAINthe 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 six patches. The two
alloc_tagfixes from [2] are folded in as patches 5 and 6 and replace the versions currently in the mm tree. Sashiko keeps flagging the percpu counter leak [3], patch 5 fixes it, and now the whole set goes through review again.[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/Patch 1 moves
release_module_tags()abovereserve_module_tags(), since the failure paths now have to call it.Patch 2 cleans up the populate failure path: the reservation is released, module_tags.size rolled back and the PTEs a failed
vmap_pages_range()left behind unmapped, so a later populate of the same range is safe. It carries both Fixes tags so it backports wherever patch 4 goes, which uses itsprev_size.Patch 3 introduces
SH_ENTSIZE_STANDALONEto mark sections with a separate allocation. The percpu section was previously excluded from the layout by clearing itsSHF_ALLOC, which per the ELF spec says the section occupies memory during execution, and percpu does, only outside the regular module layout. The mark lives insh_entsizenow,find_sec(".data..percpu")gives stable results again andapply_relocations()goes back to testing onlySHF_ALLOC. The section would show up under/sys/module/*/sections/, but it has one instance per CPU and no single address, and the entry never existed, soadd_sect_attrs()andadd_notes_attrs()skip it.Patch 4 moves the codetag allocation out of
move_module()in front oflayout_sections(), so the placement is decided in one step and the race is gone. On overflow profiling is shut down, the reservation released, module_tags.size rolled back and-EAGAINreturned, the section is laid out as regular module data and 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 5 skips the percpu counter allocation when profiling is off. After the shutdown modules load their codetag section as regular data,
load_module()still allocated counters for every tag andrelease_module_tags()cannot find them on unload, so they leaked (Suggested by Suren).Patch 6 defers the
/proc/allocinforemoval to a workqueue.shutdown_mem_profiling()runs undermod_lock, and the synchronousremove_proc_entry()deadlocks with a reader takingmod_lockfor read inallocinfo_start(). The file is also created at the end ofalloc_tag_init(), a leftover file after a failed init would panic its readers (Found by Sashiko).Tested on an
x86_64virtual machine:Booted without sysctl.vm.mem_profiling=1,compressed:
Quoted 8 lines
# cat /proc/allocinfo is fineBooted 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!
Do you have your overflow_tag module posted anywhere in public (github perhaps?)
Quoted 116 lines
# rmmod overflow_tag The module loads without profiling and unloads cleanly.Also ran continuous LTP stress for a few days, nothing abnormal so far.
Changes in v10:
- fold in the twoalloc_tagfixes from [2] as patches 5 and 6, they replace the versions in the mm tree and fix the percpu leak Sashiko keeps flagging [3]
- create/proc/allocinfoat the end ofalloc_tag_init(), a leftover file after a failed init would panic its readers (Found by Sashiko)
- count note sections withsect_visible()inadd_notes_attrs()too, the count has to match the fill loopChanges in v9:
- do not export .data..percpu under/sys/module/*/sections/(Petr Pavlu).
- move the populate failure cleanup in front of the rework, v8 patch 4 is patch 2 now. It declaresprev_sizeitself, which the overflow path of the rework also uses, so it carries both Fixes tags and the two patches backport togetherChanges in v8:
- roll back module_tags.size when the reservation is released, so a concurrent load which already passedneeds_section_mem()does not skip populate for the freed gap (Sashiko)
- unmap the PTEs a failedvmap_pages_range()installed, a retry to populate the same range would BUG on them
- zero the separately allocated codetag memory for anSHT_NOBITSsection, 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 inapply_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 withSH_ENTSIZE_STANDALONEinstead of clearingSHF_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 beforelayout_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-EAGAINkeeps the fallback, other errors fail the loadChanges 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 inmodule_frob_arch_sections()(Reported by Sashiko)
- drop theload_module()mem_profiling_supportcheck; the percpu counter leak is pre-existing and orthogonal to this fixChanges in v4:
- add a new patch (1/2) to moverelease_module_tags()abovereserve_module_tags(); the overflow fix is 2/2
- release the reservation on the-EAGAINpath
- return-EAGAINinstead of-ENOMEMso the module can still load without profiling (Suren)
- resetsh_addr, mem[type].size and sym/strSHF_ALLOCbefore retry
- skip percpu counters inload_module()when profiling is offChanges in v3:
- usepr_warn_once()instead ofpr_warn()
- return-ENOMEMinstead of-ENOSPC(Suren)
- expand the commit message to describe the/proc/allocinfoimpact (Andrew)Changes in v2:
- return an error aftershutdown_mem_profiling()to skipvm_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]/
v8: https://lore.kernel.org/all/[email protected]/
v9: https://lore.kernel.org/all/[email protected]/Hao Ge (6):
alloc_tag: moverelease_module_tags()abovereserve_module_tags()
alloc_tag: clean up the populate failure path
module: introduceSH_ENTSIZE_STANDALONEfor separately allocated
sections
module: allocate codetag sections before the regular module layout
alloc_tag: skip percpu counter allocation when profiling is disabled
alloc_tag: Defer/proc/allocinforemoval to a workqueueinclude/linux/module.h | 2 + kernel/module/internal.h | 8 +++ kernel/module/kallsyms.c | 13 +--- kernel/module/main.c | 133 +++++++++++++++++++----------------- kernel/module/sysfs.c | 17 +++-- lib/codetag.c | 10 ++- mm/alloc_tag.c | 141 +++++++++++++++++++++++---------------- 7 files changed, 188 insertions(+), 136 deletions(-)--
2.25.1
Hao Ge
reviewerHi Suren
Quoted 84 lines · Suren Baghdasaryan
Quoted 83 lines · Hao Ge
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()andmove_module()both askedcodetag_needs_module_section()where a codetag section goes, andmem_profiling_supportcan 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-EAGAINthe 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 six patches. The two
alloc_tagfixes from [2] are folded in as patches 5 and 6 and replace the versions currently in the mm tree. Sashiko keeps flagging the percpu counter leak [3], patch 5 fixes it, and now the whole set goes through review again.[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/Patch 1 moves
release_module_tags()abovereserve_module_tags(), since the failure paths now have to call it.Patch 2 cleans up the populate failure path: the reservation is released, module_tags.size rolled back and the PTEs a failed
vmap_pages_range()left behind unmapped, so a later populate of the same range is safe. It carries both Fixes tags so it backports wherever patch 4 goes, which uses itsprev_size.Patch 3 introduces
SH_ENTSIZE_STANDALONEto mark sections with a separate allocation. The percpu section was previously excluded from the layout by clearing itsSHF_ALLOC, which per the ELF spec says the section occupies memory during execution, and percpu does, only outside the regular module layout. The mark lives insh_entsizenow,find_sec(".data..percpu")gives stable results again andapply_relocations()goes back to testing onlySHF_ALLOC. The section would show up under/sys/module/*/sections/, but it has one instance per CPU and no single address, and the entry never existed, soadd_sect_attrs()andadd_notes_attrs()skip it.Patch 4 moves the codetag allocation out of
move_module()in front oflayout_sections(), so the placement is decided in one step and the race is gone. On overflow profiling is shut down, the reservation released, module_tags.size rolled back and-EAGAINreturned, the section is laid out as regular module data and 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 5 skips the percpu counter allocation when profiling is off. After the shutdown modules load their codetag section as regular data,
load_module()still allocated counters for every tag andrelease_module_tags()cannot find them on unload, so they leaked (Suggested by Suren).Patch 6 defers the
/proc/allocinforemoval to a workqueue.shutdown_mem_profiling()runs undermod_lock, and the synchronousremove_proc_entry()deadlocks with a reader takingmod_lockfor read inallocinfo_start(). The file is also created at the end ofalloc_tag_init(), a leftover file after a failed init would panic its readers (Found by Sashiko).Tested on an
x86_64virtual machine:Booted without sysctl.vm.mem_profiling=1,compressed:
# cat /proc/allocinfo is fine
Quoted 9 lines
Quoted 6 lines
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!Do you have your
overflow_tagmodule posted anywhere in public (github perhaps?)
This is our simple test program:
--- overflow_tag/overflow_tag.c | 109 ++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 overflow_tag/overflow_tag.c
overflow_tag/overflow_tag.c new file +109 -0
@@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* overflow_tag - overflow the compressed allocation tag index +*/ + +#include <linux/alloc_tag.h> +#include <linux/debugfs.h> +#include <linux/module.h> +#include <linux/slab.h> + +#ifndef CONFIG_MEM_ALLOC_PROFILING +#error "overflow_tag requires CONFIG_MEM_ALLOC_PROFILING=y" +#endif + +#ifndef NR_OVERFLOW_TAG_BITS +#define NR_OVERFLOW_TAG_BITS 13 +#endif + +#define NR_OVERFLOW_TAGS (1UL << NR_OVERFLOW_TAG_BITS) + +#define MAX_TRIGGER_PAGES 10000 + +static struct alloc_tag overflow_tags[NR_OVERFLOW_TAGS] __used __aligned(8) +__section (ALLOC_TAG_SECTION_NAME ) = { + [0 ...NR_OVERFLOW_TAGS -1 ] = { + .ct = { + .modname =KBUILD_MODNAME , + .function ="overflow_tags" , + .filename = __FILE__, + .lineno = __LINE__, + }, + .counters =NULL , + }, +}; + +static int overflow_alloc_and_free (unsigned long nr_pages) +{ +struct page **pages; +unsigned long i; + + pages =kvmalloc_array (nr_pages,sizeof (*pages),GFP_KERNEL ); +if (!pages) +return -ENOMEM ; + +for (i =0 ; i < nr_pages; i++) + pages[i] =alloc_hooks_tag ( + &overflow_tags[NR_OVERFLOW_TAGS -1 ], +alloc_pages_noprof (GFP_KERNEL ,0 )); + +for (i =0 ; i < nr_pages; i++) +if (pages[i]) +__free_pages (pages[i],0 ); + +kvfree (pages); +return 0 ; +} + +static ssize_t overflow_tag_alloc_write (struct file *file, +const char __user *ubuf,size_t count, +loff_t *ppos) +{ +unsigned long nr_pages; +int err; + + err =kstrtoul_from_user (ubuf, count,0 , &nr_pages); +if (err) +return err; + +if (!nr_pages || nr_pages >MAX_TRIGGER_PAGES ) +return -EINVAL ; + + err =overflow_alloc_and_free (nr_pages); +if (err) +return err; + +pr_info ("allocated and freed %lu pages through the last tag\n" , + nr_pages); + +return count; +} + +static const struct file_operations overflow_tag_fops = { + .owner =THIS_MODULE , + .write = overflow_tag_alloc_write, +}; + +static struct dentry *overflow_tag_dir; + +static int __init overflow_tag_init (void ) +{ + overflow_tag_dir =debugfs_create_dir ("overflow_tag" ,NULL ); +debugfs_create_file ("alloc_and_free" ,0200 , overflow_tag_dir,NULL , + &overflow_tag_fops); + +pr_info ("loaded with %lu allocation tags\n" ,NR_OVERFLOW_TAGS ); +return 0 ; +} + +static void __exit overflow_tag_exit(void) +{ +debugfs_remove_recursive (overflow_tag_dir); +} + +module_init (overflow_tag_init); +module_exit (overflow_tag_exit); + +MODULE_AUTHOR ("Hao Ge <[email protected]>" ); +MODULE_DESCRIPTION ("Test module overflowing the compressed allocation tag index" ); +MODULE_LICENSE ("GPL" );
Signature · 27 lines
2.25.1
The test machine uses 13 bits for tag index. Relevant kernel config is as follows:
CONFIG_NUMA_BALANCING=y
CONFIG_NR_CPUS=32
CONFIG_NODES_SHIFT=10
CONFIG_SPARSEMEM=y
CONFIG_SPARSEMEM_VMEMMAP=y
CONFIG_ZONE_DEVICE=y
# CONFIG_LRU_GEN is not set
CONFIG_MEM_ALLOC_PROFILING=y
# CONFIG_MEM_ALLOC_PROFILING_DEBUG is not set
Steps to reproduce the corruption on the unfixed kernel:
# boot with sysctl.vm.mem_profiling=0,compressed
# insmod overflow_tag.ko
# echo 1 > /proc/sys/vm/mem_profiling
# echo 10 > /sys/kernel/debug/overflow_tag/alloc_and_free
# cat /proc/allocinfo
Observed corruption after a 10-page run:
40960 10 overflow_tag.c:30 [overflow_tag] func:overflow_tags
-40960 18446744073709551606 overflow_tag.c:41 [overflow_tag] func:overflow_alloc_and_free
Thanks
Best Regards
HaoQuoted 116 lines
Quoted 116 lines
# rmmod overflow_tag The module loads without profiling and unloads cleanly.Also ran continuous LTP stress for a few days, nothing abnormal so far.
Changes in v10:
- fold in the twoalloc_tagfixes from [2] as patches 5 and 6, they replace the versions in the mm tree and fix the percpu leak Sashiko keeps flagging [3]
- create/proc/allocinfoat the end ofalloc_tag_init(), a leftover file after a failed init would panic its readers (Found by Sashiko)
- count note sections withsect_visible()inadd_notes_attrs()too, the count has to match the fill loopChanges in v9:
- do not export .data..percpu under/sys/module/*/sections/(Petr Pavlu).
- move the populate failure cleanup in front of the rework, v8 patch 4 is patch 2 now. It declaresprev_sizeitself, which the overflow path of the rework also uses, so it carries both Fixes tags and the two patches backport togetherChanges in v8:
- roll back module_tags.size when the reservation is released, so a concurrent load which already passedneeds_section_mem()does not skip populate for the freed gap (Sashiko)
- unmap the PTEs a failedvmap_pages_range()installed, a retry to populate the same range would BUG on them
- zero the separately allocated codetag memory for anSHT_NOBITSsection, 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 inapply_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 withSH_ENTSIZE_STANDALONEinstead of clearingSHF_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 beforelayout_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-EAGAINkeeps the fallback, other errors fail the loadChanges 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 inmodule_frob_arch_sections()(Reported by Sashiko)
- drop theload_module()mem_profiling_supportcheck; the percpu counter leak is pre-existing and orthogonal to this fixChanges in v4:
- add a new patch (1/2) to moverelease_module_tags()abovereserve_module_tags(); the overflow fix is 2/2
- release the reservation on the-EAGAINpath
- return-EAGAINinstead of-ENOMEMso the module can still load without profiling (Suren)
- resetsh_addr, mem[type].size and sym/strSHF_ALLOCbefore retry
- skip percpu counters inload_module()when profiling is offChanges in v3:
- usepr_warn_once()instead ofpr_warn()
- return-ENOMEMinstead of-ENOSPC(Suren)
- expand the commit message to describe the/proc/allocinfoimpact (Andrew)Changes in v2:
- return an error aftershutdown_mem_profiling()to skipvm_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]/
v8: https://lore.kernel.org/all/[email protected]/
v9: https://lore.kernel.org/all/[email protected]/Hao Ge (6):
alloc_tag: moverelease_module_tags()abovereserve_module_tags()
alloc_tag: clean up the populate failure path
module: introduceSH_ENTSIZE_STANDALONEfor separately allocated
sections
module: allocate codetag sections before the regular module layout
alloc_tag: skip percpu counter allocation when profiling is disabled
alloc_tag: Defer/proc/allocinforemoval to a workqueueinclude/linux/module.h | 2 + kernel/module/internal.h | 8 +++ kernel/module/kallsyms.c | 13 +--- kernel/module/main.c | 133 +++++++++++++++++++----------------- kernel/module/sysfs.c | 17 +++-- lib/codetag.c | 10 ++- mm/alloc_tag.c | 141 +++++++++++++++++++++++---------------- 7 files changed, 188 insertions(+), 136 deletions(-)--
2.25.1