GNU Linux-libre 4.19.245-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 zeropage)
183 {
184         int vm_alloc_shared = dst_vma->vm_flags & VM_SHARED;
185         int vm_shared = dst_vma->vm_flags & VM_SHARED;
186         ssize_t err;
187         pte_t *dst_pte;
188         unsigned long src_addr, dst_addr;
189         long copied;
190         struct page *page;
191         struct hstate *h;
192         unsigned long vma_hpagesize;
193         pgoff_t idx;
194         u32 hash;
195         struct address_space *mapping;
196
197         /*
198          * There is no default zero huge page for all huge page sizes as
199          * supported by hugetlb.  A PMD_SIZE huge pages may exist as used
200          * by THP.  Since we can not reliably insert a zero page, this
201          * feature is not supported.
202          */
203         if (zeropage) {
204                 up_read(&dst_mm->mmap_sem);
205                 return -EINVAL;
206         }
207
208         src_addr = src_start;
209         dst_addr = dst_start;
210         copied = 0;
211         page = NULL;
212         vma_hpagesize = vma_kernel_pagesize(dst_vma);
213
214         /*
215          * Validate alignment based on huge page size
216          */
217         err = -EINVAL;
218         if (dst_start & (vma_hpagesize - 1) || len & (vma_hpagesize - 1))
219                 goto out_unlock;
220
221 retry:
222         /*
223          * On routine entry dst_vma is set.  If we had to drop mmap_sem and
224          * retry, dst_vma will be set to NULL and we must lookup again.
225          */
226         if (!dst_vma) {
227                 err = -ENOENT;
228                 dst_vma = find_vma(dst_mm, dst_start);
229                 if (!dst_vma || !is_vm_hugetlb_page(dst_vma))
230                         goto out_unlock;
231                 /*
232                  * Check the vma is registered in uffd, this is
233                  * required to enforce the VM_MAYWRITE check done at
234                  * uffd registration time.
235                  */
236                 if (!dst_vma->vm_userfaultfd_ctx.ctx)
237                         goto out_unlock;
238
239                 if (dst_start < dst_vma->vm_start ||
240                     dst_start + len > dst_vma->vm_end)
241                         goto out_unlock;
242
243                 err = -EINVAL;
244                 if (vma_hpagesize != vma_kernel_pagesize(dst_vma))
245                         goto out_unlock;
246
247                 vm_shared = dst_vma->vm_flags & VM_SHARED;
248         }
249
250         if (WARN_ON(dst_addr & (vma_hpagesize - 1) ||
251                     (len - copied) & (vma_hpagesize - 1)))
252                 goto out_unlock;
253
254         /*
255          * If not shared, ensure the dst_vma has a anon_vma.
256          */
257         err = -ENOMEM;
258         if (!vm_shared) {
259                 if (unlikely(anon_vma_prepare(dst_vma)))
260                         goto out_unlock;
261         }
262
263         h = hstate_vma(dst_vma);
264
265         while (src_addr < src_start + len) {
266                 pte_t dst_pteval;
267
268                 BUG_ON(dst_addr >= dst_start + len);
269                 VM_BUG_ON(dst_addr & ~huge_page_mask(h));
270
271                 /*
272                  * Serialize via hugetlb_fault_mutex
273                  */
274                 idx = linear_page_index(dst_vma, dst_addr);
275                 mapping = dst_vma->vm_file->f_mapping;
276                 hash = hugetlb_fault_mutex_hash(h, mapping, idx);
277                 mutex_lock(&hugetlb_fault_mutex_table[hash]);
278
279                 err = -ENOMEM;
280                 dst_pte = huge_pte_alloc(dst_mm, dst_addr, huge_page_size(h));
281                 if (!dst_pte) {
282                         mutex_unlock(&hugetlb_fault_mutex_table[hash]);
283                         goto out_unlock;
284                 }
285
286                 err = -EEXIST;
287                 dst_pteval = huge_ptep_get(dst_pte);
288                 if (!huge_pte_none(dst_pteval)) {
289                         mutex_unlock(&hugetlb_fault_mutex_table[hash]);
290                         goto out_unlock;
291                 }
292
293                 err = hugetlb_mcopy_atomic_pte(dst_mm, dst_pte, dst_vma,
294                                                 dst_addr, src_addr, &page);
295
296                 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
297                 vm_alloc_shared = vm_shared;
298
299                 cond_resched();
300
301                 if (unlikely(err == -ENOENT)) {
302                         up_read(&dst_mm->mmap_sem);
303                         BUG_ON(!page);
304
305                         err = copy_huge_page_from_user(page,
306                                                 (const void __user *)src_addr,
307                                                 pages_per_huge_page(h), true);
308                         if (unlikely(err)) {
309                                 err = -EFAULT;
310                                 goto out;
311                         }
312                         down_read(&dst_mm->mmap_sem);
313
314                         dst_vma = NULL;
315                         goto retry;
316                 } else
317                         BUG_ON(page);
318
319                 if (!err) {
320                         dst_addr += vma_hpagesize;
321                         src_addr += vma_hpagesize;
322                         copied += vma_hpagesize;
323
324                         if (fatal_signal_pending(current))
325                                 err = -EINTR;
326                 }
327                 if (err)
328                         break;
329         }
330
331 out_unlock:
332         up_read(&dst_mm->mmap_sem);
333 out:
334         if (page) {
335                 /*
336                  * We encountered an error and are about to free a newly
337                  * allocated huge page.
338                  *
339                  * Reservation handling is very subtle, and is different for
340                  * private and shared mappings.  See the routine
341                  * restore_reserve_on_error for details.  Unfortunately, we
342                  * can not call restore_reserve_on_error now as it would
343                  * require holding mmap_sem.
344                  *
345                  * If a reservation for the page existed in the reservation
346                  * map of a private mapping, the map was modified to indicate
347                  * the reservation was consumed when the page was allocated.
348                  * We clear the PagePrivate flag now so that the global
349                  * reserve count will not be incremented in free_huge_page.
350                  * The reservation map will still indicate the reservation
351                  * was consumed and possibly prevent later page allocation.
352                  * This is better than leaking a global reservation.  If no
353                  * reservation existed, it is still safe to clear PagePrivate
354                  * as no adjustments to reservation counts were made during
355                  * allocation.
356                  *
357                  * The reservation map for shared mappings indicates which
358                  * pages have reservations.  When a huge page is allocated
359                  * for an address with a reservation, no change is made to
360                  * the reserve map.  In this case PagePrivate will be set
361                  * to indicate that the global reservation count should be
362                  * incremented when the page is freed.  This is the desired
363                  * behavior.  However, when a huge page is allocated for an
364                  * address without a reservation a reservation entry is added
365                  * to the reservation map, and PagePrivate will not be set.
366                  * When the page is freed, the global reserve count will NOT
367                  * be incremented and it will appear as though we have leaked
368                  * reserved page.  In this case, set PagePrivate so that the
369                  * global reserve count will be incremented to match the
370                  * reservation map entry which was created.
371                  *
372                  * Note that vm_alloc_shared is based on the flags of the vma
373                  * for which the page was originally allocated.  dst_vma could
374                  * be different or NULL on error.
375                  */
376                 if (vm_alloc_shared)
377                         SetPagePrivate(page);
378                 else
379                         ClearPagePrivate(page);
380                 put_page(page);
381         }
382         BUG_ON(copied < 0);
383         BUG_ON(err > 0);
384         BUG_ON(!copied && !err);
385         return copied ? copied : err;
386 }
387 #else /* !CONFIG_HUGETLB_PAGE */
388 /* fail at build time if gcc attempts to use this */
389 extern ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,
390                                       struct vm_area_struct *dst_vma,
391                                       unsigned long dst_start,
392                                       unsigned long src_start,
393                                       unsigned long len,
394                                       bool zeropage);
395 #endif /* CONFIG_HUGETLB_PAGE */
396
397 static __always_inline ssize_t mfill_atomic_pte(struct mm_struct *dst_mm,
398                                                 pmd_t *dst_pmd,
399                                                 struct vm_area_struct *dst_vma,
400                                                 unsigned long dst_addr,
401                                                 unsigned long src_addr,
402                                                 struct page **page,
403                                                 bool zeropage)
404 {
405         ssize_t err;
406
407         /*
408          * The normal page fault path for a shmem will invoke the
409          * fault, fill the hole in the file and COW it right away. The
410          * result generates plain anonymous memory. So when we are
411          * asked to fill an hole in a MAP_PRIVATE shmem mapping, we'll
412          * generate anonymous memory directly without actually filling
413          * the hole. For the MAP_PRIVATE case the robustness check
414          * only happens in the pagetable (to verify it's still none)
415          * and not in the radix tree.
416          */
417         if (!(dst_vma->vm_flags & VM_SHARED)) {
418                 if (!zeropage)
419                         err = mcopy_atomic_pte(dst_mm, dst_pmd, dst_vma,
420                                                dst_addr, src_addr, page);
421                 else
422                         err = mfill_zeropage_pte(dst_mm, dst_pmd,
423                                                  dst_vma, dst_addr);
424         } else {
425                 if (!zeropage)
426                         err = shmem_mcopy_atomic_pte(dst_mm, dst_pmd,
427                                                      dst_vma, dst_addr,
428                                                      src_addr, page);
429                 else
430                         err = shmem_mfill_zeropage_pte(dst_mm, dst_pmd,
431                                                        dst_vma, dst_addr);
432         }
433
434         return err;
435 }
436
437 static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,
438                                               unsigned long dst_start,
439                                               unsigned long src_start,
440                                               unsigned long len,
441                                               bool zeropage,
442                                               bool *mmap_changing)
443 {
444         struct vm_area_struct *dst_vma;
445         ssize_t err;
446         pmd_t *dst_pmd;
447         unsigned long src_addr, dst_addr;
448         long copied;
449         struct page *page;
450
451         /*
452          * Sanitize the command parameters:
453          */
454         BUG_ON(dst_start & ~PAGE_MASK);
455         BUG_ON(len & ~PAGE_MASK);
456
457         /* Does the address range wrap, or is the span zero-sized? */
458         BUG_ON(src_start + len <= src_start);
459         BUG_ON(dst_start + len <= dst_start);
460
461         src_addr = src_start;
462         dst_addr = dst_start;
463         copied = 0;
464         page = NULL;
465 retry:
466         down_read(&dst_mm->mmap_sem);
467
468         /*
469          * If memory mappings are changing because of non-cooperative
470          * operation (e.g. mremap) running in parallel, bail out and
471          * request the user to retry later
472          */
473         err = -EAGAIN;
474         if (mmap_changing && READ_ONCE(*mmap_changing))
475                 goto out_unlock;
476
477         /*
478          * Make sure the vma is not shared, that the dst range is
479          * both valid and fully within a single existing vma.
480          */
481         err = -ENOENT;
482         dst_vma = find_vma(dst_mm, dst_start);
483         if (!dst_vma)
484                 goto out_unlock;
485         /*
486          * Check the vma is registered in uffd, this is required to
487          * enforce the VM_MAYWRITE check done at uffd registration
488          * time.
489          */
490         if (!dst_vma->vm_userfaultfd_ctx.ctx)
491                 goto out_unlock;
492
493         if (dst_start < dst_vma->vm_start ||
494             dst_start + len > dst_vma->vm_end)
495                 goto out_unlock;
496
497         err = -EINVAL;
498         /*
499          * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
500          * it will overwrite vm_ops, so vma_is_anonymous must return false.
501          */
502         if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
503             dst_vma->vm_flags & VM_SHARED))
504                 goto out_unlock;
505
506         /*
507          * If this is a HUGETLB vma, pass off to appropriate routine
508          */
509         if (is_vm_hugetlb_page(dst_vma))
510                 return  __mcopy_atomic_hugetlb(dst_mm, dst_vma, dst_start,
511                                                 src_start, len, zeropage);
512
513         if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
514                 goto out_unlock;
515
516         /*
517          * Ensure the dst_vma has a anon_vma or this page
518          * would get a NULL anon_vma when moved in the
519          * dst_vma.
520          */
521         err = -ENOMEM;
522         if (!(dst_vma->vm_flags & VM_SHARED) &&
523             unlikely(anon_vma_prepare(dst_vma)))
524                 goto out_unlock;
525
526         while (src_addr < src_start + len) {
527                 pmd_t dst_pmdval;
528
529                 BUG_ON(dst_addr >= dst_start + len);
530
531                 dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
532                 if (unlikely(!dst_pmd)) {
533                         err = -ENOMEM;
534                         break;
535                 }
536
537                 dst_pmdval = pmd_read_atomic(dst_pmd);
538                 /*
539                  * If the dst_pmd is mapped as THP don't
540                  * override it and just be strict.
541                  */
542                 if (unlikely(pmd_trans_huge(dst_pmdval))) {
543                         err = -EEXIST;
544                         break;
545                 }
546                 if (unlikely(pmd_none(dst_pmdval)) &&
547                     unlikely(__pte_alloc(dst_mm, dst_pmd, dst_addr))) {
548                         err = -ENOMEM;
549                         break;
550                 }
551                 /* If an huge pmd materialized from under us fail */
552                 if (unlikely(pmd_trans_huge(*dst_pmd))) {
553                         err = -EFAULT;
554                         break;
555                 }
556
557                 BUG_ON(pmd_none(*dst_pmd));
558                 BUG_ON(pmd_trans_huge(*dst_pmd));
559
560                 err = mfill_atomic_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
561                                        src_addr, &page, zeropage);
562                 cond_resched();
563
564                 if (unlikely(err == -ENOENT)) {
565                         void *page_kaddr;
566
567                         up_read(&dst_mm->mmap_sem);
568                         BUG_ON(!page);
569
570                         page_kaddr = kmap(page);
571                         err = copy_from_user(page_kaddr,
572                                              (const void __user *) src_addr,
573                                              PAGE_SIZE);
574                         kunmap(page);
575                         if (unlikely(err)) {
576                                 err = -EFAULT;
577                                 goto out;
578                         }
579                         flush_dcache_page(page);
580                         goto retry;
581                 } else
582                         BUG_ON(page);
583
584                 if (!err) {
585                         dst_addr += PAGE_SIZE;
586                         src_addr += PAGE_SIZE;
587                         copied += PAGE_SIZE;
588
589                         if (fatal_signal_pending(current))
590                                 err = -EINTR;
591                 }
592                 if (err)
593                         break;
594         }
595
596 out_unlock:
597         up_read(&dst_mm->mmap_sem);
598 out:
599         if (page)
600                 put_page(page);
601         BUG_ON(copied < 0);
602         BUG_ON(err > 0);
603         BUG_ON(!copied && !err);
604         return copied ? copied : err;
605 }
606
607 ssize_t mcopy_atomic(struct mm_struct *dst_mm, unsigned long dst_start,
608                      unsigned long src_start, unsigned long len,
609                      bool *mmap_changing)
610 {
611         return __mcopy_atomic(dst_mm, dst_start, src_start, len, false,
612                               mmap_changing);
613 }
614
615 ssize_t mfill_zeropage(struct mm_struct *dst_mm, unsigned long start,
616                        unsigned long len, bool *mmap_changing)
617 {
618         return __mcopy_atomic(dst_mm, start, 0, len, true, mmap_changing);
619 }