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