diff mbox series

[v2,1/4] mm/mremap: Optimize the start addresses in move_page_tables()

Message ID 20230519190934.339332-2-joel@joelfernandes.org (mailing list archive)
State New
Headers show
Series Optimize mremap during mutual alignment within PMD | expand

Commit Message

Joel Fernandes May 19, 2023, 7:09 p.m. UTC
Recently, we see reports [1] of a warning that triggers due to
move_page_tables() doing a downward and overlapping move on a
mutually-aligned offset within a PMD. By mutual alignment, I
mean the source and destination addresses of the mremap are at
the same offset within a PMD.

This mutual alignment along with the fact that the move is downward is
sufficient to cause a warning related to having an allocated PMD that
does not have PTEs in it.

This warning will only trigger when there is mutual alignment in the
move operation. A solution, as suggested by Linus Torvalds [2], is to
initiate the copy process at the PMD level whenever such alignment is
present. Implementing this approach will not only prevent the warning
from being triggered, but it will also optimize the operation as this
method should enhance the speed of the copy process whenever there's a
possibility to start copying at the PMD level.

Some more points:
a. The optimization can be done only when both the source and
destination of the mremap do not have anything mapped below it up to a
PMD boundary. I add support to detect that.

b. #1 is not a problem for the call to move_page_tables() from exec.c as
nothing is expected to be mapped below the source/destination. However,
for non-overlapping mutually aligned moves as triggered by mremap(2),
I added support for checking such cases.

c. I currently only optimize for PMD moves, in the future I/we can build
on this work and do PUD moves as well if there is a need for this. But I
want to take it one step at a time.

[1] https://lore.kernel.org/all/ZB2GTBD%2FLWTrkOiO@dhcp22.suse.cz/
[2] https://lore.kernel.org/all/CAHk-=whd7msp8reJPfeGNyt0LiySMT0egExx3TVZSX3Ok6X=9g@mail.gmail.com/

Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Joel Fernandes (Google) <joel@joelfernandes.org>
---
 mm/mremap.c | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)

Comments

