implement lightweight guard pages
Subsystems (15)
v4 cover implement lightweight guard pages
Userland library functions such as allocators and threading implementations often require regions of memory to act as 'guard pages' - mappings which, when accessed, result in a fatal signal being sent to the accessing process.
The current means by which these are implemented is via a PROT_NONE mmap() mapping, which provides the required semantics however incur an overhead of a VMA for each such region.
With a great many processes and threads, this can rapidly add up and incur a significant memory penalty. It also has the added problem of preventing merges that might otherwise be permitted.
This series takes a different approach - an idea suggested by Vlasimil Babka (and before him David Hildenbrand and Jann Horn - perhaps more - the provenance becomes a little tricky to ascertain after this - please forgive any omissions!) - rather than locating the guard pages at the VMA layer, instead placing them in page tables mapping the required ranges.
Early testing of the prototype version of this code suggests a 5 times speed up in memory mapping invocations (in conjunction with use of process_madvise()) and a 13% reduction in VMAs on an entirely idle android system and unoptimised code.
We expect with optimisation and a loaded system with a larger number of guard pages this could significantly increase, but in any case these numbers are encouraging.
This way, rather than having separate VMAs specifying which parts of a range are guard pages, instead we have a VMA spanning the entire range of memory a user is permitted to access and including ranges which are to be 'guarded'.
After mapping this, a user can specify which parts of the range should result in a fatal signal when accessed.
By restricting the ability to specify guard pages to memory mapped by existing VMAs, we can rely on the mappings being torn down when the mappings are ultimately unmapped and everything works simply as if the memory were not faulted in, from the point of view of the containing VMAs.
This mechanism in effect poisons memory ranges similar to hardware memory poisoning, only it is an entirely software-controlled form of poisoning.
The mechanism is implemented via madvise() behaviour - MADV_GUARD_INSTALL which installs page table-level guard page markers - and MADV_GUARD_REMOVE - which clears them.
Guard markers can be installed across multiple VMAs and any existing mappings will be cleared, that is zapped, before installing the guard page markers in the page tables.
There is no concept of 'nested' guard markers, multiple attempts to install guard markers in a range will, after the first attempt, have no effect.
Importantly, removing guard markers over a range that contains both guard markers and ordinary backed memory has no effect on anything but the guard markers (including leaving huge pages un-split), so a user can safely remove guard markers over a range of memory leaving the rest intact.
The actual mechanism by which the page table entries are specified makes use of existing logic - PTE markers, which are used for the userfaultfd UFFDIO_POISON mechanism.
Unfortunately PTE_MARKER_POISONED is not suited for the guard page mechanism as it results in VM_FAULT_HWPOISON semantics in the fault handler, so we add our own specific PTE_MARKER_GUARD and adapt existing logic to handle it.
We also extend the generic page walk mechanism to allow for installation of PTEs (carefully restricted to memory management logic only to prevent unwanted abuse).
We ensure that zapping performed by MADV_DONTNEED and MADV_FREE do not remove guard markers, nor does forking (except when VM_WIPEONFORK is specified for a VMA which implies a total removal of memory characteristics).
It's important to note that the guard page implementation is emphatically NOT a security feature, so a user can remove the markers if they wish. We simply implement it in such a way as to provide the least surprising behaviour.
An extensive set of self-tests are provided which ensure behaviour is as expected and additionally self-documents expected behaviour of guard ranges.
v4
* Use restart_syscall() to implement -ERESTARTNOINTR to ensure correctly handled by kernel - tested this code path and confirmed it works correctly. Thanks to Vlastimil for pointing this issue out!
* Updated the vector_madvise() handler to not unnecessarily invoke cond_resched() as suggested by Vlastimil.
* Updated guard page tests to add a test for a vector operation which overwrites existing mappings. Tested this against the -ERESTARTNOINTR case and confirmed working.
* Improved page walk logic further, refactoring handling logic as suggested by Vlastimil.
* Moved MAX_MADVISE_GUARD_RETRIES to mm/madvise.c as suggested by Vlastimil.
v3
* Cleaned up mm/pagewalk.c logic a bit to make things clearer, as suggested by Vlastiml.
* Explicitly avoid splitting THP on PTE installation, as suggested by Vlastimil. Note this has no impact on the guard pages logic, which has page table entry handlers at PUD, PMD and PTE level.
* Added WARN_ON_ONCE() to mm/hugetlb.c path where we don't expect a guard marker, as suggested by Vlastimil.
* Reverted change to is_poisoned_swp_entry() to exclude guard pages which has the effect of MADV_FREE _not_ clearing guard pages. After discussion with Vlastimil, it became apparent that the ability to 'cancel' the freeing operation by writing to the mapping after having issued an MADV_FREE would mean that we would risk unexpected behaviour should the guard pages be removed, so we now do not remove markers here at all.
* Added comment to PTE_MARKER_GUARD to highlight that memory tagged with the marker behaves as if it were a region mapped PROT_NONE, as highlighted by David.
* Rename poison -> install, unpoison -> remove (i.e. MADV_GUARD_INSTALL / MADV_GUARD_REMOVE over MADV_GUARD_POISON / MADV_GUARD_REMOVE) at the request of David and John who both find the poison analogy confusing/overloaded.
* After a lot of discussion, replace the looping behaviour should page faults race with guard page installation with a modest reattempt followed by returning -ERESTARTNOINTR to have the operation abort and re-enter, relieving lock contention and avoiding the possibility of allowing a malicious sandboxed process to impact the mmap lock or stall the overall process more than necessary, as suggested by Jann and Vlastimil having raised the issue.
* Adjusted the page table walker so a populated huge PUD or PMD is correctly treated as being populated, necessitating a zap. In v2 we incorrectly skipped over these, which would cause the logic to wrongly proceed as if nothing were populated and the install succeeded. Instead, explicitly check to see if a huge page - if so, do not split but rather abort the operation and let zap take care of things.
* Updated the guard remove logic to not unnecessarily split huge pages either.
* Added a debug check to assert that the number of installed PTEs matches expectation, accounting for any existing guard pages.
* Adapted vector_madvise() used by the process_madvise() system call to handle -ERESTARTNOINTR correctly.
https://lore.kernel.org/all/[email protected]/
v2
* The macros in kselftest_harness.h seem to be broken - __EXPECT() is terminated by '} while (0); OPTIONAL_HANDLER(_assert)' meaning it is not safe in single line if / else or for /which blocks, however working around this results in checkpatch producing invalid warnings, as reported by Shuah.
* Fixing these macros is out of scope for this series, so compromise and instead rewrite test blocks so as to use multiple lines by separating out a decl in most cases. This has the side effect of, for the most part, making things more readable.
* Heavily document the use of the volatile keyword - we can't avoid checkpatch complaining about this, so we explain it, as reported by Shuah.
* Updated commit message to highlight that we skip tests we lack permissions for, as reported by Shuah.
* Replaced a perror() with ksft_exit_fail_perror(), as reported by Shuah.
* Added user friendly messages to cases where tests are skipped due to lack of permissions, as reported by Shuah.
* Update the tool header to include the new MADV_GUARD_POISON/UNPOISON defines and directly include asm-generic/mman.h to get the platform-neutral versions to ensure we import them.
* Finally fixed Vlastimil's email address in Suggested-by tags from suze to suse, as reported by Vlastimil.
* Added linux-api to cc list, as reported by Vlastimil.
https://lore.kernel.org/all/[email protected]/
v1
* Un-RFC'd as appears no major objections to approach but rather debate on implementation.
* Fixed issue with arches which need mmu_context.h and tlbfush.h. header imports in pagewalker logic to be able to use update_mmu_cache() as reported by the kernel test bot.
* Added comments in page walker logic to clarify who can use ops->install_pte and why as well as adding a check_ops_valid() helper function, as suggested by Christoph.
* Pass false in full parameter in pte_clear_not_present_full() as suggested by Jann.
* Stopped erroneously requiring a write lock for the poison operation as suggested by Jann and Suren.
* Moved anon_vma_prepare() to the start of madvise_guard_poison() to be consistent with how this is used elsewhere in the kernel as suggested by Jann.
* Avoid returning -EAGAIN if we are raced on page faults, just keep looping and duck out if a fatal signal is pending or a conditional reschedule is needed, as suggested by Jann.
* Avoid needlessly splitting huge PUDs and PMDs by specifying ACTION_CONTINUE, as suggested by Jann.
https://lore.kernel.org/all/[email protected]/
RFC
https://lore.kernel.org/all/[email protected]/
Lorenzo Stoakes (5):
mm: pagewalk: add the ability to install PTEs
mm: add PTE_MARKER_GUARD PTE marker
mm: madvise: implement lightweight guard page mechanism
tools: testing: update tools UAPI header for mman-common.h selftests/mm: add self tests for guard page feature
arch/alpha/include/uapi/asm/mman.h | 3 + arch/mips/include/uapi/asm/mman.h | 3 + arch/parisc/include/uapi/asm/mman.h | 3 + arch/xtensa/include/uapi/asm/mman.h | 3 + include/linux/mm_inline.h | 2 +- include/linux/pagewalk.h | 18 +- include/linux/swapops.h | 24 +- include/uapi/asm-generic/mman-common.h | 3 + mm/hugetlb.c | 4 + mm/internal.h | 6 + mm/madvise.c | 239 ++++ mm/memory.c | 18 +- mm/mprotect.c | 6 +- mm/mseal.c | 1 + mm/pagewalk.c | 246 +++- tools/include/uapi/asm-generic/mman-common.h | 3 + tools/testing/selftests/mm/.gitignore | 1 + tools/testing/selftests/mm/Makefile | 1 + tools/testing/selftests/mm/guard-pages.c | 1243 ++++++++++++++++++ 19 files changed, 1751 insertions(+), 76 deletions(-) create mode 100644 tools/testing/selftests/mm/guard-pages.c
--
2.47.0
PATCH v4 1/5 mm: pagewalk: add the ability to install PTEs
The existing generic pagewalk logic permits the walking of page tables, invoking callbacks at individual page table levels via user-provided mm_walk_ops callbacks.
This is useful for traversing existing page table entries, but precludes the ability to establish new ones.
Existing mechanism for performing a walk which also installs page table entries if necessary are heavily duplicated throughout the kernel, each with semantic differences from one another and largely unavailable for use elsewhere.
Rather than add yet another implementation, we extend the generic pagewalk logic to enable the installation of page table entries by adding a new install_pte() callback in mm_walk_ops. If this is specified, then upon encountering a missing page table entry, we allocate and install a new one and continue the traversal.
If a THP huge page is encountered at either the PMD or PUD level we split it only if there are ops->pte_entry() (or ops->pmd_entry at PUD level), otherwise if there is only an ops->install_pte(), we avoid the unnecessary split.
We do not support hugetlb at this stage.
If this function returns an error, or an allocation fails during the operation, we abort the operation altogether. It is up to the caller to deal appropriately with partially populated page table ranges.
If install_pte() is defined, the semantics of pte_entry() change - this callback is then only invoked if the entry already exists. This is a useful property, as it allows a caller to handle existing PTEs while installing new ones where necessary in the specified range.
If install_pte() is not defined, then there is no functional difference to this patch, so all existing logic will work precisely as it did before.
As we only permit the installation of PTEs where a mapping does not already exist there is no need for TLB management, however we do invoke update_mmu_cache() for architectures which require manual maintenance of mappings for other CPUs.
We explicitly do not allow the existing page walk API to expose this feature as it is dangerous and intended for internal mm use only. Therefore we provide a new walk_page_range_mm() function exposed only to mm/internal.h.
We take the opportunity to additionally clean up the page walker logic to be a little easier to follow.{
{# modified: mm/pagewalk.c
--- include/linux/pagewalk.h | 18 ++- mm/internal.h | 6 + mm/pagewalk.c | 246 ++++++++++++++++++++++++++++----------- 3 files changed, 201 insertions(+), 69 deletions(-)
include/linux/pagewalk.h +15 -3
@@ -25,12 +25,15 @@ enum page_walk_lock {* this handler is required to be able to handle * pmd_trans_huge() pmds. They may simply choose to * split_huge_page() instead of handling it explicitly. -* @pte_entry: if set, called for each PTE (lowest-level) entry, -* including empty ones +* @pte_entry: if set, called for each PTE (lowest-level) entry +* including empty ones, except if @install_pte is set. +* If @install_pte is set, @pte_entry is called only for +* existing PTEs. * @pte_hole: if set, called for each hole at all levels, * depth is -1 if not known, 0:PGD, 1:P4D, 2:PUD, 3:PMD. * Any folded depths (where PTRS_PER_P?D is equal to 1) -* are skipped. +* are skipped. If @install_pte is specified, this will +* not trigger for any populated ranges. * @hugetlb_entry: if set, called for each hugetlb entry. This hook * function is called with the vma lock held, in order to * protect against a concurrent freeing of the pte_t* or
@@ -51,6 +54,13 @@ enum page_walk_lock {* @pre_vma: if set, called before starting walk on a non-null vma. * @post_vma: if set, called after a walk on a non-null vma, provided * that @pre_vma and the vma walk succeeded. +* @install_pte: if set, missing page table entries are installed and +* thus all levels are always walked in the specified +* range. This callback is then invoked at the PTE level +* (having split any THP pages prior), providing the PTE to +* install. If allocations fail, the walk is aborted. This +* operation is only available for userland memory. Not +* usable for hugetlb ranges. * * p?d_entry callbacks are called even if those levels are folded on a * particular architecture/configuration.
@@ -76,6 +86,8 @@ struct mm_walk_ops {int (*pre_vma)(unsigned long start,unsigned long end,struct mm_walk *walk);void (*post_vma)(struct mm_walk *walk); +int (*install_pte)(unsigned long addr,unsigned long next, +pte_t *ptep,struct mm_walk *walk);enum page_walk_lock walk_lock; };
mm/internal.h +6 -0
@@ -12,6 +12,7 @@#include <linux/mm.h> #include <linux/mm_inline.h> #include <linux/pagemap.h> +#include <linux/pagewalk.h> #include <linux/rmap.h> #include <linux/swap.h> #include <linux/swapops.h>
@@ -1502,4 +1503,9 @@ static inline void accept_page(struct page *page) }#endif /* CONFIG_UNACCEPTED_MEMORY */ +/* pagewalk.c */ +int walk_page_range_mm (struct mm_struct *mm,unsigned long start, +unsigned long end,const struct mm_walk_ops *ops, +void *private); +#endif /* __MM_INTERNAL_H */
mm/pagewalk.c +180 -66
409 lines not on this page · raw message
Signature · 1 line
2.47.0
PATCH v4 2/5 mm: add PTE_MARKER_GUARD PTE marker
In reply to Lorenzo StoakesAdd a new PTE marker that results in any access causing the accessing process to segfault.
This is preferable to PTE_MARKER_POISONED, which results in the same handling as hardware poisoned memory, and is thus undesirable for cases where we simply wish to 'soft' poison a range.
This is in preparation for implementing the ability to specify guard pages at the page table level, i.e. ranges that, when accessed, should cause process termination.
Additionally, rename zap_drop_file_uffd_wp() to zap_drop_markers() - the function checks the ZAP_FLAG_DROP_MARKER flag so naming it for this single purpose was simply incorrect.
We then reuse the same logic to determine whether a zap should clear a guard entry - this should only be performed on teardown and never on MADV_DONTNEED or MADV_FREE.
We additionally add a WARN_ON_ONCE() in hugetlb logic should a guard marker be encountered there, as we explicitly do not support this operation and this should not occur.
--- include/linux/mm_inline.h | 2 +- include/linux/swapops.h | 24 +++++++++++++++++++++++- mm/hugetlb.c | 4 ++++ mm/memory.c | 18 +++++++++++++++--- mm/mprotect.c | 6 ++++-- 5 files changed, 47 insertions(+), 7 deletions(-)
include/linux/mm_inline.h +1 -1
@@ -544,7 +544,7 @@ static inline pte_marker copy_pte_marker( {pte_marker srcm =pte_marker_get (entry);/* Always copy error entries. */ -pte_marker dstm = srcm &PTE_MARKER_POISONED ; +pte_marker dstm = srcm & (PTE_MARKER_POISONED |PTE_MARKER_GUARD );/* Only copy PTE markers if UFFD register matches. */ if ((srcm &PTE_MARKER_UFFD_WP ) &&userfaultfd_wp (dst_vma))
include/linux/swapops.h +23 -1
@@ -426,9 +426,19 @@ typedef unsigned long pte_marker;* "Poisoned" here is meant in the very general sense of "future accesses are * invalid", instead of referring very specifically to hardware memory errors. * This marker is meant to represent any of various different causes of this. +* +* Note that, when encountered by the faulting logic, PTEs with this marker will +* result in VM_FAULT_HWPOISON and thus regardless trigger hardware memory error +* logic. */ #define PTE_MARKER_POISONED BIT(1) -#define PTE_MARKER_MASK (BIT(2) - 1) +/* +* Indicates that, on fault, this PTE will case a SIGSEGV signal to be +* sent. This means guard markers behave in effect as if the region were mapped +* PROT_NONE, rather than if they were a memory hole or equivalent. +*/ +#define PTE_MARKER_GUARD BIT(2) +#define PTE_MARKER_MASK (BIT(3) - 1)static inline swp_entry_t make_pte_marker_entry (pte_marker marker) {
@@ -464,6 +474,18 @@ static inline int is_poisoned_swp_entry(swp_entry_t entry) {return is_pte_marker_entry (entry) && (pte_marker_get (entry) &PTE_MARKER_POISONED ); + +} + +static inline swp_entry_t make_guard_swp_entry (void ) +{ +return make_pte_marker_entry (PTE_MARKER_GUARD ); +} + +static inline int is_guard_swp_entry (swp_entry_t entry) +{ +return is_pte_marker_entry (entry) && + (pte_marker_get (entry) &PTE_MARKER_GUARD ); }/*
mm/hugetlb.c +4 -0
@@ -6353,6 +6353,10 @@ vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma, ret =VM_FAULT_HWPOISON_LARGE |VM_FAULT_SET_HINDEX (hstate_index (h)); goto out_mutex; + }else if (WARN_ON_ONCE (marker &PTE_MARKER_GUARD )) { +/* This isn't supported in hugetlb. */ + ret =VM_FAULT_SIGSEGV ; + goto out_mutex; } }
mm/memory.c +15 -3
@@ -1455,7 +1455,7 @@ static inline bool should_zap_folio(struct zap_details *details,return !folio_test_anon (folio); } -static inline bool zap_drop_file_uffd_wp (struct zap_details *details) +static inline bool zap_drop_markers (struct zap_details *details) {if (!details)return false;
@@ -1476,7 +1476,7 @@ zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,if (vma_is_anonymous (vma))return ; -if (zap_drop_file_uffd_wp (details)) +if (zap_drop_markers (details))return ;for (;;) {
@@ -1671,7 +1671,15 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb,* drop the marker if explicitly requested. */ if (!vma_is_anonymous (vma) && - !zap_drop_file_uffd_wp (details)) + !zap_drop_markers (details)) +continue ; + }else if (is_guard_swp_entry (entry)) { +/* +* Ordinary zapping should not remove guard PTE +* markers. Only do so if we should remove PTE markers +* in general. +*/ +if (!zap_drop_markers (details))continue ; }else if (is_hwpoison_entry (entry) ||is_poisoned_swp_entry (entry)) {
@@ -4003,6 +4011,10 @@ static vm_fault_t handle_pte_marker(struct vm_fault *vmf)if (marker &PTE_MARKER_POISONED )return VM_FAULT_HWPOISON ; +/* Hitting a guard page is always a fatal condition. */ +if (marker &PTE_MARKER_GUARD ) +return VM_FAULT_SIGSEGV ; +if (pte_marker_entry_uffd_wp (entry))return pte_marker_handle_uffd_wp (vmf);
mm/mprotect.c +4 -2
@@ -236,9 +236,11 @@ static long change_pte_range(struct mmu_gather *tlb, }else if (is_pte_marker_entry (entry)) {/* * Ignore error swap entries unconditionally, -* because any access should sigbus anyway. +* because any access should sigbus/sigsegv +* anyway. */ -if (is_poisoned_swp_entry (entry)) +if (is_poisoned_swp_entry (entry) || +is_guard_swp_entry (entry))continue ;/* * If this is uffd-wp pte marker and we'd like
Signature · 1 line
2.47.0
PATCH v4 3/5 mm: madvise: implement lightweight guard page mechanism
In reply to Lorenzo StoakesImplement a new lightweight guard page feature, that is regions of userland virtual memory that, when accessed, cause a fatal signal to arise.
Currently users must establish PROT_NONE ranges to achieve this.
However this is very costly memory-wise - we need a VMA for each and every one of these regions AND they become unmergeable with surrounding VMAs.
In addition repeated mmap() calls require repeated kernel context switches and contention of the mmap lock to install these ranges, potentially also having to unmap memory if installed over existing ranges.
The lightweight guard approach eliminates the VMA cost altogether - rather than establishing a PROT_NONE VMA, it operates at the level of page table entries - establishing PTE markers such that accesses to them cause a fault followed by a SIGSGEV signal being raised.
This is achieved through the PTE marker mechanism, which we have already extended to provide PTE_MARKER_GUARD, which we installed via the generic page walking logic which we have extended for this purpose.
These guard ranges are established with MADV_GUARD_INSTALL. If the range in which they are installed contain any existing mappings, they will be zapped, i.e. free the range and unmap memory (thus mimicking the behaviour of MADV_DONTNEED in this respect).
Any existing guard entries will be left untouched. There is therefore no nesting of guarded pages.
Guarded ranges are NOT cleared by MADV_DONTNEED nor MADV_FREE (in both instances the memory range may be reused at which point a user would expect guards to still be in place), but they are cleared via MADV_GUARD_REMOVE, process teardown or unmapping of memory ranges.
The guard property can be removed from ranges via MADV_GUARD_REMOVE. The ranges over which this is applied, should they contain non-guard entries, will be untouched, with only guard entries being cleared.
We permit this operation on anonymous memory only, and only VMAs which are non-special, non-huge and not mlock()'d (if we permitted this we'd have to drop locked pages which would be rather counterintuitive).
Racing page faults can cause repeated attempts to install guard pages that are interrupted, result in a zap, and this process can end up being repeated. If this happens more than would be expected in normal operation, we rescind locks and retry the whole thing, which avoids lock contention in this scenario.
--- arch/alpha/include/uapi/asm/mman.h | 3 + arch/mips/include/uapi/asm/mman.h | 3 + arch/parisc/include/uapi/asm/mman.h | 3 + arch/xtensa/include/uapi/asm/mman.h | 3 + include/uapi/asm-generic/mman-common.h | 3 + mm/madvise.c | 239 +++++++++++++++++++++++++ mm/mseal.c | 1 + 7 files changed, 255 insertions(+)
arch/alpha/include/uapi/asm/mman.h +3 -0
@@ -78,6 +78,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_INSTALL 102/* fatal signal on access to range */ +#define MADV_GUARD_REMOVE 103/* unguard range */ +/* compatibility flags */ #define MAP_FILE 0
arch/mips/include/uapi/asm/mman.h +3 -0
@@ -105,6 +105,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_INSTALL 102/* fatal signal on access to range */ +#define MADV_GUARD_REMOVE 103/* unguard range */ +/* compatibility flags */ #define MAP_FILE 0
arch/parisc/include/uapi/asm/mman.h +3 -0
@@ -75,6 +75,9 @@#define MADV_HWPOISON 100/* poison a page for testing */ #define MADV_SOFT_OFFLINE 101/* soft offline page for testing */ +#define MADV_GUARD_INSTALL 102/* fatal signal on access to range */ +#define MADV_GUARD_REMOVE 103/* unguard range */ +/* compatibility flags */ #define MAP_FILE 0
arch/xtensa/include/uapi/asm/mman.h +3 -0
@@ -113,6 +113,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_INSTALL 102/* fatal signal on access to range */ +#define MADV_GUARD_REMOVE 103/* unguard range */ +/* compatibility flags */ #define MAP_FILE 0
include/uapi/asm-generic/mman-common.h +3 -0
@@ -79,6 +79,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_INSTALL 102/* fatal signal on access to range */ +#define MADV_GUARD_REMOVE 103/* unguard range */ +/* compatibility flags */ #define MAP_FILE 0
mm/madvise.c +239 -0
275 lines not on this page · raw message
mm/mseal.c +1 -0
@@ -30,6 +30,7 @@ static bool is_madv_discard(int behavior)case MADV_REMOVE :case MADV_DONTFORK :case MADV_WIPEONFORK : +case MADV_GUARD_INSTALL :return true; }
Signature · 1 line
2.47.0
Re: [PATCH v4 3/5] mm: madvise: implement lightweight guard page mechanism
Quoted 48 lines · Lorenzo Stoakes
Implement a new lightweight guard page feature, that is regions of userland virtual memory that, when accessed, cause a fatal signal to arise.
Currently users must establish
PROT_NONEranges to achieve this.However this is very costly memory-wise - we need a VMA for each and every one of these regions AND they become unmergeable with surrounding VMAs.
In addition repeated
mmap()calls require repeated kernel context switches and contention of the mmap lock to install these ranges, potentially also having to unmap memory if installed over existing ranges.The lightweight guard approach eliminates the VMA cost altogether - rather than establishing a
PROT_NONEVMA, it operates at the level of page table entries - establishing PTE markers such that accesses to them cause a fault followed by a SIGSGEV signal being raised.This is achieved through the PTE marker mechanism, which we have already extended to provide
PTE_MARKER_GUARD, which we installed via the generic page walking logic which we have extended for this purpose.These guard ranges are established with
MADV_GUARD_INSTALL. If the range in which they are installed contain any existing mappings, they will be zapped, i.e. free the range and unmap memory (thus mimicking the behaviour ofMADV_DONTNEEDin this respect).Any existing guard entries will be left untouched. There is therefore no nesting of guarded pages.
Guarded ranges are NOT cleared by
MADV_DONTNEEDnorMADV_FREE(in both instances the memory range may be reused at which point a user would expect guards to still be in place), but they are cleared viaMADV_GUARD_REMOVE, process teardown or unmapping of memory ranges.The guard property can be removed from ranges via
MADV_GUARD_REMOVE. The ranges over which this is applied, should they contain non-guard entries, will be untouched, with only guard entries being cleared.We permit this operation on anonymous memory only, and only VMAs which are non-special, non-huge and not mlock()'d (if we permitted this we'd have to drop locked pages which would be rather counterintuitive).
Racing page faults can cause repeated attempts to install guard pages that are interrupted, result in a zap, and this process can end up being repeated. If this happens more than would be expected in normal operation, we rescind locks and retry the whole thing, which avoids lock contention in this scenario.
Quoted 4 lines
Suggested-by Vlastimil Babka <[email protected]>Suggested-by Jann Horn <[email protected]>Suggested-by David Hildenbrand <[email protected]>Signed-off-by Lorenzo Stoakes <[email protected]>
PATCH v4 4/5 tools: testing: update tools UAPI header for mman-common.h
In reply to Lorenzo StoakesImport the new MADV_GUARD_INSTALL/REMOVE madvise flags.
--- tools/include/uapi/asm-generic/mman-common.h | 3 +++ 1 file changed, 3 insertions(+)
tools/include/uapi/asm-generic/mman-common.h +3 -0
@@ -79,6 +79,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_INSTALL 102/* fatal signal on access to range */ +#define MADV_GUARD_REMOVE 103/* unguard range */ +/* compatibility flags */ #define MAP_FILE 0
Signature · 1 line
2.47.0
PATCH v4 5/5 selftests/mm: add self tests for guard page feature
In reply to Lorenzo StoakesUtilise the kselftest harmness to implement tests for the guard page implementation.
We start by implement basic tests asserting that guard pages can be installed, removed and that touching guard pages result in SIGSEGV. We also assert that, in removing guard pages from a range, non-guard pages remain intact.
We then examine different operations on regions containing guard markers behave to ensure correct behaviour:
* Operations over multiple VMAs operate as expected.
* Invoking MADV_GUARD_INSTALL / MADV_GUARD_REMOVE via process_madvise() in batches works correctly.
* Ensuring that munmap() correctly tears down guard markers.
* Using mprotect() to adjust protection bits does not in any way override or cause issues with guard markers.
* Ensuring that splitting and merging VMAs around guard markers causes no issue - i.e. that a marker which 'belongs' to one VMA can function just as well 'belonging' to another.
* Ensuring that madvise(..., MADV_DONTNEED) and madvise(..., MADV_FREE) do not remove guard markers.
* Ensuring that mlock()'ing a range containing guard markers does not cause issues.
* Ensuring that mremap() can move a guard range and retain guard markers.
* Ensuring that mremap() can expand a guard range and retain guard markers (perhaps moving the range).
* Ensuring that mremap() can shrink a guard range and retain guard markers.
* Ensuring that forking a process correctly retains guard markers.
* Ensuring that forking a VMA with VM_WIPEONFORK set behaves sanely.
* Ensuring that lazyfree simply clears guard markers.
* Ensuring that userfaultfd can co-exist with guard pages.
* Ensuring that madvise(..., MADV_POPULATE_READ) and madvise(..., MADV_POPULATE_WRITE) error out when encountering guard markers.
* Ensuring that madvise(..., MADV_COLD) and madvise(..., MADV_PAGEOUT) do not remove guard markers.
If any test is unable to be run due to lack of permissions, that test is skipped.
--- tools/testing/selftests/mm/.gitignore | 1 + tools/testing/selftests/mm/Makefile | 1 + tools/testing/selftests/mm/guard-pages.c | 1243 ++++++++++++++++++++++ 3 files changed, 1245 insertions(+) create mode 100644 tools/testing/selftests/mm/guard-pages.c
tools/testing/selftests/mm/.gitignore +1 -0
@@ -54,3 +54,4 @@ droppable hugetlb_dio pkey_sighandler_tests_32 pkey_sighandler_tests_64 +guard-pages
tools/testing/selftests/mm/Makefile +1 -0
@@ -79,6 +79,7 @@ TEST_GEN_FILES += hugetlb_fault_after_madv TEST_GEN_FILES += hugetlb_madv_vs_map TEST_GEN_FILES += hugetlb_dio TEST_GEN_FILES += droppable +TEST_GEN_FILES += guard-pages ifneq ($(ARCH),arm64) TEST_GEN_FILES += soft-dirty
tools/testing/selftests/mm/guard-pages.c new file +1243 -0
1,243 lines not on this page · raw message
Signature · 1 line
2.47.0
Quoted 9 lines · On Mon, 28 Oct 2024 14:13:26 +0000 Lorenzo Stoakes…
Userland library functions such as allocators and threading implementations often require regions of memory to act as 'guard pages' - mappings which, when accessed, result in a fatal signal being sent to the accessing process.
The current means by which these are implemented is via a
PROT_NONEmmap()mapping, which provides the required semantics however incur an overhead of a VMA for each such region.
Quoted 6 lines
With a great many processes and threads, this can rapidly add up and incur a significant memory penalty. It also has the added problem of preventing merges that might otherwise be permitted.
This series takes a different approach - an idea suggested by Vlasimil Babka (and before him David Hildenbrand and Jann Horn - perhaps more - the
Nit. s/Vlasimil/Vlastimil/ ;)
Thanks,
SJ
[...]
Quoted 11 lines · SeongJae Park
Quoted 9 lines · On Mon, 28 Oct 2024 14:13:26 +0000 Lorenzo Stoakes…
Userland library functions such as allocators and threading implementations often require regions of memory to act as 'guard pages' - mappings which, when accessed, result in a fatal signal being sent to the accessing process.
The current means by which these are implemented is via a
PROT_NONEmmap()mapping, which provides the required semantics however incur an overhead of a VMA for each such region.
Quoted 8 lines
Quoted 6 lines
With a great many processes and threads, this can rapidly add up and incur a significant memory penalty. It also has the added problem of preventing merges that might otherwise be permitted.
This series takes a different approach - an idea suggested by Vlasimil Babka (and before him David Hildenbrand and Jann Horn - perhaps more - the
Nit. s/Vlasimil/Vlastimil/ ;)
Ugh oops sorry Vlastimil! This was a silly typo... Andrew would you mind fixing this up? I'll edit my local file for this so if I respin this will be corrected.
Thanks!
Quoted 6 lines
Thanks,
SJ[...]
Quoted 78 lines · Lorenzo Stoakes
Userland library functions such as allocators and threading implementations often require regions of memory to act as 'guard pages' - mappings which, when accessed, result in a fatal signal being sent to the accessing process.
The current means by which these are implemented is via a
PROT_NONEmmap()mapping, which provides the required semantics however incur an overhead of a VMA for each such region.With a great many processes and threads, this can rapidly add up and incur a significant memory penalty. It also has the added problem of preventing merges that might otherwise be permitted.
This series takes a different approach - an idea suggested by Vlasimil Babka (and before him David Hildenbrand and Jann Horn - perhaps more - the provenance becomes a little tricky to ascertain after this - please forgive any omissions!) - rather than locating the guard pages at the VMA layer, instead placing them in page tables mapping the required ranges.
Early testing of the prototype version of this code suggests a 5 times speed up in memory mapping invocations (in conjunction with use of
process_madvise()) and a 13% reduction in VMAs on an entirely idle android system and unoptimised code.We expect with optimisation and a loaded system with a larger number of guard pages this could significantly increase, but in any case these numbers are encouraging.
This way, rather than having separate VMAs specifying which parts of a range are guard pages, instead we have a VMA spanning the entire range of memory a user is permitted to access and including ranges which are to be 'guarded'.
After mapping this, a user can specify which parts of the range should result in a fatal signal when accessed.
By restricting the ability to specify guard pages to memory mapped by existing VMAs, we can rely on the mappings being torn down when the mappings are ultimately unmapped and everything works simply as if the memory were not faulted in, from the point of view of the containing VMAs.
This mechanism in effect poisons memory ranges similar to hardware memory poisoning, only it is an entirely software-controlled form of poisoning.
The mechanism is implemented via
madvise()behaviour -MADV_GUARD_INSTALLwhich installs page table-level guard page markers - andMADV_GUARD_REMOVE- which clears them.Guard markers can be installed across multiple VMAs and any existing mappings will be cleared, that is zapped, before installing the guard page markers in the page tables.
There is no concept of 'nested' guard markers, multiple attempts to install guard markers in a range will, after the first attempt, have no effect.
Importantly, removing guard markers over a range that contains both guard markers and ordinary backed memory has no effect on anything but the guard markers (including leaving huge pages un-split), so a user can safely remove guard markers over a range of memory leaving the rest intact.
The actual mechanism by which the page table entries are specified makes use of existing logic - PTE markers, which are used for the userfaultfd
UFFDIO_POISONmechanism.Unfortunately
PTE_MARKER_POISONEDis not suited for the guard page mechanism as it results inVM_FAULT_HWPOISONsemantics in the fault handler, so we add our own specificPTE_MARKER_GUARDand adapt existing logic to handle it.We also extend the generic page walk mechanism to allow for installation of PTEs (carefully restricted to memory management logic only to prevent unwanted abuse).
We ensure that zapping performed by
MADV_DONTNEEDandMADV_FREEdo not remove guard markers, nor does forking (except whenVM_WIPEONFORKis specified for a VMA which implies a total removal of memory characteristics).
Quoted 8 lines
It's important to note that the guard page implementation is emphatically NOT a security feature, so a user can remove the markers if they wish. We simply implement it in such a way as to provide the least surprising behaviour.
An extensive set of self-tests are provided which ensure behaviour is as expected and additionally self-documents expected behaviour of guard ranges.
Dear Lorenzo,
Dear colleagues,
sorry about raising an old thread.
It looks like this feature is now used in glibc [1]. And we noticed failures in CRIU [2] CI on Fedora Rawhide userspace. Now a question is how we can properly detect such "guarded" pages from user space. As I can see from MADV_GUARD_INSTALL implementation, it does not modify VMA flags anyhow, but only page tables. It means that /proc/<pid>/maps and /proc/<pid>/smaps interfaces are useless in this case. (Please, correct me if I'm missing anything here.)
I wonder if you have any ideas / suggestions regarding Checkpoint/Restore here. We (CRIU devs) are happy to develop some patches to bring some uAPI to expose MADV_GUARDs, but before going into this we decided to raise this question in LKML.
+CC [email protected]
+CC Andrei Vagin <[email protected]>
+CC Pavel Tikhomirov <[email protected]>
Kind regards,
Alex
[1] https://github.com/bminor/glibc/commit/a6fbe36b7f31292981422692236465ab56670ea9
[2] https://github.com/checkpoint-restore/criu/pull/2625
Quoted 143 lines
Suggested-by Vlastimil Babka <[email protected]>Suggested-by Jann Horn <[email protected]>Suggested-by David Hildenbrand <[email protected]>v4
* Userestart_syscall()to implement-ERESTARTNOINTRto ensure correctly handled by kernel - tested this code path and confirmed it works correctly. Thanks to Vlastimil for pointing this issue out!
* Updated thevector_madvise()handler to not unnecessarily invokecond_resched()as suggested by Vlastimil.
* Updated guard page tests to add a test for a vector operation which overwrites existing mappings. Tested this against the-ERESTARTNOINTRcase and confirmed working.
* Improved page walk logic further, refactoring handling logic as suggested by Vlastimil.
* MovedMAX_MADVISE_GUARD_RETRIEStomm/madvise.cas suggested by Vlastimil.v3
* Cleaned upmm/pagewalk.clogic a bit to make things clearer, as suggested by Vlastiml.
* Explicitly avoid splitting THP on PTE installation, as suggested by Vlastimil. Note this has no impact on the guard pages logic, which has page table entry handlers at PUD, PMD and PTE level.
* AddedWARN_ON_ONCE()tomm/hugetlb.cpath where we don't expect a guard marker, as suggested by Vlastimil.
* Reverted change tois_poisoned_swp_entry()to exclude guard pages which has the effect ofMADV_FREE_not_ clearing guard pages. After discussion with Vlastimil, it became apparent that the ability to 'cancel' the freeing operation by writing to the mapping after having issued anMADV_FREEwould mean that we would risk unexpected behaviour should the guard pages be removed, so we now do not remove markers here at all.
* Added comment toPTE_MARKER_GUARDto highlight that memory tagged with the marker behaves as if it were a region mappedPROT_NONE, as highlighted by David.
* Rename poison -> install, unpoison -> remove (i.e.MADV_GUARD_INSTALL/MADV_GUARD_REMOVEoverMADV_GUARD_POISON/MADV_GUARD_REMOVE) at the request of David and John who both find the poison analogy confusing/overloaded.
* After a lot of discussion, replace the looping behaviour should page faults race with guard page installation with a modest reattempt followed by returning-ERESTARTNOINTRto have the operation abort and re-enter, relieving lock contention and avoiding the possibility of allowing a malicious sandboxed process to impact the mmap lock or stall the overall process more than necessary, as suggested by Jann and Vlastimil having raised the issue.
* Adjusted the page table walker so a populated huge PUD or PMD is correctly treated as being populated, necessitating a zap. In v2 we incorrectly skipped over these, which would cause the logic to wrongly proceed as if nothing were populated and the install succeeded. Instead, explicitly check to see if a huge page - if so, do not split but rather abort the operation and let zap take care of things.
* Updated the guard remove logic to not unnecessarily split huge pages either.
* Added a debug check to assert that the number of installed PTEs matches expectation, accounting for any existing guard pages.
* Adaptedvector_madvise()used by theprocess_madvise()system call to handle-ERESTARTNOINTRcorrectly.
https://lore.kernel.org/all/[email protected]/v2
* The macros inkselftest_harness.hseem to be broken -__EXPECT()is terminated by '} while (0);OPTIONAL_HANDLER(_assert)' meaning it is not safe in single line if / else or for /which blocks, however working around this results in checkpatch producing invalid warnings, as reported by Shuah.
* Fixing these macros is out of scope for this series, so compromise and instead rewrite test blocks so as to use multiple lines by separating out a decl in most cases. This has the side effect of, for the most part, making things more readable.
* Heavily document the use of the volatile keyword - we can't avoid checkpatch complaining about this, so we explain it, as reported by Shuah.
* Updated commit message to highlight that we skip tests we lack permissions for, as reported by Shuah.
* Replaced aperror()withksft_exit_fail_perror(), as reported by Shuah.
* Added user friendly messages to cases where tests are skipped due to lack of permissions, as reported by Shuah.
* Update the tool header to include the new MADV_GUARD_POISON/UNPOISON defines and directly includeasm-generic/mman.hto get the platform-neutral versions to ensure we import them.
* Finally fixed Vlastimil's email address in Suggested-by tags from suze to suse, as reported by Vlastimil.
* Added linux-api to cc list, as reported by Vlastimil.
https://lore.kernel.org/all/[email protected]/v1
* Un-RFC'd as appears no major objections to approach but rather debate on implementation.
* Fixed issue with arches which needmmu_context.handtlbfush.h. header imports in pagewalker logic to be able to useupdate_mmu_cache()as reported by the kernel test bot.
* Added comments in page walker logic to clarify who can useops->install_pteand why as well as adding acheck_ops_valid()helper function, as suggested by Christoph.
* Pass false in full parameter inpte_clear_not_present_full()as suggested by Jann.
* Stopped erroneously requiring a write lock for the poison operation as suggested by Jann and Suren.
* Movedanon_vma_prepare()to the start ofmadvise_guard_poison()to be consistent with how this is used elsewhere in the kernel as suggested by Jann.
* Avoid returning-EAGAINif we are raced on page faults, just keep looping and duck out if a fatal signal is pending or a conditional reschedule is needed, as suggested by Jann.
* Avoid needlessly splitting huge PUDs and PMDs by specifyingACTION_CONTINUE, as suggested by Jann.
https://lore.kernel.org/all/[email protected]/RFC
https://lore.kernel.org/all/[email protected]/Lorenzo Stoakes (5):
mm: pagewalk: add the ability to install PTEs
mm: addPTE_MARKER_GUARDPTE marker
mm: madvise: implement lightweight guard page mechanism
tools: testing: update tools UAPI header formman-common.hselftests/mm: add self tests for guard page featurearch/alpha/include/uapi/asm/mman.h | 3 + arch/mips/include/uapi/asm/mman.h | 3 + arch/parisc/include/uapi/asm/mman.h | 3 + arch/xtensa/include/uapi/asm/mman.h | 3 + include/linux/mm_inline.h | 2 +- include/linux/pagewalk.h | 18 +- include/linux/swapops.h | 24 +- include/uapi/asm-generic/mman-common.h | 3 + mm/hugetlb.c | 4 + mm/internal.h | 6 + mm/madvise.c | 239 ++++ mm/memory.c | 18 +- mm/mprotect.c | 6 +- mm/mseal.c | 1 + mm/pagewalk.c | 246 +++- tools/include/uapi/asm-generic/mman-common.h | 3 + tools/testing/selftests/mm/.gitignore | 1 + tools/testing/selftests/mm/Makefile | 1 + tools/testing/selftests/mm/guard-pages.c | 1243 ++++++++++++++++++ 19 files changed, 1751 insertions(+), 76 deletions(-) create mode 100644 tools/testing/selftests/mm/guard-pages.c--
2.47.0
Quoted 100 lines · Alexander Mikhalitsyn
Quoted 78 lines · Lorenzo Stoakes
Userland library functions such as allocators and threading implementations often require regions of memory to act as 'guard pages' - mappings which, when accessed, result in a fatal signal being sent to the accessing process.
The current means by which these are implemented is via a
PROT_NONEmmap()mapping, which provides the required semantics however incur an overhead of a VMA for each such region.With a great many processes and threads, this can rapidly add up and incur a significant memory penalty. It also has the added problem of preventing merges that might otherwise be permitted.
This series takes a different approach - an idea suggested by Vlasimil Babka (and before him David Hildenbrand and Jann Horn - perhaps more - the provenance becomes a little tricky to ascertain after this - please forgive any omissions!) - rather than locating the guard pages at the VMA layer, instead placing them in page tables mapping the required ranges.
Early testing of the prototype version of this code suggests a 5 times speed up in memory mapping invocations (in conjunction with use of
process_madvise()) and a 13% reduction in VMAs on an entirely idle android system and unoptimised code.We expect with optimisation and a loaded system with a larger number of guard pages this could significantly increase, but in any case these numbers are encouraging.
This way, rather than having separate VMAs specifying which parts of a range are guard pages, instead we have a VMA spanning the entire range of memory a user is permitted to access and including ranges which are to be 'guarded'.
After mapping this, a user can specify which parts of the range should result in a fatal signal when accessed.
By restricting the ability to specify guard pages to memory mapped by existing VMAs, we can rely on the mappings being torn down when the mappings are ultimately unmapped and everything works simply as if the memory were not faulted in, from the point of view of the containing VMAs.
This mechanism in effect poisons memory ranges similar to hardware memory poisoning, only it is an entirely software-controlled form of poisoning.
The mechanism is implemented via
madvise()behaviour -MADV_GUARD_INSTALLwhich installs page table-level guard page markers - andMADV_GUARD_REMOVE- which clears them.Guard markers can be installed across multiple VMAs and any existing mappings will be cleared, that is zapped, before installing the guard page markers in the page tables.
There is no concept of 'nested' guard markers, multiple attempts to install guard markers in a range will, after the first attempt, have no effect.
Importantly, removing guard markers over a range that contains both guard markers and ordinary backed memory has no effect on anything but the guard markers (including leaving huge pages un-split), so a user can safely remove guard markers over a range of memory leaving the rest intact.
The actual mechanism by which the page table entries are specified makes use of existing logic - PTE markers, which are used for the userfaultfd
UFFDIO_POISONmechanism.Unfortunately
PTE_MARKER_POISONEDis not suited for the guard page mechanism as it results inVM_FAULT_HWPOISONsemantics in the fault handler, so we add our own specificPTE_MARKER_GUARDand adapt existing logic to handle it.We also extend the generic page walk mechanism to allow for installation of PTEs (carefully restricted to memory management logic only to prevent unwanted abuse).
We ensure that zapping performed by
MADV_DONTNEEDandMADV_FREEdo not remove guard markers, nor does forking (except whenVM_WIPEONFORKis specified for a VMA which implies a total removal of memory characteristics).Quoted 8 lines
It's important to note that the guard page implementation is emphatically NOT a security feature, so a user can remove the markers if they wish. We simply implement it in such a way as to provide the least surprising behaviour.
An extensive set of self-tests are provided which ensure behaviour is as expected and additionally self-documents expected behaviour of guard ranges.
Dear Lorenzo,
Dear colleagues,sorry about raising an old thread.
It looks like this feature is now used in glibc [1]. And we noticed failures in CRIU [2] CI on Fedora Rawhide userspace. Now a question is how we can properly detect such "guarded" pages from user space. As I can see from
MADV_GUARD_INSTALLimplementation, it does not modify VMA flags anyhow, but only page tables. It means that /proc/<pid>/maps and /proc/<pid>/smaps interfaces are useless in this case. (Please, correct me if I'm missing anything here.)
Quoted 3 lines
I wonder if you have any ideas / suggestions regarding Checkpoint/Restore here. We (CRIU devs) are happy to develop some patches to bring some uAPI to expose
MADV_GUARDs, but before going into this we decided to raise this question in LKML.
See [1] and [2]
[1] https://lkml.kernel.org/r/[email protected]
[2] https://lwn.net/Articles/1011366/
Signature · 3 lines
Cheers, David / dhildenb
Quoted 2 lines · David Hildenbrand
Quoted 1 line · Alexander Mikhalitsyn
On Mon, Oct 28, 2024 at 02:13:26PM +0000, Lorenzo Stoakes wrote:
[snip]
Quoted 6 lines
Quoted 6 lines
Dear Lorenzo,
Dear colleagues,sorry about raising an old thread.
No worries!
Quoted 6 lines
Quoted 6 lines
It looks like this feature is now used in glibc [1]. And we noticed failures in CRIU [2] CI on Fedora Rawhide userspace. Now a question is how we can properly detect such "guarded" pages from user space. As I can see from
MADV_GUARD_INSTALLimplementation, it does not modify VMA flags anyhow, but only page tables. It means that /proc/<pid>/maps and /proc/<pid>/smaps interfaces are useless in this case. (Please, correct me if I'm missing anything here.)
Sorry to hear that.
Quoted 4 lines
Quoted 4 lines
I wonder if you have any ideas / suggestions regarding Checkpoint/Restore here. We (CRIU devs) are happy to develop some patches to bring some uAPI to expose
MADV_GUARDs, but before going into this we decided to raise this question in LKML.
There's no need.
Quoted 7 lines
See [1] and [2]
[1]
https://lkml.kernel.org/r/[email protected]
[2] https://lwn.net/Articles/1011366/
As per David, there is already a feature heading for 6.15 which will allow this to be exposed by /proc/$pid/pagemap.
In addition, I plan to add a 'maybe has guard regions' flag that can be observed in smaps to assist narrowing down which VMAs to check.
However unfortunately due to the nature of the feature there is no getting around the need to traverse page tables.
That thread (and LWN article :) go into extensive detail as to why. In essence - it's the basis of its design to express this information at the page table level only, and any attempt to encode this at the VMA level (other than a 'maybe' flag) would eliminate the purpose of the feature.
Let me know if there's any way I can help!
Cheers, Lorenzo
Quoted 7 lines
--
Cheers,David / dhildenb
Quoted 17 lines · Lorenzo Stoakes
Quoted 2 lines · David Hildenbrand
Quoted 1 line · Alexander Mikhalitsyn
On Mon, Oct 28, 2024 at 02:13:26PM +0000, Lorenzo Stoakes wrote:
[snip]
Quoted 6 lines
Quoted 6 lines
Dear Lorenzo,
Dear colleagues,sorry about raising an old thread.
No worries!
Quoted 8 lines
Quoted 6 lines
Quoted 6 lines
It looks like this feature is now used in glibc [1]. And we noticed failures in CRIU [2] CI on Fedora Rawhide userspace. Now a question is how we can properly detect such "guarded" pages from user space. As I can see from
MADV_GUARD_INSTALLimplementation, it does not modify VMA flags anyhow, but only page tables. It means that /proc/<pid>/maps and /proc/<pid>/smaps interfaces are useless in this case. (Please, correct me if I'm missing anything here.)Sorry to hear that.
No problem at all ;)
Quoted 10 lines
Quoted 5 lines
Quoted 5 lines
I wonder if you have any ideas / suggestions regarding Checkpoint/Restore here. We (CRIU devs) are happy to develop some patches to bring some uAPI to expose
MADV_GUARDs, but before going into this we decided to raise this question in LKML.There's no need.
Quoted 2 lines
Quoted 8 lines
Quoted 5 lines
See [1] and [2]
[1]
https://lkml.kernel.org/r/[email protected]
[2] https://lwn.net/Articles/1011366/As per David, there is already a feature heading for 6.15 which will allow this to be exposed by
/proc/$pid/pagemap.
Yeah, that's indeed very helpful!
Quoted 11 lines
In addition, I plan to add a 'maybe has guard regions' flag that can be observed in smaps to assist narrowing down which VMAs to check.
However unfortunately due to the nature of the feature there is no getting around the need to traverse page tables.
That thread (and LWN article :) go into extensive detail as to why. In essence - it's the basis of its design to express this information at the page table level only, and any attempt to encode this at the VMA level (other than a 'maybe' flag) would eliminate the purpose of the feature.
Thank you very much for these explanations!
I'll read the LWN article too.
Quoted 2 lines
Let me know if there's any way I can help!
Keep in contact! ;)
Kind regards,
Alex
Quoted 10 lines
Cheers, Lorenzo
Quoted 7 lines
--
Cheers,David / dhildenb
Quoted 102 lines · David Hildenbrand
Quoted 100 lines · Alexander Mikhalitsyn
Quoted 78 lines · Lorenzo Stoakes
Userland library functions such as allocators and threading implementations often require regions of memory to act as 'guard pages' - mappings which, when accessed, result in a fatal signal being sent to the accessing process.
The current means by which these are implemented is via a
PROT_NONEmmap()mapping, which provides the required semantics however incur an overhead of a VMA for each such region.With a great many processes and threads, this can rapidly add up and incur a significant memory penalty. It also has the added problem of preventing merges that might otherwise be permitted.
This series takes a different approach - an idea suggested by Vlasimil Babka (and before him David Hildenbrand and Jann Horn - perhaps more - the provenance becomes a little tricky to ascertain after this - please forgive any omissions!) - rather than locating the guard pages at the VMA layer, instead placing them in page tables mapping the required ranges.
Early testing of the prototype version of this code suggests a 5 times speed up in memory mapping invocations (in conjunction with use of
process_madvise()) and a 13% reduction in VMAs on an entirely idle android system and unoptimised code.We expect with optimisation and a loaded system with a larger number of guard pages this could significantly increase, but in any case these numbers are encouraging.
This way, rather than having separate VMAs specifying which parts of a range are guard pages, instead we have a VMA spanning the entire range of memory a user is permitted to access and including ranges which are to be 'guarded'.
After mapping this, a user can specify which parts of the range should result in a fatal signal when accessed.
By restricting the ability to specify guard pages to memory mapped by existing VMAs, we can rely on the mappings being torn down when the mappings are ultimately unmapped and everything works simply as if the memory were not faulted in, from the point of view of the containing VMAs.
This mechanism in effect poisons memory ranges similar to hardware memory poisoning, only it is an entirely software-controlled form of poisoning.
The mechanism is implemented via
madvise()behaviour -MADV_GUARD_INSTALLwhich installs page table-level guard page markers - andMADV_GUARD_REMOVE- which clears them.Guard markers can be installed across multiple VMAs and any existing mappings will be cleared, that is zapped, before installing the guard page markers in the page tables.
There is no concept of 'nested' guard markers, multiple attempts to install guard markers in a range will, after the first attempt, have no effect.
Importantly, removing guard markers over a range that contains both guard markers and ordinary backed memory has no effect on anything but the guard markers (including leaving huge pages un-split), so a user can safely remove guard markers over a range of memory leaving the rest intact.
The actual mechanism by which the page table entries are specified makes use of existing logic - PTE markers, which are used for the userfaultfd
UFFDIO_POISONmechanism.Unfortunately
PTE_MARKER_POISONEDis not suited for the guard page mechanism as it results inVM_FAULT_HWPOISONsemantics in the fault handler, so we add our own specificPTE_MARKER_GUARDand adapt existing logic to handle it.We also extend the generic page walk mechanism to allow for installation of PTEs (carefully restricted to memory management logic only to prevent unwanted abuse).
We ensure that zapping performed by
MADV_DONTNEEDandMADV_FREEdo not remove guard markers, nor does forking (except whenVM_WIPEONFORKis specified for a VMA which implies a total removal of memory characteristics).Quoted 8 lines
It's important to note that the guard page implementation is emphatically NOT a security feature, so a user can remove the markers if they wish. We simply implement it in such a way as to provide the least surprising behaviour.
An extensive set of self-tests are provided which ensure behaviour is as expected and additionally self-documents expected behaviour of guard ranges.
Dear Lorenzo,
Dear colleagues,sorry about raising an old thread.
It looks like this feature is now used in glibc [1]. And we noticed failures in CRIU [2] CI on Fedora Rawhide userspace. Now a question is how we can properly detect such "guarded" pages from user space. As I can see from
MADV_GUARD_INSTALLimplementation, it does not modify VMA flags anyhow, but only page tables. It means that /proc/<pid>/maps and /proc/<pid>/smaps interfaces are useless in this case. (Please, correct me if I'm missing anything here.)
Quoted 6 lines
Quoted 3 lines
I wonder if you have any ideas / suggestions regarding Checkpoint/Restore here. We (CRIU devs) are happy to develop some patches to bring some uAPI to expose
MADV_GUARDs, but before going into this we decided to raise this question in LKML.See [1] and [2]
Hi David,
Huge thanks for such a fast and helpful reply ;)
Quoted 10 lines
[1]
https://lkml.kernel.org/r/[email protected]
[2] https://lwn.net/Articles/1011366/--
Cheers,David / dhildenb
Kind regards,
Alex