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