Linus Torvalds May 19, 2023, 7:21 p.m. UTC | #1
On Fri, May 19, 2023 at 12:09 PM Joel Fernandes (Google)
<joel@joelfernandes.org> wrote:
>
> +static bool check_addr_in_prev(struct vm_area_struct *vma, unsigned long addr,
> +                              unsigned long mask)
> +{
> +       int addr_masked = addr & mask;
> +       struct vm_area_struct *prev = NULL, *cur = NULL;
> +
> +       /* If the masked address is within vma, there is no prev mapping of concern. */
> +       if (vma->vm_start <= addr_masked)
> +               return false;

Hmm.

I should have caught this last time, but I didn't.

That test smells bad to me. Or maybe it's just the comment.

I *suspect* that the test is literally just for the stack movement
case by execve, where it catches the case where we're doing the
movement entirely within the one vma we set up.

But in the *general* case I think the above is horribly wrong: if you
want to move pages within an existing mapping, the page moving code
can't just randomly say "I'll expand the area you wanted to move".

Again, in that general mremap() case (as opposed to the special stack
moving case for execve), I *think* that the caller has already split
the vma's at the point of the move, and this test simply cannot ever
trigger.

So I think the _code_ works, but I think the comment in particular is
questionable, and I'm a bit surprised about the code too,. because I
thought execve() only expanded to exactly the moving area.

End result: I think the patch on the whole looks nice, and smaller
than I expected. I also suspect it works in practice, but I'd like
that test clarified. Does it *actually* trigger for the stack moving
case? Because I think it must (never* trigger for the mremap case?

And maybe I'm the one confused here, and all I really need is an
explanation with small words and simple grammar starting with "No,
Linus, this is for case xyz"

                  Linus
Joel Fernandes May 19, 2023, 10:52 p.m. UTC | #2
Hi Linus,

On Fri, May 19, 2023 at 3:21 PM Linus Torvalds
<torvalds@linux-foundation.org> wrote:
>
> On Fri, May 19, 2023 at 12:09 PM Joel Fernandes (Google)
> <joel@joelfernandes.org> wrote:
> >
> > +static bool check_addr_in_prev(struct vm_area_struct *vma, unsigned long addr,
> > +                              unsigned long mask)
> > +{
> > +       int addr_masked = addr & mask;
> > +       struct vm_area_struct *prev = NULL, *cur = NULL;
> > +
> > +       /* If the masked address is within vma, there is no prev mapping of concern. */
> > +       if (vma->vm_start <= addr_masked)
> > +               return false;
>
> Hmm.
>
> I should have caught this last time, but I didn't.
>
> That test smells bad to me. Or maybe it's just the comment.
>
> I *suspect* that the test is literally just for the stack movement
> case by execve, where it catches the case where we're doing the
> movement entirely within the one vma we set up.

Yes that's right, the test is only for the stack movement case. For
the regular mremap case, I don't think there is a way for it to
trigger.

> But in the *general* case I think the above is horribly wrong: if you
> want to move pages within an existing mapping, the page moving code
> can't just randomly say "I'll expand the area you wanted to move".
> Again, in that general mremap() case (as opposed to the special stack
> moving case for execve), I *think* that the caller has already split
> the vma's at the point of the move, and this test simply cannot ever
> trigger.

Yes, the test simply cannot ever trigger for mremap() but we still
need the test for the stack case. That's why I had considered adding
it and I had indeed reviewed the stack case when adding the test. I
could update the comment to mention that, if you want.

> So I think the _code_ works, but I think the comment in particular is
> questionable, and I'm a bit surprised about the code too,. because I
> thought execve() only expanded to exactly the moving area.

It expands to cover both the new start and the old end of the stack AFAICS:
          /*
           * cover the whole range: [new_start, old_end)
           */
          if (vma_expand(&vmi, vma, new_start, old_end, vma->vm_pgoff, NULL))
                  return -ENOMEM;

In this case, it will trigger for the stack because this same expanded
vma is passed as both the new vma and the old vma to
move_page_tables().

           */
          if (length != move_page_tables(vma, old_start,
                                         vma, new_start, length, false))
                  return -ENOMEM;

So AFAICS, it is possible that old_start will start later than this
newly expanded VMA. So for such a situation, old_start can be
realigned to PMD and the test allows that by saying it need not worry
about aligning down to an existing VMA.

> End result: I think the patch on the whole looks nice, and smaller
> than I expected. I also suspect it works in practice, but I'd like
> that test clarified. Does it *actually* trigger for the stack moving
> case? Because I think it must (never* trigger for the mremap case?

You are right that the test will not trigger for the mremap case. But
from a correctness standpoint, I thought of leaving it there for the
stack (and who knows for what other future reasons the test may be needed).
I can update the comment describing the stack if you like.

> And maybe I'm the one confused here, and all I really need is an
> explanation with small words and simple grammar starting with "No,
> Linus, this is for case xyz"

Hopefully it is clear now and you agree. Let me know if you want me to
do something more. I can make some time next week to trace the stack
case a bit more if you like and report back on any behaviors, however
the mremap tests I did are looking good and working as expected.

thanks,

 - Joel
Linus Torvalds May 20, 2023, 2:34 a.m. UTC | #3
On Fri, May 19, 2023 at 3:52 PM Joel Fernandes <joel@joelfernandes.org> wrote:
> >
> > I *suspect* that the test is literally just for the stack movement
> > case by execve, where it catches the case where we're doing the
> > movement entirely within the one vma we set up.
>
> Yes that's right, the test is only for the stack movement case. For
> the regular mremap case, I don't think there is a way for it to
> trigger.

So I feel the test is simply redundant.

For the regular mremap case, it never triggers.

And for the stack movement case by execve, I don't think it matters if
you just were to change the logic of the subsequent checks a bit.

In particular, you do this:

        /* If the masked address is within vma, there is no prev
mapping of concern. */
        if (vma->vm_start <= addr_masked)
                return false;

        /*
         * Attempt to find vma before prev that contains the address.
         * On any issue, assume the address is within a previous mapping.
         * @mmap write lock is held here, so the lookup is safe.
         */
        cur = find_vma_prev(vma->vm_mm, vma->vm_start, &prev);
        if (!cur || cur != vma || !prev)
                return true;

        /* The masked address fell within a previous mapping. */
        if (prev->vm_end > addr_masked)
                return true;

        return false;

And I think that

        if (!cur || cur != vma || !prev)
                return true;

is actively wrong, because if there is no 'prev', then you should return false.

So I *think* all of the above could just be replaced with this instead:

        find_vma_prev(vma->vm_mm, vma->vm_start, &prev);
        return prev && prev->vm_end  > addr_masked;

because only if we have a 'prev', and the prev is into that masked
address, do we need to avoid doing the masking.

With that simplified test, do you even care about that whole "the
masked address was already in the vma"? Not that I can see.

And we don't even care about the return value of 'find_vma_prev()',
because it had better be 'vma'. We're giving it 'vma->vm_start' as an
address, for chrissake!

So if you *really* wanted to, you could do something like

        cur = find_vma_prev(..);
        if (WARN_ON_ONCE(cut != vma))
                return true;

but even that WARN_ON_ONCE() seems pretty bogus. If it triggers, we
have some serious corruption going on.

So I stil find that whole "vma->vm_start <= addr_masked" test a bit
confusing, since it seems entirely redundant.

Is it just because you wanted to avoid calling "find_vma_prev()" at
all? Maybe just say that in the comment.

                  Linus
Joel Fernandes May 20, 2023, 3:17 a.m. UTC | #4
Hi Linus,

On Fri, May 19, 2023 at 10:34 PM Linus Torvalds
<torvalds@linux-foundation.org> wrote:
>
> On Fri, May 19, 2023 at 3:52 PM Joel Fernandes <joel@joelfernandes.org> wrote:
> > >
> > > I *suspect* that the test is literally just for the stack movement
> > > case by execve, where it catches the case where we're doing the
> > > movement entirely within the one vma we set up.
> >
> > Yes that's right, the test is only for the stack movement case. For
> > the regular mremap case, I don't think there is a way for it to
> > trigger.
>
> So I feel the test is simply redundant.
>
> For the regular mremap case, it never triggers.

Unfortunately, I just found that mremap-ing a range purely within a
VMA can actually cause the old and new VMA passed to
move_page_tables() to be the same.

I added a printk to the beginning of move_page_tables that prints all the args:
printk("move_page_tables(vma=(%lx,%lx), old_addr=%lx,
new_vma=(%lx,%lx), new_addr=%lx, len=%lx)\n", vma->vm_start,
vma->vm_end, old_addr, new_vma->vm_start, new_vma->vm_end, new_addr,
len);

Then I wrote a simple test to move 1MB purely within a 10MB range and
I found on running the test that the old and new vma passed to
move_page_tables() are exactly the same.

[   19.697596] move_page_tables(vma=(7f1f985f7000,7f1f98ff7000),
old_addr=7f1f987f7000, new_vma=(7f1f985f7000,7f1f98ff7000),
new_addr=7f1f98af7000, len=100000)

That is a bit counter intuitive as I really thought we'd be splitting
the VMAs with such a move. Any idea what am I missing?

Also, such a usecase will break with my patch as we may accidentally
overwrite parts of a range that were not part of the mremap request.
Maybe I should just turn off the optimization if vma == new_vma,
however that will also turn it off for the stack move so then maybe
another way is to special case stack moves in move_page_tables().

So this means I have to go back to the drawing board a bit on this
patch, and also add more tests in mremap_test.c to test such
within-VMA moving. I believe there are no such existing tests... More
work to do for me. :-)

> And for the stack movement case by execve, I don't think it matters if
> you just were to change the logic of the subsequent checks a bit.
>
> In particular, you do this:
>
>         /* If the masked address is within vma, there is no prev
> mapping of concern. */
>         if (vma->vm_start <= addr_masked)
>                 return false;
>
>         /*
>          * Attempt to find vma before prev that contains the address.
>          * On any issue, assume the address is within a previous mapping.
>          * @mmap write lock is held here, so the lookup is safe.
>          */
>         cur = find_vma_prev(vma->vm_mm, vma->vm_start, &prev);
>         if (!cur || cur != vma || !prev)
>                 return true;
>         /* The masked address fell within a previous mapping. */
>         if (prev->vm_end > addr_masked)
>                 return true;
>
>         return false;
>
> And I think that
>
>         if (!cur || cur != vma || !prev)
>                 return true;
>
> is actively wrong, because if there is no 'prev', then you should return false.

During my tests, I observed that there was always an existing,
unrelated memory mapping present prior to the new memory region
allocated by mmap. Based on this observation, I concluded that if
there is no previous mapping (i.e., if prev is NULL), it indicates a
potential issue with find_vma_prev(). Therefore, I designed this
function to return here indicating that the masked address is not
suitable for optimization, whenever prev is NULL.

That's obviously confusing so I'll try to rewrite this part of the
patch a bit better with appropriate comments.

> So I *think* all of the above could just be replaced with this instead:
>
>         find_vma_prev(vma->vm_mm, vma->vm_start, &prev);
>         return prev && prev->vm_end  > addr_masked;
>
> because only if we have a 'prev', and the prev is into that masked
> address, do we need to avoid doing the masking.
>
> With that simplified test, do you even care about that whole "the
> masked address was already in the vma"? Not that I can see.
>
> And we don't even care about the return value of 'find_vma_prev()',
> because it had better be 'vma'. We're giving it 'vma->vm_start' as an
> address, for chrissake!
>
> So if you *really* wanted to, you could do something like
>
>         cur = find_vma_prev(..);
>         if (WARN_ON_ONCE(cut != vma))
>                 return true;
>
> but even that WARN_ON_ONCE() seems pretty bogus. If it triggers, we
> have some serious corruption going on.
>
> So I stil find that whole "vma->vm_start <= addr_masked" test a bit
> confusing, since it seems entirely redundant.
>
> Is it just because you wanted to avoid calling "find_vma_prev()" at
> all? Maybe just say that in the comment.

Yes exactly, I did not want to run find_vma_prev() unnecessarily. I
will add such clarifications in the comments.

Thanks for all the comments so far, I will continue to work on this.

 - Joel
Joel Fernandes May 20, 2023, 3:56 a.m. UTC | #5
On Fri, May 19, 2023 at 11:17 PM Joel Fernandes <joel@joelfernandes.org> wrote:
>
> Hi Linus,
>
> On Fri, May 19, 2023 at 10:34 PM Linus Torvalds
> <torvalds@linux-foundation.org> wrote:
> >
> > On Fri, May 19, 2023 at 3:52 PM Joel Fernandes <joel@joelfernandes.org> wrote:
> > > >
> > > > I *suspect* that the test is literally just for the stack movement
> > > > case by execve, where it catches the case where we're doing the
> > > > movement entirely within the one vma we set up.
> > >
> > > Yes that's right, the test is only for the stack movement case. For
> > > the regular mremap case, I don't think there is a way for it to
> > > trigger.
> >
> > So I feel the test is simply redundant.
> >
> > For the regular mremap case, it never triggers.
>
> Unfortunately, I just found that mremap-ing a range purely within a
> VMA can actually cause the old and new VMA passed to
> move_page_tables() to be the same.
>
> I added a printk to the beginning of move_page_tables that prints all the args:
> printk("move_page_tables(vma=(%lx,%lx), old_addr=%lx,
> new_vma=(%lx,%lx), new_addr=%lx, len=%lx)\n", vma->vm_start,
> vma->vm_end, old_addr, new_vma->vm_start, new_vma->vm_end, new_addr,
> len);
>
> Then I wrote a simple test to move 1MB purely within a 10MB range and
> I found on running the test that the old and new vma passed to
> move_page_tables() are exactly the same.
>
> [   19.697596] move_page_tables(vma=(7f1f985f7000,7f1f98ff7000),
> old_addr=7f1f987f7000, new_vma=(7f1f985f7000,7f1f98ff7000),
> new_addr=7f1f98af7000, len=100000)
>
> That is a bit counter intuitive as I really thought we'd be splitting
> the VMAs with such a move. Any idea what am I missing?
>
> Also, such a usecase will break with my patch as we may accidentally
> overwrite parts of a range that were not part of the mremap request.
> Maybe I should just turn off the optimization if vma == new_vma,
> however that will also turn it off for the stack move so then maybe
> another way is to special case stack moves in move_page_tables().
>
> So this means I have to go back to the drawing board a bit on this
> patch, and also add more tests in mremap_test.c to test such
> within-VMA moving. I believe there are no such existing tests... More
> work to do for me. :-)

