GNU Linux-libre 4.14.290-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/pagemap.h>
20 #include <linux/shmem_fs.h>
21 #include <asm/tlbflush.h>
22 #include "internal.h"
23
24 static int mcopy_atomic_pte(struct mm_struct *dst_mm,
25                             pmd_t *dst_pmd,
26                             struct vm_area_struct *dst_vma,
27                             unsigned long dst_addr,
28                             unsigned long src_addr,
29                             struct page **pagep)
30 {
31         struct mem_cgroup *memcg;
32         pte_t _dst_pte, *dst_pte;
33         spinlock_t *ptl;
34         void *page_kaddr;
35         int ret;
36         struct page *page;
37         pgoff_t offset, max_off;
38         struct inode *inode;
39
40         if (!*pagep) {
41                 ret = -ENOMEM;
42                 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, dst_vma, dst_addr);
43                 if (!page)
44                         goto out;
45
46                 page_kaddr = kmap_atomic(page);
47                 ret = copy_from_user(page_kaddr,
48                                      (const void __user *) src_addr,
49                                      PAGE_SIZE);
50                 kunmap_atomic(page_kaddr);
51
52                 /* fallback to copy_from_user outside mmap_sem */
53                 if (unlikely(ret)) {
54                         ret = -ENOENT;
55                         *pagep = page;
56                         /* don't free the page */
57                         goto out;
58                 }
59
60                 flush_dcache_page(page);
61         } else {
62                 page = *pagep;
63                 *pagep = NULL;
64         }
65
66         /*
67          * The memory barrier inside __SetPageUptodate makes sure that
68          * preceeding stores to the page contents become visible before
69          * the set_pte_at() write.
70          */
71         __SetPageUptodate(page);
72
73         ret = -ENOMEM;
74         if (mem_cgroup_try_charge(page, dst_mm, GFP_KERNEL, &memcg, false))
75                 goto out_release;
76
77         _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
78         if (dst_vma->vm_flags & VM_WRITE)
79                 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
80
81         dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
82         if (dst_vma->vm_file) {
83                 /* the shmem MAP_PRIVATE case requires checking the i_size */
84                 inode = dst_vma->vm_file->f_inode;
85                 offset = linear_page_index(dst_vma, dst_addr);
86                 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
87                 ret = -EFAULT;
88                 if (unlikely(offset >= max_off))
89                         goto out_release_uncharge_unlock;
90         }
91         ret = -EEXIST;
92         if (!pte_none(*dst_pte))
93                 goto out_release_uncharge_unlock;
94
95         inc_mm_counter(dst_mm, MM_ANONPAGES);
96         page_add_new_anon_rmap(page, dst_vma, dst_addr, false);
97         mem_cgroup_commit_charge(page, memcg, false, false);
98         lru_cache_add_active_or_unevictable(page, dst_vma);
99
100         set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
101
102         /* No need to invalidate - it was non-present before */
103         update_mmu_cache(dst_vma, dst_addr, dst_pte);
104
105         pte_unmap_unlock(dst_pte, ptl);
106         ret = 0;
107 out:
108         return ret;
109 out_release_uncharge_unlock:
110         pte_unmap_unlock(dst_pte, ptl);
111         mem_cgroup_cancel_charge(page, memcg, false);
112 out_release:
113         put_page(page);
114         goto out;
115 }
116
117 static int mfill_zeropage_pte(struct mm_struct *dst_mm,
118                               pmd_t *dst_pmd,
119                               struct vm_area_struct *dst_vma,
120                               unsigned long dst_addr)
121 {
122         pte_t _dst_pte, *dst_pte;
123         spinlock_t *ptl;
124         int ret;
125         pgoff_t offset, max_off;
126         struct inode *inode;
127
128         _dst_pte = pte_mkspecial(pfn_pte(my_zero_pfn(dst_addr),
129                                          dst_vma->vm_page_prot));
130         dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
131         if (dst_vma->vm_file) {
132                 /* the shmem MAP_PRIVATE case requires checking the i_size */
133                 inode = dst_vma->vm_file->f_inode;
134                 offset = linear_page_index(dst_vma, dst_addr);
135                 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
136                 ret = -EFAULT;
137                 if (unlikely(offset >= max_off))
138                         goto out_unlock;
139         }
140         ret = -EEXIST;
141         if (!pte_none(*dst_pte))
142                 goto out_unlock;
143         set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
144         /* No need to invalidate - it was non-present before */
145         update_mmu_cache(dst_vma, dst_addr, dst_pte);
146         ret = 0;
147 out_unlock:
148         pte_unmap_unlock(dst_pte, ptl);
149         return ret;
150 }
151
152 static pmd_t *mm_alloc_pmd(struct mm_struct *mm, unsigned long address)
153 {
154         pgd_t *pgd;
155         p4d_t *p4d;
156         pud_t *pud;
157
158         pgd = pgd_offset(mm, address);
159         p4d = p4d_alloc(mm, pgd, address);
160         if (!p4d)
161                 return NULL;
162         pud = pud_alloc(mm, p4d, address);
163         if (!pud)
164                 return NULL;
165         /*
166          * Note that we didn't run this because the pmd was
167          * missing, the *pmd may be already established and in
168          * turn it may also be a trans_huge_pmd.
169          */
170         return pmd_alloc(mm, pud, address);
171 }
172
173 #ifdef CONFIG_HUGETLB_PAGE
174 /*
175  * __mcopy_atomic processing for HUGETLB vmas.  Note that this routine is
176  * called with mmap_sem held, it will release mmap_sem before returning.
177  */
178 static __always_inline ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,
179                                               struct vm_area_struct *dst_vma,
180                                               unsigned long dst_start,
181                                               unsigned long src_start,
182                                               unsigned long len,
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                         dst_vma = NULL;
316                         goto retry;
317                 } else
318                         BUG_ON(page);
319
320                 if (!err) {
321                         dst_addr += vma_hpagesize;
322                         src_addr += vma_hpagesize;
323                         copied += vma_hpagesize;
324
325                         if (fatal_signal_pending(current))
326                                 err = -EINTR;
327                 }
328                 if (err)
329                         break;
330         }
331
332 out_unlock:
333         up_read(&dst_mm->mmap_sem);
334 out:
335         if (page) {
336                 /*
337                  * We encountered an error and are about to free a newly
338                  * allocated huge page.
339                  *
340                  * Reservation handling is very subtle, and is different for
341                  * private and shared mappings.  See the routine
342                  * restore_reserve_on_error for details.  Unfortunately, we
343                  * can not call restore_reserve_on_error now as it would
344                  * require holding mmap_sem.
345                  *
346                  * If a reservation for the page existed in the reservation
347                  * map of a private mapping, the map was modified to indicate
348                  * the reservation was consumed when the page was allocated.
349                  * We clear the PagePrivate flag now so that the global
350                  * reserve count will not be incremented in free_huge_page.
351                  * The reservation map will still indicate the reservation
352                  * was consumed and possibly prevent later page allocation.
353                  * This is better than leaking a global reservation.  If no
354                  * reservation existed, it is still safe to clear PagePrivate
355                  * as no adjustments to reservation counts were made during
356                  * allocation.
357                  *
358                  * The reservation map for shared mappings indicates which
359                  * pages have reservations.  When a huge page is allocated
360                  * for an address with a reservation, no change is made to
361                  * the reserve map.  In this case PagePrivate will be set
362                  * to indicate that the global reservation count should be
363                  * incremented when the page is freed.  This is the desired
364                  * behavior.  However, when a huge page is allocated for an
365                  * address without a reservation a reservation entry is added
366                  * to the reservation map, and PagePrivate will not be set.
367                  * When the page is freed, the global reserve count will NOT
368                  * be incremented and it will appear as though we have leaked
369                  * reserved page.  In this case, set PagePrivate so that the
370                  * global reserve count will be incremented to match the
371                  * reservation map entry which was created.
372                  *
373                  * Note that vm_alloc_shared is based on the flags of the vma
374                  * for which the page was originally allocated.  dst_vma could
375                  * be different or NULL on error.
376                  */
377                 if (vm_alloc_shared)
378                         SetPagePrivate(page);
379                 else
380                         ClearPagePrivate(page);
381                 put_page(page);
382         }
383         BUG_ON(copied < 0);
384         BUG_ON(err > 0);
385         BUG_ON(!copied && !err);
386         return copied ? copied : err;
387 }
388 #else /* !CONFIG_HUGETLB_PAGE */
389 /* fail at build time if gcc attempts to use this */
390 extern ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,
391                                       struct vm_area_struct *dst_vma,
392                                       unsigned long dst_start,
393                                       unsigned long src_start,
394                                       unsigned long len,
395                                       bool zeropage);
396 #endif /* CONFIG_HUGETLB_PAGE */
397
398 static __always_inline ssize_t mfill_atomic_pte(struct mm_struct *dst_mm,
399                                                 pmd_t *dst_pmd,
400                                                 struct vm_area_struct *dst_vma,
401                                                 unsigned long dst_addr,
402                                                 unsigned long src_addr,
403                                                 struct page **page,
404                                                 bool zeropage)
405 {
406         ssize_t err;
407
408         /*
409          * The normal page fault path for a shmem will invoke the
410          * fault, fill the hole in the file and COW it right away. The
411          * result generates plain anonymous memory. So when we are
412          * asked to fill an hole in a MAP_PRIVATE shmem mapping, we'll
413          * generate anonymous memory directly without actually filling
414          * the hole. For the MAP_PRIVATE case the robustness check
415          * only happens in the pagetable (to verify it's still none)
416          * and not in the radix tree.
417          */
418         if (!(dst_vma->vm_flags & VM_SHARED)) {
419                 if (!zeropage)
420                         err = mcopy_atomic_pte(dst_mm, dst_pmd, dst_vma,
421                                                dst_addr, src_addr, page);
422                 else
423                         err = mfill_zeropage_pte(dst_mm, dst_pmd,
424                                                  dst_vma, dst_addr);
425         } else {
426                 if (!zeropage)
427                         err = shmem_mcopy_atomic_pte(dst_mm, dst_pmd,
428                                                      dst_vma, dst_addr,
429                                                      src_addr, page);
430                 else
431                         err = shmem_mfill_zeropage_pte(dst_mm, dst_pmd,
432                                                        dst_vma, dst_addr);
433         }
434
435         return err;
436 }
437
438 static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,
439                                               unsigned long dst_start,
440                                               unsigned long src_start,
441                                               unsigned long len,
442                                               bool zeropage)
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          * Make sure the vma is not shared, that the dst range is
470          * both valid and fully within a single existing vma.
471          */
472         err = -ENOENT;
473         dst_vma = find_vma(dst_mm, dst_start);
474         if (!dst_vma)
475                 goto out_unlock;
476         /*
477          * Check the vma is registered in uffd, this is required to
478          * enforce the VM_MAYWRITE check done at uffd registration
479          * time.
480          */
481         if (!dst_vma->vm_userfaultfd_ctx.ctx)
482                 goto out_unlock;
483
484         if (dst_start < dst_vma->vm_start ||
485             dst_start + len > dst_vma->vm_end)
486                 goto out_unlock;
487
488         err = -EINVAL;
489         /*
490          * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
491          * it will overwrite vm_ops, so vma_is_anonymous must return false.
492          */
493         if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
494             dst_vma->vm_flags & VM_SHARED))
495                 goto out_unlock;
496
497         /*
498          * If this is a HUGETLB vma, pass off to appropriate routine
499          */
500         if (is_vm_hugetlb_page(dst_vma))
501                 return  __mcopy_atomic_hugetlb(dst_mm, dst_vma, dst_start,
502                                                 src_start, len, zeropage);
503
504         if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
505                 goto out_unlock;
506
507         /*
508          * Ensure the dst_vma has a anon_vma or this page
509          * would get a NULL anon_vma when moved in the
510          * dst_vma.
511          */
512         err = -ENOMEM;
513         if (!(dst_vma->vm_flags & VM_SHARED) &&
514             unlikely(anon_vma_prepare(dst_vma)))
515                 goto out_unlock;
516
517         while (src_addr < src_start + len) {
518                 pmd_t dst_pmdval;
519
520                 BUG_ON(dst_addr >= dst_start + len);
521
522                 dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
523                 if (unlikely(!dst_pmd)) {
524                         err = -ENOMEM;
525                         break;
526                 }
527
528                 dst_pmdval = pmd_read_atomic(dst_pmd);
529                 /*
530                  * If the dst_pmd is mapped as THP don't
531                  * override it and just be strict.
532                  */
533                 if (unlikely(pmd_trans_huge(dst_pmdval))) {
534                         err = -EEXIST;
535                         break;
536                 }
537                 if (unlikely(pmd_none(dst_pmdval)) &&
538                     unlikely(__pte_alloc(dst_mm, dst_pmd, dst_addr))) {
539                         err = -ENOMEM;
540                         break;
541                 }
542                 /* If an huge pmd materialized from under us fail */
543                 if (unlikely(pmd_trans_huge(*dst_pmd))) {
544                         err = -EFAULT;
545                         break;
546                 }
547
548                 BUG_ON(pmd_none(*dst_pmd));
549                 BUG_ON(pmd_trans_huge(*dst_pmd));
550
551                 err = mfill_atomic_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
552                                        src_addr, &page, zeropage);
553                 cond_resched();
554
555                 if (unlikely(err == -ENOENT)) {
556                         void *page_kaddr;
557
558                         up_read(&dst_mm->mmap_sem);
559                         BUG_ON(!page);
560
561                         page_kaddr = kmap(page);
562                         err = copy_from_user(page_kaddr,
563                                              (const void __user *) src_addr,
564                                              PAGE_SIZE);
565                         kunmap(page);
566                         if (unlikely(err)) {
567                                 err = -EFAULT;
568                                 goto out;
569                         }
570                         flush_dcache_page(page);
571                         goto retry;
572                 } else
573                         BUG_ON(page);
574
575                 if (!err) {
576                         dst_addr += PAGE_SIZE;
577                         src_addr += PAGE_SIZE;
578                         copied += PAGE_SIZE;
579
580                         if (fatal_signal_pending(current))
581                                 err = -EINTR;
582                 }
583                 if (err)
584                         break;
585         }
586
587 out_unlock:
588         up_read(&dst_mm->mmap_sem);
589 out:
590         if (page)
591                 put_page(page);
592         BUG_ON(copied < 0);
593         BUG_ON(err > 0);
594         BUG_ON(!copied && !err);
595         return copied ? copied : err;
596 }
597
598 ssize_t mcopy_atomic(struct mm_struct *dst_mm, unsigned long dst_start,
599                      unsigned long src_start, unsigned long len)
600 {
601         return __mcopy_atomic(dst_mm, dst_start, src_start, len, false);
602 }
603
604 ssize_t mfill_zeropage(struct mm_struct *dst_mm, unsigned long start,
605                        unsigned long len)
606 {
607         return __mcopy_atomic(dst_mm, start, 0, len, true);
608 }