Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  *  mm/mprotect.c
0004  *
0005  *  (C) Copyright 1994 Linus Torvalds
0006  *  (C) Copyright 2002 Christoph Hellwig
0007  *
0008  *  Address space accounting code   <alan@lxorguk.ukuu.org.uk>
0009  *  (C) Copyright 2002 Red Hat Inc, All Rights Reserved
0010  */
0011 
0012 #include <linux/pagewalk.h>
0013 #include <linux/hugetlb.h>
0014 #include <linux/shm.h>
0015 #include <linux/mman.h>
0016 #include <linux/fs.h>
0017 #include <linux/highmem.h>
0018 #include <linux/security.h>
0019 #include <linux/mempolicy.h>
0020 #include <linux/personality.h>
0021 #include <linux/syscalls.h>
0022 #include <linux/swap.h>
0023 #include <linux/swapops.h>
0024 #include <linux/mmu_notifier.h>
0025 #include <linux/migrate.h>
0026 #include <linux/perf_event.h>
0027 #include <linux/pkeys.h>
0028 #include <linux/ksm.h>
0029 #include <linux/uaccess.h>
0030 #include <linux/mm_inline.h>
0031 #include <linux/pgtable.h>
0032 #include <linux/sched/sysctl.h>
0033 #include <linux/userfaultfd_k.h>
0034 #include <asm/cacheflush.h>
0035 #include <asm/mmu_context.h>
0036 #include <asm/tlbflush.h>
0037 #include <asm/tlb.h>
0038 
0039 #include "internal.h"
0040 
0041 static inline bool can_change_pte_writable(struct vm_area_struct *vma,
0042                        unsigned long addr, pte_t pte)
0043 {
0044     struct page *page;
0045 
0046     VM_BUG_ON(!(vma->vm_flags & VM_WRITE) || pte_write(pte));
0047 
0048     if (pte_protnone(pte) || !pte_dirty(pte))
0049         return false;
0050 
0051     /* Do we need write faults for softdirty tracking? */
0052     if (vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte))
0053         return false;
0054 
0055     /* Do we need write faults for uffd-wp tracking? */
0056     if (userfaultfd_pte_wp(vma, pte))
0057         return false;
0058 
0059     if (!(vma->vm_flags & VM_SHARED)) {
0060         /*
0061          * We can only special-case on exclusive anonymous pages,
0062          * because we know that our write-fault handler similarly would
0063          * map them writable without any additional checks while holding
0064          * the PT lock.
0065          */
0066         page = vm_normal_page(vma, addr, pte);
0067         if (!page || !PageAnon(page) || !PageAnonExclusive(page))
0068             return false;
0069     }
0070 
0071     return true;
0072 }
0073 
0074 static unsigned long change_pte_range(struct mmu_gather *tlb,
0075         struct vm_area_struct *vma, pmd_t *pmd, unsigned long addr,
0076         unsigned long end, pgprot_t newprot, unsigned long cp_flags)
0077 {
0078     pte_t *pte, oldpte;
0079     spinlock_t *ptl;
0080     unsigned long pages = 0;
0081     int target_node = NUMA_NO_NODE;
0082     bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
0083     bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
0084     bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
0085 
0086     tlb_change_page_size(tlb, PAGE_SIZE);
0087 
0088     /*
0089      * Can be called with only the mmap_lock for reading by
0090      * prot_numa so we must check the pmd isn't constantly
0091      * changing from under us from pmd_none to pmd_trans_huge
0092      * and/or the other way around.
0093      */
0094     if (pmd_trans_unstable(pmd))
0095         return 0;
0096 
0097     /*
0098      * The pmd points to a regular pte so the pmd can't change
0099      * from under us even if the mmap_lock is only hold for
0100      * reading.
0101      */
0102     pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
0103 
0104     /* Get target node for single threaded private VMAs */
0105     if (prot_numa && !(vma->vm_flags & VM_SHARED) &&
0106         atomic_read(&vma->vm_mm->mm_users) == 1)
0107         target_node = numa_node_id();
0108 
0109     flush_tlb_batched_pending(vma->vm_mm);
0110     arch_enter_lazy_mmu_mode();
0111     do {
0112         oldpte = *pte;
0113         if (pte_present(oldpte)) {
0114             pte_t ptent;
0115             bool preserve_write = prot_numa && pte_write(oldpte);
0116 
0117             /*
0118              * Avoid trapping faults against the zero or KSM
0119              * pages. See similar comment in change_huge_pmd.
0120              */
0121             if (prot_numa) {
0122                 struct page *page;
0123                 int nid;
0124 
0125                 /* Avoid TLB flush if possible */
0126                 if (pte_protnone(oldpte))
0127                     continue;
0128 
0129                 page = vm_normal_page(vma, addr, oldpte);
0130                 if (!page || is_zone_device_page(page) || PageKsm(page))
0131                     continue;
0132 
0133                 /* Also skip shared copy-on-write pages */
0134                 if (is_cow_mapping(vma->vm_flags) &&
0135                     page_count(page) != 1)
0136                     continue;
0137 
0138                 /*
0139                  * While migration can move some dirty pages,
0140                  * it cannot move them all from MIGRATE_ASYNC
0141                  * context.
0142                  */
0143                 if (page_is_file_lru(page) && PageDirty(page))
0144                     continue;
0145 
0146                 /*
0147                  * Don't mess with PTEs if page is already on the node
0148                  * a single-threaded process is running on.
0149                  */
0150                 nid = page_to_nid(page);
0151                 if (target_node == nid)
0152                     continue;
0153 
0154                 /*
0155                  * Skip scanning top tier node if normal numa
0156                  * balancing is disabled
0157                  */
0158                 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
0159                     node_is_toptier(nid))
0160                     continue;
0161             }
0162 
0163             oldpte = ptep_modify_prot_start(vma, addr, pte);
0164             ptent = pte_modify(oldpte, newprot);
0165             if (preserve_write)
0166                 ptent = pte_mk_savedwrite(ptent);
0167 
0168             if (uffd_wp) {
0169                 ptent = pte_wrprotect(ptent);
0170                 ptent = pte_mkuffd_wp(ptent);
0171             } else if (uffd_wp_resolve) {
0172                 ptent = pte_clear_uffd_wp(ptent);
0173             }
0174 
0175             /*
0176              * In some writable, shared mappings, we might want
0177              * to catch actual write access -- see
0178              * vma_wants_writenotify().
0179              *
0180              * In all writable, private mappings, we have to
0181              * properly handle COW.
0182              *
0183              * In both cases, we can sometimes still change PTEs
0184              * writable and avoid the write-fault handler, for
0185              * example, if a PTE is already dirty and no other
0186              * COW or special handling is required.
0187              */
0188             if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) &&
0189                 !pte_write(ptent) &&
0190                 can_change_pte_writable(vma, addr, ptent))
0191                 ptent = pte_mkwrite(ptent);
0192 
0193             ptep_modify_prot_commit(vma, addr, pte, oldpte, ptent);
0194             if (pte_needs_flush(oldpte, ptent))
0195                 tlb_flush_pte_range(tlb, addr, PAGE_SIZE);
0196             pages++;
0197         } else if (is_swap_pte(oldpte)) {
0198             swp_entry_t entry = pte_to_swp_entry(oldpte);
0199             pte_t newpte;
0200 
0201             if (is_writable_migration_entry(entry)) {
0202                 struct page *page = pfn_swap_entry_to_page(entry);
0203 
0204                 /*
0205                  * A protection check is difficult so
0206                  * just be safe and disable write
0207                  */
0208                 if (PageAnon(page))
0209                     entry = make_readable_exclusive_migration_entry(
0210                                  swp_offset(entry));
0211                 else
0212                     entry = make_readable_migration_entry(swp_offset(entry));
0213                 newpte = swp_entry_to_pte(entry);
0214                 if (pte_swp_soft_dirty(oldpte))
0215                     newpte = pte_swp_mksoft_dirty(newpte);
0216                 if (pte_swp_uffd_wp(oldpte))
0217                     newpte = pte_swp_mkuffd_wp(newpte);
0218             } else if (is_writable_device_private_entry(entry)) {
0219                 /*
0220                  * We do not preserve soft-dirtiness. See
0221                  * copy_one_pte() for explanation.
0222                  */
0223                 entry = make_readable_device_private_entry(
0224                             swp_offset(entry));
0225                 newpte = swp_entry_to_pte(entry);
0226                 if (pte_swp_uffd_wp(oldpte))
0227                     newpte = pte_swp_mkuffd_wp(newpte);
0228             } else if (is_writable_device_exclusive_entry(entry)) {
0229                 entry = make_readable_device_exclusive_entry(
0230                             swp_offset(entry));
0231                 newpte = swp_entry_to_pte(entry);
0232                 if (pte_swp_soft_dirty(oldpte))
0233                     newpte = pte_swp_mksoft_dirty(newpte);
0234                 if (pte_swp_uffd_wp(oldpte))
0235                     newpte = pte_swp_mkuffd_wp(newpte);
0236             } else if (pte_marker_entry_uffd_wp(entry)) {
0237                 /*
0238                  * If this is uffd-wp pte marker and we'd like
0239                  * to unprotect it, drop it; the next page
0240                  * fault will trigger without uffd trapping.
0241                  */
0242                 if (uffd_wp_resolve) {
0243                     pte_clear(vma->vm_mm, addr, pte);
0244                     pages++;
0245                 }
0246                 continue;
0247             } else {
0248                 newpte = oldpte;
0249             }
0250 
0251             if (uffd_wp)
0252                 newpte = pte_swp_mkuffd_wp(newpte);
0253             else if (uffd_wp_resolve)
0254                 newpte = pte_swp_clear_uffd_wp(newpte);
0255 
0256             if (!pte_same(oldpte, newpte)) {
0257                 set_pte_at(vma->vm_mm, addr, pte, newpte);
0258                 pages++;
0259             }
0260         } else {
0261             /* It must be an none page, or what else?.. */
0262             WARN_ON_ONCE(!pte_none(oldpte));
0263             if (unlikely(uffd_wp && !vma_is_anonymous(vma))) {
0264                 /*
0265                  * For file-backed mem, we need to be able to
0266                  * wr-protect a none pte, because even if the
0267                  * pte is none, the page/swap cache could
0268                  * exist.  Doing that by install a marker.
0269                  */
0270                 set_pte_at(vma->vm_mm, addr, pte,
0271                        make_pte_marker(PTE_MARKER_UFFD_WP));
0272                 pages++;
0273             }
0274         }
0275     } while (pte++, addr += PAGE_SIZE, addr != end);
0276     arch_leave_lazy_mmu_mode();
0277     pte_unmap_unlock(pte - 1, ptl);
0278 
0279     return pages;
0280 }
0281 
0282 /*
0283  * Used when setting automatic NUMA hinting protection where it is
0284  * critical that a numa hinting PMD is not confused with a bad PMD.
0285  */
0286 static inline int pmd_none_or_clear_bad_unless_trans_huge(pmd_t *pmd)
0287 {
0288     pmd_t pmdval = pmd_read_atomic(pmd);
0289 
0290     /* See pmd_none_or_trans_huge_or_clear_bad for info on barrier */
0291 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
0292     barrier();
0293 #endif
0294 
0295     if (pmd_none(pmdval))
0296         return 1;
0297     if (pmd_trans_huge(pmdval))
0298         return 0;
0299     if (unlikely(pmd_bad(pmdval))) {
0300         pmd_clear_bad(pmd);
0301         return 1;
0302     }
0303 
0304     return 0;
0305 }
0306 
0307 /* Return true if we're uffd wr-protecting file-backed memory, or false */
0308 static inline bool
0309 uffd_wp_protect_file(struct vm_area_struct *vma, unsigned long cp_flags)
0310 {
0311     return (cp_flags & MM_CP_UFFD_WP) && !vma_is_anonymous(vma);
0312 }
0313 
0314 /*
0315  * If wr-protecting the range for file-backed, populate pgtable for the case
0316  * when pgtable is empty but page cache exists.  When {pte|pmd|...}_alloc()
0317  * failed it means no memory, we don't have a better option but stop.
0318  */
0319 #define  change_pmd_prepare(vma, pmd, cp_flags)             \
0320     do {                                \
0321         if (unlikely(uffd_wp_protect_file(vma, cp_flags))) {    \
0322             if (WARN_ON_ONCE(pte_alloc(vma->vm_mm, pmd)))   \
0323                 break;                  \
0324         }                           \
0325     } while (0)
0326 /*
0327  * This is the general pud/p4d/pgd version of change_pmd_prepare(). We need to
0328  * have separate change_pmd_prepare() because pte_alloc() returns 0 on success,
0329  * while {pmd|pud|p4d}_alloc() returns the valid pointer on success.
0330  */
0331 #define  change_prepare(vma, high, low, addr, cp_flags)         \
0332     do {                                \
0333         if (unlikely(uffd_wp_protect_file(vma, cp_flags))) {    \
0334             low##_t *p = low##_alloc(vma->vm_mm, high, addr); \
0335             if (WARN_ON_ONCE(p == NULL))            \
0336                 break;                  \
0337         }                           \
0338     } while (0)
0339 
0340 static inline unsigned long change_pmd_range(struct mmu_gather *tlb,
0341         struct vm_area_struct *vma, pud_t *pud, unsigned long addr,
0342         unsigned long end, pgprot_t newprot, unsigned long cp_flags)
0343 {
0344     pmd_t *pmd;
0345     unsigned long next;
0346     unsigned long pages = 0;
0347     unsigned long nr_huge_updates = 0;
0348     struct mmu_notifier_range range;
0349 
0350     range.start = 0;
0351 
0352     pmd = pmd_offset(pud, addr);
0353     do {
0354         unsigned long this_pages;
0355 
0356         next = pmd_addr_end(addr, end);
0357 
0358         change_pmd_prepare(vma, pmd, cp_flags);
0359         /*
0360          * Automatic NUMA balancing walks the tables with mmap_lock
0361          * held for read. It's possible a parallel update to occur
0362          * between pmd_trans_huge() and a pmd_none_or_clear_bad()
0363          * check leading to a false positive and clearing.
0364          * Hence, it's necessary to atomically read the PMD value
0365          * for all the checks.
0366          */
0367         if (!is_swap_pmd(*pmd) && !pmd_devmap(*pmd) &&
0368              pmd_none_or_clear_bad_unless_trans_huge(pmd))
0369             goto next;
0370 
0371         /* invoke the mmu notifier if the pmd is populated */
0372         if (!range.start) {
0373             mmu_notifier_range_init(&range,
0374                 MMU_NOTIFY_PROTECTION_VMA, 0,
0375                 vma, vma->vm_mm, addr, end);
0376             mmu_notifier_invalidate_range_start(&range);
0377         }
0378 
0379         if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
0380             if ((next - addr != HPAGE_PMD_SIZE) ||
0381                 uffd_wp_protect_file(vma, cp_flags)) {
0382                 __split_huge_pmd(vma, pmd, addr, false, NULL);
0383                 /*
0384                  * For file-backed, the pmd could have been
0385                  * cleared; make sure pmd populated if
0386                  * necessary, then fall-through to pte level.
0387                  */
0388                 change_pmd_prepare(vma, pmd, cp_flags);
0389             } else {
0390                 /*
0391                  * change_huge_pmd() does not defer TLB flushes,
0392                  * so no need to propagate the tlb argument.
0393                  */
0394                 int nr_ptes = change_huge_pmd(tlb, vma, pmd,
0395                         addr, newprot, cp_flags);
0396 
0397                 if (nr_ptes) {
0398                     if (nr_ptes == HPAGE_PMD_NR) {
0399                         pages += HPAGE_PMD_NR;
0400                         nr_huge_updates++;
0401                     }
0402 
0403                     /* huge pmd was handled */
0404                     goto next;
0405                 }
0406             }
0407             /* fall through, the trans huge pmd just split */
0408         }
0409         this_pages = change_pte_range(tlb, vma, pmd, addr, next,
0410                           newprot, cp_flags);
0411         pages += this_pages;
0412 next:
0413         cond_resched();
0414     } while (pmd++, addr = next, addr != end);
0415 
0416     if (range.start)
0417         mmu_notifier_invalidate_range_end(&range);
0418 
0419     if (nr_huge_updates)
0420         count_vm_numa_events(NUMA_HUGE_PTE_UPDATES, nr_huge_updates);
0421     return pages;
0422 }
0423 
0424 static inline unsigned long change_pud_range(struct mmu_gather *tlb,
0425         struct vm_area_struct *vma, p4d_t *p4d, unsigned long addr,
0426         unsigned long end, pgprot_t newprot, unsigned long cp_flags)
0427 {
0428     pud_t *pud;
0429     unsigned long next;
0430     unsigned long pages = 0;
0431 
0432     pud = pud_offset(p4d, addr);
0433     do {
0434         next = pud_addr_end(addr, end);
0435         change_prepare(vma, pud, pmd, addr, cp_flags);
0436         if (pud_none_or_clear_bad(pud))
0437             continue;
0438         pages += change_pmd_range(tlb, vma, pud, addr, next, newprot,
0439                       cp_flags);
0440     } while (pud++, addr = next, addr != end);
0441 
0442     return pages;
0443 }
0444 
0445 static inline unsigned long change_p4d_range(struct mmu_gather *tlb,
0446         struct vm_area_struct *vma, pgd_t *pgd, unsigned long addr,
0447         unsigned long end, pgprot_t newprot, unsigned long cp_flags)
0448 {
0449     p4d_t *p4d;
0450     unsigned long next;
0451     unsigned long pages = 0;
0452 
0453     p4d = p4d_offset(pgd, addr);
0454     do {
0455         next = p4d_addr_end(addr, end);
0456         change_prepare(vma, p4d, pud, addr, cp_flags);
0457         if (p4d_none_or_clear_bad(p4d))
0458             continue;
0459         pages += change_pud_range(tlb, vma, p4d, addr, next, newprot,
0460                       cp_flags);
0461     } while (p4d++, addr = next, addr != end);
0462 
0463     return pages;
0464 }
0465 
0466 static unsigned long change_protection_range(struct mmu_gather *tlb,
0467         struct vm_area_struct *vma, unsigned long addr,
0468         unsigned long end, pgprot_t newprot, unsigned long cp_flags)
0469 {
0470     struct mm_struct *mm = vma->vm_mm;
0471     pgd_t *pgd;
0472     unsigned long next;
0473     unsigned long pages = 0;
0474 
0475     BUG_ON(addr >= end);
0476     pgd = pgd_offset(mm, addr);
0477     tlb_start_vma(tlb, vma);
0478     do {
0479         next = pgd_addr_end(addr, end);
0480         change_prepare(vma, pgd, p4d, addr, cp_flags);
0481         if (pgd_none_or_clear_bad(pgd))
0482             continue;
0483         pages += change_p4d_range(tlb, vma, pgd, addr, next, newprot,
0484                       cp_flags);
0485     } while (pgd++, addr = next, addr != end);
0486 
0487     tlb_end_vma(tlb, vma);
0488 
0489     return pages;
0490 }
0491 
0492 unsigned long change_protection(struct mmu_gather *tlb,
0493                struct vm_area_struct *vma, unsigned long start,
0494                unsigned long end, pgprot_t newprot,
0495                unsigned long cp_flags)
0496 {
0497     unsigned long pages;
0498 
0499     BUG_ON((cp_flags & MM_CP_UFFD_WP_ALL) == MM_CP_UFFD_WP_ALL);
0500 
0501     if (is_vm_hugetlb_page(vma))
0502         pages = hugetlb_change_protection(vma, start, end, newprot,
0503                           cp_flags);
0504     else
0505         pages = change_protection_range(tlb, vma, start, end, newprot,
0506                         cp_flags);
0507 
0508     return pages;
0509 }
0510 
0511 static int prot_none_pte_entry(pte_t *pte, unsigned long addr,
0512                    unsigned long next, struct mm_walk *walk)
0513 {
0514     return pfn_modify_allowed(pte_pfn(*pte), *(pgprot_t *)(walk->private)) ?
0515         0 : -EACCES;
0516 }
0517 
0518 static int prot_none_hugetlb_entry(pte_t *pte, unsigned long hmask,
0519                    unsigned long addr, unsigned long next,
0520                    struct mm_walk *walk)
0521 {
0522     return pfn_modify_allowed(pte_pfn(*pte), *(pgprot_t *)(walk->private)) ?
0523         0 : -EACCES;
0524 }
0525 
0526 static int prot_none_test(unsigned long addr, unsigned long next,
0527               struct mm_walk *walk)
0528 {
0529     return 0;
0530 }
0531 
0532 static const struct mm_walk_ops prot_none_walk_ops = {
0533     .pte_entry      = prot_none_pte_entry,
0534     .hugetlb_entry      = prot_none_hugetlb_entry,
0535     .test_walk      = prot_none_test,
0536 };
0537 
0538 int
0539 mprotect_fixup(struct mmu_gather *tlb, struct vm_area_struct *vma,
0540            struct vm_area_struct **pprev, unsigned long start,
0541            unsigned long end, unsigned long newflags)
0542 {
0543     struct mm_struct *mm = vma->vm_mm;
0544     unsigned long oldflags = vma->vm_flags;
0545     long nrpages = (end - start) >> PAGE_SHIFT;
0546     unsigned long charged = 0;
0547     bool try_change_writable;
0548     pgoff_t pgoff;
0549     int error;
0550 
0551     if (newflags == oldflags) {
0552         *pprev = vma;
0553         return 0;
0554     }
0555 
0556     /*
0557      * Do PROT_NONE PFN permission checks here when we can still
0558      * bail out without undoing a lot of state. This is a rather
0559      * uncommon case, so doesn't need to be very optimized.
0560      */
0561     if (arch_has_pfn_modify_check() &&
0562         (vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
0563         (newflags & VM_ACCESS_FLAGS) == 0) {
0564         pgprot_t new_pgprot = vm_get_page_prot(newflags);
0565 
0566         error = walk_page_range(current->mm, start, end,
0567                 &prot_none_walk_ops, &new_pgprot);
0568         if (error)
0569             return error;
0570     }
0571 
0572     /*
0573      * If we make a private mapping writable we increase our commit;
0574      * but (without finer accounting) cannot reduce our commit if we
0575      * make it unwritable again. hugetlb mapping were accounted for
0576      * even if read-only so there is no need to account for them here
0577      */
0578     if (newflags & VM_WRITE) {
0579         /* Check space limits when area turns into data. */
0580         if (!may_expand_vm(mm, newflags, nrpages) &&
0581                 may_expand_vm(mm, oldflags, nrpages))
0582             return -ENOMEM;
0583         if (!(oldflags & (VM_ACCOUNT|VM_WRITE|VM_HUGETLB|
0584                         VM_SHARED|VM_NORESERVE))) {
0585             charged = nrpages;
0586             if (security_vm_enough_memory_mm(mm, charged))
0587                 return -ENOMEM;
0588             newflags |= VM_ACCOUNT;
0589         }
0590     }
0591 
0592     /*
0593      * First try to merge with previous and/or next vma.
0594      */
0595     pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
0596     *pprev = vma_merge(mm, *pprev, start, end, newflags,
0597                vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
0598                vma->vm_userfaultfd_ctx, anon_vma_name(vma));
0599     if (*pprev) {
0600         vma = *pprev;
0601         VM_WARN_ON((vma->vm_flags ^ newflags) & ~VM_SOFTDIRTY);
0602         goto success;
0603     }
0604 
0605     *pprev = vma;
0606 
0607     if (start != vma->vm_start) {
0608         error = split_vma(mm, vma, start, 1);
0609         if (error)
0610             goto fail;
0611     }
0612 
0613     if (end != vma->vm_end) {
0614         error = split_vma(mm, vma, end, 0);
0615         if (error)
0616             goto fail;
0617     }
0618 
0619 success:
0620     /*
0621      * vm_flags and vm_page_prot are protected by the mmap_lock
0622      * held in write mode.
0623      */
0624     vma->vm_flags = newflags;
0625     /*
0626      * We want to check manually if we can change individual PTEs writable
0627      * if we can't do that automatically for all PTEs in a mapping. For
0628      * private mappings, that's always the case when we have write
0629      * permissions as we properly have to handle COW.
0630      */
0631     if (vma->vm_flags & VM_SHARED)
0632         try_change_writable = vma_wants_writenotify(vma, vma->vm_page_prot);
0633     else
0634         try_change_writable = !!(vma->vm_flags & VM_WRITE);
0635     vma_set_page_prot(vma);
0636 
0637     change_protection(tlb, vma, start, end, vma->vm_page_prot,
0638               try_change_writable ? MM_CP_TRY_CHANGE_WRITABLE : 0);
0639 
0640     /*
0641      * Private VM_LOCKED VMA becoming writable: trigger COW to avoid major
0642      * fault on access.
0643      */
0644     if ((oldflags & (VM_WRITE | VM_SHARED | VM_LOCKED)) == VM_LOCKED &&
0645             (newflags & VM_WRITE)) {
0646         populate_vma_page_range(vma, start, end, NULL);
0647     }
0648 
0649     vm_stat_account(mm, oldflags, -nrpages);
0650     vm_stat_account(mm, newflags, nrpages);
0651     perf_event_mmap(vma);
0652     return 0;
0653 
0654 fail:
0655     vm_unacct_memory(charged);
0656     return error;
0657 }
0658 
0659 /*
0660  * pkey==-1 when doing a legacy mprotect()
0661  */
0662 static int do_mprotect_pkey(unsigned long start, size_t len,
0663         unsigned long prot, int pkey)
0664 {
0665     unsigned long nstart, end, tmp, reqprot;
0666     struct vm_area_struct *vma, *prev;
0667     int error;
0668     const int grows = prot & (PROT_GROWSDOWN|PROT_GROWSUP);
0669     const bool rier = (current->personality & READ_IMPLIES_EXEC) &&
0670                 (prot & PROT_READ);
0671     struct mmu_gather tlb;
0672 
0673     start = untagged_addr(start);
0674 
0675     prot &= ~(PROT_GROWSDOWN|PROT_GROWSUP);
0676     if (grows == (PROT_GROWSDOWN|PROT_GROWSUP)) /* can't be both */
0677         return -EINVAL;
0678 
0679     if (start & ~PAGE_MASK)
0680         return -EINVAL;
0681     if (!len)
0682         return 0;
0683     len = PAGE_ALIGN(len);
0684     end = start + len;
0685     if (end <= start)
0686         return -ENOMEM;
0687     if (!arch_validate_prot(prot, start))
0688         return -EINVAL;
0689 
0690     reqprot = prot;
0691 
0692     if (mmap_write_lock_killable(current->mm))
0693         return -EINTR;
0694 
0695     /*
0696      * If userspace did not allocate the pkey, do not let
0697      * them use it here.
0698      */
0699     error = -EINVAL;
0700     if ((pkey != -1) && !mm_pkey_is_allocated(current->mm, pkey))
0701         goto out;
0702 
0703     vma = find_vma(current->mm, start);
0704     error = -ENOMEM;
0705     if (!vma)
0706         goto out;
0707 
0708     if (unlikely(grows & PROT_GROWSDOWN)) {
0709         if (vma->vm_start >= end)
0710             goto out;
0711         start = vma->vm_start;
0712         error = -EINVAL;
0713         if (!(vma->vm_flags & VM_GROWSDOWN))
0714             goto out;
0715     } else {
0716         if (vma->vm_start > start)
0717             goto out;
0718         if (unlikely(grows & PROT_GROWSUP)) {
0719             end = vma->vm_end;
0720             error = -EINVAL;
0721             if (!(vma->vm_flags & VM_GROWSUP))
0722                 goto out;
0723         }
0724     }
0725 
0726     if (start > vma->vm_start)
0727         prev = vma;
0728     else
0729         prev = vma->vm_prev;
0730 
0731     tlb_gather_mmu(&tlb, current->mm);
0732     for (nstart = start ; ; ) {
0733         unsigned long mask_off_old_flags;
0734         unsigned long newflags;
0735         int new_vma_pkey;
0736 
0737         /* Here we know that vma->vm_start <= nstart < vma->vm_end. */
0738 
0739         /* Does the application expect PROT_READ to imply PROT_EXEC */
0740         if (rier && (vma->vm_flags & VM_MAYEXEC))
0741             prot |= PROT_EXEC;
0742 
0743         /*
0744          * Each mprotect() call explicitly passes r/w/x permissions.
0745          * If a permission is not passed to mprotect(), it must be
0746          * cleared from the VMA.
0747          */
0748         mask_off_old_flags = VM_READ | VM_WRITE | VM_EXEC |
0749                     VM_FLAGS_CLEAR;
0750 
0751         new_vma_pkey = arch_override_mprotect_pkey(vma, prot, pkey);
0752         newflags = calc_vm_prot_bits(prot, new_vma_pkey);
0753         newflags |= (vma->vm_flags & ~mask_off_old_flags);
0754 
0755         /* newflags >> 4 shift VM_MAY% in place of VM_% */
0756         if ((newflags & ~(newflags >> 4)) & VM_ACCESS_FLAGS) {
0757             error = -EACCES;
0758             break;
0759         }
0760 
0761         /* Allow architectures to sanity-check the new flags */
0762         if (!arch_validate_flags(newflags)) {
0763             error = -EINVAL;
0764             break;
0765         }
0766 
0767         error = security_file_mprotect(vma, reqprot, prot);
0768         if (error)
0769             break;
0770 
0771         tmp = vma->vm_end;
0772         if (tmp > end)
0773             tmp = end;
0774 
0775         if (vma->vm_ops && vma->vm_ops->mprotect) {
0776             error = vma->vm_ops->mprotect(vma, nstart, tmp, newflags);
0777             if (error)
0778                 break;
0779         }
0780 
0781         error = mprotect_fixup(&tlb, vma, &prev, nstart, tmp, newflags);
0782         if (error)
0783             break;
0784 
0785         nstart = tmp;
0786 
0787         if (nstart < prev->vm_end)
0788             nstart = prev->vm_end;
0789         if (nstart >= end)
0790             break;
0791 
0792         vma = prev->vm_next;
0793         if (!vma || vma->vm_start != nstart) {
0794             error = -ENOMEM;
0795             break;
0796         }
0797         prot = reqprot;
0798     }
0799     tlb_finish_mmu(&tlb);
0800 out:
0801     mmap_write_unlock(current->mm);
0802     return error;
0803 }
0804 
0805 SYSCALL_DEFINE3(mprotect, unsigned long, start, size_t, len,
0806         unsigned long, prot)
0807 {
0808     return do_mprotect_pkey(start, len, prot, -1);
0809 }
0810 
0811 #ifdef CONFIG_ARCH_HAS_PKEYS
0812 
0813 SYSCALL_DEFINE4(pkey_mprotect, unsigned long, start, size_t, len,
0814         unsigned long, prot, int, pkey)
0815 {
0816     return do_mprotect_pkey(start, len, prot, pkey);
0817 }
0818 
0819 SYSCALL_DEFINE2(pkey_alloc, unsigned long, flags, unsigned long, init_val)
0820 {
0821     int pkey;
0822     int ret;
0823 
0824     /* No flags supported yet. */
0825     if (flags)
0826         return -EINVAL;
0827     /* check for unsupported init values */
0828     if (init_val & ~PKEY_ACCESS_MASK)
0829         return -EINVAL;
0830 
0831     mmap_write_lock(current->mm);
0832     pkey = mm_pkey_alloc(current->mm);
0833 
0834     ret = -ENOSPC;
0835     if (pkey == -1)
0836         goto out;
0837 
0838     ret = arch_set_user_pkey_access(current, pkey, init_val);
0839     if (ret) {
0840         mm_pkey_free(current->mm, pkey);
0841         goto out;
0842     }
0843     ret = pkey;
0844 out:
0845     mmap_write_unlock(current->mm);
0846     return ret;
0847 }
0848 
0849 SYSCALL_DEFINE1(pkey_free, int, pkey)
0850 {
0851     int ret;
0852 
0853     mmap_write_lock(current->mm);
0854     ret = mm_pkey_free(current->mm, pkey);
0855     mmap_write_unlock(current->mm);
0856 
0857     /*
0858      * We could provide warnings or errors if any VMA still
0859      * has the pkey set here.
0860      */
0861     return ret;
0862 }
0863 
0864 #endif /* CONFIG_ARCH_HAS_PKEYS */