I also realize that I don't really need to check whether the masked
source address falls under a VMA neighboring to that of the source's.
I only need to do so for the destination. And for the destination
masked address, I need to forbid the optimization if after masking,
the destination addr will fall within *any* mapping whether it is its
own or a neighbor one. Since we cannot afford to corrupt those. I
believe that will also take care of both the intra-VMA moves as well
as the stack usecase. And also cut down one of the two find_vma_prev()
calls.

I will rewrite the patch to address these soon. Thanks for patience
and all the comments,

Thanks!

 - Joel
Linus Torvalds May 20, 2023, 4:01 a.m. UTC | #6
On Fri, May 19, 2023 at 8:57 PM Joel Fernandes <joel@joelfernandes.org> wrote:
>
> I also realize that I don't really need to check whether the masked
> source address falls under a VMA neighboring to that of the source's.

I don't think that's true.

You can't start randomly moving other source vma's that may have other contents.

               Linus
Joel Fernandes May 20, 2023, 4:14 a.m. UTC | #7
On Sat, May 20, 2023 at 12:01 AM Linus Torvalds
<torvalds@linux-foundation.org> wrote:
>
> On Fri, May 19, 2023 at 8:57 PM Joel Fernandes <joel@joelfernandes.org> wrote:
> >
> > I also realize that I don't really need to check whether the masked
> > source address falls under a VMA neighboring to that of the source's.
>
> I don't think that's true.
>
> You can't start randomly moving other source vma's that may have other contents.

