implement lightweight guard pages
Subsystems (14)
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.
Any poisoned region of memory is also able to 'unpoisoned', that is, to have its poison markers removed.
The mechanism is implemented via madvise() behaviour - MADV_GUARD_POISON which simply poisons ranges - and MADV_GUARD_UNPOISON - which clears this poisoning.
Poisoning can be performed across multiple VMAs and any existing mappings will be cleared, that is zapped, before installing the poisoned page table mappings.
There is no concept of 'nested' poisoning, multiple attempts to poison a range will, after the first poisoning, have no effect.
Importantly, unpoisoning of poisoned ranges has no effect on non-poisoned memory, so a user can safely unpoison a range of memory and clear only poison page table mappings 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, for instance, MADV_DONTNEED, does not remove guard poison 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 poisoning 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 poisoned ranges.
Lorenzo Stoakes (4):
mm: pagewalk: add the ability to install PTEs
mm: add PTE_MARKER_GUARD PTE marker
mm: madvise: implement lightweight guard page mechanism 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 | 26 +- include/uapi/asm-generic/mman-common.h | 3 + mm/hugetlb.c | 3 + mm/internal.h | 6 + mm/madvise.c | 158 +++ mm/memory.c | 18 +- mm/mprotect.c | 3 +- mm/mseal.c | 1 + mm/pagewalk.c | 174 ++-- tools/testing/selftests/mm/.gitignore | 1 + tools/testing/selftests/mm/Makefile | 1 + tools/testing/selftests/mm/guard-pages.c | 1168 ++++++++++++++++++++++ 18 files changed, 1525 insertions(+), 69 deletions(-) create mode 100644 tools/testing/selftests/mm/guard-pages.c
--
2.46.2
RFC PATCH 1/4 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, we make use of existing logic to split it. Then once we reach the PTE level, we invoke the install_pte() callback which provides a PTE entry to install. 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.
--- include/linux/pagewalk.h | 18 +++- mm/internal.h | 6 ++ mm/pagewalk.c | 174 ++++++++++++++++++++++++++------------- 3 files changed, 136 insertions(+), 62 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>
@@ -1443,4 +1444,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 +115 -59
300 lines not on this page · raw message
Signature · 1 line
2.46.2
kernel test robot
build botRe: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
kernel test robot noticed the following build errors:
Hi Lorenzo,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on akpm-mm/mm-everything]
[also build test ERROR on deller-parisc/for-next arnd-asm-generic/master linus/master v6.11 next-20240927] [cannot apply to jcmvbkbc-xtensa/xtensa-for-next]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Lorenzo-Stoakes/mm-pagewalk-add-the-ability-to-install-PTEs/20240927-205253 base: https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything patch link: https://lore.kernel.org/r/59e218670565accf978aeb8cf4745de4c0738773.1727440966.git.lorenzo.stoakes%40oracle.com patch subject: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs config: microblaze-allnoconfig (https://download.01.org/0day-ci/archive/20240930/[email protected]/config) compiler: microblaze-linux-gcc (GCC) 14.1.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240930/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
mm/pagewalk.c: In function 'walk_pte_range_inner':
>> mm/pagewalk.c:45:33: error: implicit declaration of function 'update_mmu_cache'; did you mean 'update_mmu_tlb'? [-Wimplicit-function-declaration]
45 | update_mmu_cache(walk->vma, addr, pte);
| ^~~~~~~~~~~~~~~~
| update_mmu_tlbvim +45 mm/pagewalk.c
26
27 static int walk_pte_range_inner(pte_t *pte, unsigned long addr,
28 unsigned long end, struct mm_walk *walk)
29 {
30 const struct mm_walk_ops *ops = walk->ops;
31 int err = 0;
32
33 for (;;) {
34 if (ops->install_pte && pte_none(ptep_get(pte))) {
35 pte_t new_pte;
36
37 err = ops->install_pte(addr, addr + PAGE_SIZE, &new_pte,
38 walk);
39 if (err)
40 break;
41
42 set_pte_at(walk->mm, addr, pte, new_pte);
43 /* Non-present before, so for arches that need it. */
44 if (!WARN_ON_ONCE(walk->no_vma))
> 45 update_mmu_cache(walk->vma, addr, pte);
46 } else {
47 err = ops->pte_entry(pte, addr, addr + PAGE_SIZE, walk);
48 if (err)
49 break;
50 }
51 if (addr >= end - PAGE_SIZE)
52 break;
53 addr += PAGE_SIZE;
54 pte++;
55 }
56 return err;
57 }
58 Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
Quoted 7 lines · kernel test robot
Hi Lorenzo,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on akpm-mm/mm-everything]
[also build test ERROR on deller-parisc/for-next arnd-asm-generic/master linus/master v6.11 next-20240927]
Thanks for the report!
Quoted 1 line
[cannot apply to jcmvbkbc-xtensa/xtensa-for-next]
Hm strange that it doesn't apply there.
Quoted 1 line
[If your patch is applied to the wrong git tree, kindly drop us a note.
This is aplied vs. Andrew's mm-unstable tree.
Quoted 16 lines
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]url: https://github.com/intel-lab-lkp/linux/commits/Lorenzo-Stoakes/mm-pagewalk-add-the-ability-to-install-PTEs/20240927-205253 base: https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything patch link: https://lore.kernel.org/r/59e218670565accf978aeb8cf4745de4c0738773.1727440966.git.lorenzo.stoakes%40oracle.com patch subject: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs config: microblaze-allnoconfig (https://download.01.org/0day-ci/archive/20240930/[email protected]/config) compiler: microblaze-linux-gcc (GCC) 14.1.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240930/[email protected]/reproduce)If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
Quoted 7 lines
All errors (new ones prefixed by >>):
mm/pagewalk.c: In function 'walk_pte_range_inner':Quoted 1 line
Quoted 1 line
mm/pagewalk.c:45:33: error: implicit declaration of function 'update_mmu_cache'; did you mean 'update_mmu_tlb'? [-Wimplicit-function-declaration]45 | update_mmu_cache(walk->vma, addr, pte); | ^~~~~~~~~~~~~~~~ | update_mmu_tlb
This is a header thing, we need to import <asm/tlbflush.h> here afaict. Another one of these functions that is, by chance, imported on x86-64 (my local arch), but not on other arches.
I will update this on respin, and reply to the thread on-list to publicly note this.
Quoted 41 lines
vim +45
mm/pagewalk.c26 27 static int walk_pte_range_inner(pte_t *pte, unsigned long addr, 28 unsigned long end, struct mm_walk *walk) 29 { 30 const struct mm_walk_ops *ops = walk->ops; 31 int err = 0; 32 33 for (;;) { 34 if (ops->install_pte && pte_none(ptep_get(pte))) { 35 pte_t new_pte; 36 37 err = ops->install_pte(addr, addr + PAGE_SIZE, &new_pte, 38 walk); 39 if (err) 40 break; 41 42 set_pte_at(walk->mm, addr, pte, new_pte); 43 /* Non-present before, so for arches that need it. */ 44 if (!WARN_ON_ONCE(walk->no_vma))Quoted 1 line
45
update_mmu_cache(walk->vma, addr, pte);46 } else { 47 err = ops->pte_entry(pte, addr, addr + PAGE_SIZE, walk); 48 if (err) 49 break; 50 } 51 if (addr >= end - PAGE_SIZE) 52 break; 53 addr += PAGE_SIZE; 54 pte++; 55 } 56 return err; 57 } 58--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
Re: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
In reply to Lorenzo StoakesQuoted 125 lines · Lorenzo Stoakes
The existing generic pagewalk logic permits the walking of page tables, invoking callbacks at individual page table levels via user-provided
mm_walk_opscallbacks.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 inmm_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, we make use of existing logic to split it. Then once we reach the PTE level, we invoke the
install_pte()callback which provides a PTE entry to install. 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 ofpte_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 tomm/internal.h.Signed-off-by Lorenzo Stoakes <[email protected]>--- include/linux/pagewalk.h | 18 +++- mm/internal.h | 6 ++ mm/pagewalk.c | 174 ++++++++++++++++++++++++++------------- 3 files changed, 136 insertions(+), 62 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> @@ -1443,4 +1444,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 +0
-0
mm/pagewalk.c line 7
Quoted 2 lines
mm/pagewalk.c +0
-0@@ -6,6 +6,8 @@#include <linux/swap.h> #include <linux/swapops.h>
We need to add an include here for asm/tlbflush.h I believe to make update_mmu_cache() available, this was overlooked as for x86 this is included through some other header.
I will add on respin.
Quoted 317 lines
mm/pagewalk.c +115
-60+#include "internal.h" +/* * We want to know the real level where a entry is located ignoring any * folding of levels which may be happening. For example if p4d is folded then @@ -29,9 +31,23 @@ static int walk_pte_range_inner(pte_t *pte, unsigned long addr,int err =0 ;for (;;) { - err = ops->pte_entry (pte, addr, addr +PAGE_SIZE , walk); -if (err) -break ; +if (ops->install_pte &&pte_none (ptep_get (pte))) { +pte_t new_pte; + + err = ops->install_pte (addr, addr +PAGE_SIZE , &new_pte, + walk); +if (err) +break ; + +set_pte_at (walk->mm, addr, pte, new_pte); +/* Non-present before, so for arches that need it. */ +if (!WARN_ON_ONCE (walk->no_vma)) +update_mmu_cache (walk->vma, addr, pte); + }else { + err = ops->pte_entry (pte, addr, addr +PAGE_SIZE , walk); +if (err) +break ; + }if (addr >= end -PAGE_SIZE )break ; addr +=PAGE_SIZE ;@@ -89,11 +105,14 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, again: next =pmd_addr_end (addr, end);if (pmd_none (*pmd)) { -if (ops->pte_hole) +if (ops->install_pte) + err =__pte_alloc (walk->mm, pmd); +else if (ops->pte_hole) err = ops->pte_hole (addr, next, depth, walk);if (err)break ; -continue ; +if (!ops->install_pte) +continue ; } walk->action =ACTION_SUBTREE ;@@ -116,7 +135,7 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,*/ if ((!walk->vma && (pmd_leaf (*pmd) || !pmd_present (*pmd))) || walk->action ==ACTION_CONTINUE || - !(ops->pte_entry)) + !(ops->pte_entry || ops->install_pte))continue ;if (walk->vma)@@ -148,11 +167,14 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, again: next =pud_addr_end (addr, end);if (pud_none (*pud)) { -if (ops->pte_hole) +if (ops->install_pte) + err =__pmd_alloc (walk->mm, pud, addr); +else if (ops->pte_hole) err = ops->pte_hole (addr, next, depth, walk);if (err)break ; -continue ; +if (!ops->install_pte) +continue ; } walk->action =ACTION_SUBTREE ;@@ -167,7 +189,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,if ((!walk->vma && (pud_leaf (*pud) || !pud_present (*pud))) || walk->action ==ACTION_CONTINUE || - !(ops->pmd_entry || ops->pte_entry)) + !(ops->pmd_entry || ops->pte_entry || ops->install_pte))continue ;if (walk->vma)@@ -196,18 +218,22 @@ static int walk_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end, do { next = p4d_addr_end(addr, end); if (p4d_none_or_clear_bad(p4d)) { - if (ops->pte_hole) + if (ops->install_pte) + err = __pud_alloc(walk->mm, p4d, addr); + else if (ops->pte_hole) err = ops->pte_hole(addr, next, depth, walk); if (err) break; - continue; + if (!ops->install_pte) + continue; } if (ops->p4d_entry) { err = ops->p4d_entry(p4d, addr, next, walk); if (err) break; } - if (ops->pud_entry || ops->pmd_entry || ops->pte_entry) + if (ops->pud_entry || ops->pmd_entry || ops->pte_entry || + ops->install_pte) err = walk_pud_range(p4d, addr, next, walk); if (err) break;@@ -231,18 +257,22 @@ static int walk_pgd_range(unsigned long addr, unsigned long end, do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) { - if (ops->pte_hole) + if (ops->install_pte) + err = __p4d_alloc(walk->mm, pgd, addr); + else if (ops->pte_hole) err = ops->pte_hole(addr, next, 0, walk); if (err) break; - continue; + if (!ops->install_pte) + continue; } if (ops->pgd_entry) { err = ops->pgd_entry(pgd, addr, next, walk); if (err) break; } - if (ops->p4d_entry || ops->pud_entry || ops->pmd_entry || ops->pte_entry) + if (ops->p4d_entry || ops->pud_entry || ops->pmd_entry || + ops->pte_entry || ops->install_pte) err = walk_p4d_range(pgd, addr, next, walk); if (err) break;@@ -334,6 +364,11 @@ static int __walk_page_range(unsigned long start, unsigned long end,int err =0 ;struct vm_area_struct *vma = walk->vma;const struct mm_walk_ops *ops = walk->ops; +bool is_hugetlb =is_vm_hugetlb_page (vma); + +/* We do not support hugetlb PTE installation. */ +if (ops->install_pte && is_hugetlb) +return -EINVAL ;if (ops->pre_vma) { err = ops->pre_vma (start, end, walk);@@ -341,7 +376,7 @@ static int __walk_page_range(unsigned long start, unsigned long end,return err; } -if (is_vm_hugetlb_page (vma)) { +if (is_hugetlb) {if (ops->hugetlb_entry) err =walk_hugetlb_range (start, end, walk); }else @@ -380,47 +415,7 @@ static inline void process_vma_walk_lock(struct vm_area_struct *vma,#endif } -/** -* walk_page_range - walk page table with caller specific callbacks -* @mm: mm_struct representing the target process of page table walk -* @start: start address of the virtual address range -* @end: end address of the virtual address range -* @ops: operation to call during the walk -* @private: private data for callbacks' usage -* -* Recursively walk the page table tree of the process represented by @mm -* within the virtual address range [@start, @end). During walking, we can do -* some caller-specific works for each entry, by setting up pmd_entry(), -* pte_entry(), and/or hugetlb_entry(). If you don't set up for some of these -* callbacks, the associated entries/pages are just ignored. -* The return values of these callbacks are commonly defined like below: -* -* - 0 : succeeded to handle the current entry, and if you don't reach the -* end address yet, continue to walk. -* - >0 : succeeded to handle the current entry, and return to the caller -* with caller specific value. -* - <0 : failed to handle the current entry, and return to the caller -* with error code. -* -* Before starting to walk page table, some callers want to check whether -* they really want to walk over the current vma, typically by checking -* its vm_flags. walk_page_test() and @ops->test_walk() are used for this -* purpose. -* -* If operations need to be staged before and committed after a vma is walked, -* there are two callbacks, pre_vma() and post_vma(). Note that post_vma(), -* since it is intended to handle commit-type operations, can't return any -* errors. -* -* struct mm_walk keeps current values of some common data like vma and pmd, -* which are useful for the access from callbacks. If you want to pass some -* caller-specific data to callbacks, @private should be helpful. -* -* Locking: -* Callers of walk_page_range() and walk_page_vma() should hold @mm->mmap_lock, -* because these function traverse vma list and/or access to vma's data. -*/ -int walk_page_range (struct mm_struct *mm,unsigned long start, +int walk_page_range_mm (struct mm_struct *mm,unsigned long start,unsigned long end,const struct mm_walk_ops *ops,void *private) {@@ -479,6 +474,57 @@ int walk_page_range(struct mm_struct *mm, unsigned long start,return err; } +/** +* walk_page_range - walk page table with caller specific callbacks +* @mm: mm_struct representing the target process of page table walk +* @start: start address of the virtual address range +* @end: end address of the virtual address range +* @ops: operation to call during the walk +* @private: private data for callbacks' usage +* +* Recursively walk the page table tree of the process represented by @mm +* within the virtual address range [@start, @end). During walking, we can do +* some caller-specific works for each entry, by setting up pmd_entry(), +* pte_entry(), and/or hugetlb_entry(). If you don't set up for some of these +* callbacks, the associated entries/pages are just ignored. +* The return values of these callbacks are commonly defined like below: +* +* - 0 : succeeded to handle the current entry, and if you don't reach the +* end address yet, continue to walk. +* - >0 : succeeded to handle the current entry, and return to the caller +* with caller specific value. +* - <0 : failed to handle the current entry, and return to the caller +* with error code. +* +* Before starting to walk page table, some callers want to check whether +* they really want to walk over the current vma, typically by checking +* its vm_flags. walk_page_test() and @ops->test_walk() are used for this +* purpose. +* +* If operations need to be staged before and committed after a vma is walked, +* there are two callbacks, pre_vma() and post_vma(). Note that post_vma(), +* since it is intended to handle commit-type operations, can't return any +* errors. +* +* struct mm_walk keeps current values of some common data like vma and pmd, +* which are useful for the access from callbacks. If you want to pass some +* caller-specific data to callbacks, @private should be helpful. +* +* Locking: +* Callers of walk_page_range() and walk_page_vma() should hold @mm->mmap_lock, +* because these function traverse vma list and/or access to vma's data. +*/ +int walk_page_range (struct mm_struct *mm,unsigned long start, +unsigned long end,const struct mm_walk_ops *ops, +void *private) +{ +/* For internal use only. */ +if (ops->install_pte) +return -EINVAL ; + +return walk_page_range_mm (mm, start, end, ops, private); +} +/** * walk_page_range_novma - walk a range of pagetables not backed by a vma * @mm: mm_struct representing the target process of page table walk @@ -494,7 +540,7 @@ int walk_page_range(struct mm_struct *mm, unsigned long start,* walking the kernel pages tables or page tables for firmware. * * Note: Be careful to walk the kernel pages tables, the caller may be need to -* take other effective approache (mmap lock may be insufficient) to prevent +* take other effective approaches (mmap lock may be insufficient) to prevent * the intermediate kernel page tables belonging to the specified address range * from being freed (e.g. memory hot-remove). */ @@ -511,7 +557,7 @@ int walk_page_range_novma(struct mm_struct *mm, unsigned long start, .no_vma = true }; -if (start >= end || !walk.mm) +if (start >= end || !walk.mm || ops->install_pte)return -EINVAL ;/* @@ -556,6 +602,9 @@ int walk_page_range_vma(struct vm_area_struct *vma, unsigned long start,return -EINVAL ;if (start < vma->vm_start || end > vma->vm_end)return -EINVAL ; +/* For internal use only. */ +if (ops->install_pte) +return -EINVAL ;process_mm_walk_lock (walk.mm, ops->walk_lock);process_vma_walk_lock (vma, ops->walk_lock);@@ -574,6 +623,9 @@ int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops,if (!walk.mm)return -EINVAL ; +/* For internal use only. */ +if (ops->install_pte) +return -EINVAL ;process_mm_walk_lock (walk.mm, ops->walk_lock);process_vma_walk_lock (vma, ops->walk_lock);@@ -623,6 +675,10 @@ int walk_page_mapping(struct address_space *mapping, pgoff_t first_index,unsigned long start_addr, end_addr;int err =0 ; +/* For internal use only. */ +if (ops->install_pte) +return -EINVAL ; +lockdep_assert_held (&mapping->i_mmap_rwsem);vma_interval_tree_foreach (vma, &mapping->i_mmap, first_index, first_index + nr - 1) { --2.46.2
Re: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
In reply to Lorenzo StoakesQuoted 5 lines · Lorenzo Stoakes
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 inmm_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.
[...]
Quoted 2 lines
Signed-off-by Lorenzo Stoakes <[email protected]>
Re: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
Quoted 7 lines · Jann Horn
Quoted 5 lines · Lorenzo Stoakes
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 inmm_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.
Quoted 5 lines
[...]
Quoted 2 lines
Signed-off-by Lorenzo Stoakes <[email protected]>Reviewed-by Jann Horn <[email protected]>
Thanks!
Re: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
In reply to Lorenzo StoakesHi Lorenzo,
sorry for only replying to this so late.
Quoted 11 lines · Lorenzo Stoakes
The existing generic pagewalk logic permits the walking of page tables, invoking callbacks at individual page table levels via user-provided
mm_walk_opscallbacks.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.
I do like the idea of having common code for installing page tables!
Minor nits below:
mm/pagewalk.c static inline void process_vma_walk_lock(struct vm_area_struct *vma, · line 420
Quoted 3 lines
mm/pagewalk.c +1
-0+int walk_page_range_mm (struct mm_struct *mm,unsigned long start,unsigned long end,const struct mm_walk_ops *ops,void *private)
It would be good to have a minimum level of documentation for this function, including how it differs from walk_page_range and why it should remain internal.
mm/pagewalk.c int walk_page_range(struct mm_struct *mm, unsigned long start, · line 523
Quoted 3 lines
mm/pagewalk.c +3
-0+/* For internal use only. */ +if (ops->install_pte) +return -EINVAL ;
And this should probably be expanded a bit, including that no exported symbol should allow inserting arbitrary PTEs. Maybe best done with a helper to share that comment with the other places that have this check.
Re: [RFC PATCH 1/4] mm: pagewalk: add the ability to install PTEs
Quoted 3 lines · Christoph Hellwig
Hi Lorenzo,
sorry for only replying to this so late.
No worries, and thanks for taking a look! :)
Quoted 9 lines · Lorenzo Stoakes
Quoted 7 lines
The existing generic pagewalk logic permits the walking of page tables, invoking callbacks at individual page table levels via user-provided
mm_walk_opscallbacks.This is useful for traversing existing page table entries, but precludes the ability to establish new ones.
Quoted 7 lines
Quoted 4 lines
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.
I do like the idea of having common code for installing page tables!
Awesome.
Quoted 9 lines
Minor nits below:
mm/pagewalk.c static inline void process_vma_walk_lock(struct vm_area_struct *vma, · line 420
Quoted 3 lines
mm/pagewalk.c +1
-0+int walk_page_range_mm (struct mm_struct *mm,unsigned long start,unsigned long end,const struct mm_walk_ops *ops,void *private)It would be good to have a minimum level of documentation for this function, including how it differs from
walk_page_rangeand why it should remain internal.
Will add on respin!
Quoted 10 lines
mm/pagewalk.c int walk_page_range(struct mm_struct *mm, unsigned long start, · line 523
Quoted 4 lines
mm/pagewalk.c +3
-0+/* For internal use only. */ +if (ops->install_pte) +return -EINVAL ;And this should probably be expanded a bit, including that no exported symbol should allow inserting arbitrary PTEs. Maybe best done with a helper to share that comment with the other places that have this check.
Yeah a helper makes sense actually, a more general 'are these ops valid?' thing. Will update on next respin with some explanation.
The next iteration I plan to un-RFC as seems generally the concept is unopposed for this series, will make these changes then.
Thanks!
RFC PATCH 2/4 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 the like.
--- include/linux/mm_inline.h | 2 +- include/linux/swapops.h | 26 ++++++++++++++++++++++++-- mm/hugetlb.c | 3 +++ mm/memory.c | 18 +++++++++++++++--- 4 files changed, 43 insertions(+), 6 deletions(-)
include/linux/mm_inline.h +1 -1
@@ -531,7 +531,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 +24 -2
@@ -426,9 +426,15 @@ 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. */ +#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) {
@@ -461,9 +467,25 @@ static inline swp_entry_t make_poisoned_swp_entry(void) }static inline int is_poisoned_swp_entry (swp_entry_t entry) +{ +/* +* We treat guard pages as poisoned too as these have the same semantics +* as poisoned ranges, only with different fault handling. +*/ +return is_pte_marker_entry (entry) && + (pte_marker_get (entry) & + (PTE_MARKER_POISONED |PTE_MARKER_GUARD )); +} + +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_POISONED ); + (pte_marker_get (entry) &PTE_MARKER_GUARD ); }/*
mm/hugetlb.c +3 -0
@@ -6348,6 +6348,9 @@ 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 (marker &PTE_MARKER_GUARD ) { + ret =VM_FAULT_SIGSEGV ; + goto out_mutex; } }
mm/memory.c +15 -3
@@ -1457,7 +1457,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;
@@ -1478,7 +1478,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 (;;) {
@@ -1673,7 +1673,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)) {
@@ -4005,6 +4013,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);
Signature · 1 line
2.46.2
Jann Horn
reviewerRe: [RFC PATCH 2/4] mm: add PTE_MARKER_GUARD PTE marker
Quoted 2 lines · Lorenzo Stoakes
Add a new PTE marker that results in any access causing the accessing process to segfault.
[...]
include/linux/swapops.h static inline swp_entry_t make_poisoned_swp_entry(void) · line 478
Quoted 10 lines
static inline int
is_poisoned_swp_entry(swp_entry_t entry)include/linux/swapops.h +9
-0+{ +/* +* We treat guard pages as poisoned too as these have the same semantics +* as poisoned ranges, only with different fault handling. +*/ +return is_pte_marker_entry (entry) && + (pte_marker_get (entry) & + (PTE_MARKER_POISONED |PTE_MARKER_GUARD )); +}
This means MADV_FREE will also clear guard PTEs, right?
Quoted 27 lines
mm/memory.c +2
-3@@ -1457,7 +1457,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;@@ -1478,7 +1478,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 (;;) {@@ -1673,7 +1673,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))
mm/memory.c static unsigned long zap_pte_range(struct mmu_gather *tlb, · line 1685
Quoted 10 lines
mm/memory.c +9
-0+ !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 ;
Just a comment: It's nice that the feature is restricted to anonymous VMAs, otherwise we'd have to figure out here what to do about unmap_mapping_folio() (which sets ZAP_FLAG_DROP_MARKER together with details.single_folio)...
Quoted 16 lines
mm/memory.c +4
-1}else if (is_hwpoison_entry (entry) ||is_poisoned_swp_entry (entry)) {@@ -4005,6 +4013,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); --2.46.2
Re: [RFC PATCH 2/4] mm: add PTE_MARKER_GUARD PTE marker
Quoted 5 lines · Jann Horn
Quoted 2 lines · Lorenzo Stoakes
Add a new PTE marker that results in any access causing the accessing process to segfault.
[...]
Quoted 12 lines
include/linux/swapops.h static inline swp_entry_t make_poisoned_swp_entry(void) · line 478
Quoted 10 lines
static inline int
is_poisoned_swp_entry(swp_entry_t entry)include/linux/swapops.h +9
-0+{ +/* +* We treat guard pages as poisoned too as these have the same semantics +* as poisoned ranges, only with different fault handling. +*/ +return is_pte_marker_entry (entry) && + (pte_marker_get (entry) & + (PTE_MARKER_POISONED |PTE_MARKER_GUARD )); +}This means
MADV_FREEwill also clear guard PTEs, right?
Yes, this is expected, it acts like unmap in effect (with a delayed effect), so we give it the same semantics. The same thing happens with hardware poisoning.
You can see in the tests what expectations we have with different operations, we assert there this specific behaviour:
/* Lazyfree range. */
ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_FREE), 0);
/* This should simply clear the poison markers. */
for (i = 0; i < 10; i++) {
ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size]));
}The tests somewhat self-document expected behaviour.
Quoted 35 lines
Quoted 35 lines
mm/memory.c +9
-3@@ -1457,7 +1457,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;@@ -1478,7 +1478,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 (;;) {@@ -1673,7 +1673,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.
Quoted 8 lines
mm/memory.c static unsigned long zap_pte_range(struct mmu_gather *tlb, · line 1685
Quoted 3 lines
mm/memory.c +2
-0+*/ +if (!zap_drop_markers (details))continue ;Just a comment: It's nice that the feature is restricted to anonymous VMAs, otherwise we'd have to figure out here what to do about
unmap_mapping_folio()(which setsZAP_FLAG_DROP_MARKERtogether with details.single_folio)...
Yes this is not the only issue with file-backed mappings. Readahead being another, and plenty more.
We will probably look at how we might do this once this patch set lands, and tackle all of these fun things then...
Quoted 18 lines
Quoted 18 lines
mm/memory.c +4
-1}else if (is_hwpoison_entry (entry) ||is_poisoned_swp_entry (entry)) {@@ -4005,6 +4013,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); --2.46.2
RFC PATCH 3/4 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 - poisoning PTEs such that accesses to them cause a fault followed by a SIGSGEV signal being raised.
This is achieved through the PTE marker mechanism, which a previous commit in this series extended to permit this to be done, installed via the generic page walking logic, also extended by a prior commit for this purpose.
These poison ranges are established with MADV_GUARD_POISON, and 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 poison entries will be left untouched. There is no nesting of poisoned pages.
Poisoned ranges are NOT cleared by MADV_DONTNEED, as this would be rather unexpected behaviour, but are cleared on process teardown or unmapping of memory ranges.
Ranges can have the poison property removed by MADV_GUARD_UNPOISON - 'remedying' the poisoning. The ranges over which this is applied, should they contain non-poison entries, will be untouched, only poison entries will be 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).
The poisoning of the range must be performed under mmap write lock as we have to install an anon_vma to ensure correct behaviour on fork.
--- 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 | 158 +++++++++++++++++++++++++ mm/mprotect.c | 3 +- mm/mseal.c | 1 + 8 files changed, 176 insertions(+), 1 deletion(-)
arch/alpha/include/uapi/asm/mman.h +3 -0
@@ -78,6 +78,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* 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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* 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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* 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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* 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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0
mm/madvise.c +158 -0
182 lines not on this page · raw message
mm/mprotect.c +2 -1
@@ -236,7 +236,8 @@ 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))continue ;
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_POISON :return true; }
Signature · 1 line
2.46.2
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Hi Lorenzo,
Please add me to this series, I 'm interested in everything related to mseal :-), thanks.
I also added Kees into the cc, since mseal is a security feature.
Quoted 341 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 - poisoning PTEs such that accesses to them cause a fault followed by a SIGSGEV signal being raised.This is achieved through the PTE marker mechanism, which a previous commit in this series extended to permit this to be done, installed via the generic page walking logic, also extended by a prior commit for this purpose.
These poison ranges are established with
MADV_GUARD_POISON, and 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 poison entries will be left untouched. There is no nesting of poisoned pages.
Poisoned ranges are NOT cleared by
MADV_DONTNEED, as this would be rather unexpected behaviour, but are cleared on process teardown or unmapping of memory ranges.Ranges can have the poison property removed by
MADV_GUARD_UNPOISON- 'remedying' the poisoning. The ranges over which this is applied, should they contain non-poison entries, will be untouched, only poison entries will be 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).
The poisoning of the range must be performed under mmap write lock as we have to install an
anon_vmato ensure correct behaviour on fork.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]>--- 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 | 158 +++++++++++++++++++++++++ mm/mprotect.c | 3 +- mm/mseal.c | 1 + 8 files changed, 176 insertions(+), 1 deletion(-)arch/alpha/include/uapi/asm/mman.h +3
-0@@ -78,6 +78,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/mips/include/uapi/asm/mman.h +3
-0@@ -105,6 +105,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/xtensa/include/uapi/asm/mman.h +3
-0@@ -113,6 +113,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0include/uapi/asm-generic/mman-common.h +3
-0@@ -79,6 +79,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0mm/madvise.c +158
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */ return 0 ;default :/* be safe, default to 1. list exceptions explicitly */ @@ -1017,6 +1018,157 @@ static long madvise_remove(struct vm_area_struct *vma,return error; } +static bool is_valid_guard_vma (struct vm_area_struct *vma,bool allow_locked) +{ +vm_flags_t disallowed =VM_SPECIAL |VM_HUGETLB ; + +/* +* A user could lock after poisoning but that's fine, as they'd not be +* able to fault in. The issue arises when we try to zap existing locked +* VMAs. We don't want to do that. +*/ +if (!allow_locked) + disallowed |=VM_LOCKED ; + +if (!vma_is_anonymous (vma)) +return false; + +if ((vma->vm_flags & (VM_MAYWRITE | disallowed)) !=VM_MAYWRITE ) +return false; + +return true; +} + +static int guard_poison_install_pte (unsigned long addr,unsigned long next, +pte_t *ptep,struct mm_walk *walk) +{ +unsigned long *num_installed = (unsigned long *)walk->private; + + (*num_installed)++; +/* Simply install a PTE marker, this causes segfault on access. */ + *ptep =make_pte_marker (PTE_MARKER_GUARD ); + +return 0 ; +} + +static bool is_guard_pte_marker (pte_t ptent) +{ +return is_pte_marker (ptent) && +is_guard_swp_entry (pte_to_swp_entry (ptent)); +} + +static int guard_poison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +/* +* If not a guard marker, simply abort the operation. We return a value +* > 0 indicating a non-error abort. +*/ +return !is_guard_pte_marker (ptent); +} + +static const struct mm_walk_ops guard_poison_walk_ops = { + .install_pte = guard_poison_install_pte, + .pte_entry = guard_poison_pte_entry, +/* We might need to install an anon_vma. */ + .walk_lock =PGWALK_WRLOCK , +}; + +static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err =walk_page_range_mm (vma->vm_mm, start, end, + &guard_poison_walk_ops, + &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. +*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma); + +if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap +* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); +else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ +return -EAGAIN ; + + retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) { +/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true); +update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK , +}; + +static long madvise_guard_unpoison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ + *prev = vma; +/* +* We're ok with unpoisoning mlock()'d ranges, as this is a +* non-destructive action. +*/ +if (!is_valid_guard_vma (vma,/* allow_locked = */ true)) +return -EINVAL ; + +return walk_page_range (vma->vm_mm, start, end, + &guard_unpoison_walk_ops,NULL ); +} +/* * Apply an madvise behavior to a region of a vma. madvise_update_vma * will handle splitting a vm area into separate areas, each area with its own @@ -1098,6 +1250,10 @@ static int madvise_vma_behavior(struct vm_area_struct *vma,break ;case MADV_COLLAPSE :return madvise_collapse (vma, prev, start, end); +case MADV_GUARD_POISON : +return madvise_guard_poison (vma, prev, start, end); +case MADV_GUARD_UNPOISON : +return madvise_guard_unpoison (vma, prev, start, end); } anon_name =anon_vma_name (vma);@@ -1197,6 +1353,8 @@ madvise_behavior_valid(int behavior)case MADV_DODUMP :case MADV_WIPEONFORK :case MADV_KEEPONFORK : +case MADV_GUARD_POISON : +case MADV_GUARD_UNPOISON :#ifdef CONFIG_MEMORY_FAILURE case MADV_SOFT_OFFLINE :case MADV_HWPOISON :mm/mprotect.c +2
-1@@ -236,7 +236,8 @@ 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))continue ;mm/mseal.c +0
-0
mm/mseal.c static bool is_madv_discard(int behavior) · line 33
Quoted 4 lines
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_POISON :
Can you please describe the rationale to add this to the existing mseal's semantic ?
I didn't not find any description from the cover letter or this patch's description, hence asking.
Thanks
-Jeff
Quoted 7 lines
mm/mseal.c +0
-1return true; } --2.46.2
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 4 lines · Jeff Xu
Hi Lorenzo,
Please add me to this series, I 'm interested in everything related to mseal :-), thanks.
Hi Jeff, more than happy to cc you on this going forward :)
The only change to mseal is a trivial change because the poison operation discards, wasn't intentional, but apologies, I should have cc'd you regardless! Will do so on any such interaction with mseal moving forward.
Quoted 2 lines
I also added Kees into the cc, since mseal is a security feature.
Sure no problem happy to keep Kees cc-d too (Kees - ping me if you'd prefer not :>), however a note on this - guard pages _themselves_ are emphatically NOT a security feature, and make no guarantees on this front, but rather are a convenience/effiency thing.
Obviously however I am adding madvise() functionality here, and all such functionality must take into account whether or not they are discard operations as to ensure mseal semantics are obeyed - see below for my argument as to why I feel the poison operation falls under this.
Quoted 353 lines
Quoted 341 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 - poisoning PTEs such that accesses to them cause a fault followed by a SIGSGEV signal being raised.This is achieved through the PTE marker mechanism, which a previous commit in this series extended to permit this to be done, installed via the generic page walking logic, also extended by a prior commit for this purpose.
These poison ranges are established with
MADV_GUARD_POISON, and 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 poison entries will be left untouched. There is no nesting of poisoned pages.
Poisoned ranges are NOT cleared by
MADV_DONTNEED, as this would be rather unexpected behaviour, but are cleared on process teardown or unmapping of memory ranges.Ranges can have the poison property removed by
MADV_GUARD_UNPOISON- 'remedying' the poisoning. The ranges over which this is applied, should they contain non-poison entries, will be untouched, only poison entries will be 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).
The poisoning of the range must be performed under mmap write lock as we have to install an
anon_vmato ensure correct behaviour on fork.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]>--- 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 | 158 +++++++++++++++++++++++++ mm/mprotect.c | 3 +- mm/mseal.c | 1 + 8 files changed, 176 insertions(+), 1 deletion(-)arch/alpha/include/uapi/asm/mman.h +3
-0@@ -78,6 +78,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/mips/include/uapi/asm/mman.h +3
-0@@ -105,6 +105,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/xtensa/include/uapi/asm/mman.h +3
-0@@ -113,6 +113,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0include/uapi/asm-generic/mman-common.h +3
-0@@ -79,6 +79,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0mm/madvise.c +158
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */ return 0 ;default :/* be safe, default to 1. list exceptions explicitly */ @@ -1017,6 +1018,157 @@ static long madvise_remove(struct vm_area_struct *vma,return error; } +static bool is_valid_guard_vma (struct vm_area_struct *vma,bool allow_locked) +{ +vm_flags_t disallowed =VM_SPECIAL |VM_HUGETLB ; + +/* +* A user could lock after poisoning but that's fine, as they'd not be +* able to fault in. The issue arises when we try to zap existing locked +* VMAs. We don't want to do that. +*/ +if (!allow_locked) + disallowed |=VM_LOCKED ; + +if (!vma_is_anonymous (vma)) +return false; + +if ((vma->vm_flags & (VM_MAYWRITE | disallowed)) !=VM_MAYWRITE ) +return false; + +return true; +} + +static int guard_poison_install_pte (unsigned long addr,unsigned long next, +pte_t *ptep,struct mm_walk *walk) +{ +unsigned long *num_installed = (unsigned long *)walk->private; + + (*num_installed)++; +/* Simply install a PTE marker, this causes segfault on access. */ + *ptep =make_pte_marker (PTE_MARKER_GUARD ); + +return 0 ; +} + +static bool is_guard_pte_marker (pte_t ptent) +{ +return is_pte_marker (ptent) && +is_guard_swp_entry (pte_to_swp_entry (ptent)); +} + +static int guard_poison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +/* +* If not a guard marker, simply abort the operation. We return a value +* > 0 indicating a non-error abort. +*/ +return !is_guard_pte_marker (ptent); +} + +static const struct mm_walk_ops guard_poison_walk_ops = { + .install_pte = guard_poison_install_pte, + .pte_entry = guard_poison_pte_entry, +/* We might need to install an anon_vma. */ + .walk_lock =PGWALK_WRLOCK , +}; + +static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err =walk_page_range_mm (vma->vm_mm, start, end, + &guard_poison_walk_ops, + &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. +*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma); + +if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap +* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); +else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ +return -EAGAIN ; + + retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) { +/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true); +update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK , +}; + +static long madvise_guard_unpoison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ + *prev = vma; +/* +* We're ok with unpoisoning mlock()'d ranges, as this is a +* non-destructive action. +*/ +if (!is_valid_guard_vma (vma,/* allow_locked = */ true)) +return -EINVAL ; + +return walk_page_range (vma->vm_mm, start, end, + &guard_unpoison_walk_ops,NULL ); +} +/* * Apply an madvise behavior to a region of a vma. madvise_update_vma * will handle splitting a vm area into separate areas, each area with its own @@ -1098,6 +1250,10 @@ static int madvise_vma_behavior(struct vm_area_struct *vma,break ;case MADV_COLLAPSE :return madvise_collapse (vma, prev, start, end); +case MADV_GUARD_POISON : +return madvise_guard_poison (vma, prev, start, end); +case MADV_GUARD_UNPOISON : +return madvise_guard_unpoison (vma, prev, start, end); } anon_name =anon_vma_name (vma);@@ -1197,6 +1353,8 @@ madvise_behavior_valid(int behavior)case MADV_DODUMP :case MADV_WIPEONFORK :case MADV_KEEPONFORK : +case MADV_GUARD_POISON : +case MADV_GUARD_UNPOISON :#ifdef CONFIG_MEMORY_FAILURE case MADV_SOFT_OFFLINE :case MADV_HWPOISON :mm/mprotect.c +2
-1@@ -236,7 +236,8 @@ 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))continue ;mm/mseal.c +0
-0mm/mseal.c static bool is_madv_discard(int behavior) · line 33
Quoted 4 lines
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_POISON :Can you please describe the rationale to add this to the existing mseal's semantic ?
Quoted 2 lines
I didn't not find any description from the cover letter or this patch's description, hence asking.
Sure, this is because when you guard-poison ranges that have existing mappings, it zaps them, which performs basically the exact same operation as MADV_DONTNEED, and obviously discards any underlying data in doing so.
As a result, I felt it was correct to add this operation to the list of discard operations from the perspective of mseal.
Quoted 11 lines
Thanks
-JeffQuoted 7 lines
mm/mseal.c +0
-1return true; } --2.46.2
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Hi Lorenzo
Quoted 4 lines · Lorenzo Stoakes
Quoted 2 lines · Jeff Xu
Hi Lorenzo,
Quoted 9 lines
Quoted 2 lines
Please add me to this series, I 'm interested in everything related to mseal :-), thanks.
Hi Jeff, more than happy to cc you on this going forward :)
The only change to mseal is a trivial change because the poison operation discards, wasn't intentional, but apologies, I should have cc'd you regardless! Will do so on any such interaction with mseal moving forward.
No problems :-).
I do sometimes scan the emails to search for mseal keyword and that is how I find this patch series.
Quoted 8 lines
Quoted 2 lines
I also added Kees into the cc, since mseal is a security feature.
Sure no problem happy to keep Kees cc-d too (Kees - ping me if you'd prefer not :>), however a note on this - guard pages _themselves_ are emphatically NOT a security feature, and make no guarantees on this front, but rather are a convenience/effiency thing.
It is a nice feature nevertheless. I imagine the guide page can detect cases such as trying to go-over the main stack ?
Quoted 361 lines
Obviously however I am adding
madvise()functionality here, and all such functionality must take into account whether or not they are discard operations as to ensure mseal semantics are obeyed - see below for my argument as to why I feel the poison operation falls under this.Quoted 353 lines
Quoted 341 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 - poisoning PTEs such that accesses to them cause a fault followed by a SIGSGEV signal being raised.This is achieved through the PTE marker mechanism, which a previous commit in this series extended to permit this to be done, installed via the generic page walking logic, also extended by a prior commit for this purpose.
These poison ranges are established with
MADV_GUARD_POISON, and 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 poison entries will be left untouched. There is no nesting of poisoned pages.
Poisoned ranges are NOT cleared by
MADV_DONTNEED, as this would be rather unexpected behaviour, but are cleared on process teardown or unmapping of memory ranges.Ranges can have the poison property removed by
MADV_GUARD_UNPOISON- 'remedying' the poisoning. The ranges over which this is applied, should they contain non-poison entries, will be untouched, only poison entries will be 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).
The poisoning of the range must be performed under mmap write lock as we have to install an
anon_vmato ensure correct behaviour on fork.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]>--- 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 | 158 +++++++++++++++++++++++++ mm/mprotect.c | 3 +- mm/mseal.c | 1 + 8 files changed, 176 insertions(+), 1 deletion(-)arch/alpha/include/uapi/asm/mman.h +3
-0@@ -78,6 +78,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/mips/include/uapi/asm/mman.h +3
-0@@ -105,6 +105,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/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_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0arch/xtensa/include/uapi/asm/mman.h +3
-0@@ -113,6 +113,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0include/uapi/asm-generic/mman-common.h +3
-0@@ -79,6 +79,9 @@#define MADV_COLLAPSE 25/* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102/* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103/* revoke guard poisoning */ +/* compatibility flags */ #define MAP_FILE 0mm/madvise.c +158
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */ return 0 ;default :/* be safe, default to 1. list exceptions explicitly */ @@ -1017,6 +1018,157 @@ static long madvise_remove(struct vm_area_struct *vma,return error; } +static bool is_valid_guard_vma (struct vm_area_struct *vma,bool allow_locked) +{ +vm_flags_t disallowed =VM_SPECIAL |VM_HUGETLB ; + +/* +* A user could lock after poisoning but that's fine, as they'd not be +* able to fault in. The issue arises when we try to zap existing locked +* VMAs. We don't want to do that. +*/ +if (!allow_locked) + disallowed |=VM_LOCKED ; + +if (!vma_is_anonymous (vma)) +return false; + +if ((vma->vm_flags & (VM_MAYWRITE | disallowed)) !=VM_MAYWRITE ) +return false; + +return true; +} + +static int guard_poison_install_pte (unsigned long addr,unsigned long next, +pte_t *ptep,struct mm_walk *walk) +{ +unsigned long *num_installed = (unsigned long *)walk->private; + + (*num_installed)++; +/* Simply install a PTE marker, this causes segfault on access. */ + *ptep =make_pte_marker (PTE_MARKER_GUARD ); + +return 0 ; +} + +static bool is_guard_pte_marker (pte_t ptent) +{ +return is_pte_marker (ptent) && +is_guard_swp_entry (pte_to_swp_entry (ptent)); +} + +static int guard_poison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +/* +* If not a guard marker, simply abort the operation. We return a value +* > 0 indicating a non-error abort. +*/ +return !is_guard_pte_marker (ptent); +} + +static const struct mm_walk_ops guard_poison_walk_ops = { + .install_pte = guard_poison_install_pte, + .pte_entry = guard_poison_pte_entry, +/* We might need to install an anon_vma. */ + .walk_lock =PGWALK_WRLOCK , +}; + +static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err =walk_page_range_mm (vma->vm_mm, start, end, + &guard_poison_walk_ops, + &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. +*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma); + +if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap +* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); +else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ +return -EAGAIN ; + + retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) { +/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true); +update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK , +}; + +static long madvise_guard_unpoison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ + *prev = vma; +/* +* We're ok with unpoisoning mlock()'d ranges, as this is a +* non-destructive action. +*/ +if (!is_valid_guard_vma (vma,/* allow_locked = */ true)) +return -EINVAL ; + +return walk_page_range (vma->vm_mm, start, end, + &guard_unpoison_walk_ops,NULL ); +} +/* * Apply an madvise behavior to a region of a vma. madvise_update_vma * will handle splitting a vm area into separate areas, each area with its own @@ -1098,6 +1250,10 @@ static int madvise_vma_behavior(struct vm_area_struct *vma,break ;case MADV_COLLAPSE :return madvise_collapse (vma, prev, start, end); +case MADV_GUARD_POISON : +return madvise_guard_poison (vma, prev, start, end); +case MADV_GUARD_UNPOISON : +return madvise_guard_unpoison (vma, prev, start, end); } anon_name =anon_vma_name (vma);@@ -1197,6 +1353,8 @@ madvise_behavior_valid(int behavior)case MADV_DODUMP :case MADV_WIPEONFORK :case MADV_KEEPONFORK : +case MADV_GUARD_POISON : +case MADV_GUARD_UNPOISON :#ifdef CONFIG_MEMORY_FAILURE case MADV_SOFT_OFFLINE :case MADV_HWPOISON :mm/mprotect.c +2
-1@@ -236,7 +236,8 @@ 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))continue ;mm/mseal.c +0
-0mm/mseal.c static bool is_madv_discard(int behavior) · line 33
Quoted 4 lines
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_POISON :Can you please describe the rationale to add this to the existing mseal's semantic ?
Quoted 2 lines
I didn't not find any description from the cover letter or this patch's description, hence asking.
Quoted 7 lines
Sure, this is because when you guard-poison ranges that have existing mappings, it zaps them, which performs basically the exact same operation as
MADV_DONTNEED, and obviously discards any underlying data in doing so.As a result, I felt it was correct to add this operation to the list of discard operations from the perspective of mseal.
That makes sense. Thanks for thinking about memory sealing when adding new features.
If possible, please add the reasoning here in the commit description
in the next version, for future reference. As far as I am concerned, the mseal.c changes LGTM.
Thanks
-Jeff
Quoted 11 lines
Quoted 11 lines
Thanks
-JeffQuoted 7 lines
mm/mseal.c +0
-1return true; } --2.46.2
Jann Horn
reviewerRe: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
In reply to Lorenzo StoakesQuoted 2 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.
[...]
Quoted 6 lines
--- 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 +
I kinda wonder if we could start moving the parts of those headers that are the same for all architectures to include/uapi/linux/mman.h instead... but that's maybe out of scope for this series.
[...]
mm/madvise.c static int madvise_need_mmap_write(int behavior) · line 63
Quoted 9 lines
mm/madvise.c +1
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */
What does poisoning need a write lock for? anon_vma_prepare() doesn't need it (it only needs mmap_lock held for reading), zap_page_range_single() doesn't need it, and pagewalk also doesn't need it as long as the range being walked is covered by a VMA, which it is...
I see you set PGWALK_WRLOCK in guard_poison_walk_ops with a comment saying "We might need to install an anon_vma" - is that referring to an older version of the patch where the anon_vma_prepare() call was inside the pagewalk callback or something like that? Either way, anon_vma_prepare() doesn't need write locks (it can't, it has to work from the page fault handling path).
Quoted 3 lines
mm/madvise.c +0
-0return 0 ;default :/* be safe, default to 1. list exceptions explicitly */
[...]
Quoted 22 lines
mm/madvise.c +22
-0+static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err = walk_page_range_mm(vma->vm_mm, start, end, + &guard_poison_walk_ops,
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1110
Quoted 10 lines
mm/madvise.c +10
-0+ &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. +*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma);
I'd move this up, to before we create poison PTEs. There's no harm in attaching an anon_vma to the VMA even if the rest of the operation fails; and I think it would be weird to have error paths that don't attach an anon_vma even though they .
Quoted 10 lines
mm/madvise.c +10
-0+if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1131
Quoted 10 lines
mm/madvise.c +10
-0+* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); + else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ + return -EAGAIN;
Hmm, yeah, it would be nice if we could avoid telling userspace to loop on -EAGAIN but I guess we don't have any particularly good options here? Well, we could bail out with -EINTR if a (fatal?) signal is pending and otherwise keep looping... if we'd tell userspace "try again on -EAGAIN", we might as well do that in the kernel...
(Personally I would put curly braces around these branches because they occupy multiple lines, though the coding style doesn't explicitly say that, so I guess maybe it's a matter of personal preference... adding curly braces here would match what is done, for example, in relocate_vma_down().)
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1144
Quoted 12 lines
mm/madvise.c +12
-0+ retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) { +/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true);
I think that last parameter probably should be "false"? The sparc code calls it "fullmm", which is a term the MM code uses when talking about operations that remove all mappings in the entire mm_struct because the process has died, which allows using some faster special-case version of TLB shootdown or something along those lines.
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1154
Quoted 10 lines
mm/madvise.c +10
-0+update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK , +};
It is a _little_ weird that unpoisoning creates page tables when they don't already exist, which will also prevent creating THP entries on fault in such areas afterwards... but I guess it doesn't really matter given that poisoning has that effect, too, and you probably usually won't call MADV_GUARD_UNPOISON on an area that hasn't been poisoned before... so I guess this is not an actionable comment.
Suren Baghdasaryan
reviewerRe: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 34 lines · Jann Horn
Quoted 2 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.
[...]
Quoted 6 lines
--- 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 +I kinda wonder if we could start moving the parts of those headers that are the same for all architectures to
include/uapi/linux/mman.hinstead... but that's maybe out of scope for this series.[...]
mm/madvise.c static int madvise_need_mmap_write(int behavior) · line 63
Quoted 9 lines
mm/madvise.c +1
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */ What does poisoning need a write lock for?
anon_vma_prepare()doesn't need it (it only needsmmap_lockheld for reading),zap_page_range_single()doesn't need it, and pagewalk also doesn't need it as long as the range being walked is covered by a VMA, which it is...
Quoted 6 lines
I see you set
PGWALK_WRLOCKinguard_poison_walk_opswith a comment saying "We might need to install ananon_vma" - is that referring to an older version of the patch where theanon_vma_prepare()call was inside the pagewalk callback or something like that? Either way,anon_vma_prepare()doesn't need write locks (it can't, it has to work from the page fault handling path).
I was wondering about that too and I can't find any reason for write-locking the mm for this operation. PGWALK_WRLOCK should also be changed to PGWALK_RDLOCK as we are not modifying the VMA.
BTW, I'm testing your patchset on Android and so far it is stable!
Quoted 112 lines
Quoted 4 lines
mm/madvise.c +0
-0return 0 ;default :/* be safe, default to 1. list exceptions explicitly */ [...]
Quoted 22 lines
mm/madvise.c +22
-0+static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err = walk_page_range_mm(vma->vm_mm, start, end, + &guard_poison_walk_ops,mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1110
Quoted 10 lines
mm/madvise.c +10
-0+ &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. +*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma);I'd move this up, to before we create poison PTEs. There's no harm in attaching an
anon_vmato the VMA even if the rest of the operation fails; and I think it would be weird to have error paths that don't attach ananon_vmaeven though they .Quoted 10 lines
mm/madvise.c +10
-0+if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1131
Quoted 10 lines
mm/madvise.c +10
-0+* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); + else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ + return -EAGAIN;Hmm, yeah, it would be nice if we could avoid telling userspace to loop on
-EAGAINbut I guess we don't have any particularly good options here? Well, we could bail out with-EINTRif a (fatal?) signal is pending and otherwise keep looping... if we'd tell userspace "try again on-EAGAIN", we might as well do that in the kernel...(Personally I would put curly braces around these branches because they occupy multiple lines, though the coding style doesn't explicitly say that, so I guess maybe it's a matter of personal preference... adding curly braces here would match what is done, for example, in
relocate_vma_down().)mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1144
Quoted 12 lines
mm/madvise.c +12
-0+ retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) { +/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true);I think that last parameter probably should be "false"? The sparc code calls it "fullmm", which is a term the MM code uses when talking about operations that remove all mappings in the entire
mm_structbecause the process has died, which allows using some faster special-case version of TLB shootdown or something along those lines.mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1154
Quoted 10 lines
mm/madvise.c +10
-0+update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK , +};It is a _little_ weird that unpoisoning creates page tables when they don't already exist, which will also prevent creating THP entries on fault in such areas afterwards... but I guess it doesn't really matter given that poisoning has that effect, too, and you probably usually won't call
MADV_GUARD_UNPOISONon an area that hasn't been poisoned before... so I guess this is not an actionable comment.
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 42 lines · Suren Baghdasaryan
Quoted 34 lines · Jann Horn
Quoted 2 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.
[...]
Quoted 6 lines
--- 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 +I kinda wonder if we could start moving the parts of those headers that are the same for all architectures to
include/uapi/linux/mman.hinstead... but that's maybe out of scope for this series.[...]
mm/madvise.c static int madvise_need_mmap_write(int behavior) · line 63
Quoted 9 lines
mm/madvise.c +1
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */ What does poisoning need a write lock for?
anon_vma_prepare()doesn't need it (it only needsmmap_lockheld for reading),zap_page_range_single()doesn't need it, and pagewalk also doesn't need it as long as the range being walked is covered by a VMA, which it is...Quoted 6 lines
I see you set
PGWALK_WRLOCKinguard_poison_walk_opswith a comment saying "We might need to install ananon_vma" - is that referring to an older version of the patch where theanon_vma_prepare()call was inside the pagewalk callback or something like that? Either way,anon_vma_prepare()doesn't need write locks (it can't, it has to work from the page fault handling path).
Quoted 3 lines
I was wondering about that too and I can't find any reason for write-locking the mm for this operation.
PGWALK_WRLOCKshould also be changed toPGWALK_RDLOCKas we are not modifying the VMA.
Indeed, as I said to Jann you're right and I was in error to use this, will change!
Quoted 2 lines
BTW, I'm testing your patchset on Android and so far it is stable!
Thanks!
As there is no significant conceptual pushback to this series, I will un-RFC and post a version with fixes for the issues Jann raised, as well as a fix for some xtensa et al. issues with header includes.
Quoted 113 lines
Quoted 113 lines
Quoted 5 lines
mm/madvise.c +0
-0return 0 ;default :/* be safe, default to 1. list exceptions explicitly */ [...]
Quoted 22 lines
mm/madvise.c +22
-0+static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err = walk_page_range_mm(vma->vm_mm, start, end, + &guard_poison_walk_ops,mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1110
Quoted 10 lines
mm/madvise.c +10
-0+ &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. +*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma);I'd move this up, to before we create poison PTEs. There's no harm in attaching an
anon_vmato the VMA even if the rest of the operation fails; and I think it would be weird to have error paths that don't attach ananon_vmaeven though they .Quoted 10 lines
mm/madvise.c +10
-0+if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1131
Quoted 10 lines
mm/madvise.c +10
-0+* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); + else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ + return -EAGAIN;Hmm, yeah, it would be nice if we could avoid telling userspace to loop on
-EAGAINbut I guess we don't have any particularly good options here? Well, we could bail out with-EINTRif a (fatal?) signal is pending and otherwise keep looping... if we'd tell userspace "try again on-EAGAIN", we might as well do that in the kernel...(Personally I would put curly braces around these branches because they occupy multiple lines, though the coding style doesn't explicitly say that, so I guess maybe it's a matter of personal preference... adding curly braces here would match what is done, for example, in
relocate_vma_down().)mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1144
Quoted 12 lines
mm/madvise.c +12
-0+ retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) { +/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true);I think that last parameter probably should be "false"? The sparc code calls it "fullmm", which is a term the MM code uses when talking about operations that remove all mappings in the entire
mm_structbecause the process has died, which allows using some faster special-case version of TLB shootdown or something along those lines.mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1154
Quoted 10 lines
mm/madvise.c +10
-0+update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK , +};It is a _little_ weird that unpoisoning creates page tables when they don't already exist, which will also prevent creating THP entries on fault in such areas afterwards... but I guess it doesn't really matter given that poisoning has that effect, too, and you probably usually won't call
MADV_GUARD_UNPOISONon an area that hasn't been poisoned before... so I guess this is not an actionable comment.
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
In reply to Jann HornQuoted 12 lines · Jann Horn
Quoted 2 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.
[...]
Quoted 6 lines
--- 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 +
Quoted 3 lines
I kinda wonder if we could start moving the parts of those headers that are the same for all architectures to
include/uapi/linux/mman.hinstead... but that's maybe out of scope for this series.
Arnd already had a look at this in a recent series. I had the same feeling doing this...
Quoted 18 lines
[...]
mm/madvise.c static int madvise_need_mmap_write(int behavior) · line 63
Quoted 9 lines
mm/madvise.c +1
-0@@ -60,6 +60,7 @@ static int madvise_need_mmap_write(int behavior)case MADV_POPULATE_READ :case MADV_POPULATE_WRITE :case MADV_COLLAPSE : +case MADV_GUARD_UNPOISON :/* Only poisoning needs a write lock. */ What does poisoning need a write lock for?
anon_vma_prepare()doesn't need it (it only needsmmap_lockheld for reading),zap_page_range_single()doesn't need it, and pagewalk also doesn't need it as long as the range being walked is covered by a VMA, which it is...
Quoted 6 lines
I see you set
PGWALK_WRLOCKinguard_poison_walk_opswith a comment saying "We might need to install ananon_vma" - is that referring to an older version of the patch where theanon_vma_prepare()call was inside the pagewalk callback or something like that? Either way,anon_vma_prepare()doesn't need write locks (it can't, it has to work from the page fault handling path).
OK this was a misunderstanding. Actually there have been more than one, at first I thought a write lock would protect us against racing faults (nope, due to RCU vma locking now :) and then I had assumed literally changing a vma field _surely_ must require a write lock, also it appears no as __anon_vma_prepare(), amusingly, uses the mm->page_table_lock to protect against accesses to vma->anon_vma.
And yes you're right it is triggered on the fault path so has to work that way.
TL;DR will change to read lock.
Quoted 34 lines
Quoted 4 lines
mm/madvise.c +0
-0return 0 ;default :/* be safe, default to 1. list exceptions explicitly */ [...]
Quoted 29 lines
mm/madvise.c +29
-0+static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err =walk_page_range_mm (vma->vm_mm, start, end, + &guard_poison_walk_ops, + &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly.
Quoted 8 lines
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1110
Quoted 3 lines
mm/madvise.c +3
-0+*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma);I'd move this up, to before we create poison PTEs. There's no harm in attaching an
anon_vmato the VMA even if the rest of the operation fails; and I think it would be weird to have error paths that don't attach ananon_vmaeven though they .
I think you didn't finish this sentence :)
I disagree, we might have absolutely no need to do it, and I'd rather only do so _if_ we have to.
It feels like the logical spot to do it and, while the cases where it wouldn't happen are ones where pages are already poisoned (the vma->anon_vma == NULL test will fail so basically a no-op) or error on page walk.
Quoted 19 lines
Quoted 19 lines
mm/madvise.c +18
-0+if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap +* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); +else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again.
Quoted 8 lines
mm/madvise.c
Quoted 2 lines
mm/madvise.c +2
-0+*/ +return -EAGAIN ;Hmm, yeah, it would be nice if we could avoid telling userspace to loop on
-EAGAINbut I guess we don't have any particularly good options here? Well, we could bail out with-EINTRif a (fatal?) signal is pending and otherwise keep looping... if we'd tell userspace "try again on-EAGAIN", we might as well do that in the kernel...
The problem is you could conceivably go on for quite some time, while holding and contending a HIGHLY contended lock (mm->mmap_lock) so I'd really rather let userspace take care of it.
You could avoid this by having the walker be a _replace_ operation, that is
- if we encounter an existing mapping, replace in-place with a poison marker rather than install marker/zap.
However doing that would involve either completely abstracting such logic from scratch (a significant task in itself) to avoid duplication which be hugely off-topic for the patch set or worse, duplicating a whole bunch of page walking logic once again.
By being optimistic and simply having the user having to handle looping which seems reasonable (again, it's weird if you're installing poison markers and another thread could be racing you) we avoid all of that.
Quoted 6 lines
(Personally I would put curly braces around these branches because they occupy multiple lines, though the coding style doesn't explicitly say that, so I guess maybe it's a matter of personal preference... adding curly braces here would match what is done, for example, in
relocate_vma_down().)
Hey I wrote that too! ;) Sure I can change that.
Quoted 11 lines
Quoted 11 lines
mm/madvise.c +10
-0+ retried = true; + } +} + +static int guard_unpoison_pte_entry (pte_t *pte,unsigned long addr, +unsigned long next,struct mm_walk *walk) +{ +pte_t ptent =ptep_get (pte); + +if (is_guard_pte_marker (ptent)) {
Quoted 8 lines
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1144
Quoted 2 lines
mm/madvise.c +2
-0+/* Simply clear the PTE marker. */ +pte_clear_not_present_full (walk->mm, addr, pte, true);I think that last parameter probably should be "false"? The sparc code calls it "fullmm", which is a term the MM code uses when talking about operations that remove all mappings in the entire
mm_structbecause the process has died, which allows using some faster special-case version of TLB shootdown or something along those lines.
Yeah I think you're right. Will change.
Quoted 10 lines
Quoted 10 lines
mm/madvise.c +9
-0+update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK ,
Quoted 8 lines
Quoted 1 line
+};
It is a _little_ weird that unpoisoning creates page tables when they don't already exist, which will also prevent creating THP entries on fault in such areas afterwards... but I guess it doesn't really matter given that poisoning has that effect, too, and you probably usually won't call
MADV_GUARD_UNPOISONon an area that hasn't been poisoned before... so I guess this is not an actionable comment.
It doesn't? There's no .install_pte so if an entries are non-present we ignore.
HOWEVER, we do split THP. I don't think there's any way around it unless we extended the page walker to handle this more gracefully (pmd level being able to hint that we shouldn't do that or something), but that's really out of scope here.
The idea is that a caller can lazily call MADV_GUARD_UNPOISON on a range knowing things stay as they were, I guess we can add to the manpage a note that this will split THP?
Jann Horn
reviewerRe: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 44 lines · Lorenzo Stoakes
Quoted 34 lines · Jann Horn
Quoted 3 lines · Lorenzo Stoakes
return 0; default: /* be safe, default to 1. list exceptions explicitly */[...]
Quoted 29 lines
mm/madvise.c +29
-0+static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err =walk_page_range_mm (vma->vm_mm, start, end, + &guard_poison_walk_ops, + &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. Quoted 8 lines
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1110
Quoted 3 lines
mm/madvise.c +3
-0+*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma);I'd move this up, to before we create poison PTEs. There's no harm in attaching an
anon_vmato the VMA even if the rest of the operation fails; and I think it would be weird to have error paths that don't attach ananon_vmaeven though they .
Quoted 1 line
I think you didn't finish this sentence :)
Oops...
Quoted 2 lines
I disagree, we might have absolutely no need to do it, and I'd rather only do so _if_ we have to.
But there's no downside to erroring out after having installed an anon_vma, right?
Quoted 4 lines
It feels like the logical spot to do it and, while the cases where it wouldn't happen are ones where pages are already poisoned (the
vma->anon_vma== NULL test will fail so basically a no-op) or error on page walk.
My understanding is that some of the MM code basically assumes that a VMA without an anon_vma and without userfault-WP can't contain any state that needs to be preserved; or something along those lines. As you pointed out, fork() is one such case (which maybe doesn't matter so much because it can't race with this operation).
khugepaged also relies on this assumption in retract_page_tables(), though that function is not used on anonymous VMAs. If MADVISE_GUARD is extended to cover file VMAs in the future, then I think we could race with retract_page_tables() in a functionally relevant way even when MADVISE_GUARD succeeds: If khugepaged preempts us between the page walk and installing the anon_vma, retract_page_tables() could observe that we don't have an anon_vma yet and throw away a page table in which we just installed guard PTEs.
Though I guess really that's not the main reason why I'm saying this; my main reason is that almost any other path that has to ensure an anon_vma is present does that part first (usually because the ordering matters and this way around is more or less the only possible ordering). So even if there are some specific reasons why you can do the ordering the other way around here, it kinda stands out to me as being weird...
Quoted 27 lines
Quoted 18 lines
Quoted 18 lines
mm/madvise.c +18
-0+if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap +* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); +else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. Quoted 8 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ */ + return -EAGAIN;Hmm, yeah, it would be nice if we could avoid telling userspace to loop on
-EAGAINbut I guess we don't have any particularly good options here? Well, we could bail out with-EINTRif a (fatal?) signal is pending and otherwise keep looping... if we'd tell userspace "try again on-EAGAIN", we might as well do that in the kernel...
Quoted 3 lines
The problem is you could conceivably go on for quite some time, while holding and contending a HIGHLY contended lock (
mm->mmap_lock) so I'd really rather let userspace take care of it.
Hmm... so if the retry was handled in-kernel, you'd basically ideally have the retry happen all the way up in do_madvise(), where the mmap lock can be dropped and re-taken?
Quoted 8 lines
You could avoid this by having the walker be a _replace_ operation, that is
- if we encounter an existing mapping, replace in-place with a poison marker rather than install marker/zap.However doing that would involve either completely abstracting such logic from scratch (a significant task in itself) to avoid duplication which be hugely off-topic for the patch set or worse, duplicating a whole bunch of page walking logic once again.
Mmh, yeah, you'd have to extract the locked part of zap_pte_range() and add your own copy of all the stuff that happens higher up for setting up TLB flushes and such... I see how that would be a massive pain and error-prone.
Quoted 3 lines
By being optimistic and simply having the user having to handle looping which seems reasonable (again, it's weird if you're installing poison markers and another thread could be racing you) we avoid all of that.
I guess one case in which that could happen legitimately is if you race a MADV_POISON on the area 0x1ff000-0x200100 (first page is populated, second page is not, pmd entry corresponding to 0x200000 is clear) with a page fault at 0x200200? So you could have a scenario like:
1. MADV_POISON starts walk_page_range()
2. MADV_POISON sees non-zero, non-poison PTE at 0x1ff000, stops the walk
3. MADV_POISON does zap_page_range_single()
4. pagefault at 0x200200 happens and populates with a hugepage
5. MADV_POISON enters walk_page_range()
6. MADV_POISON splits the THP
7. MADV_POISON sees a populated PTE
Quoted 18 lines
Quoted 9 lines
Quoted 9 lines
mm/madvise.c +9
-0+update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK ,Quoted 8 lines
Quoted 1 line
+};
It is a _little_ weird that unpoisoning creates page tables when they don't already exist, which will also prevent creating THP entries on fault in such areas afterwards... but I guess it doesn't really matter given that poisoning has that effect, too, and you probably usually won't call
MADV_GUARD_UNPOISONon an area that hasn't been poisoned before... so I guess this is not an actionable comment.
Quoted 2 lines
It doesn't? There's no .install_pte so if an entries are non-present we ignore.
Ah, right, of course. Nevermind.
Quoted 4 lines
HOWEVER, we do split THP. I don't think there's any way around it unless we extended the page walker to handle this more gracefully (pmd level being able to hint that we shouldn't do that or something), but that's really out of scope here.
I think the walk->action == ACTION_CONTINUE check in walk_pmd_range() would let you do that, see wp_clean_pmd_entry() for an example. But yeah I guess that might just be unnecessary complexity.
Quoted 3 lines
The idea is that a caller can lazily call
MADV_GUARD_UNPOISONon a range knowing things stay as they were, I guess we can add to the manpage a note that this will split THP?
Yeah, might make sense...
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 48 lines · Jann Horn
Quoted 44 lines · Lorenzo Stoakes
Quoted 34 lines · Jann Horn
Quoted 3 lines · Lorenzo Stoakes
return 0; default: /* be safe, default to 1. list exceptions explicitly */[...]
Quoted 29 lines
mm/madvise.c +29
-0+static long madvise_guard_poison (struct vm_area_struct *vma, +struct vm_area_struct **prev, +unsigned long start,unsigned long end) +{ +long err; +bool retried = false; + + *prev = vma; +if (!is_valid_guard_vma (vma,/* allow_locked = */ false)) +return -EINVAL ; + +/* +* Optimistically try to install the guard poison pages first. If any +* non-guard pages are encountered, give up and zap the range before +* trying again. +*/ +while (true) { +unsigned long num_installed =0 ; + +/* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err =walk_page_range_mm (vma->vm_mm, start, end, + &guard_poison_walk_ops, + &num_installed); +/* +* If we install poison markers, then the range is no longer +* empty from a page table perspective and therefore it's +* appropriate to have an anon_vma. +* +* This ensures that on fork, we copy page tables correctly. Quoted 8 lines
mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1110
Quoted 3 lines
mm/madvise.c +3
-0+*/ +if (err >=0 && num_installed >0 ) { +int err_anon =anon_vma_prepare (vma);I'd move this up, to before we create poison PTEs. There's no harm in attaching an
anon_vmato the VMA even if the rest of the operation fails; and I think it would be weird to have error paths that don't attach ananon_vmaeven though they .Quoted 1 line
I think you didn't finish this sentence :)
Quoted 7 lines
Oops...
Quoted 2 lines
I disagree, we might have absolutely no need to do it, and I'd rather only do so _if_ we have to.
But there's no downside to erroring out after having installed an
anon_vma, right?
We then use a resource we don't have to. I think it's more logical to only take that action when we know we need to.
Quoted 12 lines
Quoted 5 lines
It feels like the logical spot to do it and, while the cases where it wouldn't happen are ones where pages are already poisoned (the
vma->anon_vma== NULL test will fail so basically a no-op) or error on page walk.My understanding is that some of the MM code basically assumes that a VMA without an
anon_vmaand without userfault-WP can't contain any state that needs to be preserved; or something along those lines. As you pointed out,fork()is one such case (which maybe doesn't matter so much because it can't race with this operation).
Quoted 8 lines
khugepaged also relies on this assumption in
retract_page_tables(), though that function is not used on anonymous VMAs. IfMADVISE_GUARDis extended to cover file VMAs in the future, then I think we could race withretract_page_tables()in a functionally relevant way even whenMADVISE_GUARDsucceeds: If khugepaged preempts us between the page walk and installing theanon_vma,retract_page_tables()could observe that we don't have ananon_vmayet and throw away a page table in which we just installed guard PTEs.
Well for one retract_page_tables() seems to require the VMA to be file-backed :) So we can disregard this at this stage.
We enter into a slightly strange scenario with file-backed as to how we manifest memory poisoning, because a file will have backing in the page cache or an anon page for shmem and it seems that khugepage() operates at this level and simply remaps at the higher order.
But we then introduce a way the _mapping_ can be different and we have to correctly handle that.
So I think actually you'd see this break there too?
Interesting that we special-case uffd-wp, which similarly uses PTE markers and this is commented in retract_page_tables():
/*
* When a vma is registered with uffd-wp, we cannot recycle
* the page table because there may be pte markers installed.
* Other vmas can still have the same file mapped hugely, but
* skip this one: it will always be mapped in small page size
* for uffd-wp registered ranges.
*/
if (userfaultfd_wp(vma))
continue;
So this is something (one of many) I will note down to think about when we come on to file-backed guard pages.
Quoted 8 lines
Though I guess really that's not the main reason why I'm saying this; my main reason is that almost any other path that has to ensure an
anon_vmais present does that part first (usually because the ordering matters and this way around is more or less the only possible ordering). So even if there are some specific reasons why you can do the ordering the other way around here, it kinda stands out to me as being weird...
I mean, fair enough, on the basis of convention and to avoid future issues with this I'll move it.
Quoted 28 lines
Quoted 28 lines
Quoted 27 lines
Quoted 11 lines
mm/madvise.c +10
-0+if (err_anon) + err = err_anon; + } + +if (err <=0 ) +return err; + +if (!retried) +/* +* OK some of the range have non-guard pages mapped, zap mm/madvise.c static long madvise_remove(struct vm_area_struct *vma, · line 1131
Quoted 10 lines
mm/madvise.c +10
-0+* them. This leaves existing guard pages in place. +*/ +zap_page_range_single (vma, start, end - start,NULL ); + else +/* +* If we reach here, then there is a racing fault that +* has populated the PTE after we zapped. Give up and +* let the user know to try again. +*/ + return -EAGAIN;Hmm, yeah, it would be nice if we could avoid telling userspace to loop on
-EAGAINbut I guess we don't have any particularly good options here? Well, we could bail out with-EINTRif a (fatal?) signal is pending and otherwise keep looping... if we'd tell userspace "try again on-EAGAIN", we might as well do that in the kernel...
Quoted 7 lines
Quoted 3 lines
The problem is you could conceivably go on for quite some time, while holding and contending a HIGHLY contended lock (
mm->mmap_lock) so I'd really rather let userspace take care of it.Hmm... so if the retry was handled in-kernel, you'd basically ideally have the retry happen all the way up in
do_madvise(), where the mmap lock can be dropped and re-taken?
Yeah perhaps, but that gets (really) horrible.
Quoted 10 lines
Quoted 9 lines
You could avoid this by having the walker be a _replace_ operation, that is
- if we encounter an existing mapping, replace in-place with a poison marker rather than install marker/zap.However doing that would involve either completely abstracting such logic from scratch (a significant task in itself) to avoid duplication which be hugely off-topic for the patch set or worse, duplicating a whole bunch of page walking logic once again.
Quoted 4 lines
Mmh, yeah, you'd have to extract the locked part of
zap_pte_range()and add your own copy of all the stuff that happens higher up for setting up TLB flushes and such... I see how that would be a massive pain and error-prone.
Yep, I'd really, really like to avoid doing that, the solution we have now is neat and avoids such duplication.
Quoted 11 lines
Quoted 4 lines
By being optimistic and simply having the user having to handle looping which seems reasonable (again, it's weird if you're installing poison markers and another thread could be racing you) we avoid all of that.
I guess one case in which that could happen legitimately is if you race a
MADV_POISONon the area 0x1ff000-0x200100 (first page is populated, second page is not, pmd entry corresponding to0x200000is clear) with a page fault at0x200200? So you could have a scenario like:
Quoted 7 lines
1.
MADV_POISONstartswalk_page_range()
2.MADV_POISONsees non-zero, non-poison PTE at0x1ff000, stops the walk
3.MADV_POISONdoeszap_page_range_single()
4. pagefault at0x200200happens and populates with a hugepage
5.MADV_POISONenterswalk_page_range()
6.MADV_POISONsplits the THP
7.MADV_POISONsees a populated PTE
You really shouldn't be seeing page faults in the range you are setting up poison markers for _at all_ :) it's something you'd do ahead of time.
But of course it's possible some scenario could arise like that, that's what the EAGAIN is for.
I just really don't want to get into a realm of trying to prove absolutely under all circumstances that we can't go on forever in a loop like that.
If you drop the lock for contention then you up the risk of that, it just feels dangerous.
A userland program can however live with a 'if EAGAIN try again' situation.
An alternative approach to this might be to try to take the VMA lock, but given the fraught situation with locking elsewhere I wonder if we should.
Also, you have to be realy unlucky with timing for this to happen, even in the scenario you mention (where you'd have to be unlucky with alignment too), unless you're _heavily_ page faulting in the range, either way a userland loop checking EAGAIN doesn't seem unreasonable.
Quoted 29 lines
Quoted 19 lines
Quoted 10 lines
Quoted 10 lines
mm/madvise.c +9
-0+update_mmu_cache (walk->vma, addr, pte); + } + +return 0 ; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock =PGWALK_RDLOCK ,Quoted 8 lines
Quoted 1 line
+};
It is a _little_ weird that unpoisoning creates page tables when they don't already exist, which will also prevent creating THP entries on fault in such areas afterwards... but I guess it doesn't really matter given that poisoning has that effect, too, and you probably usually won't call
MADV_GUARD_UNPOISONon an area that hasn't been poisoned before... so I guess this is not an actionable comment.Quoted 2 lines
It doesn't? There's no .install_pte so if an entries are non-present we ignore.
Ah, right, of course. Nevermind.
Quoted 4 lines
HOWEVER, we do split THP. I don't think there's any way around it unless we extended the page walker to handle this more gracefully (pmd level being able to hint that we shouldn't do that or something), but that's really out of scope here.
Quoted 4 lines
I think the
walk->action == ACTION_CONTINUEcheck inwalk_pmd_range()would let you do that, seewp_clean_pmd_entry()for an example. But yeah I guess that might just be unnecessary complexity.
Ah yeah... cool, actually think I will add that then, I hadn't noticed you could update that _in a callback_, as I first thought it was something you could set ahead of time then noticed the walker code resets it and... yeah cool.
Quoted 6 lines
Quoted 4 lines
The idea is that a caller can lazily call
MADV_GUARD_UNPOISONon a range knowing things stay as they were, I guess we can add to the manpage a note that this will split THP?Yeah, might make sense...
No need then :)
Jann Horn
reviewerRe: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 22 lines · Lorenzo Stoakes
Quoted 13 lines · Jann Horn
Quoted 5 lines · Lorenzo Stoakes
Quoted 1 line · Jann Horn
On Fri, Sep 27, 2024 at 2:51 PM Lorenzo Stoakes <[email protected]> wrote:
By being optimistic and simply having the user having to handle looping which seems reasonable (again, it's weird if you're installing poison markers and another thread could be racing you) we avoid all of that.
I guess one case in which that could happen legitimately is if you race a
MADV_POISONon the area 0x1ff000-0x200100 (first page is populated, second page is not, pmd entry corresponding to0x200000is clear) with a page fault at0x200200? So you could have a scenario like:Quoted 7 lines
1.
MADV_POISONstartswalk_page_range()
2.MADV_POISONsees non-zero, non-poison PTE at0x1ff000, stops the walk
3.MADV_POISONdoeszap_page_range_single()
4. pagefault at0x200200happens and populates with a hugepage
5.MADV_POISONenterswalk_page_range()
6.MADV_POISONsplits the THP
7.MADV_POISONsees a populated PTE
Quoted 2 lines
You really shouldn't be seeing page faults in the range you are setting up poison markers for
_atall_:) it's something you'd do ahead of time.
But that's not what happens in my example - the address where the fault happens (0x200200) *is not* in the address range that MADV_POISON is called on (0x1ff000-0x200100). The fault and the MADV_POISON are in different 4KiB pages. What causes the conflict is that the fault and the MADV_POISON overlap the same *2MiB region* (both are in the region 0x200000-0x400000), and so THP stuff can effectively cause "page faults in the range you are setting up poison markers for".
Quoted 5 lines
But of course it's possible some scenario could arise like that, that's what the EAGAIN is for.
I just really don't want to get into a realm of trying to prove absolutely under all circumstances that we can't go on forever in a loop like that.
We can have a bailout on signal_pending() or something like that, and a cond_resched(). Then as far as I know, it won't really make a difference in behavior whether the loop is in the kernel or in userspace code that's following what the manpage tells it to do - either way, the program will loop until it either finishes its work or is interrupted by a signal, and either way it can get preempted. (Well, except under PREEMPT_NONE, but that is basically asking for long scheduling delays.)
And we do have other codepaths that have to loop endlessly if they keep racing with page table updates the wrong way, though I guess those loops are not going to always scan over a large address range over and over again...
Maybe something like this would be good enough, and mirror what you'd otherwise tell userspace to do?
@@ -1598,6 +1598,7 @@ int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int beh
return madvise_inject_error(behavior, start, start + len_in);
#endif
+retry:
write = madvise_need_mmap_write(behavior);
if (write) {
if (mmap_write_lock_killable(mm))
@@ -1627,6 +1628,12 @@ int do_madvise(struct mm_struct *mm, unsigned
long start, size_t len_in, int beh
else
mmap_read_unlock(mm);+ if (error == <<<some special value>>>) {
+ if (!signal_pending(current))
+ goto retry;
+ error = -ERESTARTNOINTR;
+ }
+
return error;
}
Buuut, heh, actually, I just realized: You could even omit this and simply replace -EINTR with -ERESTARTNOINTR in your code as the error value, and then the kernel would automatically go back into the syscall for you after going through signal handing and such, without userspace noticing.
https://lore.kernel.org/all/[email protected]/
has some explanation on how this works. Basically it tells the architecture's syscall entry code to move the userspace instruction pointer back to the syscall instruction, so as soon as execution returns to userspace, the first userspace instruction that executes will immediately re-do the syscall. That might be the easiest way, even if it is maybe a *little* bit of an API abuse to use this thing without having a pending signal...
Quoted 5 lines
If you drop the lock for contention then you up the risk of that, it just feels dangerous.
A userland program can however live with a 'if EAGAIN try again' situation.
Quoted 7 lines
An alternative approach to this might be to try to take the VMA lock, but given the fraught situation with locking elsewhere I wonder if we should.
Also, you have to be realy unlucky with timing for this to happen, even in the scenario you mention (where you'd have to be unlucky with alignment too), unless you're _heavily_ page faulting in the range, either way a userland loop checking EAGAIN doesn't seem unreasonable.
Yes, we could do -EINTR and document that for userspace, and as long as everyone using this properly reads the documentation, it will be fine. Though I imagine that from the userspace programmer perspective that's a weird API design - as in, if this error code always means I have to try again, why can't the kernel do that internally. It's kind of leaking an implementation detail into the UAPI.
Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism
Quoted 27 lines · Jann Horn
Quoted 22 lines · Lorenzo Stoakes
Quoted 13 lines · Jann Horn
Quoted 5 lines · Lorenzo Stoakes
Quoted 1 line · Jann Horn
On Fri, Sep 27, 2024 at 2:51 PM Lorenzo Stoakes <[email protected]> wrote:
By being optimistic and simply having the user having to handle looping which seems reasonable (again, it's weird if you're installing poison markers and another thread could be racing you) we avoid all of that.
I guess one case in which that could happen legitimately is if you race a
MADV_POISONon the area 0x1ff000-0x200100 (first page is populated, second page is not, pmd entry corresponding to0x200000is clear) with a page fault at0x200200? So you could have a scenario like:Quoted 7 lines
1.
MADV_POISONstartswalk_page_range()
2.MADV_POISONsees non-zero, non-poison PTE at0x1ff000, stops the walk
3.MADV_POISONdoeszap_page_range_single()
4. pagefault at0x200200happens and populates with a hugepage
5.MADV_POISONenterswalk_page_range()
6.MADV_POISONsplits the THP
7.MADV_POISONsees a populated PTEQuoted 2 lines
You really shouldn't be seeing page faults in the range you are setting up poison markers for
_atall_:) it's something you'd do ahead of time.
Quoted 8 lines
But that's not what happens in my example - the address where the fault happens (
0x200200) *is not* in the address range thatMADV_POISONis called on (0x1ff000-0x200100). The fault and theMADV_POISONare in different 4KiB pages. What causes the conflict is that the fault and theMADV_POISONoverlap the same *2MiB region* (both are in the region 0x200000-0x400000), and so THP stuff can effectively cause "page faults in the range you are setting up poison markers for".
Right sorry maybe I wasn't clear in what I said - there should not be faults in the 'vicinity' of the poison pages, that is the range which you potentially intend to protect with the poison markers.
HOWEVER this is problematic clearly for something like a userspace allocator where you might be allocating small ranges that might fit within a huge page.
At the same time, I think you'd have to get pretty unlucky - you'd need to have faulted in enough for a huge page to be collapsed by THP, immediately adjacent to where you are installing this poison range, which spans multiple adjacent pages for some reason over the 2 MiB boundary (I assume you mean 0x201000 not 0x200100 btw :P).
Anyway I think this is moot as I am warming to the idea of us just looping to be honest.
There's a limit to how much can be faulted in (i.e. everything), and we hold the lock.
The user is _choosing_ to call this function and if there happens to be enormously huge amounts of faulting going on then so be it.
Quoted 48 lines
Quoted 6 lines
But of course it's possible some scenario could arise like that, that's what the EAGAIN is for.
I just really don't want to get into a realm of trying to prove absolutely under all circumstances that we can't go on forever in a loop like that.
We can have a bailout on
signal_pending()or something like that, and acond_resched(). Then as far as I know, it won't really make a difference in behavior whether the loop is in the kernel or in userspace code that's following what the manpage tells it to do - either way, the program will loop until it either finishes its work or is interrupted by a signal, and either way it can get preempted. (Well, except underPREEMPT_NONE, but that is basically asking for long scheduling delays.)And we do have other codepaths that have to loop endlessly if they keep racing with page table updates the wrong way, though I guess those loops are not going to always scan over a large address range over and over again...
Maybe something like this would be good enough, and mirror what you'd otherwise tell userspace to do?
(quoted diff) +0
-0@@ -1598,6 +1598,7 @@ int do_madvise(struct mm_struct *mm, unsignedlong start,
size_tlen_in, int behreturn madvise_inject_error(behavior, start, start + len_in);#endif
(quoted diff) +1
-0+retry: write = madvise_need_mmap_write(behavior); if (write) { if (mmap_write_lock_killable(mm))@@ -1627,6 +1628,12 @@ int do_madvise(struct mm_struct *mm, unsignedlong start,
size_tlen_in, int behelse mmap_read_unlock(mm);(quoted diff) +6
-0+ if (error == <<<some special value>>>) { + if (!signal_pending(current)) + goto retry; + error = -ERESTARTNOINTR; + } + return error; }
Quoted 2 lines
Buuut, heh, actually, I just realized: You could even omit this and simply replace
-EINTRwith-ERESTARTNOINTRin your code as the error
Interesting that that exists had no idea :)
I think I'd rather avoid it as it looks so specific and a lot more like asking for trouble than simply looping.
Quoted 26 lines
value, and then the kernel would automatically go back into the syscall for you after going through signal handing and such, without userspace noticing.
https://lore.kernel.org/all/[email protected]/
has some explanation on how this works. Basically it tells the architecture's syscall entry code to move the userspace instruction pointer back to the syscall instruction, so as soon as execution returns to userspace, the first userspace instruction that executes will immediately re-do the syscall. That might be the easiest way, even if it is maybe a *little* bit of an API abuse to use this thing without having a pending signal...Quoted 5 lines
If you drop the lock for contention then you up the risk of that, it just feels dangerous.
A userland program can however live with a 'if EAGAIN try again' situation.
Quoted 7 lines
An alternative approach to this might be to try to take the VMA lock, but given the fraught situation with locking elsewhere I wonder if we should.
Also, you have to be realy unlucky with timing for this to happen, even in the scenario you mention (where you'd have to be unlucky with alignment too), unless you're _heavily_ page faulting in the range, either way a userland loop checking EAGAIN doesn't seem unreasonable.
Quoted 6 lines
Yes, we could do
-EINTRand document that for userspace, and as long as everyone using this properly reads the documentation, it will be fine. Though I imagine that from the userspace programmer perspective that's a weird API design - as in, if this error code always means I have to try again, why can't the kernel do that internally. It's kind of leaking an implementation detail into the UAPI.
Overall I am warming to us just looping.
I mean it's hard to argue against this being 'surprising' behaviour - the user expects to be able to install poison markers and for that to just be applied regardless of faulting.
And it's not exactly a huge amount more effort for us to simply loop, I just wanted to avoid it to avoid having to think about whether there's cases that could result in an eternal loop...
We'd need a write lock to VMA lock the VMAs and prevent racing faults (or in the case of non-VMA lock kernels to simplly prevent them) which adds to contention issues arguably a lot more than simply looping under the read lock.
Let me think about this but I think I will go ahead and try to add something simple that loops + checks for pending fatal signals for the next iteration of this series.
RFC PATCH 4/4 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 established (poisoned), cleared (remedied) and that touching poisoned pages result in SIGSEGV. We also assert that, in remedying a range, non-poison pages remain intact.
We then examine different operations on regions containing poison markers behave to ensure correct behaviour:
* Operations over multiple VMAs operate as expected.
* Invoking MADV_GUARD_POISION / MADV_GUARD_REMEDY via process_madvise() in batches works correctly.
* Ensuring that munmap() correctly tears down poison markers.
* Using mprotect() to adjust protection bits does not in any way override or cause issues with poison markers.
* Ensuring that splitting and merging VMAs around poison 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) does not remove poison markers.
* Ensuring that mlock()'ing a range containing poison markers does not cause issues.
* Ensuring that mremap() can move a poisoned range and retain poison markers.
* Ensuring that mremap() can expand a poisoned range and retain poison markers (perhaps moving the range).
* Ensuring that mremap() can shrink a poisoned range and retain poison markers.
* Ensuring that forking a process correctly retains poison markers.
* Ensuring that forking a VMA with VM_WIPEONFORK set behaves sanely.
* Ensuring that lazyfree simply clears poison 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 poison markers.
* Ensuring that madvise(..., MADV_COLD) and madvise(..., MADV_PAGEOUT) do not remove poison markers.
--- tools/testing/selftests/mm/.gitignore | 1 + tools/testing/selftests/mm/Makefile | 1 + tools/testing/selftests/mm/guard-pages.c | 1168 ++++++++++++++++++++++ 3 files changed, 1170 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 +1168 -0
1,168 lines not on this page · raw message
Signature · 1 line
2.46.2
Hi!
Quoted 4 lines
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.
...
Quoted 1 line
Suggested-by Vlastimil Babka <[email protected]>
suse.cz, I believe. (They may prefer suse.com address).
BR,
Pavel
Signature · 1 line
People of Russia, stop Putin before his war on Ukraine escalates.
Quoted 10 lines · Pavel Machek
Hi!
Quoted 4 lines
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.
...
Quoted 1 line
Suggested-by Vlastimil Babka <[email protected]>suse.cz, I believe. (They may prefer suse.com address).
Sigh yes I know, I know :)
Sorry Vlasta! ;)
Quoted 6 lines
BR,
Pavel--
People of Russia, stop Putin before his war on Ukraine escalates.