Merge tag 'for-linus' of git://git.kernel.org/pub/scm/virt/kvm/kvm
[platform/kernel/linux-starfive.git] / mm / huge_memory.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Copyright (C) 2009  Red Hat, Inc.
4  */
5
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7
8 #include <linux/mm.h>
9 #include <linux/sched.h>
10 #include <linux/sched/mm.h>
11 #include <linux/sched/coredump.h>
12 #include <linux/sched/numa_balancing.h>
13 #include <linux/highmem.h>
14 #include <linux/hugetlb.h>
15 #include <linux/mmu_notifier.h>
16 #include <linux/rmap.h>
17 #include <linux/swap.h>
18 #include <linux/shrinker.h>
19 #include <linux/mm_inline.h>
20 #include <linux/swapops.h>
21 #include <linux/backing-dev.h>
22 #include <linux/dax.h>
23 #include <linux/khugepaged.h>
24 #include <linux/freezer.h>
25 #include <linux/pfn_t.h>
26 #include <linux/mman.h>
27 #include <linux/memremap.h>
28 #include <linux/pagemap.h>
29 #include <linux/debugfs.h>
30 #include <linux/migrate.h>
31 #include <linux/hashtable.h>
32 #include <linux/userfaultfd_k.h>
33 #include <linux/page_idle.h>
34 #include <linux/shmem_fs.h>
35 #include <linux/oom.h>
36 #include <linux/numa.h>
37 #include <linux/page_owner.h>
38 #include <linux/sched/sysctl.h>
39
40 #include <asm/tlb.h>
41 #include <asm/pgalloc.h>
42 #include "internal.h"
43 #include "swap.h"
44
45 #define CREATE_TRACE_POINTS
46 #include <trace/events/thp.h>
47
48 /*
49  * By default, transparent hugepage support is disabled in order to avoid
50  * risking an increased memory footprint for applications that are not
51  * guaranteed to benefit from it. When transparent hugepage support is
52  * enabled, it is for all mappings, and khugepaged scans all mappings.
53  * Defrag is invoked by khugepaged hugepage allocations and by page faults
54  * for all hugepage allocations.
55  */
56 unsigned long transparent_hugepage_flags __read_mostly =
57 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
58         (1<<TRANSPARENT_HUGEPAGE_FLAG)|
59 #endif
60 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
61         (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
62 #endif
63         (1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
64         (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
65         (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
66
67 static struct shrinker deferred_split_shrinker;
68
69 static atomic_t huge_zero_refcount;
70 struct page *huge_zero_page __read_mostly;
71 unsigned long huge_zero_pfn __read_mostly = ~0UL;
72
73 bool transparent_hugepage_active(struct vm_area_struct *vma)
74 {
75         /* The addr is used to check if the vma size fits */
76         unsigned long addr = (vma->vm_end & HPAGE_PMD_MASK) - HPAGE_PMD_SIZE;
77
78         if (!transhuge_vma_suitable(vma, addr))
79                 return false;
80         if (vma_is_anonymous(vma))
81                 return __transparent_hugepage_enabled(vma);
82         if (vma_is_shmem(vma))
83                 return shmem_huge_enabled(vma);
84         if (transhuge_vma_enabled(vma, vma->vm_flags) && file_thp_enabled(vma))
85                 return true;
86
87         return false;
88 }
89
90 static bool get_huge_zero_page(void)
91 {
92         struct page *zero_page;
93 retry:
94         if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
95                 return true;
96
97         zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
98                         HPAGE_PMD_ORDER);
99         if (!zero_page) {
100                 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
101                 return false;
102         }
103         count_vm_event(THP_ZERO_PAGE_ALLOC);
104         preempt_disable();
105         if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
106                 preempt_enable();
107                 __free_pages(zero_page, compound_order(zero_page));
108                 goto retry;
109         }
110         WRITE_ONCE(huge_zero_pfn, page_to_pfn(zero_page));
111
112         /* We take additional reference here. It will be put back by shrinker */
113         atomic_set(&huge_zero_refcount, 2);
114         preempt_enable();
115         return true;
116 }
117
118 static void put_huge_zero_page(void)
119 {
120         /*
121          * Counter should never go to zero here. Only shrinker can put
122          * last reference.
123          */
124         BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
125 }
126
127 struct page *mm_get_huge_zero_page(struct mm_struct *mm)
128 {
129         if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
130                 return READ_ONCE(huge_zero_page);
131
132         if (!get_huge_zero_page())
133                 return NULL;
134
135         if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
136                 put_huge_zero_page();
137
138         return READ_ONCE(huge_zero_page);
139 }
140
141 void mm_put_huge_zero_page(struct mm_struct *mm)
142 {
143         if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags))
144                 put_huge_zero_page();
145 }
146
147 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
148                                         struct shrink_control *sc)
149 {
150         /* we can free zero page only if last reference remains */
151         return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
152 }
153
154 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
155                                        struct shrink_control *sc)
156 {
157         if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
158                 struct page *zero_page = xchg(&huge_zero_page, NULL);
159                 BUG_ON(zero_page == NULL);
160                 WRITE_ONCE(huge_zero_pfn, ~0UL);
161                 __free_pages(zero_page, compound_order(zero_page));
162                 return HPAGE_PMD_NR;
163         }
164
165         return 0;
166 }
167
168 static struct shrinker huge_zero_page_shrinker = {
169         .count_objects = shrink_huge_zero_page_count,
170         .scan_objects = shrink_huge_zero_page_scan,
171         .seeks = DEFAULT_SEEKS,
172 };
173
174 #ifdef CONFIG_SYSFS
175 static ssize_t enabled_show(struct kobject *kobj,
176                             struct kobj_attribute *attr, char *buf)
177 {
178         const char *output;
179
180         if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
181                 output = "[always] madvise never";
182         else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
183                           &transparent_hugepage_flags))
184                 output = "always [madvise] never";
185         else
186                 output = "always madvise [never]";
187
188         return sysfs_emit(buf, "%s\n", output);
189 }
190
191 static ssize_t enabled_store(struct kobject *kobj,
192                              struct kobj_attribute *attr,
193                              const char *buf, size_t count)
194 {
195         ssize_t ret = count;
196
197         if (sysfs_streq(buf, "always")) {
198                 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
199                 set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
200         } else if (sysfs_streq(buf, "madvise")) {
201                 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
202                 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
203         } else if (sysfs_streq(buf, "never")) {
204                 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags);
205                 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags);
206         } else
207                 ret = -EINVAL;
208
209         if (ret > 0) {
210                 int err = start_stop_khugepaged();
211                 if (err)
212                         ret = err;
213         }
214         return ret;
215 }
216 static struct kobj_attribute enabled_attr =
217         __ATTR(enabled, 0644, enabled_show, enabled_store);
218
219 ssize_t single_hugepage_flag_show(struct kobject *kobj,
220                                   struct kobj_attribute *attr, char *buf,
221                                   enum transparent_hugepage_flag flag)
222 {
223         return sysfs_emit(buf, "%d\n",
224                           !!test_bit(flag, &transparent_hugepage_flags));
225 }
226
227 ssize_t single_hugepage_flag_store(struct kobject *kobj,
228                                  struct kobj_attribute *attr,
229                                  const char *buf, size_t count,
230                                  enum transparent_hugepage_flag flag)
231 {
232         unsigned long value;
233         int ret;
234
235         ret = kstrtoul(buf, 10, &value);
236         if (ret < 0)
237                 return ret;
238         if (value > 1)
239                 return -EINVAL;
240
241         if (value)
242                 set_bit(flag, &transparent_hugepage_flags);
243         else
244                 clear_bit(flag, &transparent_hugepage_flags);
245
246         return count;
247 }
248
249 static ssize_t defrag_show(struct kobject *kobj,
250                            struct kobj_attribute *attr, char *buf)
251 {
252         const char *output;
253
254         if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
255                      &transparent_hugepage_flags))
256                 output = "[always] defer defer+madvise madvise never";
257         else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
258                           &transparent_hugepage_flags))
259                 output = "always [defer] defer+madvise madvise never";
260         else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,
261                           &transparent_hugepage_flags))
262                 output = "always defer [defer+madvise] madvise never";
263         else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,
264                           &transparent_hugepage_flags))
265                 output = "always defer defer+madvise [madvise] never";
266         else
267                 output = "always defer defer+madvise madvise [never]";
268
269         return sysfs_emit(buf, "%s\n", output);
270 }
271
272 static ssize_t defrag_store(struct kobject *kobj,
273                             struct kobj_attribute *attr,
274                             const char *buf, size_t count)
275 {
276         if (sysfs_streq(buf, "always")) {
277                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
278                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
279                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
280                 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
281         } else if (sysfs_streq(buf, "defer+madvise")) {
282                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
283                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
284                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
285                 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
286         } else if (sysfs_streq(buf, "defer")) {
287                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
288                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
289                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
290                 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
291         } else if (sysfs_streq(buf, "madvise")) {
292                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
293                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
294                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
295                 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
296         } else if (sysfs_streq(buf, "never")) {
297                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags);
298                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags);
299                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags);
300                 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags);
301         } else
302                 return -EINVAL;
303
304         return count;
305 }
306 static struct kobj_attribute defrag_attr =
307         __ATTR(defrag, 0644, defrag_show, defrag_store);
308
309 static ssize_t use_zero_page_show(struct kobject *kobj,
310                                   struct kobj_attribute *attr, char *buf)
311 {
312         return single_hugepage_flag_show(kobj, attr, buf,
313                                          TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
314 }
315 static ssize_t use_zero_page_store(struct kobject *kobj,
316                 struct kobj_attribute *attr, const char *buf, size_t count)
317 {
318         return single_hugepage_flag_store(kobj, attr, buf, count,
319                                  TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
320 }
321 static struct kobj_attribute use_zero_page_attr =
322         __ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
323
324 static ssize_t hpage_pmd_size_show(struct kobject *kobj,
325                                    struct kobj_attribute *attr, char *buf)
326 {
327         return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE);
328 }
329 static struct kobj_attribute hpage_pmd_size_attr =
330         __ATTR_RO(hpage_pmd_size);
331
332 static struct attribute *hugepage_attr[] = {
333         &enabled_attr.attr,
334         &defrag_attr.attr,
335         &use_zero_page_attr.attr,
336         &hpage_pmd_size_attr.attr,
337 #ifdef CONFIG_SHMEM
338         &shmem_enabled_attr.attr,
339 #endif
340         NULL,
341 };
342
343 static const struct attribute_group hugepage_attr_group = {
344         .attrs = hugepage_attr,
345 };
346
347 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
348 {
349         int err;
350
351         *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
352         if (unlikely(!*hugepage_kobj)) {
353                 pr_err("failed to create transparent hugepage kobject\n");
354                 return -ENOMEM;
355         }
356
357         err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
358         if (err) {
359                 pr_err("failed to register transparent hugepage group\n");
360                 goto delete_obj;
361         }
362
363         err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
364         if (err) {
365                 pr_err("failed to register transparent hugepage group\n");
366                 goto remove_hp_group;
367         }
368
369         return 0;
370
371 remove_hp_group:
372         sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
373 delete_obj:
374         kobject_put(*hugepage_kobj);
375         return err;
376 }
377
378 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
379 {
380         sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
381         sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
382         kobject_put(hugepage_kobj);
383 }
384 #else
385 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
386 {
387         return 0;
388 }
389
390 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
391 {
392 }
393 #endif /* CONFIG_SYSFS */
394
395 static int __init hugepage_init(void)
396 {
397         int err;
398         struct kobject *hugepage_kobj;
399
400         if (!has_transparent_hugepage()) {
401                 /*
402                  * Hardware doesn't support hugepages, hence disable
403                  * DAX PMD support.
404                  */
405                 transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_NEVER_DAX;
406                 return -EINVAL;
407         }
408
409         /*
410          * hugepages can't be allocated by the buddy allocator
411          */
412         MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER >= MAX_ORDER);
413         /*
414          * we use page->mapping and page->index in second tail page
415          * as list_head: assuming THP order >= 2
416          */
417         MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER < 2);
418
419         err = hugepage_init_sysfs(&hugepage_kobj);
420         if (err)
421                 goto err_sysfs;
422
423         err = khugepaged_init();
424         if (err)
425                 goto err_slab;
426
427         err = register_shrinker(&huge_zero_page_shrinker);
428         if (err)
429                 goto err_hzp_shrinker;
430         err = register_shrinker(&deferred_split_shrinker);
431         if (err)
432                 goto err_split_shrinker;
433
434         /*
435          * By default disable transparent hugepages on smaller systems,
436          * where the extra memory used could hurt more than TLB overhead
437          * is likely to save.  The admin can still enable it through /sys.
438          */
439         if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) {
440                 transparent_hugepage_flags = 0;
441                 return 0;
442         }
443
444         err = start_stop_khugepaged();
445         if (err)
446                 goto err_khugepaged;
447
448         return 0;
449 err_khugepaged:
450         unregister_shrinker(&deferred_split_shrinker);
451 err_split_shrinker:
452         unregister_shrinker(&huge_zero_page_shrinker);
453 err_hzp_shrinker:
454         khugepaged_destroy();
455 err_slab:
456         hugepage_exit_sysfs(hugepage_kobj);
457 err_sysfs:
458         return err;
459 }
460 subsys_initcall(hugepage_init);
461
462 static int __init setup_transparent_hugepage(char *str)
463 {
464         int ret = 0;
465         if (!str)
466                 goto out;
467         if (!strcmp(str, "always")) {
468                 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
469                         &transparent_hugepage_flags);
470                 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
471                           &transparent_hugepage_flags);
472                 ret = 1;
473         } else if (!strcmp(str, "madvise")) {
474                 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
475                           &transparent_hugepage_flags);
476                 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
477                         &transparent_hugepage_flags);
478                 ret = 1;
479         } else if (!strcmp(str, "never")) {
480                 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
481                           &transparent_hugepage_flags);
482                 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
483                           &transparent_hugepage_flags);
484                 ret = 1;
485         }
486 out:
487         if (!ret)
488                 pr_warn("transparent_hugepage= cannot parse, ignored\n");
489         return ret;
490 }
491 __setup("transparent_hugepage=", setup_transparent_hugepage);
492
493 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
494 {
495         if (likely(vma->vm_flags & VM_WRITE))
496                 pmd = pmd_mkwrite(pmd);
497         return pmd;
498 }
499
500 #ifdef CONFIG_MEMCG
501 static inline struct deferred_split *get_deferred_split_queue(struct page *page)
502 {
503         struct mem_cgroup *memcg = page_memcg(compound_head(page));
504         struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
505
506         if (memcg)
507                 return &memcg->deferred_split_queue;
508         else
509                 return &pgdat->deferred_split_queue;
510 }
511 #else
512 static inline struct deferred_split *get_deferred_split_queue(struct page *page)
513 {
514         struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
515
516         return &pgdat->deferred_split_queue;
517 }
518 #endif
519
520 void prep_transhuge_page(struct page *page)
521 {
522         /*
523          * we use page->mapping and page->indexlru in second tail page
524          * as list_head: assuming THP order >= 2
525          */
526
527         INIT_LIST_HEAD(page_deferred_list(page));
528         set_compound_page_dtor(page, TRANSHUGE_PAGE_DTOR);
529 }
530
531 static inline bool is_transparent_hugepage(struct page *page)
532 {
533         if (!PageCompound(page))
534                 return false;
535
536         page = compound_head(page);
537         return is_huge_zero_page(page) ||
538                page[1].compound_dtor == TRANSHUGE_PAGE_DTOR;
539 }
540
541 static unsigned long __thp_get_unmapped_area(struct file *filp,
542                 unsigned long addr, unsigned long len,
543                 loff_t off, unsigned long flags, unsigned long size)
544 {
545         loff_t off_end = off + len;
546         loff_t off_align = round_up(off, size);
547         unsigned long len_pad, ret;
548
549         if (off_end <= off_align || (off_end - off_align) < size)
550                 return 0;
551
552         len_pad = len + size;
553         if (len_pad < len || (off + len_pad) < off)
554                 return 0;
555
556         ret = current->mm->get_unmapped_area(filp, addr, len_pad,
557                                               off >> PAGE_SHIFT, flags);
558
559         /*
560          * The failure might be due to length padding. The caller will retry
561          * without the padding.
562          */
563         if (IS_ERR_VALUE(ret))
564                 return 0;
565
566         /*
567          * Do not try to align to THP boundary if allocation at the address
568          * hint succeeds.
569          */
570         if (ret == addr)
571                 return addr;
572
573         ret += (off - ret) & (size - 1);
574         return ret;
575 }
576
577 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
578                 unsigned long len, unsigned long pgoff, unsigned long flags)
579 {
580         unsigned long ret;
581         loff_t off = (loff_t)pgoff << PAGE_SHIFT;
582
583         ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE);
584         if (ret)
585                 return ret;
586
587         return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
588 }
589 EXPORT_SYMBOL_GPL(thp_get_unmapped_area);
590
591 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf,
592                         struct page *page, gfp_t gfp)
593 {
594         struct vm_area_struct *vma = vmf->vma;
595         pgtable_t pgtable;
596         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
597         vm_fault_t ret = 0;
598
599         VM_BUG_ON_PAGE(!PageCompound(page), page);
600
601         if (mem_cgroup_charge(page_folio(page), vma->vm_mm, gfp)) {
602                 put_page(page);
603                 count_vm_event(THP_FAULT_FALLBACK);
604                 count_vm_event(THP_FAULT_FALLBACK_CHARGE);
605                 return VM_FAULT_FALLBACK;
606         }
607         cgroup_throttle_swaprate(page, gfp);
608
609         pgtable = pte_alloc_one(vma->vm_mm);
610         if (unlikely(!pgtable)) {
611                 ret = VM_FAULT_OOM;
612                 goto release;
613         }
614
615         clear_huge_page(page, vmf->address, HPAGE_PMD_NR);
616         /*
617          * The memory barrier inside __SetPageUptodate makes sure that
618          * clear_huge_page writes become visible before the set_pmd_at()
619          * write.
620          */
621         __SetPageUptodate(page);
622
623         vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
624         if (unlikely(!pmd_none(*vmf->pmd))) {
625                 goto unlock_release;
626         } else {
627                 pmd_t entry;
628
629                 ret = check_stable_address_space(vma->vm_mm);
630                 if (ret)
631                         goto unlock_release;
632
633                 /* Deliver the page fault to userland */
634                 if (userfaultfd_missing(vma)) {
635                         spin_unlock(vmf->ptl);
636                         put_page(page);
637                         pte_free(vma->vm_mm, pgtable);
638                         ret = handle_userfault(vmf, VM_UFFD_MISSING);
639                         VM_BUG_ON(ret & VM_FAULT_FALLBACK);
640                         return ret;
641                 }
642
643                 entry = mk_huge_pmd(page, vma->vm_page_prot);
644                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
645                 page_add_new_anon_rmap(page, vma, haddr);
646                 lru_cache_add_inactive_or_unevictable(page, vma);
647                 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
648                 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
649                 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
650                 add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
651                 mm_inc_nr_ptes(vma->vm_mm);
652                 spin_unlock(vmf->ptl);
653                 count_vm_event(THP_FAULT_ALLOC);
654                 count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC);
655         }
656
657         return 0;
658 unlock_release:
659         spin_unlock(vmf->ptl);
660 release:
661         if (pgtable)
662                 pte_free(vma->vm_mm, pgtable);
663         put_page(page);
664         return ret;
665
666 }
667
668 /*
669  * always: directly stall for all thp allocations
670  * defer: wake kswapd and fail if not immediately available
671  * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise
672  *                fail if not immediately available
673  * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately
674  *          available
675  * never: never stall for any thp allocation
676  */
677 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)
678 {
679         const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE);
680
681         /* Always do synchronous compaction */
682         if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
683                 return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);
684
685         /* Kick kcompactd and fail quickly */
686         if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
687                 return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;
688
689         /* Synchronous compaction if madvised, otherwise kick kcompactd */
690         if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags))
691                 return GFP_TRANSHUGE_LIGHT |
692                         (vma_madvised ? __GFP_DIRECT_RECLAIM :
693                                         __GFP_KSWAPD_RECLAIM);
694
695         /* Only do synchronous compaction if madvised */
696         if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
697                 return GFP_TRANSHUGE_LIGHT |
698                        (vma_madvised ? __GFP_DIRECT_RECLAIM : 0);
699
700         return GFP_TRANSHUGE_LIGHT;
701 }
702
703 /* Caller must hold page table lock. */
704 static void set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
705                 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
706                 struct page *zero_page)
707 {
708         pmd_t entry;
709         if (!pmd_none(*pmd))
710                 return;
711         entry = mk_pmd(zero_page, vma->vm_page_prot);
712         entry = pmd_mkhuge(entry);
713         if (pgtable)
714                 pgtable_trans_huge_deposit(mm, pmd, pgtable);
715         set_pmd_at(mm, haddr, pmd, entry);
716         mm_inc_nr_ptes(mm);
717 }
718
719 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf)
720 {
721         struct vm_area_struct *vma = vmf->vma;
722         gfp_t gfp;
723         struct folio *folio;
724         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
725
726         if (!transhuge_vma_suitable(vma, haddr))
727                 return VM_FAULT_FALLBACK;
728         if (unlikely(anon_vma_prepare(vma)))
729                 return VM_FAULT_OOM;
730         khugepaged_enter(vma, vma->vm_flags);
731
732         if (!(vmf->flags & FAULT_FLAG_WRITE) &&
733                         !mm_forbids_zeropage(vma->vm_mm) &&
734                         transparent_hugepage_use_zero_page()) {
735                 pgtable_t pgtable;
736                 struct page *zero_page;
737                 vm_fault_t ret;
738                 pgtable = pte_alloc_one(vma->vm_mm);
739                 if (unlikely(!pgtable))
740                         return VM_FAULT_OOM;
741                 zero_page = mm_get_huge_zero_page(vma->vm_mm);
742                 if (unlikely(!zero_page)) {
743                         pte_free(vma->vm_mm, pgtable);
744                         count_vm_event(THP_FAULT_FALLBACK);
745                         return VM_FAULT_FALLBACK;
746                 }
747                 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
748                 ret = 0;
749                 if (pmd_none(*vmf->pmd)) {
750                         ret = check_stable_address_space(vma->vm_mm);
751                         if (ret) {
752                                 spin_unlock(vmf->ptl);
753                                 pte_free(vma->vm_mm, pgtable);
754                         } else if (userfaultfd_missing(vma)) {
755                                 spin_unlock(vmf->ptl);
756                                 pte_free(vma->vm_mm, pgtable);
757                                 ret = handle_userfault(vmf, VM_UFFD_MISSING);
758                                 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
759                         } else {
760                                 set_huge_zero_page(pgtable, vma->vm_mm, vma,
761                                                    haddr, vmf->pmd, zero_page);
762                                 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
763                                 spin_unlock(vmf->ptl);
764                         }
765                 } else {
766                         spin_unlock(vmf->ptl);
767                         pte_free(vma->vm_mm, pgtable);
768                 }
769                 return ret;
770         }
771         gfp = vma_thp_gfp_mask(vma);
772         folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, vma, haddr, true);
773         if (unlikely(!folio)) {
774                 count_vm_event(THP_FAULT_FALLBACK);
775                 return VM_FAULT_FALLBACK;
776         }
777         return __do_huge_pmd_anonymous_page(vmf, &folio->page, gfp);
778 }
779
780 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
781                 pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write,
782                 pgtable_t pgtable)
783 {
784         struct mm_struct *mm = vma->vm_mm;
785         pmd_t entry;
786         spinlock_t *ptl;
787
788         ptl = pmd_lock(mm, pmd);
789         if (!pmd_none(*pmd)) {
790                 if (write) {
791                         if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) {
792                                 WARN_ON_ONCE(!is_huge_zero_pmd(*pmd));
793                                 goto out_unlock;
794                         }
795                         entry = pmd_mkyoung(*pmd);
796                         entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
797                         if (pmdp_set_access_flags(vma, addr, pmd, entry, 1))
798                                 update_mmu_cache_pmd(vma, addr, pmd);
799                 }
800
801                 goto out_unlock;
802         }
803
804         entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
805         if (pfn_t_devmap(pfn))
806                 entry = pmd_mkdevmap(entry);
807         if (write) {
808                 entry = pmd_mkyoung(pmd_mkdirty(entry));
809                 entry = maybe_pmd_mkwrite(entry, vma);
810         }
811
812         if (pgtable) {
813                 pgtable_trans_huge_deposit(mm, pmd, pgtable);
814                 mm_inc_nr_ptes(mm);
815                 pgtable = NULL;
816         }
817
818         set_pmd_at(mm, addr, pmd, entry);
819         update_mmu_cache_pmd(vma, addr, pmd);
820
821 out_unlock:
822         spin_unlock(ptl);
823         if (pgtable)
824                 pte_free(mm, pgtable);
825 }
826
827 /**
828  * vmf_insert_pfn_pmd_prot - insert a pmd size pfn
829  * @vmf: Structure describing the fault
830  * @pfn: pfn to insert
831  * @pgprot: page protection to use
832  * @write: whether it's a write fault
833  *
834  * Insert a pmd size pfn. See vmf_insert_pfn() for additional info and
835  * also consult the vmf_insert_mixed_prot() documentation when
836  * @pgprot != @vmf->vma->vm_page_prot.
837  *
838  * Return: vm_fault_t value.
839  */
840 vm_fault_t vmf_insert_pfn_pmd_prot(struct vm_fault *vmf, pfn_t pfn,
841                                    pgprot_t pgprot, bool write)
842 {
843         unsigned long addr = vmf->address & PMD_MASK;
844         struct vm_area_struct *vma = vmf->vma;
845         pgtable_t pgtable = NULL;
846
847         /*
848          * If we had pmd_special, we could avoid all these restrictions,
849          * but we need to be consistent with PTEs and architectures that
850          * can't support a 'special' bit.
851          */
852         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
853                         !pfn_t_devmap(pfn));
854         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
855                                                 (VM_PFNMAP|VM_MIXEDMAP));
856         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
857
858         if (addr < vma->vm_start || addr >= vma->vm_end)
859                 return VM_FAULT_SIGBUS;
860
861         if (arch_needs_pgtable_deposit()) {
862                 pgtable = pte_alloc_one(vma->vm_mm);
863                 if (!pgtable)
864                         return VM_FAULT_OOM;
865         }
866
867         track_pfn_insert(vma, &pgprot, pfn);
868
869         insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable);
870         return VM_FAULT_NOPAGE;
871 }
872 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd_prot);
873
874 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
875 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)
876 {
877         if (likely(vma->vm_flags & VM_WRITE))
878                 pud = pud_mkwrite(pud);
879         return pud;
880 }
881
882 static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr,
883                 pud_t *pud, pfn_t pfn, pgprot_t prot, bool write)
884 {
885         struct mm_struct *mm = vma->vm_mm;
886         pud_t entry;
887         spinlock_t *ptl;
888
889         ptl = pud_lock(mm, pud);
890         if (!pud_none(*pud)) {
891                 if (write) {
892                         if (pud_pfn(*pud) != pfn_t_to_pfn(pfn)) {
893                                 WARN_ON_ONCE(!is_huge_zero_pud(*pud));
894                                 goto out_unlock;
895                         }
896                         entry = pud_mkyoung(*pud);
897                         entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma);
898                         if (pudp_set_access_flags(vma, addr, pud, entry, 1))
899                                 update_mmu_cache_pud(vma, addr, pud);
900                 }
901                 goto out_unlock;
902         }
903
904         entry = pud_mkhuge(pfn_t_pud(pfn, prot));
905         if (pfn_t_devmap(pfn))
906                 entry = pud_mkdevmap(entry);
907         if (write) {
908                 entry = pud_mkyoung(pud_mkdirty(entry));
909                 entry = maybe_pud_mkwrite(entry, vma);
910         }
911         set_pud_at(mm, addr, pud, entry);
912         update_mmu_cache_pud(vma, addr, pud);
913
914 out_unlock:
915         spin_unlock(ptl);
916 }
917
918 /**
919  * vmf_insert_pfn_pud_prot - insert a pud size pfn
920  * @vmf: Structure describing the fault
921  * @pfn: pfn to insert
922  * @pgprot: page protection to use
923  * @write: whether it's a write fault
924  *
925  * Insert a pud size pfn. See vmf_insert_pfn() for additional info and
926  * also consult the vmf_insert_mixed_prot() documentation when
927  * @pgprot != @vmf->vma->vm_page_prot.
928  *
929  * Return: vm_fault_t value.
930  */
931 vm_fault_t vmf_insert_pfn_pud_prot(struct vm_fault *vmf, pfn_t pfn,
932                                    pgprot_t pgprot, bool write)
933 {
934         unsigned long addr = vmf->address & PUD_MASK;
935         struct vm_area_struct *vma = vmf->vma;
936
937         /*
938          * If we had pud_special, we could avoid all these restrictions,
939          * but we need to be consistent with PTEs and architectures that
940          * can't support a 'special' bit.
941          */
942         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) &&
943                         !pfn_t_devmap(pfn));
944         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
945                                                 (VM_PFNMAP|VM_MIXEDMAP));
946         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
947
948         if (addr < vma->vm_start || addr >= vma->vm_end)
949                 return VM_FAULT_SIGBUS;
950
951         track_pfn_insert(vma, &pgprot, pfn);
952
953         insert_pfn_pud(vma, addr, vmf->pud, pfn, pgprot, write);
954         return VM_FAULT_NOPAGE;
955 }
956 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud_prot);
957 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
958
959 static void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
960                 pmd_t *pmd, int flags)
961 {
962         pmd_t _pmd;
963
964         _pmd = pmd_mkyoung(*pmd);
965         if (flags & FOLL_WRITE)
966                 _pmd = pmd_mkdirty(_pmd);
967         if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
968                                 pmd, _pmd, flags & FOLL_WRITE))
969                 update_mmu_cache_pmd(vma, addr, pmd);
970 }
971
972 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
973                 pmd_t *pmd, int flags, struct dev_pagemap **pgmap)
974 {
975         unsigned long pfn = pmd_pfn(*pmd);
976         struct mm_struct *mm = vma->vm_mm;
977         struct page *page;
978
979         assert_spin_locked(pmd_lockptr(mm, pmd));
980
981         /*
982          * When we COW a devmap PMD entry, we split it into PTEs, so we should
983          * not be in this function with `flags & FOLL_COW` set.
984          */
985         WARN_ONCE(flags & FOLL_COW, "mm: In follow_devmap_pmd with FOLL_COW set");
986
987         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
988         if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
989                          (FOLL_PIN | FOLL_GET)))
990                 return NULL;
991
992         if (flags & FOLL_WRITE && !pmd_write(*pmd))
993                 return NULL;
994
995         if (pmd_present(*pmd) && pmd_devmap(*pmd))
996                 /* pass */;
997         else
998                 return NULL;
999
1000         if (flags & FOLL_TOUCH)
1001                 touch_pmd(vma, addr, pmd, flags);
1002
1003         /*
1004          * device mapped pages can only be returned if the
1005          * caller will manage the page reference count.
1006          */
1007         if (!(flags & (FOLL_GET | FOLL_PIN)))
1008                 return ERR_PTR(-EEXIST);
1009
1010         pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1011         *pgmap = get_dev_pagemap(pfn, *pgmap);
1012         if (!*pgmap)
1013                 return ERR_PTR(-EFAULT);
1014         page = pfn_to_page(pfn);
1015         if (!try_grab_page(page, flags))
1016                 page = ERR_PTR(-ENOMEM);
1017
1018         return page;
1019 }
1020
1021 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1022                   pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1023                   struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1024 {
1025         spinlock_t *dst_ptl, *src_ptl;
1026         struct page *src_page;
1027         pmd_t pmd;
1028         pgtable_t pgtable = NULL;
1029         int ret = -ENOMEM;
1030
1031         /* Skip if can be re-fill on fault */
1032         if (!vma_is_anonymous(dst_vma))
1033                 return 0;
1034
1035         pgtable = pte_alloc_one(dst_mm);
1036         if (unlikely(!pgtable))
1037                 goto out;
1038
1039         dst_ptl = pmd_lock(dst_mm, dst_pmd);
1040         src_ptl = pmd_lockptr(src_mm, src_pmd);
1041         spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1042
1043         ret = -EAGAIN;
1044         pmd = *src_pmd;
1045
1046 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1047         if (unlikely(is_swap_pmd(pmd))) {
1048                 swp_entry_t entry = pmd_to_swp_entry(pmd);
1049
1050                 VM_BUG_ON(!is_pmd_migration_entry(pmd));
1051                 if (!is_readable_migration_entry(entry)) {
1052                         entry = make_readable_migration_entry(
1053                                                         swp_offset(entry));
1054                         pmd = swp_entry_to_pmd(entry);
1055                         if (pmd_swp_soft_dirty(*src_pmd))
1056                                 pmd = pmd_swp_mksoft_dirty(pmd);
1057                         if (pmd_swp_uffd_wp(*src_pmd))
1058                                 pmd = pmd_swp_mkuffd_wp(pmd);
1059                         set_pmd_at(src_mm, addr, src_pmd, pmd);
1060                 }
1061                 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1062                 mm_inc_nr_ptes(dst_mm);
1063                 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1064                 if (!userfaultfd_wp(dst_vma))
1065                         pmd = pmd_swp_clear_uffd_wp(pmd);
1066                 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1067                 ret = 0;
1068                 goto out_unlock;
1069         }
1070 #endif
1071
1072         if (unlikely(!pmd_trans_huge(pmd))) {
1073                 pte_free(dst_mm, pgtable);
1074                 goto out_unlock;
1075         }
1076         /*
1077          * When page table lock is held, the huge zero pmd should not be
1078          * under splitting since we don't split the page itself, only pmd to
1079          * a page table.
1080          */
1081         if (is_huge_zero_pmd(pmd)) {
1082                 /*
1083                  * get_huge_zero_page() will never allocate a new page here,
1084                  * since we already have a zero page to copy. It just takes a
1085                  * reference.
1086                  */
1087                 mm_get_huge_zero_page(dst_mm);
1088                 goto out_zero_page;
1089         }
1090
1091         src_page = pmd_page(pmd);
1092         VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1093
1094         get_page(src_page);
1095         if (unlikely(page_try_dup_anon_rmap(src_page, true, src_vma))) {
1096                 /* Page maybe pinned: split and retry the fault on PTEs. */
1097                 put_page(src_page);
1098                 pte_free(dst_mm, pgtable);
1099                 spin_unlock(src_ptl);
1100                 spin_unlock(dst_ptl);
1101                 __split_huge_pmd(src_vma, src_pmd, addr, false, NULL);
1102                 return -EAGAIN;
1103         }
1104         add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1105 out_zero_page:
1106         mm_inc_nr_ptes(dst_mm);
1107         pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1108         pmdp_set_wrprotect(src_mm, addr, src_pmd);
1109         if (!userfaultfd_wp(dst_vma))
1110                 pmd = pmd_clear_uffd_wp(pmd);
1111         pmd = pmd_mkold(pmd_wrprotect(pmd));
1112         set_pmd_at(dst_mm, addr, dst_pmd, pmd);
1113
1114         ret = 0;
1115 out_unlock:
1116         spin_unlock(src_ptl);
1117         spin_unlock(dst_ptl);
1118 out:
1119         return ret;
1120 }
1121
1122 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1123 static void touch_pud(struct vm_area_struct *vma, unsigned long addr,
1124                 pud_t *pud, int flags)
1125 {
1126         pud_t _pud;
1127
1128         _pud = pud_mkyoung(*pud);
1129         if (flags & FOLL_WRITE)
1130                 _pud = pud_mkdirty(_pud);
1131         if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK,
1132                                 pud, _pud, flags & FOLL_WRITE))
1133                 update_mmu_cache_pud(vma, addr, pud);
1134 }
1135
1136 struct page *follow_devmap_pud(struct vm_area_struct *vma, unsigned long addr,
1137                 pud_t *pud, int flags, struct dev_pagemap **pgmap)
1138 {
1139         unsigned long pfn = pud_pfn(*pud);
1140         struct mm_struct *mm = vma->vm_mm;
1141         struct page *page;
1142
1143         assert_spin_locked(pud_lockptr(mm, pud));
1144
1145         if (flags & FOLL_WRITE && !pud_write(*pud))
1146                 return NULL;
1147
1148         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
1149         if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
1150                          (FOLL_PIN | FOLL_GET)))
1151                 return NULL;
1152
1153         if (pud_present(*pud) && pud_devmap(*pud))
1154                 /* pass */;
1155         else
1156                 return NULL;
1157
1158         if (flags & FOLL_TOUCH)
1159                 touch_pud(vma, addr, pud, flags);
1160
1161         /*
1162          * device mapped pages can only be returned if the
1163          * caller will manage the page reference count.
1164          *
1165          * At least one of FOLL_GET | FOLL_PIN must be set, so assert that here:
1166          */
1167         if (!(flags & (FOLL_GET | FOLL_PIN)))
1168                 return ERR_PTR(-EEXIST);
1169
1170         pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
1171         *pgmap = get_dev_pagemap(pfn, *pgmap);
1172         if (!*pgmap)
1173                 return ERR_PTR(-EFAULT);
1174         page = pfn_to_page(pfn);
1175         if (!try_grab_page(page, flags))
1176                 page = ERR_PTR(-ENOMEM);
1177
1178         return page;
1179 }
1180
1181 int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1182                   pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1183                   struct vm_area_struct *vma)
1184 {
1185         spinlock_t *dst_ptl, *src_ptl;
1186         pud_t pud;
1187         int ret;
1188
1189         dst_ptl = pud_lock(dst_mm, dst_pud);
1190         src_ptl = pud_lockptr(src_mm, src_pud);
1191         spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1192
1193         ret = -EAGAIN;
1194         pud = *src_pud;
1195         if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud)))
1196                 goto out_unlock;
1197
1198         /*
1199          * When page table lock is held, the huge zero pud should not be
1200          * under splitting since we don't split the page itself, only pud to
1201          * a page table.
1202          */
1203         if (is_huge_zero_pud(pud)) {
1204                 /* No huge zero pud yet */
1205         }
1206
1207         /*
1208          * TODO: once we support anonymous pages, use page_try_dup_anon_rmap()
1209          * and split if duplicating fails.
1210          */
1211         pudp_set_wrprotect(src_mm, addr, src_pud);
1212         pud = pud_mkold(pud_wrprotect(pud));
1213         set_pud_at(dst_mm, addr, dst_pud, pud);
1214
1215         ret = 0;
1216 out_unlock:
1217         spin_unlock(src_ptl);
1218         spin_unlock(dst_ptl);
1219         return ret;
1220 }
1221
1222 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)
1223 {
1224         pud_t entry;
1225         unsigned long haddr;
1226         bool write = vmf->flags & FAULT_FLAG_WRITE;
1227
1228         vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud);
1229         if (unlikely(!pud_same(*vmf->pud, orig_pud)))
1230                 goto unlock;
1231
1232         entry = pud_mkyoung(orig_pud);
1233         if (write)
1234                 entry = pud_mkdirty(entry);
1235         haddr = vmf->address & HPAGE_PUD_MASK;
1236         if (pudp_set_access_flags(vmf->vma, haddr, vmf->pud, entry, write))
1237                 update_mmu_cache_pud(vmf->vma, vmf->address, vmf->pud);
1238
1239 unlock:
1240         spin_unlock(vmf->ptl);
1241 }
1242 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1243
1244 void huge_pmd_set_accessed(struct vm_fault *vmf)
1245 {
1246         pmd_t entry;
1247         unsigned long haddr;
1248         bool write = vmf->flags & FAULT_FLAG_WRITE;
1249         pmd_t orig_pmd = vmf->orig_pmd;
1250
1251         vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd);
1252         if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
1253                 goto unlock;
1254
1255         entry = pmd_mkyoung(orig_pmd);
1256         if (write)
1257                 entry = pmd_mkdirty(entry);
1258         haddr = vmf->address & HPAGE_PMD_MASK;
1259         if (pmdp_set_access_flags(vmf->vma, haddr, vmf->pmd, entry, write))
1260                 update_mmu_cache_pmd(vmf->vma, vmf->address, vmf->pmd);
1261
1262 unlock:
1263         spin_unlock(vmf->ptl);
1264 }
1265
1266 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
1267 {
1268         const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
1269         struct vm_area_struct *vma = vmf->vma;
1270         struct page *page;
1271         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1272         pmd_t orig_pmd = vmf->orig_pmd;
1273
1274         vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
1275         VM_BUG_ON_VMA(!vma->anon_vma, vma);
1276
1277         VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE));
1278         VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE));
1279
1280         if (is_huge_zero_pmd(orig_pmd))
1281                 goto fallback;
1282
1283         spin_lock(vmf->ptl);
1284
1285         if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1286                 spin_unlock(vmf->ptl);
1287                 return 0;
1288         }
1289
1290         page = pmd_page(orig_pmd);
1291         VM_BUG_ON_PAGE(!PageHead(page), page);
1292
1293         /* Early check when only holding the PT lock. */
1294         if (PageAnonExclusive(page))
1295                 goto reuse;
1296
1297         if (!trylock_page(page)) {
1298                 get_page(page);
1299                 spin_unlock(vmf->ptl);
1300                 lock_page(page);
1301                 spin_lock(vmf->ptl);
1302                 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
1303                         spin_unlock(vmf->ptl);
1304                         unlock_page(page);
1305                         put_page(page);
1306                         return 0;
1307                 }
1308                 put_page(page);
1309         }
1310
1311         /* Recheck after temporarily dropping the PT lock. */
1312         if (PageAnonExclusive(page)) {
1313                 unlock_page(page);
1314                 goto reuse;
1315         }
1316
1317         /*
1318          * See do_wp_page(): we can only reuse the page exclusively if there are
1319          * no additional references. Note that we always drain the LRU
1320          * pagevecs immediately after adding a THP.
1321          */
1322         if (page_count(page) > 1 + PageSwapCache(page) * thp_nr_pages(page))
1323                 goto unlock_fallback;
1324         if (PageSwapCache(page))
1325                 try_to_free_swap(page);
1326         if (page_count(page) == 1) {
1327                 pmd_t entry;
1328
1329                 page_move_anon_rmap(page, vma);
1330                 unlock_page(page);
1331 reuse:
1332                 if (unlikely(unshare)) {
1333                         spin_unlock(vmf->ptl);
1334                         return 0;
1335                 }
1336                 entry = pmd_mkyoung(orig_pmd);
1337                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1338                 if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1))
1339                         update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1340                 spin_unlock(vmf->ptl);
1341                 return VM_FAULT_WRITE;
1342         }
1343
1344 unlock_fallback:
1345         unlock_page(page);
1346         spin_unlock(vmf->ptl);
1347 fallback:
1348         __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
1349         return VM_FAULT_FALLBACK;
1350 }
1351
1352 /*
1353  * FOLL_FORCE can write to even unwritable pmd's, but only
1354  * after we've gone through a COW cycle and they are dirty.
1355  */
1356 static inline bool can_follow_write_pmd(pmd_t pmd, unsigned int flags)
1357 {
1358         return pmd_write(pmd) ||
1359                ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pmd_dirty(pmd));
1360 }
1361
1362 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1363                                    unsigned long addr,
1364                                    pmd_t *pmd,
1365                                    unsigned int flags)
1366 {
1367         struct mm_struct *mm = vma->vm_mm;
1368         struct page *page = NULL;
1369
1370         assert_spin_locked(pmd_lockptr(mm, pmd));
1371
1372         if (flags & FOLL_WRITE && !can_follow_write_pmd(*pmd, flags))
1373                 goto out;
1374
1375         /* Avoid dumping huge zero page */
1376         if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1377                 return ERR_PTR(-EFAULT);
1378
1379         /* Full NUMA hinting faults to serialise migration in fault paths */
1380         if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
1381                 goto out;
1382
1383         page = pmd_page(*pmd);
1384         VM_BUG_ON_PAGE(!PageHead(page) && !is_zone_device_page(page), page);
1385
1386         if (!pmd_write(*pmd) && gup_must_unshare(flags, page))
1387                 return ERR_PTR(-EMLINK);
1388
1389         VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
1390                         !PageAnonExclusive(page), page);
1391
1392         if (!try_grab_page(page, flags))
1393                 return ERR_PTR(-ENOMEM);
1394
1395         if (flags & FOLL_TOUCH)
1396                 touch_pmd(vma, addr, pmd, flags);
1397
1398         page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1399         VM_BUG_ON_PAGE(!PageCompound(page) && !is_zone_device_page(page), page);
1400
1401 out:
1402         return page;
1403 }
1404
1405 /* NUMA hinting page fault entry point for trans huge pmds */
1406 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf)
1407 {
1408         struct vm_area_struct *vma = vmf->vma;
1409         pmd_t oldpmd = vmf->orig_pmd;
1410         pmd_t pmd;
1411         struct page *page;
1412         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
1413         int page_nid = NUMA_NO_NODE;
1414         int target_nid, last_cpupid = -1;
1415         bool migrated = false;
1416         bool was_writable = pmd_savedwrite(oldpmd);
1417         int flags = 0;
1418
1419         vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1420         if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1421                 spin_unlock(vmf->ptl);
1422                 goto out;
1423         }
1424
1425         pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1426         page = vm_normal_page_pmd(vma, haddr, pmd);
1427         if (!page)
1428                 goto out_map;
1429
1430         /* See similar comment in do_numa_page for explanation */
1431         if (!was_writable)
1432                 flags |= TNF_NO_GROUP;
1433
1434         page_nid = page_to_nid(page);
1435         last_cpupid = page_cpupid_last(page);
1436         target_nid = numa_migrate_prep(page, vma, haddr, page_nid,
1437                                        &flags);
1438
1439         if (target_nid == NUMA_NO_NODE) {
1440                 put_page(page);
1441                 goto out_map;
1442         }
1443
1444         spin_unlock(vmf->ptl);
1445
1446         migrated = migrate_misplaced_page(page, vma, target_nid);
1447         if (migrated) {
1448                 flags |= TNF_MIGRATED;
1449                 page_nid = target_nid;
1450         } else {
1451                 flags |= TNF_MIGRATE_FAIL;
1452                 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
1453                 if (unlikely(!pmd_same(oldpmd, *vmf->pmd))) {
1454                         spin_unlock(vmf->ptl);
1455                         goto out;
1456                 }
1457                 goto out_map;
1458         }
1459
1460 out:
1461         if (page_nid != NUMA_NO_NODE)
1462                 task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR,
1463                                 flags);
1464
1465         return 0;
1466
1467 out_map:
1468         /* Restore the PMD */
1469         pmd = pmd_modify(oldpmd, vma->vm_page_prot);
1470         pmd = pmd_mkyoung(pmd);
1471         if (was_writable)
1472                 pmd = pmd_mkwrite(pmd);
1473         set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd);
1474         update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
1475         spin_unlock(vmf->ptl);
1476         goto out;
1477 }
1478
1479 /*
1480  * Return true if we do MADV_FREE successfully on entire pmd page.
1481  * Otherwise, return false.
1482  */
1483 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1484                 pmd_t *pmd, unsigned long addr, unsigned long next)
1485 {
1486         spinlock_t *ptl;
1487         pmd_t orig_pmd;
1488         struct page *page;
1489         struct mm_struct *mm = tlb->mm;
1490         bool ret = false;
1491
1492         tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1493
1494         ptl = pmd_trans_huge_lock(pmd, vma);
1495         if (!ptl)
1496                 goto out_unlocked;
1497
1498         orig_pmd = *pmd;
1499         if (is_huge_zero_pmd(orig_pmd))
1500                 goto out;
1501
1502         if (unlikely(!pmd_present(orig_pmd))) {
1503                 VM_BUG_ON(thp_migration_supported() &&
1504                                   !is_pmd_migration_entry(orig_pmd));
1505                 goto out;
1506         }
1507
1508         page = pmd_page(orig_pmd);
1509         /*
1510          * If other processes are mapping this page, we couldn't discard
1511          * the page unless they all do MADV_FREE so let's skip the page.
1512          */
1513         if (total_mapcount(page) != 1)
1514                 goto out;
1515
1516         if (!trylock_page(page))
1517                 goto out;
1518
1519         /*
1520          * If user want to discard part-pages of THP, split it so MADV_FREE
1521          * will deactivate only them.
1522          */
1523         if (next - addr != HPAGE_PMD_SIZE) {
1524                 get_page(page);
1525                 spin_unlock(ptl);
1526                 split_huge_page(page);
1527                 unlock_page(page);
1528                 put_page(page);
1529                 goto out_unlocked;
1530         }
1531
1532         if (PageDirty(page))
1533                 ClearPageDirty(page);
1534         unlock_page(page);
1535
1536         if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1537                 pmdp_invalidate(vma, addr, pmd);
1538                 orig_pmd = pmd_mkold(orig_pmd);
1539                 orig_pmd = pmd_mkclean(orig_pmd);
1540
1541                 set_pmd_at(mm, addr, pmd, orig_pmd);
1542                 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1543         }
1544
1545         mark_page_lazyfree(page);
1546         ret = true;
1547 out:
1548         spin_unlock(ptl);
1549 out_unlocked:
1550         return ret;
1551 }
1552
1553 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd)
1554 {
1555         pgtable_t pgtable;
1556
1557         pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1558         pte_free(mm, pgtable);
1559         mm_dec_nr_ptes(mm);
1560 }
1561
1562 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1563                  pmd_t *pmd, unsigned long addr)
1564 {
1565         pmd_t orig_pmd;
1566         spinlock_t *ptl;
1567
1568         tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1569
1570         ptl = __pmd_trans_huge_lock(pmd, vma);
1571         if (!ptl)
1572                 return 0;
1573         /*
1574          * For architectures like ppc64 we look at deposited pgtable
1575          * when calling pmdp_huge_get_and_clear. So do the
1576          * pgtable_trans_huge_withdraw after finishing pmdp related
1577          * operations.
1578          */
1579         orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
1580                                                 tlb->fullmm);
1581         tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1582         if (vma_is_special_huge(vma)) {
1583                 if (arch_needs_pgtable_deposit())
1584                         zap_deposited_table(tlb->mm, pmd);
1585                 spin_unlock(ptl);
1586         } else if (is_huge_zero_pmd(orig_pmd)) {
1587                 zap_deposited_table(tlb->mm, pmd);
1588                 spin_unlock(ptl);
1589         } else {
1590                 struct page *page = NULL;
1591                 int flush_needed = 1;
1592
1593                 if (pmd_present(orig_pmd)) {
1594                         page = pmd_page(orig_pmd);
1595                         page_remove_rmap(page, vma, true);
1596                         VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1597                         VM_BUG_ON_PAGE(!PageHead(page), page);
1598                 } else if (thp_migration_supported()) {
1599                         swp_entry_t entry;
1600
1601                         VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
1602                         entry = pmd_to_swp_entry(orig_pmd);
1603                         page = pfn_swap_entry_to_page(entry);
1604                         flush_needed = 0;
1605                 } else
1606                         WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
1607
1608                 if (PageAnon(page)) {
1609                         zap_deposited_table(tlb->mm, pmd);
1610                         add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1611                 } else {
1612                         if (arch_needs_pgtable_deposit())
1613                                 zap_deposited_table(tlb->mm, pmd);
1614                         add_mm_counter(tlb->mm, mm_counter_file(page), -HPAGE_PMD_NR);
1615                 }
1616
1617                 spin_unlock(ptl);
1618                 if (flush_needed)
1619                         tlb_remove_page_size(tlb, page, HPAGE_PMD_SIZE);
1620         }
1621         return 1;
1622 }
1623
1624 #ifndef pmd_move_must_withdraw
1625 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
1626                                          spinlock_t *old_pmd_ptl,
1627                                          struct vm_area_struct *vma)
1628 {
1629         /*
1630          * With split pmd lock we also need to move preallocated
1631          * PTE page table if new_pmd is on different PMD page table.
1632          *
1633          * We also don't deposit and withdraw tables for file pages.
1634          */
1635         return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma);
1636 }
1637 #endif
1638
1639 static pmd_t move_soft_dirty_pmd(pmd_t pmd)
1640 {
1641 #ifdef CONFIG_MEM_SOFT_DIRTY
1642         if (unlikely(is_pmd_migration_entry(pmd)))
1643                 pmd = pmd_swp_mksoft_dirty(pmd);
1644         else if (pmd_present(pmd))
1645                 pmd = pmd_mksoft_dirty(pmd);
1646 #endif
1647         return pmd;
1648 }
1649
1650 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
1651                   unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
1652 {
1653         spinlock_t *old_ptl, *new_ptl;
1654         pmd_t pmd;
1655         struct mm_struct *mm = vma->vm_mm;
1656         bool force_flush = false;
1657
1658         /*
1659          * The destination pmd shouldn't be established, free_pgtables()
1660          * should have release it.
1661          */
1662         if (WARN_ON(!pmd_none(*new_pmd))) {
1663                 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1664                 return false;
1665         }
1666
1667         /*
1668          * We don't have to worry about the ordering of src and dst
1669          * ptlocks because exclusive mmap_lock prevents deadlock.
1670          */
1671         old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1672         if (old_ptl) {
1673                 new_ptl = pmd_lockptr(mm, new_pmd);
1674                 if (new_ptl != old_ptl)
1675                         spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1676                 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1677                 if (pmd_present(pmd))
1678                         force_flush = true;
1679                 VM_BUG_ON(!pmd_none(*new_pmd));
1680
1681                 if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) {
1682                         pgtable_t pgtable;
1683                         pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1684                         pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1685                 }
1686                 pmd = move_soft_dirty_pmd(pmd);
1687                 set_pmd_at(mm, new_addr, new_pmd, pmd);
1688                 if (force_flush)
1689                         flush_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
1690                 if (new_ptl != old_ptl)
1691                         spin_unlock(new_ptl);
1692                 spin_unlock(old_ptl);
1693                 return true;
1694         }
1695         return false;
1696 }
1697
1698 /*
1699  * Returns
1700  *  - 0 if PMD could not be locked
1701  *  - 1 if PMD was locked but protections unchanged and TLB flush unnecessary
1702  *      or if prot_numa but THP migration is not supported
1703  *  - HPAGE_PMD_NR if protections changed and TLB flush necessary
1704  */
1705 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1706                     pmd_t *pmd, unsigned long addr, pgprot_t newprot,
1707                     unsigned long cp_flags)
1708 {
1709         struct mm_struct *mm = vma->vm_mm;
1710         spinlock_t *ptl;
1711         pmd_t oldpmd, entry;
1712         bool preserve_write;
1713         int ret;
1714         bool prot_numa = cp_flags & MM_CP_PROT_NUMA;
1715         bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
1716         bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
1717
1718         tlb_change_page_size(tlb, HPAGE_PMD_SIZE);
1719
1720         if (prot_numa && !thp_migration_supported())
1721                 return 1;
1722
1723         ptl = __pmd_trans_huge_lock(pmd, vma);
1724         if (!ptl)
1725                 return 0;
1726
1727         preserve_write = prot_numa && pmd_write(*pmd);
1728         ret = 1;
1729
1730 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1731         if (is_swap_pmd(*pmd)) {
1732                 swp_entry_t entry = pmd_to_swp_entry(*pmd);
1733                 struct page *page = pfn_swap_entry_to_page(entry);
1734
1735                 VM_BUG_ON(!is_pmd_migration_entry(*pmd));
1736                 if (is_writable_migration_entry(entry)) {
1737                         pmd_t newpmd;
1738                         /*
1739                          * A protection check is difficult so
1740                          * just be safe and disable write
1741                          */
1742                         if (PageAnon(page))
1743                                 entry = make_readable_exclusive_migration_entry(swp_offset(entry));
1744                         else
1745                                 entry = make_readable_migration_entry(swp_offset(entry));
1746                         newpmd = swp_entry_to_pmd(entry);
1747                         if (pmd_swp_soft_dirty(*pmd))
1748                                 newpmd = pmd_swp_mksoft_dirty(newpmd);
1749                         if (pmd_swp_uffd_wp(*pmd))
1750                                 newpmd = pmd_swp_mkuffd_wp(newpmd);
1751                         set_pmd_at(mm, addr, pmd, newpmd);
1752                 }
1753                 goto unlock;
1754         }
1755 #endif
1756
1757         if (prot_numa) {
1758                 struct page *page;
1759                 /*
1760                  * Avoid trapping faults against the zero page. The read-only
1761                  * data is likely to be read-cached on the local CPU and
1762                  * local/remote hits to the zero page are not interesting.
1763                  */
1764                 if (is_huge_zero_pmd(*pmd))
1765                         goto unlock;
1766
1767                 if (pmd_protnone(*pmd))
1768                         goto unlock;
1769
1770                 page = pmd_page(*pmd);
1771                 /*
1772                  * Skip scanning top tier node if normal numa
1773                  * balancing is disabled
1774                  */
1775                 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
1776                     node_is_toptier(page_to_nid(page)))
1777                         goto unlock;
1778         }
1779         /*
1780          * In case prot_numa, we are under mmap_read_lock(mm). It's critical
1781          * to not clear pmd intermittently to avoid race with MADV_DONTNEED
1782          * which is also under mmap_read_lock(mm):
1783          *
1784          *      CPU0:                           CPU1:
1785          *                              change_huge_pmd(prot_numa=1)
1786          *                               pmdp_huge_get_and_clear_notify()
1787          * madvise_dontneed()
1788          *  zap_pmd_range()
1789          *   pmd_trans_huge(*pmd) == 0 (without ptl)
1790          *   // skip the pmd
1791          *                               set_pmd_at();
1792          *                               // pmd is re-established
1793          *
1794          * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
1795          * which may break userspace.
1796          *
1797          * pmdp_invalidate_ad() is required to make sure we don't miss
1798          * dirty/young flags set by hardware.
1799          */
1800         oldpmd = pmdp_invalidate_ad(vma, addr, pmd);
1801
1802         entry = pmd_modify(oldpmd, newprot);
1803         if (preserve_write)
1804                 entry = pmd_mk_savedwrite(entry);
1805         if (uffd_wp) {
1806                 entry = pmd_wrprotect(entry);
1807                 entry = pmd_mkuffd_wp(entry);
1808         } else if (uffd_wp_resolve) {
1809                 /*
1810                  * Leave the write bit to be handled by PF interrupt
1811                  * handler, then things like COW could be properly
1812                  * handled.
1813                  */
1814                 entry = pmd_clear_uffd_wp(entry);
1815         }
1816         ret = HPAGE_PMD_NR;
1817         set_pmd_at(mm, addr, pmd, entry);
1818
1819         if (huge_pmd_needs_flush(oldpmd, entry))
1820                 tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE);
1821
1822         BUG_ON(vma_is_anonymous(vma) && !preserve_write && pmd_write(entry));
1823 unlock:
1824         spin_unlock(ptl);
1825         return ret;
1826 }
1827
1828 /*
1829  * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise.
1830  *
1831  * Note that if it returns page table lock pointer, this routine returns without
1832  * unlocking page table lock. So callers must unlock it.
1833  */
1834 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1835 {
1836         spinlock_t *ptl;
1837         ptl = pmd_lock(vma->vm_mm, pmd);
1838         if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) ||
1839                         pmd_devmap(*pmd)))
1840                 return ptl;
1841         spin_unlock(ptl);
1842         return NULL;
1843 }
1844
1845 /*
1846  * Returns true if a given pud maps a thp, false otherwise.
1847  *
1848  * Note that if it returns true, this routine returns without unlocking page
1849  * table lock. So callers must unlock it.
1850  */
1851 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)
1852 {
1853         spinlock_t *ptl;
1854
1855         ptl = pud_lock(vma->vm_mm, pud);
1856         if (likely(pud_trans_huge(*pud) || pud_devmap(*pud)))
1857                 return ptl;
1858         spin_unlock(ptl);
1859         return NULL;
1860 }
1861
1862 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1863 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
1864                  pud_t *pud, unsigned long addr)
1865 {
1866         spinlock_t *ptl;
1867
1868         ptl = __pud_trans_huge_lock(pud, vma);
1869         if (!ptl)
1870                 return 0;
1871         /*
1872          * For architectures like ppc64 we look at deposited pgtable
1873          * when calling pudp_huge_get_and_clear. So do the
1874          * pgtable_trans_huge_withdraw after finishing pudp related
1875          * operations.
1876          */
1877         pudp_huge_get_and_clear_full(tlb->mm, addr, pud, tlb->fullmm);
1878         tlb_remove_pud_tlb_entry(tlb, pud, addr);
1879         if (vma_is_special_huge(vma)) {
1880                 spin_unlock(ptl);
1881                 /* No zero page support yet */
1882         } else {
1883                 /* No support for anonymous PUD pages yet */
1884                 BUG();
1885         }
1886         return 1;
1887 }
1888
1889 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud,
1890                 unsigned long haddr)
1891 {
1892         VM_BUG_ON(haddr & ~HPAGE_PUD_MASK);
1893         VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
1894         VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma);
1895         VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud));
1896
1897         count_vm_event(THP_SPLIT_PUD);
1898
1899         pudp_huge_clear_flush_notify(vma, haddr, pud);
1900 }
1901
1902 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,
1903                 unsigned long address)
1904 {
1905         spinlock_t *ptl;
1906         struct mmu_notifier_range range;
1907
1908         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1909                                 address & HPAGE_PUD_MASK,
1910                                 (address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE);
1911         mmu_notifier_invalidate_range_start(&range);
1912         ptl = pud_lock(vma->vm_mm, pud);
1913         if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud)))
1914                 goto out;
1915         __split_huge_pud_locked(vma, pud, range.start);
1916
1917 out:
1918         spin_unlock(ptl);
1919         /*
1920          * No need to double call mmu_notifier->invalidate_range() callback as
1921          * the above pudp_huge_clear_flush_notify() did already call it.
1922          */
1923         mmu_notifier_invalidate_range_only_end(&range);
1924 }
1925 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
1926
1927 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
1928                 unsigned long haddr, pmd_t *pmd)
1929 {
1930         struct mm_struct *mm = vma->vm_mm;
1931         pgtable_t pgtable;
1932         pmd_t _pmd;
1933         int i;
1934
1935         /*
1936          * Leave pmd empty until pte is filled note that it is fine to delay
1937          * notification until mmu_notifier_invalidate_range_end() as we are
1938          * replacing a zero pmd write protected page with a zero pte write
1939          * protected page.
1940          *
1941          * See Documentation/vm/mmu_notifier.rst
1942          */
1943         pmdp_huge_clear_flush(vma, haddr, pmd);
1944
1945         pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1946         pmd_populate(mm, &_pmd, pgtable);
1947
1948         for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1949                 pte_t *pte, entry;
1950                 entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
1951                 entry = pte_mkspecial(entry);
1952                 pte = pte_offset_map(&_pmd, haddr);
1953                 VM_BUG_ON(!pte_none(*pte));
1954                 set_pte_at(mm, haddr, pte, entry);
1955                 pte_unmap(pte);
1956         }
1957         smp_wmb(); /* make pte visible before pmd */
1958         pmd_populate(mm, pmd, pgtable);
1959 }
1960
1961 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
1962                 unsigned long haddr, bool freeze)
1963 {
1964         struct mm_struct *mm = vma->vm_mm;
1965         struct page *page;
1966         pgtable_t pgtable;
1967         pmd_t old_pmd, _pmd;
1968         bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false;
1969         bool anon_exclusive = false;
1970         unsigned long addr;
1971         int i;
1972
1973         VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
1974         VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
1975         VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
1976         VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd)
1977                                 && !pmd_devmap(*pmd));
1978
1979         count_vm_event(THP_SPLIT_PMD);
1980
1981         if (!vma_is_anonymous(vma)) {
1982                 old_pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1983                 /*
1984                  * We are going to unmap this huge page. So
1985                  * just go ahead and zap it
1986                  */
1987                 if (arch_needs_pgtable_deposit())
1988                         zap_deposited_table(mm, pmd);
1989                 if (vma_is_special_huge(vma))
1990                         return;
1991                 if (unlikely(is_pmd_migration_entry(old_pmd))) {
1992                         swp_entry_t entry;
1993
1994                         entry = pmd_to_swp_entry(old_pmd);
1995                         page = pfn_swap_entry_to_page(entry);
1996                 } else {
1997                         page = pmd_page(old_pmd);
1998                         if (!PageDirty(page) && pmd_dirty(old_pmd))
1999                                 set_page_dirty(page);
2000                         if (!PageReferenced(page) && pmd_young(old_pmd))
2001                                 SetPageReferenced(page);
2002                         page_remove_rmap(page, vma, true);
2003                         put_page(page);
2004                 }
2005                 add_mm_counter(mm, mm_counter_file(page), -HPAGE_PMD_NR);
2006                 return;
2007         }
2008
2009         if (is_huge_zero_pmd(*pmd)) {
2010                 /*
2011                  * FIXME: Do we want to invalidate secondary mmu by calling
2012                  * mmu_notifier_invalidate_range() see comments below inside
2013                  * __split_huge_pmd() ?
2014                  *
2015                  * We are going from a zero huge page write protected to zero
2016                  * small page also write protected so it does not seems useful
2017                  * to invalidate secondary mmu at this time.
2018                  */
2019                 return __split_huge_zero_page_pmd(vma, haddr, pmd);
2020         }
2021
2022         /*
2023          * Up to this point the pmd is present and huge and userland has the
2024          * whole access to the hugepage during the split (which happens in
2025          * place). If we overwrite the pmd with the not-huge version pointing
2026          * to the pte here (which of course we could if all CPUs were bug
2027          * free), userland could trigger a small page size TLB miss on the
2028          * small sized TLB while the hugepage TLB entry is still established in
2029          * the huge TLB. Some CPU doesn't like that.
2030          * See http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum
2031          * 383 on page 105. Intel should be safe but is also warns that it's
2032          * only safe if the permission and cache attributes of the two entries
2033          * loaded in the two TLB is identical (which should be the case here).
2034          * But it is generally safer to never allow small and huge TLB entries
2035          * for the same virtual address to be loaded simultaneously. So instead
2036          * of doing "pmd_populate(); flush_pmd_tlb_range();" we first mark the
2037          * current pmd notpresent (atomically because here the pmd_trans_huge
2038          * must remain set at all times on the pmd until the split is complete
2039          * for this pmd), then we flush the SMP TLB and finally we write the
2040          * non-huge version of the pmd entry with pmd_populate.
2041          */
2042         old_pmd = pmdp_invalidate(vma, haddr, pmd);
2043
2044         pmd_migration = is_pmd_migration_entry(old_pmd);
2045         if (unlikely(pmd_migration)) {
2046                 swp_entry_t entry;
2047
2048                 entry = pmd_to_swp_entry(old_pmd);
2049                 page = pfn_swap_entry_to_page(entry);
2050                 write = is_writable_migration_entry(entry);
2051                 if (PageAnon(page))
2052                         anon_exclusive = is_readable_exclusive_migration_entry(entry);
2053                 young = false;
2054                 soft_dirty = pmd_swp_soft_dirty(old_pmd);
2055                 uffd_wp = pmd_swp_uffd_wp(old_pmd);
2056         } else {
2057                 page = pmd_page(old_pmd);
2058                 if (pmd_dirty(old_pmd))
2059                         SetPageDirty(page);
2060                 write = pmd_write(old_pmd);
2061                 young = pmd_young(old_pmd);
2062                 soft_dirty = pmd_soft_dirty(old_pmd);
2063                 uffd_wp = pmd_uffd_wp(old_pmd);
2064
2065                 VM_BUG_ON_PAGE(!page_count(page), page);
2066                 page_ref_add(page, HPAGE_PMD_NR - 1);
2067
2068                 /*
2069                  * Without "freeze", we'll simply split the PMD, propagating the
2070                  * PageAnonExclusive() flag for each PTE by setting it for
2071                  * each subpage -- no need to (temporarily) clear.
2072                  *
2073                  * With "freeze" we want to replace mapped pages by
2074                  * migration entries right away. This is only possible if we
2075                  * managed to clear PageAnonExclusive() -- see
2076                  * set_pmd_migration_entry().
2077                  *
2078                  * In case we cannot clear PageAnonExclusive(), split the PMD
2079                  * only and let try_to_migrate_one() fail later.
2080                  */
2081                 anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
2082                 if (freeze && anon_exclusive && page_try_share_anon_rmap(page))
2083                         freeze = false;
2084         }
2085
2086         /*
2087          * Withdraw the table only after we mark the pmd entry invalid.
2088          * This's critical for some architectures (Power).
2089          */
2090         pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2091         pmd_populate(mm, &_pmd, pgtable);
2092
2093         for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
2094                 pte_t entry, *pte;
2095                 /*
2096                  * Note that NUMA hinting access restrictions are not
2097                  * transferred to avoid any possibility of altering
2098                  * permissions across VMAs.
2099                  */
2100                 if (freeze || pmd_migration) {
2101                         swp_entry_t swp_entry;
2102                         if (write)
2103                                 swp_entry = make_writable_migration_entry(
2104                                                         page_to_pfn(page + i));
2105                         else if (anon_exclusive)
2106                                 swp_entry = make_readable_exclusive_migration_entry(
2107                                                         page_to_pfn(page + i));
2108                         else
2109                                 swp_entry = make_readable_migration_entry(
2110                                                         page_to_pfn(page + i));
2111                         entry = swp_entry_to_pte(swp_entry);
2112                         if (soft_dirty)
2113                                 entry = pte_swp_mksoft_dirty(entry);
2114                         if (uffd_wp)
2115                                 entry = pte_swp_mkuffd_wp(entry);
2116                 } else {
2117                         entry = mk_pte(page + i, READ_ONCE(vma->vm_page_prot));
2118                         entry = maybe_mkwrite(entry, vma);
2119                         if (anon_exclusive)
2120                                 SetPageAnonExclusive(page + i);
2121                         if (!write)
2122                                 entry = pte_wrprotect(entry);
2123                         if (!young)
2124                                 entry = pte_mkold(entry);
2125                         if (soft_dirty)
2126                                 entry = pte_mksoft_dirty(entry);
2127                         if (uffd_wp)
2128                                 entry = pte_mkuffd_wp(entry);
2129                 }
2130                 pte = pte_offset_map(&_pmd, addr);
2131                 BUG_ON(!pte_none(*pte));
2132                 set_pte_at(mm, addr, pte, entry);
2133                 if (!pmd_migration)
2134                         atomic_inc(&page[i]._mapcount);
2135                 pte_unmap(pte);
2136         }
2137
2138         if (!pmd_migration) {
2139                 /*
2140                  * Set PG_double_map before dropping compound_mapcount to avoid
2141                  * false-negative page_mapped().
2142                  */
2143                 if (compound_mapcount(page) > 1 &&
2144                     !TestSetPageDoubleMap(page)) {
2145                         for (i = 0; i < HPAGE_PMD_NR; i++)
2146                                 atomic_inc(&page[i]._mapcount);
2147                 }
2148
2149                 lock_page_memcg(page);
2150                 if (atomic_add_negative(-1, compound_mapcount_ptr(page))) {
2151                         /* Last compound_mapcount is gone. */
2152                         __mod_lruvec_page_state(page, NR_ANON_THPS,
2153                                                 -HPAGE_PMD_NR);
2154                         if (TestClearPageDoubleMap(page)) {
2155                                 /* No need in mapcount reference anymore */
2156                                 for (i = 0; i < HPAGE_PMD_NR; i++)
2157                                         atomic_dec(&page[i]._mapcount);
2158                         }
2159                 }
2160                 unlock_page_memcg(page);
2161
2162                 /* Above is effectively page_remove_rmap(page, vma, true) */
2163                 munlock_vma_page(page, vma, true);
2164         }
2165
2166         smp_wmb(); /* make pte visible before pmd */
2167         pmd_populate(mm, pmd, pgtable);
2168
2169         if (freeze) {
2170                 for (i = 0; i < HPAGE_PMD_NR; i++) {
2171                         page_remove_rmap(page + i, vma, false);
2172                         put_page(page + i);
2173                 }
2174         }
2175 }
2176
2177 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
2178                 unsigned long address, bool freeze, struct folio *folio)
2179 {
2180         spinlock_t *ptl;
2181         struct mmu_notifier_range range;
2182
2183         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
2184                                 address & HPAGE_PMD_MASK,
2185                                 (address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);
2186         mmu_notifier_invalidate_range_start(&range);
2187         ptl = pmd_lock(vma->vm_mm, pmd);
2188
2189         /*
2190          * If caller asks to setup a migration entry, we need a folio to check
2191          * pmd against. Otherwise we can end up replacing wrong folio.
2192          */
2193         VM_BUG_ON(freeze && !folio);
2194         VM_WARN_ON_ONCE(folio && !folio_test_locked(folio));
2195
2196         if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) ||
2197             is_pmd_migration_entry(*pmd)) {
2198                 if (folio && folio != page_folio(pmd_page(*pmd)))
2199                         goto out;
2200                 __split_huge_pmd_locked(vma, pmd, range.start, freeze);
2201         }
2202
2203 out:
2204         spin_unlock(ptl);
2205         /*
2206          * No need to double call mmu_notifier->invalidate_range() callback.
2207          * They are 3 cases to consider inside __split_huge_pmd_locked():
2208          *  1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious
2209          *  2) __split_huge_zero_page_pmd() read only zero page and any write
2210          *    fault will trigger a flush_notify before pointing to a new page
2211          *    (it is fine if the secondary mmu keeps pointing to the old zero
2212          *    page in the meantime)
2213          *  3) Split a huge pmd into pte pointing to the same page. No need
2214          *     to invalidate secondary tlb entry they are all still valid.
2215          *     any further changes to individual pte will notify. So no need
2216          *     to call mmu_notifier->invalidate_range()
2217          */
2218         mmu_notifier_invalidate_range_only_end(&range);
2219 }
2220
2221 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
2222                 bool freeze, struct folio *folio)
2223 {
2224         pgd_t *pgd;
2225         p4d_t *p4d;
2226         pud_t *pud;
2227         pmd_t *pmd;
2228
2229         pgd = pgd_offset(vma->vm_mm, address);
2230         if (!pgd_present(*pgd))
2231                 return;
2232
2233         p4d = p4d_offset(pgd, address);
2234         if (!p4d_present(*p4d))
2235                 return;
2236
2237         pud = pud_offset(p4d, address);
2238         if (!pud_present(*pud))
2239                 return;
2240
2241         pmd = pmd_offset(pud, address);
2242
2243         __split_huge_pmd(vma, pmd, address, freeze, folio);
2244 }
2245
2246 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address)
2247 {
2248         /*
2249          * If the new address isn't hpage aligned and it could previously
2250          * contain an hugepage: check if we need to split an huge pmd.
2251          */
2252         if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) &&
2253             range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE),
2254                          ALIGN(address, HPAGE_PMD_SIZE)))
2255                 split_huge_pmd_address(vma, address, false, NULL);
2256 }
2257
2258 void vma_adjust_trans_huge(struct vm_area_struct *vma,
2259                              unsigned long start,
2260                              unsigned long end,
2261                              long adjust_next)
2262 {
2263         /* Check if we need to split start first. */
2264         split_huge_pmd_if_needed(vma, start);
2265
2266         /* Check if we need to split end next. */
2267         split_huge_pmd_if_needed(vma, end);
2268
2269         /*
2270          * If we're also updating the vma->vm_next->vm_start,
2271          * check if we need to split it.
2272          */
2273         if (adjust_next > 0) {
2274                 struct vm_area_struct *next = vma->vm_next;
2275                 unsigned long nstart = next->vm_start;
2276                 nstart += adjust_next;
2277                 split_huge_pmd_if_needed(next, nstart);
2278         }
2279 }
2280
2281 static void unmap_page(struct page *page)
2282 {
2283         struct folio *folio = page_folio(page);
2284         enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2285                 TTU_SYNC;
2286
2287         VM_BUG_ON_PAGE(!PageHead(page), page);
2288
2289         /*
2290          * Anon pages need migration entries to preserve them, but file
2291          * pages can simply be left unmapped, then faulted back on demand.
2292          * If that is ever changed (perhaps for mlock), update remap_page().
2293          */
2294         if (folio_test_anon(folio))
2295                 try_to_migrate(folio, ttu_flags);
2296         else
2297                 try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK);
2298 }
2299
2300 static void remap_page(struct folio *folio, unsigned long nr)
2301 {
2302         int i = 0;
2303
2304         /* If unmap_page() uses try_to_migrate() on file, remove this check */
2305         if (!folio_test_anon(folio))
2306                 return;
2307         for (;;) {
2308                 remove_migration_ptes(folio, folio, true);
2309                 i += folio_nr_pages(folio);
2310                 if (i >= nr)
2311                         break;
2312                 folio = folio_next(folio);
2313         }
2314 }
2315
2316 static void lru_add_page_tail(struct page *head, struct page *tail,
2317                 struct lruvec *lruvec, struct list_head *list)
2318 {
2319         VM_BUG_ON_PAGE(!PageHead(head), head);
2320         VM_BUG_ON_PAGE(PageCompound(tail), head);
2321         VM_BUG_ON_PAGE(PageLRU(tail), head);
2322         lockdep_assert_held(&lruvec->lru_lock);
2323
2324         if (list) {
2325                 /* page reclaim is reclaiming a huge page */
2326                 VM_WARN_ON(PageLRU(head));
2327                 get_page(tail);
2328                 list_add_tail(&tail->lru, list);
2329         } else {
2330                 /* head is still on lru (and we have it frozen) */
2331                 VM_WARN_ON(!PageLRU(head));
2332                 if (PageUnevictable(tail))
2333                         tail->mlock_count = 0;
2334                 else
2335                         list_add_tail(&tail->lru, &head->lru);
2336                 SetPageLRU(tail);
2337         }
2338 }
2339
2340 static void __split_huge_page_tail(struct page *head, int tail,
2341                 struct lruvec *lruvec, struct list_head *list)
2342 {
2343         struct page *page_tail = head + tail;
2344
2345         VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
2346
2347         /*
2348          * Clone page flags before unfreezing refcount.
2349          *
2350          * After successful get_page_unless_zero() might follow flags change,
2351          * for example lock_page() which set PG_waiters.
2352          *
2353          * Note that for mapped sub-pages of an anonymous THP,
2354          * PG_anon_exclusive has been cleared in unmap_page() and is stored in
2355          * the migration entry instead from where remap_page() will restore it.
2356          * We can still have PG_anon_exclusive set on effectively unmapped and
2357          * unreferenced sub-pages of an anonymous THP: we can simply drop
2358          * PG_anon_exclusive (-> PG_mappedtodisk) for these here.
2359          */
2360         page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
2361         page_tail->flags |= (head->flags &
2362                         ((1L << PG_referenced) |
2363                          (1L << PG_swapbacked) |
2364                          (1L << PG_swapcache) |
2365                          (1L << PG_mlocked) |
2366                          (1L << PG_uptodate) |
2367                          (1L << PG_active) |
2368                          (1L << PG_workingset) |
2369                          (1L << PG_locked) |
2370                          (1L << PG_unevictable) |
2371 #ifdef CONFIG_64BIT
2372                          (1L << PG_arch_2) |
2373 #endif
2374                          (1L << PG_dirty)));
2375
2376         /* ->mapping in first tail page is compound_mapcount */
2377         VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
2378                         page_tail);
2379         page_tail->mapping = head->mapping;
2380         page_tail->index = head->index + tail;
2381         page_tail->private = 0;
2382
2383         /* Page flags must be visible before we make the page non-compound. */
2384         smp_wmb();
2385
2386         /*
2387          * Clear PageTail before unfreezing page refcount.
2388          *
2389          * After successful get_page_unless_zero() might follow put_page()
2390          * which needs correct compound_head().
2391          */
2392         clear_compound_head(page_tail);
2393
2394         /* Finally unfreeze refcount. Additional reference from page cache. */
2395         page_ref_unfreeze(page_tail, 1 + (!PageAnon(head) ||
2396                                           PageSwapCache(head)));
2397
2398         if (page_is_young(head))
2399                 set_page_young(page_tail);
2400         if (page_is_idle(head))
2401                 set_page_idle(page_tail);
2402
2403         page_cpupid_xchg_last(page_tail, page_cpupid_last(head));
2404
2405         /*
2406          * always add to the tail because some iterators expect new
2407          * pages to show after the currently processed elements - e.g.
2408          * migrate_pages
2409          */
2410         lru_add_page_tail(head, page_tail, lruvec, list);
2411 }
2412
2413 static void __split_huge_page(struct page *page, struct list_head *list,
2414                 pgoff_t end)
2415 {
2416         struct folio *folio = page_folio(page);
2417         struct page *head = &folio->page;
2418         struct lruvec *lruvec;
2419         struct address_space *swap_cache = NULL;
2420         unsigned long offset = 0;
2421         unsigned int nr = thp_nr_pages(head);
2422         int i;
2423
2424         /* complete memcg works before add pages to LRU */
2425         split_page_memcg(head, nr);
2426
2427         if (PageAnon(head) && PageSwapCache(head)) {
2428                 swp_entry_t entry = { .val = page_private(head) };
2429
2430                 offset = swp_offset(entry);
2431                 swap_cache = swap_address_space(entry);
2432                 xa_lock(&swap_cache->i_pages);
2433         }
2434
2435         /* lock lru list/PageCompound, ref frozen by page_ref_freeze */
2436         lruvec = folio_lruvec_lock(folio);
2437
2438         ClearPageHasHWPoisoned(head);
2439
2440         for (i = nr - 1; i >= 1; i--) {
2441                 __split_huge_page_tail(head, i, lruvec, list);
2442                 /* Some pages can be beyond EOF: drop them from page cache */
2443                 if (head[i].index >= end) {
2444                         struct folio *tail = page_folio(head + i);
2445
2446                         if (shmem_mapping(head->mapping))
2447                                 shmem_uncharge(head->mapping->host, 1);
2448                         else if (folio_test_clear_dirty(tail))
2449                                 folio_account_cleaned(tail,
2450                                         inode_to_wb(folio->mapping->host));
2451                         __filemap_remove_folio(tail, NULL);
2452                         folio_put(tail);
2453                 } else if (!PageAnon(page)) {
2454                         __xa_store(&head->mapping->i_pages, head[i].index,
2455                                         head + i, 0);
2456                 } else if (swap_cache) {
2457                         __xa_store(&swap_cache->i_pages, offset + i,
2458                                         head + i, 0);
2459                 }
2460         }
2461
2462         ClearPageCompound(head);
2463         unlock_page_lruvec(lruvec);
2464         /* Caller disabled irqs, so they are still disabled here */
2465
2466         split_page_owner(head, nr);
2467
2468         /* See comment in __split_huge_page_tail() */
2469         if (PageAnon(head)) {
2470                 /* Additional pin to swap cache */
2471                 if (PageSwapCache(head)) {
2472                         page_ref_add(head, 2);
2473                         xa_unlock(&swap_cache->i_pages);
2474                 } else {
2475                         page_ref_inc(head);
2476                 }
2477         } else {
2478                 /* Additional pin to page cache */
2479                 page_ref_add(head, 2);
2480                 xa_unlock(&head->mapping->i_pages);
2481         }
2482         local_irq_enable();
2483
2484         remap_page(folio, nr);
2485
2486         if (PageSwapCache(head)) {
2487                 swp_entry_t entry = { .val = page_private(head) };
2488
2489                 split_swap_cluster(entry);
2490         }
2491
2492         for (i = 0; i < nr; i++) {
2493                 struct page *subpage = head + i;
2494                 if (subpage == page)
2495                         continue;
2496                 unlock_page(subpage);
2497
2498                 /*
2499                  * Subpages may be freed if there wasn't any mapping
2500                  * like if add_to_swap() is running on a lru page that
2501                  * had its mapping zapped. And freeing these pages
2502                  * requires taking the lru_lock so we do the put_page
2503                  * of the tail pages after the split is complete.
2504                  */
2505                 put_page(subpage);
2506         }
2507 }
2508
2509 /* Racy check whether the huge page can be split */
2510 bool can_split_folio(struct folio *folio, int *pextra_pins)
2511 {
2512         int extra_pins;
2513
2514         /* Additional pins from page cache */
2515         if (folio_test_anon(folio))
2516                 extra_pins = folio_test_swapcache(folio) ?
2517                                 folio_nr_pages(folio) : 0;
2518         else
2519                 extra_pins = folio_nr_pages(folio);
2520         if (pextra_pins)
2521                 *pextra_pins = extra_pins;
2522         return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 1;
2523 }
2524
2525 /*
2526  * This function splits huge page into normal pages. @page can point to any
2527  * subpage of huge page to split. Split doesn't change the position of @page.
2528  *
2529  * Only caller must hold pin on the @page, otherwise split fails with -EBUSY.
2530  * The huge page must be locked.
2531  *
2532  * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
2533  *
2534  * Both head page and tail pages will inherit mapping, flags, and so on from
2535  * the hugepage.
2536  *
2537  * GUP pin and PG_locked transferred to @page. Rest subpages can be freed if
2538  * they are not mapped.
2539  *
2540  * Returns 0 if the hugepage is split successfully.
2541  * Returns -EBUSY if the page is pinned or if anon_vma disappeared from under
2542  * us.
2543  */
2544 int split_huge_page_to_list(struct page *page, struct list_head *list)
2545 {
2546         struct folio *folio = page_folio(page);
2547         struct page *head = &folio->page;
2548         struct deferred_split *ds_queue = get_deferred_split_queue(head);
2549         XA_STATE(xas, &head->mapping->i_pages, head->index);
2550         struct anon_vma *anon_vma = NULL;
2551         struct address_space *mapping = NULL;
2552         int extra_pins, ret;
2553         pgoff_t end;
2554         bool is_hzp;
2555
2556         VM_BUG_ON_PAGE(!PageLocked(head), head);
2557         VM_BUG_ON_PAGE(!PageCompound(head), head);
2558
2559         is_hzp = is_huge_zero_page(head);
2560         VM_WARN_ON_ONCE_PAGE(is_hzp, head);
2561         if (is_hzp)
2562                 return -EBUSY;
2563
2564         if (PageWriteback(head))
2565                 return -EBUSY;
2566
2567         if (PageAnon(head)) {
2568                 /*
2569                  * The caller does not necessarily hold an mmap_lock that would
2570                  * prevent the anon_vma disappearing so we first we take a
2571                  * reference to it and then lock the anon_vma for write. This
2572                  * is similar to folio_lock_anon_vma_read except the write lock
2573                  * is taken to serialise against parallel split or collapse
2574                  * operations.
2575                  */
2576                 anon_vma = page_get_anon_vma(head);
2577                 if (!anon_vma) {
2578                         ret = -EBUSY;
2579                         goto out;
2580                 }
2581                 end = -1;
2582                 mapping = NULL;
2583                 anon_vma_lock_write(anon_vma);
2584         } else {
2585                 mapping = head->mapping;
2586
2587                 /* Truncated ? */
2588                 if (!mapping) {
2589                         ret = -EBUSY;
2590                         goto out;
2591                 }
2592
2593                 xas_split_alloc(&xas, head, compound_order(head),
2594                                 mapping_gfp_mask(mapping) & GFP_RECLAIM_MASK);
2595                 if (xas_error(&xas)) {
2596                         ret = xas_error(&xas);
2597                         goto out;
2598                 }
2599
2600                 anon_vma = NULL;
2601                 i_mmap_lock_read(mapping);
2602
2603                 /*
2604                  *__split_huge_page() may need to trim off pages beyond EOF:
2605                  * but on 32-bit, i_size_read() takes an irq-unsafe seqlock,
2606                  * which cannot be nested inside the page tree lock. So note
2607                  * end now: i_size itself may be changed at any moment, but
2608                  * head page lock is good enough to serialize the trimming.
2609                  */
2610                 end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2611                 if (shmem_mapping(mapping))
2612                         end = shmem_fallocend(mapping->host, end);
2613         }
2614
2615         /*
2616          * Racy check if we can split the page, before unmap_page() will
2617          * split PMDs
2618          */
2619         if (!can_split_folio(folio, &extra_pins)) {
2620                 ret = -EBUSY;
2621                 goto out_unlock;
2622         }
2623
2624         unmap_page(head);
2625
2626         /* block interrupt reentry in xa_lock and spinlock */
2627         local_irq_disable();
2628         if (mapping) {
2629                 /*
2630                  * Check if the head page is present in page cache.
2631                  * We assume all tail are present too, if head is there.
2632                  */
2633                 xas_lock(&xas);
2634                 xas_reset(&xas);
2635                 if (xas_load(&xas) != head)
2636                         goto fail;
2637         }
2638
2639         /* Prevent deferred_split_scan() touching ->_refcount */
2640         spin_lock(&ds_queue->split_queue_lock);
2641         if (page_ref_freeze(head, 1 + extra_pins)) {
2642                 if (!list_empty(page_deferred_list(head))) {
2643                         ds_queue->split_queue_len--;
2644                         list_del(page_deferred_list(head));
2645                 }
2646                 spin_unlock(&ds_queue->split_queue_lock);
2647                 if (mapping) {
2648                         int nr = thp_nr_pages(head);
2649
2650                         xas_split(&xas, head, thp_order(head));
2651                         if (PageSwapBacked(head)) {
2652                                 __mod_lruvec_page_state(head, NR_SHMEM_THPS,
2653                                                         -nr);
2654                         } else {
2655                                 __mod_lruvec_page_state(head, NR_FILE_THPS,
2656                                                         -nr);
2657                                 filemap_nr_thps_dec(mapping);
2658                         }
2659                 }
2660
2661                 __split_huge_page(page, list, end);
2662                 ret = 0;
2663         } else {
2664                 spin_unlock(&ds_queue->split_queue_lock);
2665 fail:
2666                 if (mapping)
2667                         xas_unlock(&xas);
2668                 local_irq_enable();
2669                 remap_page(folio, folio_nr_pages(folio));
2670                 ret = -EBUSY;
2671         }
2672
2673 out_unlock:
2674         if (anon_vma) {
2675                 anon_vma_unlock_write(anon_vma);
2676                 put_anon_vma(anon_vma);
2677         }
2678         if (mapping)
2679                 i_mmap_unlock_read(mapping);
2680 out:
2681         xas_destroy(&xas);
2682         count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
2683         return ret;
2684 }
2685
2686 void free_transhuge_page(struct page *page)
2687 {
2688         struct deferred_split *ds_queue = get_deferred_split_queue(page);
2689         unsigned long flags;
2690
2691         spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2692         if (!list_empty(page_deferred_list(page))) {
2693                 ds_queue->split_queue_len--;
2694                 list_del(page_deferred_list(page));
2695         }
2696         spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2697         free_compound_page(page);
2698 }
2699
2700 void deferred_split_huge_page(struct page *page)
2701 {
2702         struct deferred_split *ds_queue = get_deferred_split_queue(page);
2703 #ifdef CONFIG_MEMCG
2704         struct mem_cgroup *memcg = page_memcg(compound_head(page));
2705 #endif
2706         unsigned long flags;
2707
2708         VM_BUG_ON_PAGE(!PageTransHuge(page), page);
2709
2710         /*
2711          * The try_to_unmap() in page reclaim path might reach here too,
2712          * this may cause a race condition to corrupt deferred split queue.
2713          * And, if page reclaim is already handling the same page, it is
2714          * unnecessary to handle it again in shrinker.
2715          *
2716          * Check PageSwapCache to determine if the page is being
2717          * handled by page reclaim since THP swap would add the page into
2718          * swap cache before calling try_to_unmap().
2719          */
2720         if (PageSwapCache(page))
2721                 return;
2722
2723         spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2724         if (list_empty(page_deferred_list(page))) {
2725                 count_vm_event(THP_DEFERRED_SPLIT_PAGE);
2726                 list_add_tail(page_deferred_list(page), &ds_queue->split_queue);
2727                 ds_queue->split_queue_len++;
2728 #ifdef CONFIG_MEMCG
2729                 if (memcg)
2730                         set_shrinker_bit(memcg, page_to_nid(page),
2731                                          deferred_split_shrinker.id);
2732 #endif
2733         }
2734         spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2735 }
2736
2737 static unsigned long deferred_split_count(struct shrinker *shrink,
2738                 struct shrink_control *sc)
2739 {
2740         struct pglist_data *pgdata = NODE_DATA(sc->nid);
2741         struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
2742
2743 #ifdef CONFIG_MEMCG
2744         if (sc->memcg)
2745                 ds_queue = &sc->memcg->deferred_split_queue;
2746 #endif
2747         return READ_ONCE(ds_queue->split_queue_len);
2748 }
2749
2750 static unsigned long deferred_split_scan(struct shrinker *shrink,
2751                 struct shrink_control *sc)
2752 {
2753         struct pglist_data *pgdata = NODE_DATA(sc->nid);
2754         struct deferred_split *ds_queue = &pgdata->deferred_split_queue;
2755         unsigned long flags;
2756         LIST_HEAD(list), *pos, *next;
2757         struct page *page;
2758         int split = 0;
2759
2760 #ifdef CONFIG_MEMCG
2761         if (sc->memcg)
2762                 ds_queue = &sc->memcg->deferred_split_queue;
2763 #endif
2764
2765         spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2766         /* Take pin on all head pages to avoid freeing them under us */
2767         list_for_each_safe(pos, next, &ds_queue->split_queue) {
2768                 page = list_entry((void *)pos, struct page, deferred_list);
2769                 page = compound_head(page);
2770                 if (get_page_unless_zero(page)) {
2771                         list_move(page_deferred_list(page), &list);
2772                 } else {
2773                         /* We lost race with put_compound_page() */
2774                         list_del_init(page_deferred_list(page));
2775                         ds_queue->split_queue_len--;
2776                 }
2777                 if (!--sc->nr_to_scan)
2778                         break;
2779         }
2780         spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2781
2782         list_for_each_safe(pos, next, &list) {
2783                 page = list_entry((void *)pos, struct page, deferred_list);
2784                 if (!trylock_page(page))
2785                         goto next;
2786                 /* split_huge_page() removes page from list on success */
2787                 if (!split_huge_page(page))
2788                         split++;
2789                 unlock_page(page);
2790 next:
2791                 put_page(page);
2792         }
2793
2794         spin_lock_irqsave(&ds_queue->split_queue_lock, flags);
2795         list_splice_tail(&list, &ds_queue->split_queue);
2796         spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags);
2797
2798         /*
2799          * Stop shrinker if we didn't split any page, but the queue is empty.
2800          * This can happen if pages were freed under us.
2801          */
2802         if (!split && list_empty(&ds_queue->split_queue))
2803                 return SHRINK_STOP;
2804         return split;
2805 }
2806
2807 static struct shrinker deferred_split_shrinker = {
2808         .count_objects = deferred_split_count,
2809         .scan_objects = deferred_split_scan,
2810         .seeks = DEFAULT_SEEKS,
2811         .flags = SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE |
2812                  SHRINKER_NONSLAB,
2813 };
2814
2815 #ifdef CONFIG_DEBUG_FS
2816 static void split_huge_pages_all(void)
2817 {
2818         struct zone *zone;
2819         struct page *page;
2820         unsigned long pfn, max_zone_pfn;
2821         unsigned long total = 0, split = 0;
2822
2823         pr_debug("Split all THPs\n");
2824         for_each_populated_zone(zone) {
2825                 max_zone_pfn = zone_end_pfn(zone);
2826                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
2827                         if (!pfn_valid(pfn))
2828                                 continue;
2829
2830                         page = pfn_to_page(pfn);
2831                         if (!get_page_unless_zero(page))
2832                                 continue;
2833
2834                         if (zone != page_zone(page))
2835                                 goto next;
2836
2837                         if (!PageHead(page) || PageHuge(page) || !PageLRU(page))
2838                                 goto next;
2839
2840                         total++;
2841                         lock_page(page);
2842                         if (!split_huge_page(page))
2843                                 split++;
2844                         unlock_page(page);
2845 next:
2846                         put_page(page);
2847                         cond_resched();
2848                 }
2849         }
2850
2851         pr_debug("%lu of %lu THP split\n", split, total);
2852 }
2853
2854 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma)
2855 {
2856         return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) ||
2857                     is_vm_hugetlb_page(vma);
2858 }
2859
2860 static int split_huge_pages_pid(int pid, unsigned long vaddr_start,
2861                                 unsigned long vaddr_end)
2862 {
2863         int ret = 0;
2864         struct task_struct *task;
2865         struct mm_struct *mm;
2866         unsigned long total = 0, split = 0;
2867         unsigned long addr;
2868
2869         vaddr_start &= PAGE_MASK;
2870         vaddr_end &= PAGE_MASK;
2871
2872         /* Find the task_struct from pid */
2873         rcu_read_lock();
2874         task = find_task_by_vpid(pid);
2875         if (!task) {
2876                 rcu_read_unlock();
2877                 ret = -ESRCH;
2878                 goto out;
2879         }
2880         get_task_struct(task);
2881         rcu_read_unlock();
2882
2883         /* Find the mm_struct */
2884         mm = get_task_mm(task);
2885         put_task_struct(task);
2886
2887         if (!mm) {
2888                 ret = -EINVAL;
2889                 goto out;
2890         }
2891
2892         pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n",
2893                  pid, vaddr_start, vaddr_end);
2894
2895         mmap_read_lock(mm);
2896         /*
2897          * always increase addr by PAGE_SIZE, since we could have a PTE page
2898          * table filled with PTE-mapped THPs, each of which is distinct.
2899          */
2900         for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) {
2901                 struct vm_area_struct *vma = find_vma(mm, addr);
2902                 struct page *page;
2903
2904                 if (!vma || addr < vma->vm_start)
2905                         break;
2906
2907                 /* skip special VMA and hugetlb VMA */
2908                 if (vma_not_suitable_for_thp_split(vma)) {
2909                         addr = vma->vm_end;
2910                         continue;
2911                 }
2912
2913                 /* FOLL_DUMP to ignore special (like zero) pages */
2914                 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
2915
2916                 if (IS_ERR(page))
2917                         continue;
2918                 if (!page)
2919                         continue;
2920
2921                 if (!is_transparent_hugepage(page))
2922                         goto next;
2923
2924                 total++;
2925                 if (!can_split_folio(page_folio(page), NULL))
2926                         goto next;
2927
2928                 if (!trylock_page(page))
2929                         goto next;
2930
2931                 if (!split_huge_page(page))
2932                         split++;
2933
2934                 unlock_page(page);
2935 next:
2936                 put_page(page);
2937                 cond_resched();
2938         }
2939         mmap_read_unlock(mm);
2940         mmput(mm);
2941
2942         pr_debug("%lu of %lu THP split\n", split, total);
2943
2944 out:
2945         return ret;
2946 }
2947
2948 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start,
2949                                 pgoff_t off_end)
2950 {
2951         struct filename *file;
2952         struct file *candidate;
2953         struct address_space *mapping;
2954         int ret = -EINVAL;
2955         pgoff_t index;
2956         int nr_pages = 1;
2957         unsigned long total = 0, split = 0;
2958
2959         file = getname_kernel(file_path);
2960         if (IS_ERR(file))
2961                 return ret;
2962
2963         candidate = file_open_name(file, O_RDONLY, 0);
2964         if (IS_ERR(candidate))
2965                 goto out;
2966
2967         pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n",
2968                  file_path, off_start, off_end);
2969
2970         mapping = candidate->f_mapping;
2971
2972         for (index = off_start; index < off_end; index += nr_pages) {
2973                 struct page *fpage = pagecache_get_page(mapping, index,
2974                                                 FGP_ENTRY | FGP_HEAD, 0);
2975
2976                 nr_pages = 1;
2977                 if (xa_is_value(fpage) || !fpage)
2978                         continue;
2979
2980                 if (!is_transparent_hugepage(fpage))
2981                         goto next;
2982
2983                 total++;
2984                 nr_pages = thp_nr_pages(fpage);
2985
2986                 if (!trylock_page(fpage))
2987                         goto next;
2988
2989                 if (!split_huge_page(fpage))
2990                         split++;
2991
2992                 unlock_page(fpage);
2993 next:
2994                 put_page(fpage);
2995                 cond_resched();
2996         }
2997
2998         filp_close(candidate, NULL);
2999         ret = 0;
3000
3001         pr_debug("%lu of %lu file-backed THP split\n", split, total);
3002 out:
3003         putname(file);
3004         return ret;
3005 }
3006
3007 #define MAX_INPUT_BUF_SZ 255
3008
3009 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf,
3010                                 size_t count, loff_t *ppops)
3011 {
3012         static DEFINE_MUTEX(split_debug_mutex);
3013         ssize_t ret;
3014         /* hold pid, start_vaddr, end_vaddr or file_path, off_start, off_end */
3015         char input_buf[MAX_INPUT_BUF_SZ];
3016         int pid;
3017         unsigned long vaddr_start, vaddr_end;
3018
3019         ret = mutex_lock_interruptible(&split_debug_mutex);
3020         if (ret)
3021                 return ret;
3022
3023         ret = -EFAULT;
3024
3025         memset(input_buf, 0, MAX_INPUT_BUF_SZ);
3026         if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ)))
3027                 goto out;
3028
3029         input_buf[MAX_INPUT_BUF_SZ - 1] = '\0';
3030
3031         if (input_buf[0] == '/') {
3032                 char *tok;
3033                 char *buf = input_buf;
3034                 char file_path[MAX_INPUT_BUF_SZ];
3035                 pgoff_t off_start = 0, off_end = 0;
3036                 size_t input_len = strlen(input_buf);
3037
3038                 tok = strsep(&buf, ",");
3039                 if (tok) {
3040                         strcpy(file_path, tok);
3041                 } else {
3042                         ret = -EINVAL;
3043                         goto out;
3044                 }
3045
3046                 ret = sscanf(buf, "0x%lx,0x%lx", &off_start, &off_end);
3047                 if (ret != 2) {
3048                         ret = -EINVAL;
3049                         goto out;
3050                 }
3051                 ret = split_huge_pages_in_file(file_path, off_start, off_end);
3052                 if (!ret)
3053                         ret = input_len;
3054
3055                 goto out;
3056         }
3057
3058         ret = sscanf(input_buf, "%d,0x%lx,0x%lx", &pid, &vaddr_start, &vaddr_end);
3059         if (ret == 1 && pid == 1) {
3060                 split_huge_pages_all();
3061                 ret = strlen(input_buf);
3062                 goto out;
3063         } else if (ret != 3) {
3064                 ret = -EINVAL;
3065                 goto out;
3066         }
3067
3068         ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end);
3069         if (!ret)
3070                 ret = strlen(input_buf);
3071 out:
3072         mutex_unlock(&split_debug_mutex);
3073         return ret;
3074
3075 }
3076
3077 static const struct file_operations split_huge_pages_fops = {
3078         .owner   = THIS_MODULE,
3079         .write   = split_huge_pages_write,
3080         .llseek  = no_llseek,
3081 };
3082
3083 static int __init split_huge_pages_debugfs(void)
3084 {
3085         debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
3086                             &split_huge_pages_fops);
3087         return 0;
3088 }
3089 late_initcall(split_huge_pages_debugfs);
3090 #endif
3091
3092 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
3093 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
3094                 struct page *page)
3095 {
3096         struct vm_area_struct *vma = pvmw->vma;
3097         struct mm_struct *mm = vma->vm_mm;
3098         unsigned long address = pvmw->address;
3099         bool anon_exclusive;
3100         pmd_t pmdval;
3101         swp_entry_t entry;
3102         pmd_t pmdswp;
3103
3104         if (!(pvmw->pmd && !pvmw->pte))
3105                 return 0;
3106
3107         flush_cache_range(vma, address, address + HPAGE_PMD_SIZE);
3108         pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
3109
3110         anon_exclusive = PageAnon(page) && PageAnonExclusive(page);
3111         if (anon_exclusive && page_try_share_anon_rmap(page)) {
3112                 set_pmd_at(mm, address, pvmw->pmd, pmdval);
3113                 return -EBUSY;
3114         }
3115
3116         if (pmd_dirty(pmdval))
3117                 set_page_dirty(page);
3118         if (pmd_write(pmdval))
3119                 entry = make_writable_migration_entry(page_to_pfn(page));
3120         else if (anon_exclusive)
3121                 entry = make_readable_exclusive_migration_entry(page_to_pfn(page));
3122         else
3123                 entry = make_readable_migration_entry(page_to_pfn(page));
3124         pmdswp = swp_entry_to_pmd(entry);
3125         if (pmd_soft_dirty(pmdval))
3126                 pmdswp = pmd_swp_mksoft_dirty(pmdswp);
3127         set_pmd_at(mm, address, pvmw->pmd, pmdswp);
3128         page_remove_rmap(page, vma, true);
3129         put_page(page);
3130         trace_set_migration_pmd(address, pmd_val(pmdswp));
3131
3132         return 0;
3133 }
3134
3135 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
3136 {
3137         struct vm_area_struct *vma = pvmw->vma;
3138         struct mm_struct *mm = vma->vm_mm;
3139         unsigned long address = pvmw->address;
3140         unsigned long mmun_start = address & HPAGE_PMD_MASK;
3141         pmd_t pmde;
3142         swp_entry_t entry;
3143
3144         if (!(pvmw->pmd && !pvmw->pte))
3145                 return;
3146
3147         entry = pmd_to_swp_entry(*pvmw->pmd);
3148         get_page(new);
3149         pmde = pmd_mkold(mk_huge_pmd(new, vma->vm_page_prot));
3150         if (pmd_swp_soft_dirty(*pvmw->pmd))
3151                 pmde = pmd_mksoft_dirty(pmde);
3152         if (is_writable_migration_entry(entry))
3153                 pmde = maybe_pmd_mkwrite(pmde, vma);
3154         if (pmd_swp_uffd_wp(*pvmw->pmd))
3155                 pmde = pmd_wrprotect(pmd_mkuffd_wp(pmde));
3156
3157         if (PageAnon(new)) {
3158                 rmap_t rmap_flags = RMAP_COMPOUND;
3159
3160                 if (!is_readable_migration_entry(entry))
3161                         rmap_flags |= RMAP_EXCLUSIVE;
3162
3163                 page_add_anon_rmap(new, vma, mmun_start, rmap_flags);
3164         } else {
3165                 page_add_file_rmap(new, vma, true);
3166         }
3167         VM_BUG_ON(pmd_write(pmde) && PageAnon(new) && !PageAnonExclusive(new));
3168         set_pmd_at(mm, mmun_start, pvmw->pmd, pmde);
3169
3170         /* No need to invalidate - it was non-present before */
3171         update_mmu_cache_pmd(vma, address, pvmw->pmd);
3172         trace_remove_migration_pmd(address, pmd_val(pmde));
3173 }
3174 #endif