If the beginning part of the PMD is not mapped at the destination, I
thought maybe a whole PMD could be moved to it. But I guess not
because we don't want those contents to be accessible. So then in that
case we have to forbid the optimization for all intra-VMA moves except
those involving the stack. I will think more about it.

Thanks,

 - Joel
Joel Fernandes May 20, 2023, 4:22 a.m. UTC | #8
On Sat, May 20, 2023 at 12:14 AM Joel Fernandes <joel@joelfernandes.org> wrote:
>
> On Sat, May 20, 2023 at 12:01 AM Linus Torvalds
> <torvalds@linux-foundation.org> wrote:
> >
> > On Fri, May 19, 2023 at 8:57 PM Joel Fernandes <joel@joelfernandes.org> wrote:
> > >
> > > I also realize that I don't really need to check whether the masked
> > > source address falls under a VMA neighboring to that of the source's.
> >
> > I don't think that's true.
> >
> > You can't start randomly moving other source vma's that may have other contents.
>
> If the beginning part of the PMD is not mapped at the destination, I
> thought maybe a whole PMD could be moved to it. But I guess not
> because we don't want those contents to be accessible. So then in that
> case we have to forbid the optimization for all intra-VMA moves except
> those involving the stack. I will think more about it.

Duh, we can't move crap from the source like that also because it has
real data. I think I got confused between "moving" and "copying". I
feel silly, maybe it is time to go to sleep and live to fight another
day.

 - Joel
