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

From: Lorenzo Stoakes
Date: Mon Oct 14 2024 - 13:03:00 EST


On Mon, Oct 14, 2024 at 05:56:50PM +0200, Jann Horn wrote:
> 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?

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.

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

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.

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

I mean, fair enough, on the basis of convention and to avoid future issues
with this I'll move it.

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

Yeah perhaps, but that gets (really) horrible.

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

Yep, I'd really, really like to avoid doing that, the solution we have now
is neat and avoids such duplication.

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

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.

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

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.

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

No need then :)