GNU Linux-libre 4.19.314-gnu1
[releases.git] / mm / userfaultfd.c
1 /*
2  *  mm/userfaultfd.c
3  *
4  *  Copyright (C) 2015  Red Hat, Inc.
5  *
6  *  This work is licensed under the terms of the GNU GPL, version 2. See
7  *  the COPYING file in the top-level directory.
8  */
9
10 #include <linux/mm.h>
11 #include <linux/sched/signal.h>
12 #include <linux/pagemap.h>
13 #include <linux/rmap.h>
14 #include <linux/swap.h>
15 #include <linux/swapops.h>
16 #include <linux/userfaultfd_k.h>
17 #include <linux/mmu_notifier.h>
18 #include <linux/hugetlb.h>
19 #include <linux/shmem_fs.h>
20 #include <asm/tlbflush.h>
21 #include "internal.h"
22
23 static int mcopy_atomic_pte(struct mm_struct *dst_mm,
24                             pmd_t *dst_pmd,
25                             struct vm_area_struct *dst_vma,
26                             unsigned long dst_addr,
27                             unsigned long src_addr,
28                             struct page **pagep)
29 {
30         struct mem_cgroup *memcg;
31         pte_t _dst_pte, *dst_pte;
32         spinlock_t *ptl;
33         void *page_kaddr;
34         int ret;
35         struct page *page;
36         pgoff_t offset, max_off;
37         struct inode *inode;
38
39         if (!*pagep) {
40                 ret = -ENOMEM;
41                 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, dst_vma, dst_addr);
42                 if (!page)
43                         goto out;
44
45                 page_kaddr = kmap_atomic(page);
46                 ret = copy_from_user(page_kaddr,
47                                      (const void __user *) src_addr,
48                                      PAGE_SIZE);
49                 kunmap_atomic(page_kaddr);
50
51                 /* fallback to copy_from_user outside mmap_sem */
52                 if (unlikely(ret)) {
53                         ret = -ENOENT;
54                         *pagep = page;
55                         /* don't free the page */
56                         goto out;
57                 }
58
59                 flush_dcache_page(page);
60         } else {
61                 page = *pagep;
62                 *pagep = NULL;
63         }
64
65         /*
66          * The memory barrier inside __SetPageUptodate makes sure that
67          * preceeding stores to the page contents become visible before
68          * the set_pte_at() write.
69          */
70         __SetPageUptodate(page);
71
72         ret = -ENOMEM;
73         if (mem_cgroup_try_charge(page, dst_mm, GFP_KERNEL, &memcg, false))
74                 goto out_release;
75
76         _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
77         if (dst_vma->vm_flags & VM_WRITE)
78                 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
79
80         dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
81         if (dst_vma->vm_file) {
82                 /* the shmem MAP_PRIVATE case requires checking the i_size */
83                 inode = dst_vma->vm_file->f_inode;
84                 offset = linear_page_index(dst_vma, dst_addr);
85                 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
86                 ret = -EFAULT;
87                 if (unlikely(offset >= max_off))
88                         goto out_release_uncharge_unlock;
89         }
90         ret = -EEXIST;
91         if (!pte_none(*dst_pte))
92                 goto out_release_uncharge_unlock;
93
94         inc_mm_counter(dst_mm, MM_ANONPAGES);
95         page_add_new_anon_rmap(page, dst_vma, dst_addr, false);
96         mem_cgroup_commit_charge(page, memcg, false, false);
97         lru_cache_add_active_or_unevictable(page, dst_vma);
98
99         set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
100
101         /* No need to invalidate - it was non-present before */
102         update_mmu_cache(dst_vma, dst_addr, dst_pte);
103
104         pte_unmap_unlock(dst_pte, ptl);
105         ret = 0;
106 out:
107         return ret;
108 out_release_uncharge_unlock:
109         pte_unmap_unlock(dst_pte, ptl);
110         mem_cgroup_cancel_charge(page, memcg, false);
111 out_release:
112         put_page(page);
113         goto out;
114 }
115
116 static int mfill_zeropage_pte(struct mm_struct *dst_mm,
117                               pmd_t *dst_pmd,
118                               struct vm_area_struct *dst_vma,
119                               unsigned long dst_addr)
120 {
121         pte_t _dst_pte, *dst_pte;
122         spinlock_t *ptl;
123         int ret;
124         pgoff_t offset, max_off;
125         struct inode *inode;
126
127         _dst_pte = pte_mkspecial(pfn_pte(my_zero_pfn(dst_addr),
128                                          dst_vma->vm_page_prot));
129         dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
130         if (dst_vma->vm_file) {
131                 /* the shmem MAP_PRIVATE case requires checking the i_size */
132                 inode = dst_vma->vm_file->f_inode;
133                 offset = linear_page_index(dst_vma, dst_addr);
134                 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
135                 ret = -EFAULT;
136                 if (unlikely(offset >= max_off))
137                         goto out_unlock;
138         }
139         ret = -EEXIST;
140         if (!pte_none(*dst_pte))
141                 goto out_unlock;
142         set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
143         /* No need to invalidate - it was non-present before */
144         update_mmu_cache(dst_vma, dst_addr, dst_pte);
145         ret = 0;
146 out_unlock:
147         pte_unmap_unlock(dst_pte, ptl);
148         return ret;
149 }
150
151 static pmd_t *mm_alloc_pmd(struct mm_struct *mm, unsigned long address)
152 {
153         pgd_t *pgd;
154         p4d_t *p4d;
155         pud_t *pud;
156
157         pgd = pgd_offset(mm, address);
158         p4d = p4d_alloc(mm, pgd, address);
159         if (!p4d)
160                 return NULL;
161         pud = pud_alloc(mm, p4d, address);
162         if (!pud)
163                 return NULL;
164         /*
165          * Note that we didn't run this because the pmd was
166          * missing, the *pmd may be already established and in
167          * turn it may also be a trans_huge_pmd.
168          */
169         return pmd_alloc(mm, pud, address);
170 }
171
172 #ifdef CONFIG_HUGETLB_PAGE
173 /*
174  * __mcopy_atomic processing for HUGETLB vmas.  Note that this routine is
175  * called with mmap_sem held, it will release mmap_sem before returning.
176  */
177 static __always_inline ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,
178                                               struct vm_area_struct *dst_vma,
179                                               unsigned long dst_start,
180                                               unsigned long src_start,
181                                               unsigned long len,
182                                               bool *mmap_changing,
183                                               bool zeropage)
184 {
185         int vm_alloc_shared = dst_vma->vm_flags & VM_SHARED;
186         int vm_shared = dst_vma->vm_flags & VM_SHARED;
187         ssize_t err;
188         pte_t *dst_pte;
189         unsigned long src_addr, dst_addr;
190         long copied;
191         struct page *page;
192         struct hstate *h;
193         unsigned long vma_hpagesize;
194         pgoff_t idx;
195         u32 hash;
196         struct address_space *mapping;
197
198         /*
199          * There is no default zero huge page for all huge page sizes as
200          * supported by hugetlb.  A PMD_SIZE huge pages may exist as used
201          * by THP.  Since we can not reliably insert a zero page, this
202          * feature is not supported.
203          */
204         if (zeropage) {
205                 up_read(&dst_mm->mmap_sem);
206                 return -EINVAL;
207         }
208
209         src_addr = src_start;
210         dst_addr = dst_start;
211         copied = 0;
212         page = NULL;
213         vma_hpagesize = vma_kernel_pagesize(dst_vma);
214
215         /*
216          * Validate alignment based on huge page size
217          */
218         err = -EINVAL;
219         if (dst_start & (vma_hpagesize - 1) || len & (vma_hpagesize - 1))
220                 goto out_unlock;
221
222 retry:
223         /*
224          * On routine entry dst_vma is set.  If we had to drop mmap_sem and
225          * retry, dst_vma will be set to NULL and we must lookup again.
226          */
227         if (!dst_vma) {
228                 err = -ENOENT;
229                 dst_vma = find_vma(dst_mm, dst_start);
230                 if (!dst_vma || !is_vm_hugetlb_page(dst_vma))
231                         goto out_unlock;
232                 /*
233                  * Check the vma is registered in uffd, this is
234                  * required to enforce the VM_MAYWRITE check done at
235                  * uffd registration time.
236                  */
237                 if (!dst_vma->vm_userfaultfd_ctx.ctx)
238                         goto out_unlock;
239
240                 if (dst_start < dst_vma->vm_start ||
241                     dst_start + len > dst_vma->vm_end)
242                         goto out_unlock;
243
244                 err = -EINVAL;
245                 if (vma_hpagesize != vma_kernel_pagesize(dst_vma))
246                         goto out_unlock;
247
248                 vm_shared = dst_vma->vm_flags & VM_SHARED;
249         }
250
251         if (WARN_ON(dst_addr & (vma_hpagesize - 1) ||
252                     (len - copied) & (vma_hpagesize - 1)))
253                 goto out_unlock;
254
255         /*
256          * If not shared, ensure the dst_vma has a anon_vma.
257          */
258         err = -ENOMEM;
259         if (!vm_shared) {
260                 if (unlikely(anon_vma_prepare(dst_vma)))
261                         goto out_unlock;
262         }
263
264         h = hstate_vma(dst_vma);
265
266         while (src_addr < src_start + len) {
267                 pte_t dst_pteval;
268
269                 BUG_ON(dst_addr >= dst_start + len);
270                 VM_BUG_ON(dst_addr & ~huge_page_mask(h));
271
272                 /*
273                  * Serialize via hugetlb_fault_mutex
274                  */
275                 idx = linear_page_index(dst_vma, dst_addr);
276                 mapping = dst_vma->vm_file->f_mapping;
277                 hash = hugetlb_fault_mutex_hash(h, mapping, idx);
278                 mutex_lock(&hugetlb_fault_mutex_table[hash]);
279
280                 err = -ENOMEM;
281                 dst_pte = huge_pte_alloc(dst_mm, dst_addr, huge_page_size(h));
282                 if (!dst_pte) {
283                         mutex_unlock(&hugetlb_fault_mutex_table[hash]);
284                         goto out_unlock;
285                 }
286
287                 err = -EEXIST;
288                 dst_pteval = huge_ptep_get(dst_pte);
289                 if (!huge_pte_none(dst_pteval)) {
290                         mutex_unlock(&hugetlb_fault_mutex_table[hash]);
291                         goto out_unlock;
292                 }
293
294                 err = hugetlb_mcopy_atomic_pte(dst_mm, dst_pte, dst_vma,
295                                                 dst_addr, src_addr, &page);
296
297                 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
298                 vm_alloc_shared = vm_shared;
299
300                 cond_resched();
301
302                 if (unlikely(err == -ENOENT)) {
303                         up_read(&dst_mm->mmap_sem);
304                         BUG_ON(!page);
305
306                         err = copy_huge_page_from_user(page,
307                                                 (const void __user *)src_addr,
308                                                 pages_per_huge_page(h), true);
309                         if (unlikely(err)) {
310                                 err = -EFAULT;
311                                 goto out;
312                         }
313                         down_read(&dst_mm->mmap_sem);
314                         /*
315                          * If memory mappings are changing because of non-cooperative
316                          * operation (e.g. mremap) running in parallel, bail out and
317                          * request the user to retry later
318                          */
319                         if (mmap_changing && READ_ONCE(*mmap_changing)) {
320                                 err = -EAGAIN;
321                                 break;
322                         }
323
324                         dst_vma = NULL;
325                         goto retry;
326                 } else
327                         BUG_ON(page);
328
329                 if (!err) {
330                         dst_addr += vma_hpagesize;
331                         src_addr += vma_hpagesize;
332                         copied += vma_hpagesize;
333
334                         if (fatal_signal_pending(current))
335                                 err = -EINTR;
336                 }
337                 if (err)
338                         break;
339         }
340
341 out_unlock:
342         up_read(&dst_mm->mmap_sem);
343 out:
344         if (page) {
345                 /*
346                  * We encountered an error and are about to free a newly
347                  * allocated huge page.
348                  *
349                  * Reservation handling is very subtle, and is different for
350                  * private and shared mappings.  See the routine
351                  * restore_reserve_on_error for details.  Unfortunately, we
352                  * can not call restore_reserve_on_error now as it would
353                  * require holding mmap_sem.
354                  *
355                  * If a reservation for the page existed in the reservation
356                  * map of a private mapping, the map was modified to indicate
357                  * the reservation was consumed when the page was allocated.
358                  * We clear the PagePrivate flag now so that the global
359                  * reserve count will not be incremented in free_huge_page.
360                  * The reservation map will still indicate the reservation
361                  * was consumed and possibly prevent later page allocation.
362                  * This is better than leaking a global reservation.  If no
363                  * reservation existed, it is still safe to clear PagePrivate
364                  * as no adjustments to reservation counts were made during
365                  * allocation.
366                  *
367                  * The reservation map for shared mappings indicates which
368                  * pages have reservations.  When a huge page is allocated
369                  * for an address with a reservation, no change is made to
370                  * the reserve map.  In this case PagePrivate will be set
371                  * to indicate that the global reservation count should be
372                  * incremented when the page is freed.  This is the desired
373                  * behavior.  However, when a huge page is allocated for an
374                  * address without a reservation a reservation entry is added
375                  * to the reservation map, and PagePrivate will not be set.
376                  * When the page is freed, the global reserve count will NOT
377                  * be incremented and it will appear as though we have leaked
378                  * reserved page.  In this case, set PagePrivate so that the
379                  * global reserve count will be incremented to match the
380                  * reservation map entry which was created.
381                  *
382                  * Note that vm_alloc_shared is based on the flags of the vma
383                  * for which the page was originally allocated.  dst_vma could
384                  * be different or NULL on error.
385                  */
386                 if (vm_alloc_shared)
387                         SetPagePrivate(page);
388                 else
389                         ClearPagePrivate(page);
390                 put_page(page);
391         }
392         BUG_ON(copied < 0);
393         BUG_ON(err > 0);
394         BUG_ON(!copied && !err);
395         return copied ? copied : err;
396 }
397 #else /* !CONFIG_HUGETLB_PAGE */
398 /* fail at build time if gcc attempts to use this */
399 extern ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,
400                                       struct vm_area_struct *dst_vma,
401                                       unsigned long dst_start,
402                                       unsigned long src_start,
403                                       unsigned long len,
404                                       bool *mmap_changing,
405                                       bool zeropage);
406 #endif /* CONFIG_HUGETLB_PAGE */
407
408 static __always_inline ssize_t mfill_atomic_pte(struct mm_struct *dst_mm,
409                                                 pmd_t *dst_pmd,
410                                                 struct vm_area_struct *dst_vma,
411                                                 unsigned long dst_addr,
412                                                 unsigned long src_addr,
413                                                 struct page **page,
414                                                 bool zeropage)
415 {
416         ssize_t err;
417
418         /*
419          * The normal page fault path for a shmem will invoke the
420          * fault, fill the hole in the file and COW it right away. The
421          * result generates plain anonymous memory. So when we are
422          * asked to fill an hole in a MAP_PRIVATE shmem mapping, we'll
423          * generate anonymous memory directly without actually filling
424          * the hole. For the MAP_PRIVATE case the robustness check
425          * only happens in the pagetable (to verify it's still none)
426          * and not in the radix tree.
427          */
428         if (!(dst_vma->vm_flags & VM_SHARED)) {
429                 if (!zeropage)
430                         err = mcopy_atomic_pte(dst_mm, dst_pmd, dst_vma,
431                                                dst_addr, src_addr, page);
432                 else
433                         err = mfill_zeropage_pte(dst_mm, dst_pmd,
434                                                  dst_vma, dst_addr);
435         } else {
436                 if (!zeropage)
437                         err = shmem_mcopy_atomic_pte(dst_mm, dst_pmd,
438                                                      dst_vma, dst_addr,
439                                                      src_addr, page);
440                 else
441                         err = shmem_mfill_zeropage_pte(dst_mm, dst_pmd,
442                                                        dst_vma, dst_addr);
443         }
444
445         return err;
446 }
447
448 static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,
449                                               unsigned long dst_start,
450                                               unsigned long src_start,
451                                               unsigned long len,
452                                               bool zeropage,
453                                               bool *mmap_changing)
454 {
455         struct vm_area_struct *dst_vma;
456         ssize_t err;
457         pmd_t *dst_pmd;
458         unsigned long src_addr, dst_addr;
459         long copied;
460         struct page *page;
461
462         /*
463          * Sanitize the command parameters:
464          */
465         BUG_ON(dst_start & ~PAGE_MASK);
466         BUG_ON(len & ~PAGE_MASK);
467
468         /* Does the address range wrap, or is the span zero-sized? */
469         BUG_ON(src_start + len <= src_start);
470         BUG_ON(dst_start + len <= dst_start);
471
472         src_addr = src_start;
473         dst_addr = dst_start;
474         copied = 0;
475         page = NULL;
476 retry:
477         down_read(&dst_mm->mmap_sem);
478
479         /*
480          * If memory mappings are changing because of non-cooperative
481          * operation (e.g. mremap) running in parallel, bail out and
482          * request the user to retry later
483          */
484         err = -EAGAIN;
485         if (mmap_changing && READ_ONCE(*mmap_changing))
486                 goto out_unlock;
487
488         /*
489          * Make sure the vma is not shared, that the dst range is
490          * both valid and fully within a single existing vma.
491          */
492         err = -ENOENT;
493         dst_vma = find_vma(dst_mm, dst_start);
494         if (!dst_vma)
495                 goto out_unlock;
496         /*
497          * Check the vma is registered in uffd, this is required to
498          * enforce the VM_MAYWRITE check done at uffd registration
499          * time.
500          */
501         if (!dst_vma->vm_userfaultfd_ctx.ctx)
502                 goto out_unlock;
503
504         if (dst_start < dst_vma->vm_start ||
505             dst_start + len > dst_vma->vm_end)
506                 goto out_unlock;
507
508         err = -EINVAL;
509         /*
510          * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
511          * it will overwrite vm_ops, so vma_is_anonymous must return false.
512          */
513         if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
514             dst_vma->vm_flags & VM_SHARED))
515                 goto out_unlock;
516
517         /*
518          * If this is a HUGETLB vma, pass off to appropriate routine
519          */
520         if (is_vm_hugetlb_page(dst_vma))
521                 return  __mcopy_atomic_hugetlb(dst_mm, dst_vma, dst_start,
522                                                src_start, len, mmap_changing,
523                                                zeropage);
524
525         if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
526                 goto out_unlock;
527
528         /*
529          * Ensure the dst_vma has a anon_vma or this page
530          * would get a NULL anon_vma when moved in the
531          * dst_vma.
532          */
533         err = -ENOMEM;
534         if (!(dst_vma->vm_flags & VM_SHARED) &&
535             unlikely(anon_vma_prepare(dst_vma)))
536                 goto out_unlock;
537
538         while (src_addr < src_start + len) {
539                 pmd_t dst_pmdval;
540
541                 BUG_ON(dst_addr >= dst_start + len);
542
543                 dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
544                 if (unlikely(!dst_pmd)) {
545                         err = -ENOMEM;
546                         break;
547                 }
548
549                 dst_pmdval = pmd_read_atomic(dst_pmd);
550                 /*
551                  * If the dst_pmd is mapped as THP don't
552                  * override it and just be strict.
553                  */
554                 if (unlikely(pmd_trans_huge(dst_pmdval))) {
555                         err = -EEXIST;
556                         break;
557                 }
558                 if (unlikely(pmd_none(dst_pmdval)) &&
559                     unlikely(__pte_alloc(dst_mm, dst_pmd, dst_addr))) {
560                         err = -ENOMEM;
561                         break;
562                 }
563                 /* If an huge pmd materialized from under us fail */
564                 if (unlikely(pmd_trans_huge(*dst_pmd))) {
565                         err = -EFAULT;
566                         break;
567                 }
568
569                 BUG_ON(pmd_none(*dst_pmd));
570                 BUG_ON(pmd_trans_huge(*dst_pmd));
571
572                 err = mfill_atomic_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
573                                        src_addr, &page, zeropage);
574                 cond_resched();
575
576                 if (unlikely(err == -ENOENT)) {
577                         void *page_kaddr;
578
579                         up_read(&dst_mm->mmap_sem);
580                         BUG_ON(!page);
581
582                         page_kaddr = kmap(page);
583                         err = copy_from_user(page_kaddr,
584                                              (const void __user *) src_addr,
585                                              PAGE_SIZE);
586                         kunmap(page);
587                         if (unlikely(err)) {
588                                 err = -EFAULT;
589                                 goto out;
590                         }
591                         flush_dcache_page(page);
592                         goto retry;
593                 } else
594                         BUG_ON(page);
595
596                 if (!err) {
597                         dst_addr += PAGE_SIZE;
598                         src_addr += PAGE_SIZE;
599                         copied += PAGE_SIZE;
600
601                         if (fatal_signal_pending(current))
602                                 err = -EINTR;
603                 }
604                 if (err)
605                         break;
606         }
607
608 out_unlock:
609         up_read(&dst_mm->mmap_sem);
610 out:
611         if (page)
612                 put_page(page);
613         BUG_ON(copied < 0);
614         BUG_ON(err > 0);
615         BUG_ON(!copied && !err);
616         return copied ? copied : err;
617 }
618
619 ssize_t mcopy_atomic(struct mm_struct *dst_mm, unsigned long dst_start,
620                      unsigned long src_start, unsigned long len,
621                      bool *mmap_changing)
622 {
623         return __mcopy_atomic(dst_mm, dst_start, src_start, len, false,
624                               mmap_changing);
625 }
626
627 ssize_t mfill_zeropage(struct mm_struct *dst_mm, unsigned long start,
628                        unsigned long len, bool *mmap_changing)
629 {
630         return __mcopy_atomic(dst_mm, start, 0, len, true, mmap_changing);
631 }