Joel Fernandes May 20, 2023, 5:04 a.m. UTC | #9
On Fri, May 19, 2023 at 09:01:07PM -0700, Linus Torvalds wrote:
> On Fri, May 19, 2023 at 8:57 PM Joel Fernandes <joel@joelfernandes.org> wrote:
> >
> > I also realize that I don't really need to check whether the masked
> > source address falls under a VMA neighboring to that of the source's.
> 
> I don't think that's true.
> 
> You can't start randomly moving other source vma's that may have other contents.

Here is the rewritten patch, this is untested and I am just sharing as a
preview (sorry if I have been noisy). I will test it soon and send a proper patch.

Basically, I detect any moves within the same VMA except when it happens for
stack moving down. And will add another patch later to test moves within a VMA.

---8<-----------------------

From: "Joel Fernandes (Google)" <joel@joelfernandes.org>
Subject: [PATCH v3] mm/mremap: Optimize the start addresses in move_page_tables()

Recently, we see reports [1] of a warning that triggers due to
move_page_tables() doing a downward and overlapping move on a
mutually-aligned offset within a PMD. By mutual alignment, I
mean the source and destination addresses of the mremap are at
the same offset within a PMD.

This mutual alignment along with the fact that the move is downward is
sufficient to cause a warning related to having an allocated PMD that
does not have PTEs in it.

