Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  *  mm/mremap.c
0004  *
0005  *  (C) Copyright 1996 Linus Torvalds
0006  *
0007  *  Address space accounting code   <alan@lxorguk.ukuu.org.uk>
0008  *  (C) Copyright 2002 Red Hat Inc, All Rights Reserved
0009  */
0010 
0011 #include <linux/mm.h>
0012 #include <linux/hugetlb.h>
0013 #include <linux/shm.h>
0014 #include <linux/ksm.h>
0015 #include <linux/mman.h>
0016 #include <linux/swap.h>
0017 #include <linux/capability.h>
0018 #include <linux/fs.h>
0019 #include <linux/swapops.h>
0020 #include <linux/highmem.h>
0021 #include <linux/security.h>
0022 #include <linux/syscalls.h>
0023 #include <linux/mmu_notifier.h>
0024 #include <linux/uaccess.h>
0025 #include <linux/userfaultfd_k.h>
0026 
0027 #include <asm/cacheflush.h>
0028 #include <asm/tlb.h>
0029 #include <asm/pgalloc.h>
0030 
0031 #include "internal.h"
0032 
0033 static pud_t *get_old_pud(struct mm_struct *mm, unsigned long addr)
0034 {
0035     pgd_t *pgd;
0036     p4d_t *p4d;
0037     pud_t *pud;
0038 
0039     pgd = pgd_offset(mm, addr);
0040     if (pgd_none_or_clear_bad(pgd))
0041         return NULL;
0042 
0043     p4d = p4d_offset(pgd, addr);
0044     if (p4d_none_or_clear_bad(p4d))
0045         return NULL;
0046 
0047     pud = pud_offset(p4d, addr);
0048     if (pud_none_or_clear_bad(pud))
0049         return NULL;
0050 
0051     return pud;
0052 }
0053 
0054 static pmd_t *get_old_pmd(struct mm_struct *mm, unsigned long addr)
0055 {
0056     pud_t *pud;
0057     pmd_t *pmd;
0058 
0059     pud = get_old_pud(mm, addr);
0060     if (!pud)
0061         return NULL;
0062 
0063     pmd = pmd_offset(pud, addr);
0064     if (pmd_none(*pmd))
0065         return NULL;
0066 
0067     return pmd;
0068 }
0069 
0070 static pud_t *alloc_new_pud(struct mm_struct *mm, struct vm_area_struct *vma,
0071                 unsigned long addr)
0072 {
0073     pgd_t *pgd;
0074     p4d_t *p4d;
0075 
0076     pgd = pgd_offset(mm, addr);
0077     p4d = p4d_alloc(mm, pgd, addr);
0078     if (!p4d)
0079         return NULL;
0080 
0081     return pud_alloc(mm, p4d, addr);
0082 }
0083 
0084 static pmd_t *alloc_new_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
0085                 unsigned long addr)
0086 {
0087     pud_t *pud;
0088     pmd_t *pmd;
0089 
0090     pud = alloc_new_pud(mm, vma, addr);
0091     if (!pud)
0092         return NULL;
0093 
0094     pmd = pmd_alloc(mm, pud, addr);
0095     if (!pmd)
0096         return NULL;
0097 
0098     VM_BUG_ON(pmd_trans_huge(*pmd));
0099 
0100     return pmd;
0101 }
0102 
0103 static void take_rmap_locks(struct vm_area_struct *vma)
0104 {
0105     if (vma->vm_file)
0106         i_mmap_lock_write(vma->vm_file->f_mapping);
0107     if (vma->anon_vma)
0108         anon_vma_lock_write(vma->anon_vma);
0109 }
0110 
0111 static void drop_rmap_locks(struct vm_area_struct *vma)
0112 {
0113     if (vma->anon_vma)
0114         anon_vma_unlock_write(vma->anon_vma);
0115     if (vma->vm_file)
0116         i_mmap_unlock_write(vma->vm_file->f_mapping);
0117 }
0118 
0119 static pte_t move_soft_dirty_pte(pte_t pte)
0120 {
0121     /*
0122      * Set soft dirty bit so we can notice
0123      * in userspace the ptes were moved.
0124      */
0125 #ifdef CONFIG_MEM_SOFT_DIRTY
0126     if (pte_present(pte))
0127         pte = pte_mksoft_dirty(pte);
0128     else if (is_swap_pte(pte))
0129         pte = pte_swp_mksoft_dirty(pte);
0130 #endif
0131     return pte;
0132 }
0133 
0134 static void move_ptes(struct vm_area_struct *vma, pmd_t *old_pmd,
0135         unsigned long old_addr, unsigned long old_end,
0136         struct vm_area_struct *new_vma, pmd_t *new_pmd,
0137         unsigned long new_addr, bool need_rmap_locks)
0138 {
0139     struct mm_struct *mm = vma->vm_mm;
0140     pte_t *old_pte, *new_pte, pte;
0141     spinlock_t *old_ptl, *new_ptl;
0142     bool force_flush = false;
0143     unsigned long len = old_end - old_addr;
0144 
0145     /*
0146      * When need_rmap_locks is true, we take the i_mmap_rwsem and anon_vma
0147      * locks to ensure that rmap will always observe either the old or the
0148      * new ptes. This is the easiest way to avoid races with
0149      * truncate_pagecache(), page migration, etc...
0150      *
0151      * When need_rmap_locks is false, we use other ways to avoid
0152      * such races:
0153      *
0154      * - During exec() shift_arg_pages(), we use a specially tagged vma
0155      *   which rmap call sites look for using vma_is_temporary_stack().
0156      *
0157      * - During mremap(), new_vma is often known to be placed after vma
0158      *   in rmap traversal order. This ensures rmap will always observe
0159      *   either the old pte, or the new pte, or both (the page table locks
0160      *   serialize access to individual ptes, but only rmap traversal
0161      *   order guarantees that we won't miss both the old and new ptes).
0162      */
0163     if (need_rmap_locks)
0164         take_rmap_locks(vma);
0165 
0166     /*
0167      * We don't have to worry about the ordering of src and dst
0168      * pte locks because exclusive mmap_lock prevents deadlock.
0169      */
0170     old_pte = pte_offset_map_lock(mm, old_pmd, old_addr, &old_ptl);
0171     new_pte = pte_offset_map(new_pmd, new_addr);
0172     new_ptl = pte_lockptr(mm, new_pmd);
0173     if (new_ptl != old_ptl)
0174         spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
0175     flush_tlb_batched_pending(vma->vm_mm);
0176     arch_enter_lazy_mmu_mode();
0177 
0178     for (; old_addr < old_end; old_pte++, old_addr += PAGE_SIZE,
0179                    new_pte++, new_addr += PAGE_SIZE) {
0180         if (pte_none(*old_pte))
0181             continue;
0182 
0183         pte = ptep_get_and_clear(mm, old_addr, old_pte);
0184         /*
0185          * If we are remapping a valid PTE, make sure
0186          * to flush TLB before we drop the PTL for the
0187          * PTE.
0188          *
0189          * NOTE! Both old and new PTL matter: the old one
0190          * for racing with page_mkclean(), the new one to
0191          * make sure the physical page stays valid until
0192          * the TLB entry for the old mapping has been
0193          * flushed.
0194          */
0195         if (pte_present(pte))
0196             force_flush = true;
0197         pte = move_pte(pte, new_vma->vm_page_prot, old_addr, new_addr);
0198         pte = move_soft_dirty_pte(pte);
0199         set_pte_at(mm, new_addr, new_pte, pte);
0200     }
0201 
0202     arch_leave_lazy_mmu_mode();
0203     if (force_flush)
0204         flush_tlb_range(vma, old_end - len, old_end);
0205     if (new_ptl != old_ptl)
0206         spin_unlock(new_ptl);
0207     pte_unmap(new_pte - 1);
0208     pte_unmap_unlock(old_pte - 1, old_ptl);
0209     if (need_rmap_locks)
0210         drop_rmap_locks(vma);
0211 }
0212 
0213 #ifndef arch_supports_page_table_move
0214 #define arch_supports_page_table_move arch_supports_page_table_move
0215 static inline bool arch_supports_page_table_move(void)
0216 {
0217     return IS_ENABLED(CONFIG_HAVE_MOVE_PMD) ||
0218         IS_ENABLED(CONFIG_HAVE_MOVE_PUD);
0219 }
0220 #endif
0221 
0222 #ifdef CONFIG_HAVE_MOVE_PMD
0223 static bool move_normal_pmd(struct vm_area_struct *vma, unsigned long old_addr,
0224           unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
0225 {
0226     spinlock_t *old_ptl, *new_ptl;
0227     struct mm_struct *mm = vma->vm_mm;
0228     pmd_t pmd;
0229 
0230     if (!arch_supports_page_table_move())
0231         return false;
0232     /*
0233      * The destination pmd shouldn't be established, free_pgtables()
0234      * should have released it.
0235      *
0236      * However, there's a case during execve() where we use mremap
0237      * to move the initial stack, and in that case the target area
0238      * may overlap the source area (always moving down).
0239      *
0240      * If everything is PMD-aligned, that works fine, as moving
0241      * each pmd down will clear the source pmd. But if we first
0242      * have a few 4kB-only pages that get moved down, and then
0243      * hit the "now the rest is PMD-aligned, let's do everything
0244      * one pmd at a time", we will still have the old (now empty
0245      * of any 4kB pages, but still there) PMD in the page table
0246      * tree.
0247      *
0248      * Warn on it once - because we really should try to figure
0249      * out how to do this better - but then say "I won't move
0250      * this pmd".
0251      *
0252      * One alternative might be to just unmap the target pmd at
0253      * this point, and verify that it really is empty. We'll see.
0254      */
0255     if (WARN_ON_ONCE(!pmd_none(*new_pmd)))
0256         return false;
0257 
0258     /*
0259      * We don't have to worry about the ordering of src and dst
0260      * ptlocks because exclusive mmap_lock prevents deadlock.
0261      */
0262     old_ptl = pmd_lock(vma->vm_mm, old_pmd);
0263     new_ptl = pmd_lockptr(mm, new_pmd);
0264     if (new_ptl != old_ptl)
0265         spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
0266 
0267     /* Clear the pmd */
0268     pmd = *old_pmd;
0269     pmd_clear(old_pmd);
0270 
0271     VM_BUG_ON(!pmd_none(*new_pmd));
0272 
0273     pmd_populate(mm, new_pmd, pmd_pgtable(pmd));
0274     flush_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
0275     if (new_ptl != old_ptl)
0276         spin_unlock(new_ptl);
0277     spin_unlock(old_ptl);
0278 
0279     return true;
0280 }
0281 #else
0282 static inline bool move_normal_pmd(struct vm_area_struct *vma,
0283         unsigned long old_addr, unsigned long new_addr, pmd_t *old_pmd,
0284         pmd_t *new_pmd)
0285 {
0286     return false;
0287 }
0288 #endif
0289 
0290 #if CONFIG_PGTABLE_LEVELS > 2 && defined(CONFIG_HAVE_MOVE_PUD)
0291 static bool move_normal_pud(struct vm_area_struct *vma, unsigned long old_addr,
0292           unsigned long new_addr, pud_t *old_pud, pud_t *new_pud)
0293 {
0294     spinlock_t *old_ptl, *new_ptl;
0295     struct mm_struct *mm = vma->vm_mm;
0296     pud_t pud;
0297 
0298     if (!arch_supports_page_table_move())
0299         return false;
0300     /*
0301      * The destination pud shouldn't be established, free_pgtables()
0302      * should have released it.
0303      */
0304     if (WARN_ON_ONCE(!pud_none(*new_pud)))
0305         return false;
0306 
0307     /*
0308      * We don't have to worry about the ordering of src and dst
0309      * ptlocks because exclusive mmap_lock prevents deadlock.
0310      */
0311     old_ptl = pud_lock(vma->vm_mm, old_pud);
0312     new_ptl = pud_lockptr(mm, new_pud);
0313     if (new_ptl != old_ptl)
0314         spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
0315 
0316     /* Clear the pud */
0317     pud = *old_pud;
0318     pud_clear(old_pud);
0319 
0320     VM_BUG_ON(!pud_none(*new_pud));
0321 
0322     pud_populate(mm, new_pud, pud_pgtable(pud));
0323     flush_tlb_range(vma, old_addr, old_addr + PUD_SIZE);
0324     if (new_ptl != old_ptl)
0325         spin_unlock(new_ptl);
0326     spin_unlock(old_ptl);
0327 
0328     return true;
0329 }
0330 #else
0331 static inline bool move_normal_pud(struct vm_area_struct *vma,
0332         unsigned long old_addr, unsigned long new_addr, pud_t *old_pud,
0333         pud_t *new_pud)
0334 {
0335     return false;
0336 }
0337 #endif
0338 
0339 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
0340 static bool move_huge_pud(struct vm_area_struct *vma, unsigned long old_addr,
0341               unsigned long new_addr, pud_t *old_pud, pud_t *new_pud)
0342 {
0343     spinlock_t *old_ptl, *new_ptl;
0344     struct mm_struct *mm = vma->vm_mm;
0345     pud_t pud;
0346 
0347     /*
0348      * The destination pud shouldn't be established, free_pgtables()
0349      * should have released it.
0350      */
0351     if (WARN_ON_ONCE(!pud_none(*new_pud)))
0352         return false;
0353 
0354     /*
0355      * We don't have to worry about the ordering of src and dst
0356      * ptlocks because exclusive mmap_lock prevents deadlock.
0357      */
0358     old_ptl = pud_lock(vma->vm_mm, old_pud);
0359     new_ptl = pud_lockptr(mm, new_pud);
0360     if (new_ptl != old_ptl)
0361         spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
0362 
0363     /* Clear the pud */
0364     pud = *old_pud;
0365     pud_clear(old_pud);
0366 
0367     VM_BUG_ON(!pud_none(*new_pud));
0368 
0369     /* Set the new pud */
0370     /* mark soft_ditry when we add pud level soft dirty support */
0371     set_pud_at(mm, new_addr, new_pud, pud);
0372     flush_pud_tlb_range(vma, old_addr, old_addr + HPAGE_PUD_SIZE);
0373     if (new_ptl != old_ptl)
0374         spin_unlock(new_ptl);
0375     spin_unlock(old_ptl);
0376 
0377     return true;
0378 }
0379 #else
0380 static bool move_huge_pud(struct vm_area_struct *vma, unsigned long old_addr,
0381               unsigned long new_addr, pud_t *old_pud, pud_t *new_pud)
0382 {
0383     WARN_ON_ONCE(1);
0384     return false;
0385 
0386 }
0387 #endif
0388 
0389 enum pgt_entry {
0390     NORMAL_PMD,
0391     HPAGE_PMD,
0392     NORMAL_PUD,
0393     HPAGE_PUD,
0394 };
0395 
0396 /*
0397  * Returns an extent of the corresponding size for the pgt_entry specified if
0398  * valid. Else returns a smaller extent bounded by the end of the source and
0399  * destination pgt_entry.
0400  */
0401 static __always_inline unsigned long get_extent(enum pgt_entry entry,
0402             unsigned long old_addr, unsigned long old_end,
0403             unsigned long new_addr)
0404 {
0405     unsigned long next, extent, mask, size;
0406 
0407     switch (entry) {
0408     case HPAGE_PMD:
0409     case NORMAL_PMD:
0410         mask = PMD_MASK;
0411         size = PMD_SIZE;
0412         break;
0413     case HPAGE_PUD:
0414     case NORMAL_PUD:
0415         mask = PUD_MASK;
0416         size = PUD_SIZE;
0417         break;
0418     default:
0419         BUILD_BUG();
0420         break;
0421     }
0422 
0423     next = (old_addr + size) & mask;
0424     /* even if next overflowed, extent below will be ok */
0425     extent = next - old_addr;
0426     if (extent > old_end - old_addr)
0427         extent = old_end - old_addr;
0428     next = (new_addr + size) & mask;
0429     if (extent > next - new_addr)
0430         extent = next - new_addr;
0431     return extent;
0432 }
0433 
0434 /*
0435  * Attempts to speedup the move by moving entry at the level corresponding to
0436  * pgt_entry. Returns true if the move was successful, else false.
0437  */
0438 static bool move_pgt_entry(enum pgt_entry entry, struct vm_area_struct *vma,
0439             unsigned long old_addr, unsigned long new_addr,
0440             void *old_entry, void *new_entry, bool need_rmap_locks)
0441 {
0442     bool moved = false;
0443 
0444     /* See comment in move_ptes() */
0445     if (need_rmap_locks)
0446         take_rmap_locks(vma);
0447 
0448     switch (entry) {
0449     case NORMAL_PMD:
0450         moved = move_normal_pmd(vma, old_addr, new_addr, old_entry,
0451                     new_entry);
0452         break;
0453     case NORMAL_PUD:
0454         moved = move_normal_pud(vma, old_addr, new_addr, old_entry,
0455                     new_entry);
0456         break;
0457     case HPAGE_PMD:
0458         moved = IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
0459             move_huge_pmd(vma, old_addr, new_addr, old_entry,
0460                       new_entry);
0461         break;
0462     case HPAGE_PUD:
0463         moved = IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
0464             move_huge_pud(vma, old_addr, new_addr, old_entry,
0465                       new_entry);
0466         break;
0467 
0468     default:
0469         WARN_ON_ONCE(1);
0470         break;
0471     }
0472 
0473     if (need_rmap_locks)
0474         drop_rmap_locks(vma);
0475 
0476     return moved;
0477 }
0478 
0479 unsigned long move_page_tables(struct vm_area_struct *vma,
0480         unsigned long old_addr, struct vm_area_struct *new_vma,
0481         unsigned long new_addr, unsigned long len,
0482         bool need_rmap_locks)
0483 {
0484     unsigned long extent, old_end;
0485     struct mmu_notifier_range range;
0486     pmd_t *old_pmd, *new_pmd;
0487     pud_t *old_pud, *new_pud;
0488 
0489     if (!len)
0490         return 0;
0491 
0492     old_end = old_addr + len;
0493 
0494     if (is_vm_hugetlb_page(vma))
0495         return move_hugetlb_page_tables(vma, new_vma, old_addr,
0496                         new_addr, len);
0497 
0498     flush_cache_range(vma, old_addr, old_end);
0499     mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
0500                 old_addr, old_end);
0501     mmu_notifier_invalidate_range_start(&range);
0502 
0503     for (; old_addr < old_end; old_addr += extent, new_addr += extent) {
0504         cond_resched();
0505         /*
0506          * If extent is PUD-sized try to speed up the move by moving at the
0507          * PUD level if possible.
0508          */
0509         extent = get_extent(NORMAL_PUD, old_addr, old_end, new_addr);
0510 
0511         old_pud = get_old_pud(vma->vm_mm, old_addr);
0512         if (!old_pud)
0513             continue;
0514         new_pud = alloc_new_pud(vma->vm_mm, vma, new_addr);
0515         if (!new_pud)
0516             break;
0517         if (pud_trans_huge(*old_pud) || pud_devmap(*old_pud)) {
0518             if (extent == HPAGE_PUD_SIZE) {
0519                 move_pgt_entry(HPAGE_PUD, vma, old_addr, new_addr,
0520                            old_pud, new_pud, need_rmap_locks);
0521                 /* We ignore and continue on error? */
0522                 continue;
0523             }
0524         } else if (IS_ENABLED(CONFIG_HAVE_MOVE_PUD) && extent == PUD_SIZE) {
0525 
0526             if (move_pgt_entry(NORMAL_PUD, vma, old_addr, new_addr,
0527                        old_pud, new_pud, true))
0528                 continue;
0529         }
0530 
0531         extent = get_extent(NORMAL_PMD, old_addr, old_end, new_addr);
0532         old_pmd = get_old_pmd(vma->vm_mm, old_addr);
0533         if (!old_pmd)
0534             continue;
0535         new_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr);
0536         if (!new_pmd)
0537             break;
0538         if (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd) ||
0539             pmd_devmap(*old_pmd)) {
0540             if (extent == HPAGE_PMD_SIZE &&
0541                 move_pgt_entry(HPAGE_PMD, vma, old_addr, new_addr,
0542                        old_pmd, new_pmd, need_rmap_locks))
0543                 continue;
0544             split_huge_pmd(vma, old_pmd, old_addr);
0545             if (pmd_trans_unstable(old_pmd))
0546                 continue;
0547         } else if (IS_ENABLED(CONFIG_HAVE_MOVE_PMD) &&
0548                extent == PMD_SIZE) {
0549             /*
0550              * If the extent is PMD-sized, try to speed the move by
0551              * moving at the PMD level if possible.
0552              */
0553             if (move_pgt_entry(NORMAL_PMD, vma, old_addr, new_addr,
0554                        old_pmd, new_pmd, true))
0555                 continue;
0556         }
0557 
0558         if (pte_alloc(new_vma->vm_mm, new_pmd))
0559             break;
0560         move_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma,
0561               new_pmd, new_addr, need_rmap_locks);
0562     }
0563 
0564     mmu_notifier_invalidate_range_end(&range);
0565 
0566     return len + old_addr - old_end;    /* how much done */
0567 }
0568 
0569 static unsigned long move_vma(struct vm_area_struct *vma,
0570         unsigned long old_addr, unsigned long old_len,
0571         unsigned long new_len, unsigned long new_addr,
0572         bool *locked, unsigned long flags,
0573         struct vm_userfaultfd_ctx *uf, struct list_head *uf_unmap)
0574 {
0575     long to_account = new_len - old_len;
0576     struct mm_struct *mm = vma->vm_mm;
0577     struct vm_area_struct *new_vma;
0578     unsigned long vm_flags = vma->vm_flags;
0579     unsigned long new_pgoff;
0580     unsigned long moved_len;
0581     unsigned long excess = 0;
0582     unsigned long hiwater_vm;
0583     int split = 0;
0584     int err = 0;
0585     bool need_rmap_locks;
0586 
0587     /*
0588      * We'd prefer to avoid failure later on in do_munmap:
0589      * which may split one vma into three before unmapping.
0590      */
0591     if (mm->map_count >= sysctl_max_map_count - 3)
0592         return -ENOMEM;
0593 
0594     if (unlikely(flags & MREMAP_DONTUNMAP))
0595         to_account = new_len;
0596 
0597     if (vma->vm_ops && vma->vm_ops->may_split) {
0598         if (vma->vm_start != old_addr)
0599             err = vma->vm_ops->may_split(vma, old_addr);
0600         if (!err && vma->vm_end != old_addr + old_len)
0601             err = vma->vm_ops->may_split(vma, old_addr + old_len);
0602         if (err)
0603             return err;
0604     }
0605 
0606     /*
0607      * Advise KSM to break any KSM pages in the area to be moved:
0608      * it would be confusing if they were to turn up at the new
0609      * location, where they happen to coincide with different KSM
0610      * pages recently unmapped.  But leave vma->vm_flags as it was,
0611      * so KSM can come around to merge on vma and new_vma afterwards.
0612      */
0613     err = ksm_madvise(vma, old_addr, old_addr + old_len,
0614                         MADV_UNMERGEABLE, &vm_flags);
0615     if (err)
0616         return err;
0617 
0618     if (vm_flags & VM_ACCOUNT) {
0619         if (security_vm_enough_memory_mm(mm, to_account >> PAGE_SHIFT))
0620             return -ENOMEM;
0621     }
0622 
0623     new_pgoff = vma->vm_pgoff + ((old_addr - vma->vm_start) >> PAGE_SHIFT);
0624     new_vma = copy_vma(&vma, new_addr, new_len, new_pgoff,
0625                &need_rmap_locks);
0626     if (!new_vma) {
0627         if (vm_flags & VM_ACCOUNT)
0628             vm_unacct_memory(to_account >> PAGE_SHIFT);
0629         return -ENOMEM;
0630     }
0631 
0632     moved_len = move_page_tables(vma, old_addr, new_vma, new_addr, old_len,
0633                      need_rmap_locks);
0634     if (moved_len < old_len) {
0635         err = -ENOMEM;
0636     } else if (vma->vm_ops && vma->vm_ops->mremap) {
0637         err = vma->vm_ops->mremap(new_vma);
0638     }
0639 
0640     if (unlikely(err)) {
0641         /*
0642          * On error, move entries back from new area to old,
0643          * which will succeed since page tables still there,
0644          * and then proceed to unmap new area instead of old.
0645          */
0646         move_page_tables(new_vma, new_addr, vma, old_addr, moved_len,
0647                  true);
0648         vma = new_vma;
0649         old_len = new_len;
0650         old_addr = new_addr;
0651         new_addr = err;
0652     } else {
0653         mremap_userfaultfd_prep(new_vma, uf);
0654     }
0655 
0656     if (is_vm_hugetlb_page(vma)) {
0657         clear_vma_resv_huge_pages(vma);
0658     }
0659 
0660     /* Conceal VM_ACCOUNT so old reservation is not undone */
0661     if (vm_flags & VM_ACCOUNT && !(flags & MREMAP_DONTUNMAP)) {
0662         vma->vm_flags &= ~VM_ACCOUNT;
0663         excess = vma->vm_end - vma->vm_start - old_len;
0664         if (old_addr > vma->vm_start &&
0665             old_addr + old_len < vma->vm_end)
0666             split = 1;
0667     }
0668 
0669     /*
0670      * If we failed to move page tables we still do total_vm increment
0671      * since do_munmap() will decrement it by old_len == new_len.
0672      *
0673      * Since total_vm is about to be raised artificially high for a
0674      * moment, we need to restore high watermark afterwards: if stats
0675      * are taken meanwhile, total_vm and hiwater_vm appear too high.
0676      * If this were a serious issue, we'd add a flag to do_munmap().
0677      */
0678     hiwater_vm = mm->hiwater_vm;
0679     vm_stat_account(mm, vma->vm_flags, new_len >> PAGE_SHIFT);
0680 
0681     /* Tell pfnmap has moved from this vma */
0682     if (unlikely(vma->vm_flags & VM_PFNMAP))
0683         untrack_pfn_moved(vma);
0684 
0685     if (unlikely(!err && (flags & MREMAP_DONTUNMAP))) {
0686         /* We always clear VM_LOCKED[ONFAULT] on the old vma */
0687         vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
0688 
0689         /*
0690          * anon_vma links of the old vma is no longer needed after its page
0691          * table has been moved.
0692          */
0693         if (new_vma != vma && vma->vm_start == old_addr &&
0694             vma->vm_end == (old_addr + old_len))
0695             unlink_anon_vmas(vma);
0696 
0697         /* Because we won't unmap we don't need to touch locked_vm */
0698         return new_addr;
0699     }
0700 
0701     if (do_munmap(mm, old_addr, old_len, uf_unmap) < 0) {
0702         /* OOM: unable to split vma, just get accounts right */
0703         if (vm_flags & VM_ACCOUNT && !(flags & MREMAP_DONTUNMAP))
0704             vm_acct_memory(old_len >> PAGE_SHIFT);
0705         excess = 0;
0706     }
0707 
0708     if (vm_flags & VM_LOCKED) {
0709         mm->locked_vm += new_len >> PAGE_SHIFT;
0710         *locked = true;
0711     }
0712 
0713     mm->hiwater_vm = hiwater_vm;
0714 
0715     /* Restore VM_ACCOUNT if one or two pieces of vma left */
0716     if (excess) {
0717         vma->vm_flags |= VM_ACCOUNT;
0718         if (split)
0719             vma->vm_next->vm_flags |= VM_ACCOUNT;
0720     }
0721 
0722     return new_addr;
0723 }
0724 
0725 static struct vm_area_struct *vma_to_resize(unsigned long addr,
0726     unsigned long old_len, unsigned long new_len, unsigned long flags)
0727 {
0728     struct mm_struct *mm = current->mm;
0729     struct vm_area_struct *vma;
0730     unsigned long pgoff;
0731 
0732     vma = vma_lookup(mm, addr);
0733     if (!vma)
0734         return ERR_PTR(-EFAULT);
0735 
0736     /*
0737      * !old_len is a special case where an attempt is made to 'duplicate'
0738      * a mapping.  This makes no sense for private mappings as it will
0739      * instead create a fresh/new mapping unrelated to the original.  This
0740      * is contrary to the basic idea of mremap which creates new mappings
0741      * based on the original.  There are no known use cases for this
0742      * behavior.  As a result, fail such attempts.
0743      */
0744     if (!old_len && !(vma->vm_flags & (VM_SHARED | VM_MAYSHARE))) {
0745         pr_warn_once("%s (%d): attempted to duplicate a private mapping with mremap.  This is not supported.\n", current->comm, current->pid);
0746         return ERR_PTR(-EINVAL);
0747     }
0748 
0749     if ((flags & MREMAP_DONTUNMAP) &&
0750             (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP)))
0751         return ERR_PTR(-EINVAL);
0752 
0753     /* We can't remap across vm area boundaries */
0754     if (old_len > vma->vm_end - addr)
0755         return ERR_PTR(-EFAULT);
0756 
0757     if (new_len == old_len)
0758         return vma;
0759 
0760     /* Need to be careful about a growing mapping */
0761     pgoff = (addr - vma->vm_start) >> PAGE_SHIFT;
0762     pgoff += vma->vm_pgoff;
0763     if (pgoff + (new_len >> PAGE_SHIFT) < pgoff)
0764         return ERR_PTR(-EINVAL);
0765 
0766     if (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP))
0767         return ERR_PTR(-EFAULT);
0768 
0769     if (mlock_future_check(mm, vma->vm_flags, new_len - old_len))
0770         return ERR_PTR(-EAGAIN);
0771 
0772     if (!may_expand_vm(mm, vma->vm_flags,
0773                 (new_len - old_len) >> PAGE_SHIFT))
0774         return ERR_PTR(-ENOMEM);
0775 
0776     return vma;
0777 }
0778 
0779 static unsigned long mremap_to(unsigned long addr, unsigned long old_len,
0780         unsigned long new_addr, unsigned long new_len, bool *locked,
0781         unsigned long flags, struct vm_userfaultfd_ctx *uf,
0782         struct list_head *uf_unmap_early,
0783         struct list_head *uf_unmap)
0784 {
0785     struct mm_struct *mm = current->mm;
0786     struct vm_area_struct *vma;
0787     unsigned long ret = -EINVAL;
0788     unsigned long map_flags = 0;
0789 
0790     if (offset_in_page(new_addr))
0791         goto out;
0792 
0793     if (new_len > TASK_SIZE || new_addr > TASK_SIZE - new_len)
0794         goto out;
0795 
0796     /* Ensure the old/new locations do not overlap */
0797     if (addr + old_len > new_addr && new_addr + new_len > addr)
0798         goto out;
0799 
0800     /*
0801      * move_vma() need us to stay 4 maps below the threshold, otherwise
0802      * it will bail out at the very beginning.
0803      * That is a problem if we have already unmaped the regions here
0804      * (new_addr, and old_addr), because userspace will not know the
0805      * state of the vma's after it gets -ENOMEM.
0806      * So, to avoid such scenario we can pre-compute if the whole
0807      * operation has high chances to success map-wise.
0808      * Worst-scenario case is when both vma's (new_addr and old_addr) get
0809      * split in 3 before unmapping it.
0810      * That means 2 more maps (1 for each) to the ones we already hold.
0811      * Check whether current map count plus 2 still leads us to 4 maps below
0812      * the threshold, otherwise return -ENOMEM here to be more safe.
0813      */
0814     if ((mm->map_count + 2) >= sysctl_max_map_count - 3)
0815         return -ENOMEM;
0816 
0817     if (flags & MREMAP_FIXED) {
0818         ret = do_munmap(mm, new_addr, new_len, uf_unmap_early);
0819         if (ret)
0820             goto out;
0821     }
0822 
0823     if (old_len > new_len) {
0824         ret = do_munmap(mm, addr+new_len, old_len - new_len, uf_unmap);
0825         if (ret)
0826             goto out;
0827         old_len = new_len;
0828     }
0829 
0830     vma = vma_to_resize(addr, old_len, new_len, flags);
0831     if (IS_ERR(vma)) {
0832         ret = PTR_ERR(vma);
0833         goto out;
0834     }
0835 
0836     /* MREMAP_DONTUNMAP expands by old_len since old_len == new_len */
0837     if (flags & MREMAP_DONTUNMAP &&
0838         !may_expand_vm(mm, vma->vm_flags, old_len >> PAGE_SHIFT)) {
0839         ret = -ENOMEM;
0840         goto out;
0841     }
0842 
0843     if (flags & MREMAP_FIXED)
0844         map_flags |= MAP_FIXED;
0845 
0846     if (vma->vm_flags & VM_MAYSHARE)
0847         map_flags |= MAP_SHARED;
0848 
0849     ret = get_unmapped_area(vma->vm_file, new_addr, new_len, vma->vm_pgoff +
0850                 ((addr - vma->vm_start) >> PAGE_SHIFT),
0851                 map_flags);
0852     if (IS_ERR_VALUE(ret))
0853         goto out;
0854 
0855     /* We got a new mapping */
0856     if (!(flags & MREMAP_FIXED))
0857         new_addr = ret;
0858 
0859     ret = move_vma(vma, addr, old_len, new_len, new_addr, locked, flags, uf,
0860                uf_unmap);
0861 
0862 out:
0863     return ret;
0864 }
0865 
0866 static int vma_expandable(struct vm_area_struct *vma, unsigned long delta)
0867 {
0868     unsigned long end = vma->vm_end + delta;
0869     if (end < vma->vm_end) /* overflow */
0870         return 0;
0871     if (vma->vm_next && vma->vm_next->vm_start < end) /* intersection */
0872         return 0;
0873     if (get_unmapped_area(NULL, vma->vm_start, end - vma->vm_start,
0874                   0, MAP_FIXED) & ~PAGE_MASK)
0875         return 0;
0876     return 1;
0877 }
0878 
0879 /*
0880  * Expand (or shrink) an existing mapping, potentially moving it at the
0881  * same time (controlled by the MREMAP_MAYMOVE flag and available VM space)
0882  *
0883  * MREMAP_FIXED option added 5-Dec-1999 by Benjamin LaHaise
0884  * This option implies MREMAP_MAYMOVE.
0885  */
0886 SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,
0887         unsigned long, new_len, unsigned long, flags,
0888         unsigned long, new_addr)
0889 {
0890     struct mm_struct *mm = current->mm;
0891     struct vm_area_struct *vma;
0892     unsigned long ret = -EINVAL;
0893     bool locked = false;
0894     bool downgraded = false;
0895     struct vm_userfaultfd_ctx uf = NULL_VM_UFFD_CTX;
0896     LIST_HEAD(uf_unmap_early);
0897     LIST_HEAD(uf_unmap);
0898 
0899     /*
0900      * There is a deliberate asymmetry here: we strip the pointer tag
0901      * from the old address but leave the new address alone. This is
0902      * for consistency with mmap(), where we prevent the creation of
0903      * aliasing mappings in userspace by leaving the tag bits of the
0904      * mapping address intact. A non-zero tag will cause the subsequent
0905      * range checks to reject the address as invalid.
0906      *
0907      * See Documentation/arm64/tagged-address-abi.rst for more information.
0908      */
0909     addr = untagged_addr(addr);
0910 
0911     if (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE | MREMAP_DONTUNMAP))
0912         return ret;
0913 
0914     if (flags & MREMAP_FIXED && !(flags & MREMAP_MAYMOVE))
0915         return ret;
0916 
0917     /*
0918      * MREMAP_DONTUNMAP is always a move and it does not allow resizing
0919      * in the process.
0920      */
0921     if (flags & MREMAP_DONTUNMAP &&
0922             (!(flags & MREMAP_MAYMOVE) || old_len != new_len))
0923         return ret;
0924 
0925 
0926     if (offset_in_page(addr))
0927         return ret;
0928 
0929     old_len = PAGE_ALIGN(old_len);
0930     new_len = PAGE_ALIGN(new_len);
0931 
0932     /*
0933      * We allow a zero old-len as a special case
0934      * for DOS-emu "duplicate shm area" thing. But
0935      * a zero new-len is nonsensical.
0936      */
0937     if (!new_len)
0938         return ret;
0939 
0940     if (mmap_write_lock_killable(current->mm))
0941         return -EINTR;
0942     vma = vma_lookup(mm, addr);
0943     if (!vma) {
0944         ret = -EFAULT;
0945         goto out;
0946     }
0947 
0948     if (is_vm_hugetlb_page(vma)) {
0949         struct hstate *h __maybe_unused = hstate_vma(vma);
0950 
0951         old_len = ALIGN(old_len, huge_page_size(h));
0952         new_len = ALIGN(new_len, huge_page_size(h));
0953 
0954         /* addrs must be huge page aligned */
0955         if (addr & ~huge_page_mask(h))
0956             goto out;
0957         if (new_addr & ~huge_page_mask(h))
0958             goto out;
0959 
0960         /*
0961          * Don't allow remap expansion, because the underlying hugetlb
0962          * reservation is not yet capable to handle split reservation.
0963          */
0964         if (new_len > old_len)
0965             goto out;
0966     }
0967 
0968     if (flags & (MREMAP_FIXED | MREMAP_DONTUNMAP)) {
0969         ret = mremap_to(addr, old_len, new_addr, new_len,
0970                 &locked, flags, &uf, &uf_unmap_early,
0971                 &uf_unmap);
0972         goto out;
0973     }
0974 
0975     /*
0976      * Always allow a shrinking remap: that just unmaps
0977      * the unnecessary pages..
0978      * __do_munmap does all the needed commit accounting, and
0979      * downgrades mmap_lock to read if so directed.
0980      */
0981     if (old_len >= new_len) {
0982         int retval;
0983 
0984         retval = __do_munmap(mm, addr+new_len, old_len - new_len,
0985                   &uf_unmap, true);
0986         if (retval < 0 && old_len != new_len) {
0987             ret = retval;
0988             goto out;
0989         /* Returning 1 indicates mmap_lock is downgraded to read. */
0990         } else if (retval == 1)
0991             downgraded = true;
0992         ret = addr;
0993         goto out;
0994     }
0995 
0996     /*
0997      * Ok, we need to grow..
0998      */
0999     vma = vma_to_resize(addr, old_len, new_len, flags);
1000     if (IS_ERR(vma)) {
1001         ret = PTR_ERR(vma);
1002         goto out;
1003     }
1004 
1005     /* old_len exactly to the end of the area..
1006      */
1007     if (old_len == vma->vm_end - addr) {
1008         /* can we just expand the current mapping? */
1009         if (vma_expandable(vma, new_len - old_len)) {
1010             long pages = (new_len - old_len) >> PAGE_SHIFT;
1011 
1012             if (vma->vm_flags & VM_ACCOUNT) {
1013                 if (security_vm_enough_memory_mm(mm, pages)) {
1014                     ret = -ENOMEM;
1015                     goto out;
1016                 }
1017             }
1018 
1019             if (vma_adjust(vma, vma->vm_start, addr + new_len,
1020                        vma->vm_pgoff, NULL)) {
1021                 vm_unacct_memory(pages);
1022                 ret = -ENOMEM;
1023                 goto out;
1024             }
1025 
1026             vm_stat_account(mm, vma->vm_flags, pages);
1027             if (vma->vm_flags & VM_LOCKED) {
1028                 mm->locked_vm += pages;
1029                 locked = true;
1030                 new_addr = addr;
1031             }
1032             ret = addr;
1033             goto out;
1034         }
1035     }
1036 
1037     /*
1038      * We weren't able to just expand or shrink the area,
1039      * we need to create a new one and move it..
1040      */
1041     ret = -ENOMEM;
1042     if (flags & MREMAP_MAYMOVE) {
1043         unsigned long map_flags = 0;
1044         if (vma->vm_flags & VM_MAYSHARE)
1045             map_flags |= MAP_SHARED;
1046 
1047         new_addr = get_unmapped_area(vma->vm_file, 0, new_len,
1048                     vma->vm_pgoff +
1049                     ((addr - vma->vm_start) >> PAGE_SHIFT),
1050                     map_flags);
1051         if (IS_ERR_VALUE(new_addr)) {
1052             ret = new_addr;
1053             goto out;
1054         }
1055 
1056         ret = move_vma(vma, addr, old_len, new_len, new_addr,
1057                    &locked, flags, &uf, &uf_unmap);
1058     }
1059 out:
1060     if (offset_in_page(ret))
1061         locked = false;
1062     if (downgraded)
1063         mmap_read_unlock(current->mm);
1064     else
1065         mmap_write_unlock(current->mm);
1066     if (locked && new_len > old_len)
1067         mm_populate(new_addr + old_len, new_len - old_len);
1068     userfaultfd_unmap_complete(mm, &uf_unmap_early);
1069     mremap_userfaultfd_complete(&uf, addr, ret, old_len);
1070     userfaultfd_unmap_complete(mm, &uf_unmap);
1071     return ret;
1072 }