Re: [RFC PATCH 3/4] mm: madvise: implement lightweight guard page mechanism

From: Jann Horn
Date: Mon Oct 14 2024 - 11:58:43 EST


On Mon, Oct 14, 2024 at 1:09 PM Lorenzo Stoakes
<lorenzo.stoakes@xxxxxxxxxx> wrote:
> On Fri, Oct 11, 2024 at 08:11:36PM +0200, Jann Horn wrote:
> > On Fri, Sep 27, 2024 at 2:51 PM Lorenzo Stoakes <lorenzo.stoakes@xxxxxxxxxx> wrote:
> > > return 0;
> > > default:
> > > /* be safe, default to 1. list exceptions explicitly */
> > [...]
> > > +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);
> >
> > 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 .
>
> I think you didn't finish this sentence :)

Oops...

> 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?

> 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...

> > > + 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;
> >
> > 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...
>
> 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?

> 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.

> 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

> > > + 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.
>
> It doesn't? There's no .install_pte so if an entries are non-present we
> ignore.

Ah, right, of course. Nevermind.

> 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.

> 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?

Yeah, might make sense...