This warning will only trigger when there is mutual alignment in the
move operation. A solution, as suggested by Linus Torvalds [2], is to
initiate the copy process at the PMD level whenever such alignment is
present. Implementing this approach will not only prevent the warning
from being triggered, but it will also optimize the operation as this
method should enhance the speed of the copy process whenever there's a
possibility to start copying at the PMD level.

Some more points:
a. The optimization can be done only when both the source and
destination of the mremap do not have anything mapped below it up to a
PMD boundary. I add support to detect that.

b. #1 is not a problem for the call to move_page_tables() from exec.c as
nothing is expected to be mapped below the source/destination. However,
for non-overlapping mutually aligned moves as triggered by mremap(2),
I added support for checking such cases.

c. I currently only optimize for PMD moves, in the future I/we can build
on this work and do PUD moves as well if there is a need for this. But I
want to take it one step at a time.

[1] https://lore.kernel.org/all/ZB2GTBD%2FLWTrkOiO@dhcp22.suse.cz/
[2] https://lore.kernel.org/all/CAHk-=whd7msp8reJPfeGNyt0LiySMT0egExx3TVZSX3Ok6X=9g@mail.gmail.com/

Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Joel Fernandes (Google) <joel@joelfernandes.org>
---
 fs/exec.c          |  2 +-
 include/linux/mm.h |  2 +-
 mm/mremap.c        | 71 ++++++++++++++++++++++++++++++++++++++++++++--
 3 files changed, 70 insertions(+), 5 deletions(-)

diff --git a/fs/exec.c b/fs/exec.c
index 7c44d0c65b1b..7a7217353115 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -707,7 +707,7 @@ static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift)
 	 * process cleanup to remove whatever mess we made.
 	 */
 	if (length != move_page_tables(vma, old_start,
-				       vma, new_start, length, false))
+				       vma, new_start, length, false, true))
 		return -ENOMEM;
 
 	lru_add_drain();
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 1f79667824eb..dd415cd2493d 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -2265,7 +2265,7 @@ int get_cmdline(struct task_struct *task, char *buffer, int buflen);
 extern unsigned long move_page_tables(struct vm_area_struct *vma,
 		unsigned long old_addr, struct vm_area_struct *new_vma,
 		unsigned long new_addr, unsigned long len,
-		bool need_rmap_locks);
+		bool need_rmap_locks, bool for_stack);
 
 /*
  * Flags used by change_protection().  For now we make it a bitmap so
diff --git a/mm/mremap.c b/mm/mremap.c
index 411a85682b58..5f2e0c7fc839 100644
--- a/mm/mremap.c
+++ b/mm/mremap.c
@@ -478,10 +478,56 @@ static bool move_pgt_entry(enum pgt_entry entry, struct vm_area_struct *vma,
 	return moved;
 }
 
+/*
+ * A helper to check if we can align down. Required for
+ * move_page_tables() and realign_addr() to determine if there is any
+ * mapping to the newly aligned address.
+ */
+static bool can_align_down(struct vm_area_struct *vma, unsigned long addr,
+			       unsigned long mask)
+{
+	int addr_masked = addr & mask;
+	struct vm_area_struct *prev = NULL, *cur = NULL;
+
+	/* If the masked address is within vma, we cannot align the address down. */
+	if (vma->vm_start <= addr_masked)
+		return false;
+
+	/*
+	 * Attempt to find vma before prev that contains the address.
+	 * On any issue, assume the address is within a previous mapping.
+	 * @mmap write lock is held here, so the lookup is safe.
+	 */
+	cur = find_vma_prev(vma->vm_mm, vma->vm_start, &prev);
+	if (!cur || cur != vma || !prev)
+		return false;
+
+	/* The masked address fell within a previous mapping. */
+	if (prev->vm_end > addr_masked)
+		return false;
+
+	return true;
+}
+
+/* Opportunistically realign to specified boundary for faster copy. */
+static void realign_addr(unsigned long *old_addr, struct vm_area_struct *old_vma,
+			 unsigned long *new_addr, struct vm_area_struct *new_vma,
+			 unsigned long mask)
+{
+	if ((*old_addr & ~mask) &&
+	    (*old_addr & ~mask) == (*new_addr & ~mask) &&
+	    can_align_down(old_vma, *old_addr, mask) &&
+	    can_align_down(new_vma, *new_addr, mask)) {
+		*old_addr = *old_addr & mask;
+		*new_addr = *new_addr & mask;
+	}
+}
+
 unsigned long move_page_tables(struct vm_area_struct *vma,
 		unsigned long old_addr, struct vm_area_struct *new_vma,
 		unsigned long new_addr, unsigned long len,
-		bool need_rmap_locks)
+		bool need_rmap_locks,
+		bool for_stack)
 {
 	unsigned long extent, old_end;
 	struct mmu_notifier_range range;
@@ -493,6 +539,18 @@ unsigned long move_page_tables(struct vm_area_struct *vma,
 
 	old_end = old_addr + len;
 
+	/*
+	 * If possible, realign addresses to PMD boundary for faster copy.
+	 * Don't align for intra-VMA moves as we may destroy existing mappings.
+	 * For the stack moving down, both the source and dest ranges are
+	 * within the same vma but we don't expect anything to exist between
+	 * start of the old stack and end of the new stack.
+	 */
+	if ((vma != new_vma || for_stack)
+		&& (len >= PMD_SIZE - (old_addr & ~PMD_MASK))) {
+		realign_addr(&old_addr, vma, &new_addr, new_vma, PMD_MASK);
+	}
+
 	if (is_vm_hugetlb_page(vma))
 		return move_hugetlb_page_tables(vma, new_vma, old_addr,
 						new_addr, len);
@@ -565,6 +623,13 @@ unsigned long move_page_tables(struct vm_area_struct *vma,
 
 	mmu_notifier_invalidate_range_end(&range);
 
+	/*
+	 * Prevent negative return values when {old,new}_addr was realigned
+	 * but we broke out of the above loop for the first PMD itself.
+	 */
+	if (len + old_addr < old_end)
+		return 0;
+
 	return len + old_addr - old_end;	/* how much done */
 }
 
@@ -633,7 +698,7 @@ static unsigned long move_vma(struct vm_area_struct *vma,
 	}
 
 	moved_len = move_page_tables(vma, old_addr, new_vma, new_addr, old_len,
-				     need_rmap_locks);
+				     need_rmap_locks, false);
 	if (moved_len < old_len) {
 		err = -ENOMEM;
 	} else if (vma->vm_ops && vma->vm_ops->mremap) {
@@ -647,7 +712,7 @@ static unsigned long move_vma(struct vm_area_struct *vma,
 		 * and then proceed to unmap new area instead of old.
 		 */
 		move_page_tables(new_vma, new_addr, vma, old_addr, moved_len,
-				 true);
+				 true, false);
 		vma = new_vma;
 		old_len = new_len;
 		old_addr = new_addr;
diff mbox series

Patch

diff --git a/mm/mremap.c b/mm/mremap.c
index 411a85682b58..be81eb3a80a8 100644
--- a/mm/mremap.c
+++ b/mm/mremap.c
@@ -478,6 +478,51 @@  static bool move_pgt_entry(enum pgt_entry entry, struct vm_area_struct *vma,
 	return moved;
 }
 
+/*
+ * A helper to check if a previous mapping exists. Required for
+ * move_page_tables() and realign_addr() to determine if a previous mapping
+ * exists before we can do realignment optimizations.
+ */
+static bool check_addr_in_prev(struct vm_area_struct *vma, unsigned long addr,
+			       unsigned long mask)
+{
+	int addr_masked = addr & mask;
+	struct vm_area_struct *prev = NULL, *cur = NULL;
+
+	/* If the masked address is within vma, there is no prev mapping of concern. */
+	if (vma->vm_start <= addr_masked)
+		return false;
+
+	/*
+	 * Attempt to find vma before prev that contains the address.
+	 * On any issue, assume the address is within a previous mapping.
+	 * @mmap write lock is held here, so the lookup is safe.
+	 */
+	cur = find_vma_prev(vma->vm_mm, vma->vm_start, &prev);
+	if (!cur || cur != vma || !prev)
+		return true;
+
+	/* The masked address fell within a previous mapping. */
+	if (prev->vm_end > addr_masked)
+		return true;
+
+	return false;
+}
+
+/* Opportunistically realign to specified boundary for faster copy. */
+static void realign_addr(unsigned long *old_addr, struct vm_area_struct *old_vma,
+			 unsigned long *new_addr, struct vm_area_struct *new_vma,
+			 unsigned long mask)
+{
+	if ((*old_addr & ~mask) &&
+	    (*old_addr & ~mask) == (*new_addr & ~mask) &&
+	    !check_addr_in_prev(old_vma, *old_addr, mask) &&
+	    !check_addr_in_prev(new_vma, *new_addr, mask)) {
+		*old_addr = *old_addr & mask;
+		*new_addr = *new_addr & mask;
+	}
+}
+
 unsigned long move_page_tables(struct vm_area_struct *vma,
 		unsigned long old_addr, struct vm_area_struct *new_vma,
 		unsigned long new_addr, unsigned long len,
@@ -493,6 +538,10 @@  unsigned long move_page_tables(struct vm_area_struct *vma,
 
 	old_end = old_addr + len;
 
+	/* If possible, realign addresses to PMD boundary for faster copy. */
+	if (len >= PMD_SIZE - (old_addr & ~PMD_MASK))
+		realign_addr(&old_addr, vma, &new_addr, new_vma, PMD_MASK);
+
 	if (is_vm_hugetlb_page(vma))
 		return move_hugetlb_page_tables(vma, new_vma, old_addr,
 						new_addr, len);
@@ -565,6 +614,13 @@  unsigned long move_page_tables(struct vm_area_struct *vma,
 
 	mmu_notifier_invalidate_range_end(&range);
 
+	/*
+	 * Prevent negative return values when {old,new}_addr was realigned
+	 * but we broke out of the above loop for the first PMD itself.
+	 */
+	if (len + old_addr < old_end)
+		return 0;
+
 	return len + old_addr - old_end;	/* how much done */
 }