mm: add a call to flush_cache_vmap() in vmap_pfn()
[platform/kernel/linux-starfive.git] / mm / khugepaged.c
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3
4 #include <linux/mm.h>
5 #include <linux/sched.h>
6 #include <linux/sched/mm.h>
7 #include <linux/sched/coredump.h>
8 #include <linux/mmu_notifier.h>
9 #include <linux/rmap.h>
10 #include <linux/swap.h>
11 #include <linux/mm_inline.h>
12 #include <linux/kthread.h>
13 #include <linux/khugepaged.h>
14 #include <linux/freezer.h>
15 #include <linux/mman.h>
16 #include <linux/hashtable.h>
17 #include <linux/userfaultfd_k.h>
18 #include <linux/page_idle.h>
19 #include <linux/page_table_check.h>
20 #include <linux/swapops.h>
21 #include <linux/shmem_fs.h>
22
23 #include <asm/tlb.h>
24 #include <asm/pgalloc.h>
25 #include "internal.h"
26 #include "mm_slot.h"
27
28 enum scan_result {
29         SCAN_FAIL,
30         SCAN_SUCCEED,
31         SCAN_PMD_NULL,
32         SCAN_PMD_NONE,
33         SCAN_PMD_MAPPED,
34         SCAN_EXCEED_NONE_PTE,
35         SCAN_EXCEED_SWAP_PTE,
36         SCAN_EXCEED_SHARED_PTE,
37         SCAN_PTE_NON_PRESENT,
38         SCAN_PTE_UFFD_WP,
39         SCAN_PTE_MAPPED_HUGEPAGE,
40         SCAN_PAGE_RO,
41         SCAN_LACK_REFERENCED_PAGE,
42         SCAN_PAGE_NULL,
43         SCAN_SCAN_ABORT,
44         SCAN_PAGE_COUNT,
45         SCAN_PAGE_LRU,
46         SCAN_PAGE_LOCK,
47         SCAN_PAGE_ANON,
48         SCAN_PAGE_COMPOUND,
49         SCAN_ANY_PROCESS,
50         SCAN_VMA_NULL,
51         SCAN_VMA_CHECK,
52         SCAN_ADDRESS_RANGE,
53         SCAN_DEL_PAGE_LRU,
54         SCAN_ALLOC_HUGE_PAGE_FAIL,
55         SCAN_CGROUP_CHARGE_FAIL,
56         SCAN_TRUNCATED,
57         SCAN_PAGE_HAS_PRIVATE,
58 };
59
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/huge_memory.h>
62
63 static struct task_struct *khugepaged_thread __read_mostly;
64 static DEFINE_MUTEX(khugepaged_mutex);
65
66 /* default scan 8*512 pte (or vmas) every 30 second */
67 static unsigned int khugepaged_pages_to_scan __read_mostly;
68 static unsigned int khugepaged_pages_collapsed;
69 static unsigned int khugepaged_full_scans;
70 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
71 /* during fragmentation poll the hugepage allocator once every minute */
72 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
73 static unsigned long khugepaged_sleep_expire;
74 static DEFINE_SPINLOCK(khugepaged_mm_lock);
75 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
76 /*
77  * default collapse hugepages if there is at least one pte mapped like
78  * it would have happened if the vma was large enough during page
79  * fault.
80  *
81  * Note that these are only respected if collapse was initiated by khugepaged.
82  */
83 static unsigned int khugepaged_max_ptes_none __read_mostly;
84 static unsigned int khugepaged_max_ptes_swap __read_mostly;
85 static unsigned int khugepaged_max_ptes_shared __read_mostly;
86
87 #define MM_SLOTS_HASH_BITS 10
88 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
89
90 static struct kmem_cache *mm_slot_cache __read_mostly;
91
92 #define MAX_PTE_MAPPED_THP 8
93
94 struct collapse_control {
95         bool is_khugepaged;
96
97         /* Num pages scanned per node */
98         u32 node_load[MAX_NUMNODES];
99
100         /* nodemask for allocation fallback */
101         nodemask_t alloc_nmask;
102 };
103
104 /**
105  * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
106  * @slot: hash lookup from mm to mm_slot
107  * @nr_pte_mapped_thp: number of pte mapped THP
108  * @pte_mapped_thp: address array corresponding pte mapped THP
109  */
110 struct khugepaged_mm_slot {
111         struct mm_slot slot;
112
113         /* pte-mapped THP in this mm */
114         int nr_pte_mapped_thp;
115         unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
116 };
117
118 /**
119  * struct khugepaged_scan - cursor for scanning
120  * @mm_head: the head of the mm list to scan
121  * @mm_slot: the current mm_slot we are scanning
122  * @address: the next address inside that to be scanned
123  *
124  * There is only the one khugepaged_scan instance of this cursor structure.
125  */
126 struct khugepaged_scan {
127         struct list_head mm_head;
128         struct khugepaged_mm_slot *mm_slot;
129         unsigned long address;
130 };
131
132 static struct khugepaged_scan khugepaged_scan = {
133         .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
134 };
135
136 #ifdef CONFIG_SYSFS
137 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
138                                          struct kobj_attribute *attr,
139                                          char *buf)
140 {
141         return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
142 }
143
144 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
145                                           struct kobj_attribute *attr,
146                                           const char *buf, size_t count)
147 {
148         unsigned int msecs;
149         int err;
150
151         err = kstrtouint(buf, 10, &msecs);
152         if (err)
153                 return -EINVAL;
154
155         khugepaged_scan_sleep_millisecs = msecs;
156         khugepaged_sleep_expire = 0;
157         wake_up_interruptible(&khugepaged_wait);
158
159         return count;
160 }
161 static struct kobj_attribute scan_sleep_millisecs_attr =
162         __ATTR_RW(scan_sleep_millisecs);
163
164 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
165                                           struct kobj_attribute *attr,
166                                           char *buf)
167 {
168         return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
169 }
170
171 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
172                                            struct kobj_attribute *attr,
173                                            const char *buf, size_t count)
174 {
175         unsigned int msecs;
176         int err;
177
178         err = kstrtouint(buf, 10, &msecs);
179         if (err)
180                 return -EINVAL;
181
182         khugepaged_alloc_sleep_millisecs = msecs;
183         khugepaged_sleep_expire = 0;
184         wake_up_interruptible(&khugepaged_wait);
185
186         return count;
187 }
188 static struct kobj_attribute alloc_sleep_millisecs_attr =
189         __ATTR_RW(alloc_sleep_millisecs);
190
191 static ssize_t pages_to_scan_show(struct kobject *kobj,
192                                   struct kobj_attribute *attr,
193                                   char *buf)
194 {
195         return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
196 }
197 static ssize_t pages_to_scan_store(struct kobject *kobj,
198                                    struct kobj_attribute *attr,
199                                    const char *buf, size_t count)
200 {
201         unsigned int pages;
202         int err;
203
204         err = kstrtouint(buf, 10, &pages);
205         if (err || !pages)
206                 return -EINVAL;
207
208         khugepaged_pages_to_scan = pages;
209
210         return count;
211 }
212 static struct kobj_attribute pages_to_scan_attr =
213         __ATTR_RW(pages_to_scan);
214
215 static ssize_t pages_collapsed_show(struct kobject *kobj,
216                                     struct kobj_attribute *attr,
217                                     char *buf)
218 {
219         return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
220 }
221 static struct kobj_attribute pages_collapsed_attr =
222         __ATTR_RO(pages_collapsed);
223
224 static ssize_t full_scans_show(struct kobject *kobj,
225                                struct kobj_attribute *attr,
226                                char *buf)
227 {
228         return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
229 }
230 static struct kobj_attribute full_scans_attr =
231         __ATTR_RO(full_scans);
232
233 static ssize_t defrag_show(struct kobject *kobj,
234                            struct kobj_attribute *attr, char *buf)
235 {
236         return single_hugepage_flag_show(kobj, attr, buf,
237                                          TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
238 }
239 static ssize_t defrag_store(struct kobject *kobj,
240                             struct kobj_attribute *attr,
241                             const char *buf, size_t count)
242 {
243         return single_hugepage_flag_store(kobj, attr, buf, count,
244                                  TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
245 }
246 static struct kobj_attribute khugepaged_defrag_attr =
247         __ATTR_RW(defrag);
248
249 /*
250  * max_ptes_none controls if khugepaged should collapse hugepages over
251  * any unmapped ptes in turn potentially increasing the memory
252  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
253  * reduce the available free memory in the system as it
254  * runs. Increasing max_ptes_none will instead potentially reduce the
255  * free memory in the system during the khugepaged scan.
256  */
257 static ssize_t max_ptes_none_show(struct kobject *kobj,
258                                   struct kobj_attribute *attr,
259                                   char *buf)
260 {
261         return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
262 }
263 static ssize_t max_ptes_none_store(struct kobject *kobj,
264                                    struct kobj_attribute *attr,
265                                    const char *buf, size_t count)
266 {
267         int err;
268         unsigned long max_ptes_none;
269
270         err = kstrtoul(buf, 10, &max_ptes_none);
271         if (err || max_ptes_none > HPAGE_PMD_NR - 1)
272                 return -EINVAL;
273
274         khugepaged_max_ptes_none = max_ptes_none;
275
276         return count;
277 }
278 static struct kobj_attribute khugepaged_max_ptes_none_attr =
279         __ATTR_RW(max_ptes_none);
280
281 static ssize_t max_ptes_swap_show(struct kobject *kobj,
282                                   struct kobj_attribute *attr,
283                                   char *buf)
284 {
285         return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
286 }
287
288 static ssize_t max_ptes_swap_store(struct kobject *kobj,
289                                    struct kobj_attribute *attr,
290                                    const char *buf, size_t count)
291 {
292         int err;
293         unsigned long max_ptes_swap;
294
295         err  = kstrtoul(buf, 10, &max_ptes_swap);
296         if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
297                 return -EINVAL;
298
299         khugepaged_max_ptes_swap = max_ptes_swap;
300
301         return count;
302 }
303
304 static struct kobj_attribute khugepaged_max_ptes_swap_attr =
305         __ATTR_RW(max_ptes_swap);
306
307 static ssize_t max_ptes_shared_show(struct kobject *kobj,
308                                     struct kobj_attribute *attr,
309                                     char *buf)
310 {
311         return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
312 }
313
314 static ssize_t max_ptes_shared_store(struct kobject *kobj,
315                                      struct kobj_attribute *attr,
316                                      const char *buf, size_t count)
317 {
318         int err;
319         unsigned long max_ptes_shared;
320
321         err  = kstrtoul(buf, 10, &max_ptes_shared);
322         if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
323                 return -EINVAL;
324
325         khugepaged_max_ptes_shared = max_ptes_shared;
326
327         return count;
328 }
329
330 static struct kobj_attribute khugepaged_max_ptes_shared_attr =
331         __ATTR_RW(max_ptes_shared);
332
333 static struct attribute *khugepaged_attr[] = {
334         &khugepaged_defrag_attr.attr,
335         &khugepaged_max_ptes_none_attr.attr,
336         &khugepaged_max_ptes_swap_attr.attr,
337         &khugepaged_max_ptes_shared_attr.attr,
338         &pages_to_scan_attr.attr,
339         &pages_collapsed_attr.attr,
340         &full_scans_attr.attr,
341         &scan_sleep_millisecs_attr.attr,
342         &alloc_sleep_millisecs_attr.attr,
343         NULL,
344 };
345
346 struct attribute_group khugepaged_attr_group = {
347         .attrs = khugepaged_attr,
348         .name = "khugepaged",
349 };
350 #endif /* CONFIG_SYSFS */
351
352 int hugepage_madvise(struct vm_area_struct *vma,
353                      unsigned long *vm_flags, int advice)
354 {
355         switch (advice) {
356         case MADV_HUGEPAGE:
357 #ifdef CONFIG_S390
358                 /*
359                  * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
360                  * can't handle this properly after s390_enable_sie, so we simply
361                  * ignore the madvise to prevent qemu from causing a SIGSEGV.
362                  */
363                 if (mm_has_pgste(vma->vm_mm))
364                         return 0;
365 #endif
366                 *vm_flags &= ~VM_NOHUGEPAGE;
367                 *vm_flags |= VM_HUGEPAGE;
368                 /*
369                  * If the vma become good for khugepaged to scan,
370                  * register it here without waiting a page fault that
371                  * may not happen any time soon.
372                  */
373                 khugepaged_enter_vma(vma, *vm_flags);
374                 break;
375         case MADV_NOHUGEPAGE:
376                 *vm_flags &= ~VM_HUGEPAGE;
377                 *vm_flags |= VM_NOHUGEPAGE;
378                 /*
379                  * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
380                  * this vma even if we leave the mm registered in khugepaged if
381                  * it got registered before VM_NOHUGEPAGE was set.
382                  */
383                 break;
384         }
385
386         return 0;
387 }
388
389 int __init khugepaged_init(void)
390 {
391         mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
392                                           sizeof(struct khugepaged_mm_slot),
393                                           __alignof__(struct khugepaged_mm_slot),
394                                           0, NULL);
395         if (!mm_slot_cache)
396                 return -ENOMEM;
397
398         khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
399         khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
400         khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
401         khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
402
403         return 0;
404 }
405
406 void __init khugepaged_destroy(void)
407 {
408         kmem_cache_destroy(mm_slot_cache);
409 }
410
411 static inline int hpage_collapse_test_exit(struct mm_struct *mm)
412 {
413         return atomic_read(&mm->mm_users) == 0;
414 }
415
416 void __khugepaged_enter(struct mm_struct *mm)
417 {
418         struct khugepaged_mm_slot *mm_slot;
419         struct mm_slot *slot;
420         int wakeup;
421
422         mm_slot = mm_slot_alloc(mm_slot_cache);
423         if (!mm_slot)
424                 return;
425
426         slot = &mm_slot->slot;
427
428         /* __khugepaged_exit() must not run from under us */
429         VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
430         if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
431                 mm_slot_free(mm_slot_cache, mm_slot);
432                 return;
433         }
434
435         spin_lock(&khugepaged_mm_lock);
436         mm_slot_insert(mm_slots_hash, mm, slot);
437         /*
438          * Insert just behind the scanning cursor, to let the area settle
439          * down a little.
440          */
441         wakeup = list_empty(&khugepaged_scan.mm_head);
442         list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
443         spin_unlock(&khugepaged_mm_lock);
444
445         mmgrab(mm);
446         if (wakeup)
447                 wake_up_interruptible(&khugepaged_wait);
448 }
449
450 void khugepaged_enter_vma(struct vm_area_struct *vma,
451                           unsigned long vm_flags)
452 {
453         if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
454             hugepage_flags_enabled()) {
455                 if (hugepage_vma_check(vma, vm_flags, false, false, true))
456                         __khugepaged_enter(vma->vm_mm);
457         }
458 }
459
460 void __khugepaged_exit(struct mm_struct *mm)
461 {
462         struct khugepaged_mm_slot *mm_slot;
463         struct mm_slot *slot;
464         int free = 0;
465
466         spin_lock(&khugepaged_mm_lock);
467         slot = mm_slot_lookup(mm_slots_hash, mm);
468         mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
469         if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
470                 hash_del(&slot->hash);
471                 list_del(&slot->mm_node);
472                 free = 1;
473         }
474         spin_unlock(&khugepaged_mm_lock);
475
476         if (free) {
477                 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
478                 mm_slot_free(mm_slot_cache, mm_slot);
479                 mmdrop(mm);
480         } else if (mm_slot) {
481                 /*
482                  * This is required to serialize against
483                  * hpage_collapse_test_exit() (which is guaranteed to run
484                  * under mmap sem read mode). Stop here (after we return all
485                  * pagetables will be destroyed) until khugepaged has finished
486                  * working on the pagetables under the mmap_lock.
487                  */
488                 mmap_write_lock(mm);
489                 mmap_write_unlock(mm);
490         }
491 }
492
493 static void release_pte_page(struct page *page)
494 {
495         mod_node_page_state(page_pgdat(page),
496                         NR_ISOLATED_ANON + page_is_file_lru(page),
497                         -compound_nr(page));
498         unlock_page(page);
499         putback_lru_page(page);
500 }
501
502 static void release_pte_pages(pte_t *pte, pte_t *_pte,
503                 struct list_head *compound_pagelist)
504 {
505         struct page *page, *tmp;
506
507         while (--_pte >= pte) {
508                 pte_t pteval = *_pte;
509
510                 page = pte_page(pteval);
511                 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
512                                 !PageCompound(page))
513                         release_pte_page(page);
514         }
515
516         list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
517                 list_del(&page->lru);
518                 release_pte_page(page);
519         }
520 }
521
522 static bool is_refcount_suitable(struct page *page)
523 {
524         int expected_refcount;
525
526         expected_refcount = total_mapcount(page);
527         if (PageSwapCache(page))
528                 expected_refcount += compound_nr(page);
529
530         return page_count(page) == expected_refcount;
531 }
532
533 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
534                                         unsigned long address,
535                                         pte_t *pte,
536                                         struct collapse_control *cc,
537                                         struct list_head *compound_pagelist)
538 {
539         struct page *page = NULL;
540         pte_t *_pte;
541         int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
542         bool writable = false;
543
544         for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
545              _pte++, address += PAGE_SIZE) {
546                 pte_t pteval = *_pte;
547                 if (pte_none(pteval) || (pte_present(pteval) &&
548                                 is_zero_pfn(pte_pfn(pteval)))) {
549                         ++none_or_zero;
550                         if (!userfaultfd_armed(vma) &&
551                             (!cc->is_khugepaged ||
552                              none_or_zero <= khugepaged_max_ptes_none)) {
553                                 continue;
554                         } else {
555                                 result = SCAN_EXCEED_NONE_PTE;
556                                 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
557                                 goto out;
558                         }
559                 }
560                 if (!pte_present(pteval)) {
561                         result = SCAN_PTE_NON_PRESENT;
562                         goto out;
563                 }
564                 if (pte_uffd_wp(pteval)) {
565                         result = SCAN_PTE_UFFD_WP;
566                         goto out;
567                 }
568                 page = vm_normal_page(vma, address, pteval);
569                 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
570                         result = SCAN_PAGE_NULL;
571                         goto out;
572                 }
573
574                 VM_BUG_ON_PAGE(!PageAnon(page), page);
575
576                 if (page_mapcount(page) > 1) {
577                         ++shared;
578                         if (cc->is_khugepaged &&
579                             shared > khugepaged_max_ptes_shared) {
580                                 result = SCAN_EXCEED_SHARED_PTE;
581                                 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
582                                 goto out;
583                         }
584                 }
585
586                 if (PageCompound(page)) {
587                         struct page *p;
588                         page = compound_head(page);
589
590                         /*
591                          * Check if we have dealt with the compound page
592                          * already
593                          */
594                         list_for_each_entry(p, compound_pagelist, lru) {
595                                 if (page == p)
596                                         goto next;
597                         }
598                 }
599
600                 /*
601                  * We can do it before isolate_lru_page because the
602                  * page can't be freed from under us. NOTE: PG_lock
603                  * is needed to serialize against split_huge_page
604                  * when invoked from the VM.
605                  */
606                 if (!trylock_page(page)) {
607                         result = SCAN_PAGE_LOCK;
608                         goto out;
609                 }
610
611                 /*
612                  * Check if the page has any GUP (or other external) pins.
613                  *
614                  * The page table that maps the page has been already unlinked
615                  * from the page table tree and this process cannot get
616                  * an additional pin on the page.
617                  *
618                  * New pins can come later if the page is shared across fork,
619                  * but not from this process. The other process cannot write to
620                  * the page, only trigger CoW.
621                  */
622                 if (!is_refcount_suitable(page)) {
623                         unlock_page(page);
624                         result = SCAN_PAGE_COUNT;
625                         goto out;
626                 }
627
628                 /*
629                  * Isolate the page to avoid collapsing an hugepage
630                  * currently in use by the VM.
631                  */
632                 if (isolate_lru_page(page)) {
633                         unlock_page(page);
634                         result = SCAN_DEL_PAGE_LRU;
635                         goto out;
636                 }
637                 mod_node_page_state(page_pgdat(page),
638                                 NR_ISOLATED_ANON + page_is_file_lru(page),
639                                 compound_nr(page));
640                 VM_BUG_ON_PAGE(!PageLocked(page), page);
641                 VM_BUG_ON_PAGE(PageLRU(page), page);
642
643                 if (PageCompound(page))
644                         list_add_tail(&page->lru, compound_pagelist);
645 next:
646                 /*
647                  * If collapse was initiated by khugepaged, check that there is
648                  * enough young pte to justify collapsing the page
649                  */
650                 if (cc->is_khugepaged &&
651                     (pte_young(pteval) || page_is_young(page) ||
652                      PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
653                                                                      address)))
654                         referenced++;
655
656                 if (pte_write(pteval))
657                         writable = true;
658         }
659
660         if (unlikely(!writable)) {
661                 result = SCAN_PAGE_RO;
662         } else if (unlikely(cc->is_khugepaged && !referenced)) {
663                 result = SCAN_LACK_REFERENCED_PAGE;
664         } else {
665                 result = SCAN_SUCCEED;
666                 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
667                                                     referenced, writable, result);
668                 return result;
669         }
670 out:
671         release_pte_pages(pte, _pte, compound_pagelist);
672         trace_mm_collapse_huge_page_isolate(page, none_or_zero,
673                                             referenced, writable, result);
674         return result;
675 }
676
677 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
678                                       struct vm_area_struct *vma,
679                                       unsigned long address,
680                                       spinlock_t *ptl,
681                                       struct list_head *compound_pagelist)
682 {
683         struct page *src_page, *tmp;
684         pte_t *_pte;
685         for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
686                                 _pte++, page++, address += PAGE_SIZE) {
687                 pte_t pteval = *_pte;
688
689                 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
690                         clear_user_highpage(page, address);
691                         add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
692                         if (is_zero_pfn(pte_pfn(pteval))) {
693                                 /*
694                                  * ptl mostly unnecessary.
695                                  */
696                                 spin_lock(ptl);
697                                 ptep_clear(vma->vm_mm, address, _pte);
698                                 spin_unlock(ptl);
699                         }
700                 } else {
701                         src_page = pte_page(pteval);
702                         copy_user_highpage(page, src_page, address, vma);
703                         if (!PageCompound(src_page))
704                                 release_pte_page(src_page);
705                         /*
706                          * ptl mostly unnecessary, but preempt has to
707                          * be disabled to update the per-cpu stats
708                          * inside page_remove_rmap().
709                          */
710                         spin_lock(ptl);
711                         ptep_clear(vma->vm_mm, address, _pte);
712                         page_remove_rmap(src_page, vma, false);
713                         spin_unlock(ptl);
714                         free_page_and_swap_cache(src_page);
715                 }
716         }
717
718         list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
719                 list_del(&src_page->lru);
720                 mod_node_page_state(page_pgdat(src_page),
721                                     NR_ISOLATED_ANON + page_is_file_lru(src_page),
722                                     -compound_nr(src_page));
723                 unlock_page(src_page);
724                 free_swap_cache(src_page);
725                 putback_lru_page(src_page);
726         }
727 }
728
729 static void khugepaged_alloc_sleep(void)
730 {
731         DEFINE_WAIT(wait);
732
733         add_wait_queue(&khugepaged_wait, &wait);
734         __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
735         schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
736         remove_wait_queue(&khugepaged_wait, &wait);
737 }
738
739 struct collapse_control khugepaged_collapse_control = {
740         .is_khugepaged = true,
741 };
742
743 static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
744 {
745         int i;
746
747         /*
748          * If node_reclaim_mode is disabled, then no extra effort is made to
749          * allocate memory locally.
750          */
751         if (!node_reclaim_enabled())
752                 return false;
753
754         /* If there is a count for this node already, it must be acceptable */
755         if (cc->node_load[nid])
756                 return false;
757
758         for (i = 0; i < MAX_NUMNODES; i++) {
759                 if (!cc->node_load[i])
760                         continue;
761                 if (node_distance(nid, i) > node_reclaim_distance)
762                         return true;
763         }
764         return false;
765 }
766
767 #define khugepaged_defrag()                                     \
768         (transparent_hugepage_flags &                           \
769          (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
770
771 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
772 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
773 {
774         return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
775 }
776
777 #ifdef CONFIG_NUMA
778 static int hpage_collapse_find_target_node(struct collapse_control *cc)
779 {
780         int nid, target_node = 0, max_value = 0;
781
782         /* find first node with max normal pages hit */
783         for (nid = 0; nid < MAX_NUMNODES; nid++)
784                 if (cc->node_load[nid] > max_value) {
785                         max_value = cc->node_load[nid];
786                         target_node = nid;
787                 }
788
789         for_each_online_node(nid) {
790                 if (max_value == cc->node_load[nid])
791                         node_set(nid, cc->alloc_nmask);
792         }
793
794         return target_node;
795 }
796 #else
797 static int hpage_collapse_find_target_node(struct collapse_control *cc)
798 {
799         return 0;
800 }
801 #endif
802
803 static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node,
804                                       nodemask_t *nmask)
805 {
806         *hpage = __alloc_pages(gfp, HPAGE_PMD_ORDER, node, nmask);
807         if (unlikely(!*hpage)) {
808                 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
809                 return false;
810         }
811
812         prep_transhuge_page(*hpage);
813         count_vm_event(THP_COLLAPSE_ALLOC);
814         return true;
815 }
816
817 /*
818  * If mmap_lock temporarily dropped, revalidate vma
819  * before taking mmap_lock.
820  * Returns enum scan_result value.
821  */
822
823 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
824                                    bool expect_anon,
825                                    struct vm_area_struct **vmap,
826                                    struct collapse_control *cc)
827 {
828         struct vm_area_struct *vma;
829
830         if (unlikely(hpage_collapse_test_exit(mm)))
831                 return SCAN_ANY_PROCESS;
832
833         *vmap = vma = find_vma(mm, address);
834         if (!vma)
835                 return SCAN_VMA_NULL;
836
837         if (!transhuge_vma_suitable(vma, address))
838                 return SCAN_ADDRESS_RANGE;
839         if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
840                                 cc->is_khugepaged))
841                 return SCAN_VMA_CHECK;
842         /*
843          * Anon VMA expected, the address may be unmapped then
844          * remapped to file after khugepaged reaquired the mmap_lock.
845          *
846          * hugepage_vma_check may return true for qualified file
847          * vmas.
848          */
849         if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
850                 return SCAN_PAGE_ANON;
851         return SCAN_SUCCEED;
852 }
853
854 /*
855  * See pmd_trans_unstable() for how the result may change out from
856  * underneath us, even if we hold mmap_lock in read.
857  */
858 static int find_pmd_or_thp_or_none(struct mm_struct *mm,
859                                    unsigned long address,
860                                    pmd_t **pmd)
861 {
862         pmd_t pmde;
863
864         *pmd = mm_find_pmd(mm, address);
865         if (!*pmd)
866                 return SCAN_PMD_NULL;
867
868         pmde = pmd_read_atomic(*pmd);
869
870 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
871         /* See comments in pmd_none_or_trans_huge_or_clear_bad() */
872         barrier();
873 #endif
874         if (pmd_none(pmde))
875                 return SCAN_PMD_NONE;
876         if (!pmd_present(pmde))
877                 return SCAN_PMD_NULL;
878         if (pmd_trans_huge(pmde))
879                 return SCAN_PMD_MAPPED;
880         if (pmd_devmap(pmde))
881                 return SCAN_PMD_NULL;
882         if (pmd_bad(pmde))
883                 return SCAN_PMD_NULL;
884         return SCAN_SUCCEED;
885 }
886
887 static int check_pmd_still_valid(struct mm_struct *mm,
888                                  unsigned long address,
889                                  pmd_t *pmd)
890 {
891         pmd_t *new_pmd;
892         int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
893
894         if (result != SCAN_SUCCEED)
895                 return result;
896         if (new_pmd != pmd)
897                 return SCAN_FAIL;
898         return SCAN_SUCCEED;
899 }
900
901 /*
902  * Bring missing pages in from swap, to complete THP collapse.
903  * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
904  *
905  * Called and returns without pte mapped or spinlocks held.
906  * Note that if false is returned, mmap_lock will be released.
907  */
908
909 static int __collapse_huge_page_swapin(struct mm_struct *mm,
910                                        struct vm_area_struct *vma,
911                                        unsigned long haddr, pmd_t *pmd,
912                                        int referenced)
913 {
914         int swapped_in = 0;
915         vm_fault_t ret = 0;
916         unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
917
918         for (address = haddr; address < end; address += PAGE_SIZE) {
919                 struct vm_fault vmf = {
920                         .vma = vma,
921                         .address = address,
922                         .pgoff = linear_page_index(vma, haddr),
923                         .flags = FAULT_FLAG_ALLOW_RETRY,
924                         .pmd = pmd,
925                 };
926
927                 vmf.pte = pte_offset_map(pmd, address);
928                 vmf.orig_pte = *vmf.pte;
929                 if (!is_swap_pte(vmf.orig_pte)) {
930                         pte_unmap(vmf.pte);
931                         continue;
932                 }
933                 ret = do_swap_page(&vmf);
934
935                 /*
936                  * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
937                  * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
938                  * we do not retry here and swap entry will remain in pagetable
939                  * resulting in later failure.
940                  */
941                 if (ret & VM_FAULT_RETRY) {
942                         trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
943                         /* Likely, but not guaranteed, that page lock failed */
944                         return SCAN_PAGE_LOCK;
945                 }
946                 if (ret & VM_FAULT_ERROR) {
947                         mmap_read_unlock(mm);
948                         trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
949                         return SCAN_FAIL;
950                 }
951                 swapped_in++;
952         }
953
954         /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
955         if (swapped_in)
956                 lru_add_drain();
957
958         trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
959         return SCAN_SUCCEED;
960 }
961
962 static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
963                               struct collapse_control *cc)
964 {
965         gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
966                      GFP_TRANSHUGE);
967         int node = hpage_collapse_find_target_node(cc);
968
969         if (!hpage_collapse_alloc_page(hpage, gfp, node, &cc->alloc_nmask))
970                 return SCAN_ALLOC_HUGE_PAGE_FAIL;
971         if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
972                 return SCAN_CGROUP_CHARGE_FAIL;
973         count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
974         return SCAN_SUCCEED;
975 }
976
977 static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
978                               int referenced, int unmapped,
979                               struct collapse_control *cc)
980 {
981         LIST_HEAD(compound_pagelist);
982         pmd_t *pmd, _pmd;
983         pte_t *pte;
984         pgtable_t pgtable;
985         struct page *hpage;
986         spinlock_t *pmd_ptl, *pte_ptl;
987         int result = SCAN_FAIL;
988         struct vm_area_struct *vma;
989         struct mmu_notifier_range range;
990
991         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
992
993         /*
994          * Before allocating the hugepage, release the mmap_lock read lock.
995          * The allocation can take potentially a long time if it involves
996          * sync compaction, and we do not need to hold the mmap_lock during
997          * that. We will recheck the vma after taking it again in write mode.
998          */
999         mmap_read_unlock(mm);
1000
1001         result = alloc_charge_hpage(&hpage, mm, cc);
1002         if (result != SCAN_SUCCEED)
1003                 goto out_nolock;
1004
1005         mmap_read_lock(mm);
1006         result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1007         if (result != SCAN_SUCCEED) {
1008                 mmap_read_unlock(mm);
1009                 goto out_nolock;
1010         }
1011
1012         result = find_pmd_or_thp_or_none(mm, address, &pmd);
1013         if (result != SCAN_SUCCEED) {
1014                 mmap_read_unlock(mm);
1015                 goto out_nolock;
1016         }
1017
1018         if (unmapped) {
1019                 /*
1020                  * __collapse_huge_page_swapin will return with mmap_lock
1021                  * released when it fails. So we jump out_nolock directly in
1022                  * that case.  Continuing to collapse causes inconsistency.
1023                  */
1024                 result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1025                                                      referenced);
1026                 if (result != SCAN_SUCCEED)
1027                         goto out_nolock;
1028         }
1029
1030         mmap_read_unlock(mm);
1031         /*
1032          * Prevent all access to pagetables with the exception of
1033          * gup_fast later handled by the ptep_clear_flush and the VM
1034          * handled by the anon_vma lock + PG_lock.
1035          */
1036         mmap_write_lock(mm);
1037         result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1038         if (result != SCAN_SUCCEED)
1039                 goto out_up_write;
1040         /* check if the pmd is still valid */
1041         result = check_pmd_still_valid(mm, address, pmd);
1042         if (result != SCAN_SUCCEED)
1043                 goto out_up_write;
1044
1045         anon_vma_lock_write(vma->anon_vma);
1046
1047         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
1048                                 address, address + HPAGE_PMD_SIZE);
1049         mmu_notifier_invalidate_range_start(&range);
1050
1051         pte = pte_offset_map(pmd, address);
1052         pte_ptl = pte_lockptr(mm, pmd);
1053
1054         pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1055         /*
1056          * This removes any huge TLB entry from the CPU so we won't allow
1057          * huge and small TLB entries for the same virtual address to
1058          * avoid the risk of CPU bugs in that area.
1059          *
1060          * Parallel fast GUP is fine since fast GUP will back off when
1061          * it detects PMD is changed.
1062          */
1063         _pmd = pmdp_collapse_flush(vma, address, pmd);
1064         spin_unlock(pmd_ptl);
1065         mmu_notifier_invalidate_range_end(&range);
1066         tlb_remove_table_sync_one();
1067
1068         spin_lock(pte_ptl);
1069         result =  __collapse_huge_page_isolate(vma, address, pte, cc,
1070                                                &compound_pagelist);
1071         spin_unlock(pte_ptl);
1072
1073         if (unlikely(result != SCAN_SUCCEED)) {
1074                 pte_unmap(pte);
1075                 spin_lock(pmd_ptl);
1076                 BUG_ON(!pmd_none(*pmd));
1077                 /*
1078                  * We can only use set_pmd_at when establishing
1079                  * hugepmds and never for establishing regular pmds that
1080                  * points to regular pagetables. Use pmd_populate for that
1081                  */
1082                 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1083                 spin_unlock(pmd_ptl);
1084                 anon_vma_unlock_write(vma->anon_vma);
1085                 goto out_up_write;
1086         }
1087
1088         /*
1089          * All pages are isolated and locked so anon_vma rmap
1090          * can't run anymore.
1091          */
1092         anon_vma_unlock_write(vma->anon_vma);
1093
1094         __collapse_huge_page_copy(pte, hpage, vma, address, pte_ptl,
1095                                   &compound_pagelist);
1096         pte_unmap(pte);
1097         /*
1098          * spin_lock() below is not the equivalent of smp_wmb(), but
1099          * the smp_wmb() inside __SetPageUptodate() can be reused to
1100          * avoid the copy_huge_page writes to become visible after
1101          * the set_pmd_at() write.
1102          */
1103         __SetPageUptodate(hpage);
1104         pgtable = pmd_pgtable(_pmd);
1105
1106         _pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1107         _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1108
1109         spin_lock(pmd_ptl);
1110         BUG_ON(!pmd_none(*pmd));
1111         page_add_new_anon_rmap(hpage, vma, address);
1112         lru_cache_add_inactive_or_unevictable(hpage, vma);
1113         pgtable_trans_huge_deposit(mm, pmd, pgtable);
1114         set_pmd_at(mm, address, pmd, _pmd);
1115         update_mmu_cache_pmd(vma, address, pmd);
1116         spin_unlock(pmd_ptl);
1117
1118         hpage = NULL;
1119
1120         result = SCAN_SUCCEED;
1121 out_up_write:
1122         mmap_write_unlock(mm);
1123 out_nolock:
1124         if (hpage) {
1125                 mem_cgroup_uncharge(page_folio(hpage));
1126                 put_page(hpage);
1127         }
1128         trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1129         return result;
1130 }
1131
1132 static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1133                                    struct vm_area_struct *vma,
1134                                    unsigned long address, bool *mmap_locked,
1135                                    struct collapse_control *cc)
1136 {
1137         pmd_t *pmd;
1138         pte_t *pte, *_pte;
1139         int result = SCAN_FAIL, referenced = 0;
1140         int none_or_zero = 0, shared = 0;
1141         struct page *page = NULL;
1142         unsigned long _address;
1143         spinlock_t *ptl;
1144         int node = NUMA_NO_NODE, unmapped = 0;
1145         bool writable = false;
1146
1147         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1148
1149         result = find_pmd_or_thp_or_none(mm, address, &pmd);
1150         if (result != SCAN_SUCCEED)
1151                 goto out;
1152
1153         memset(cc->node_load, 0, sizeof(cc->node_load));
1154         nodes_clear(cc->alloc_nmask);
1155         pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1156         for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1157              _pte++, _address += PAGE_SIZE) {
1158                 pte_t pteval = *_pte;
1159                 if (is_swap_pte(pteval)) {
1160                         ++unmapped;
1161                         if (!cc->is_khugepaged ||
1162                             unmapped <= khugepaged_max_ptes_swap) {
1163                                 /*
1164                                  * Always be strict with uffd-wp
1165                                  * enabled swap entries.  Please see
1166                                  * comment below for pte_uffd_wp().
1167                                  */
1168                                 if (pte_swp_uffd_wp(pteval)) {
1169                                         result = SCAN_PTE_UFFD_WP;
1170                                         goto out_unmap;
1171                                 }
1172                                 continue;
1173                         } else {
1174                                 result = SCAN_EXCEED_SWAP_PTE;
1175                                 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1176                                 goto out_unmap;
1177                         }
1178                 }
1179                 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1180                         ++none_or_zero;
1181                         if (!userfaultfd_armed(vma) &&
1182                             (!cc->is_khugepaged ||
1183                              none_or_zero <= khugepaged_max_ptes_none)) {
1184                                 continue;
1185                         } else {
1186                                 result = SCAN_EXCEED_NONE_PTE;
1187                                 count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1188                                 goto out_unmap;
1189                         }
1190                 }
1191                 if (pte_uffd_wp(pteval)) {
1192                         /*
1193                          * Don't collapse the page if any of the small
1194                          * PTEs are armed with uffd write protection.
1195                          * Here we can also mark the new huge pmd as
1196                          * write protected if any of the small ones is
1197                          * marked but that could bring unknown
1198                          * userfault messages that falls outside of
1199                          * the registered range.  So, just be simple.
1200                          */
1201                         result = SCAN_PTE_UFFD_WP;
1202                         goto out_unmap;
1203                 }
1204                 if (pte_write(pteval))
1205                         writable = true;
1206
1207                 page = vm_normal_page(vma, _address, pteval);
1208                 if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1209                         result = SCAN_PAGE_NULL;
1210                         goto out_unmap;
1211                 }
1212
1213                 if (page_mapcount(page) > 1) {
1214                         ++shared;
1215                         if (cc->is_khugepaged &&
1216                             shared > khugepaged_max_ptes_shared) {
1217                                 result = SCAN_EXCEED_SHARED_PTE;
1218                                 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1219                                 goto out_unmap;
1220                         }
1221                 }
1222
1223                 page = compound_head(page);
1224
1225                 /*
1226                  * Record which node the original page is from and save this
1227                  * information to cc->node_load[].
1228                  * Khugepaged will allocate hugepage from the node has the max
1229                  * hit record.
1230                  */
1231                 node = page_to_nid(page);
1232                 if (hpage_collapse_scan_abort(node, cc)) {
1233                         result = SCAN_SCAN_ABORT;
1234                         goto out_unmap;
1235                 }
1236                 cc->node_load[node]++;
1237                 if (!PageLRU(page)) {
1238                         result = SCAN_PAGE_LRU;
1239                         goto out_unmap;
1240                 }
1241                 if (PageLocked(page)) {
1242                         result = SCAN_PAGE_LOCK;
1243                         goto out_unmap;
1244                 }
1245                 if (!PageAnon(page)) {
1246                         result = SCAN_PAGE_ANON;
1247                         goto out_unmap;
1248                 }
1249
1250                 /*
1251                  * Check if the page has any GUP (or other external) pins.
1252                  *
1253                  * Here the check is racy it may see total_mapcount > refcount
1254                  * in some cases.
1255                  * For example, one process with one forked child process.
1256                  * The parent has the PMD split due to MADV_DONTNEED, then
1257                  * the child is trying unmap the whole PMD, but khugepaged
1258                  * may be scanning the parent between the child has
1259                  * PageDoubleMap flag cleared and dec the mapcount.  So
1260                  * khugepaged may see total_mapcount > refcount.
1261                  *
1262                  * But such case is ephemeral we could always retry collapse
1263                  * later.  However it may report false positive if the page
1264                  * has excessive GUP pins (i.e. 512).  Anyway the same check
1265                  * will be done again later the risk seems low.
1266                  */
1267                 if (!is_refcount_suitable(page)) {
1268                         result = SCAN_PAGE_COUNT;
1269                         goto out_unmap;
1270                 }
1271
1272                 /*
1273                  * If collapse was initiated by khugepaged, check that there is
1274                  * enough young pte to justify collapsing the page
1275                  */
1276                 if (cc->is_khugepaged &&
1277                     (pte_young(pteval) || page_is_young(page) ||
1278                      PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1279                                                                      address)))
1280                         referenced++;
1281         }
1282         if (!writable) {
1283                 result = SCAN_PAGE_RO;
1284         } else if (cc->is_khugepaged &&
1285                    (!referenced ||
1286                     (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1287                 result = SCAN_LACK_REFERENCED_PAGE;
1288         } else {
1289                 result = SCAN_SUCCEED;
1290         }
1291 out_unmap:
1292         pte_unmap_unlock(pte, ptl);
1293         if (result == SCAN_SUCCEED) {
1294                 result = collapse_huge_page(mm, address, referenced,
1295                                             unmapped, cc);
1296                 /* collapse_huge_page will return with the mmap_lock released */
1297                 *mmap_locked = false;
1298         }
1299 out:
1300         trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1301                                      none_or_zero, result, unmapped);
1302         return result;
1303 }
1304
1305 static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1306 {
1307         struct mm_slot *slot = &mm_slot->slot;
1308         struct mm_struct *mm = slot->mm;
1309
1310         lockdep_assert_held(&khugepaged_mm_lock);
1311
1312         if (hpage_collapse_test_exit(mm)) {
1313                 /* free mm_slot */
1314                 hash_del(&slot->hash);
1315                 list_del(&slot->mm_node);
1316
1317                 /*
1318                  * Not strictly needed because the mm exited already.
1319                  *
1320                  * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1321                  */
1322
1323                 /* khugepaged_mm_lock actually not necessary for the below */
1324                 mm_slot_free(mm_slot_cache, mm_slot);
1325                 mmdrop(mm);
1326         }
1327 }
1328
1329 #ifdef CONFIG_SHMEM
1330 /*
1331  * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
1332  * khugepaged should try to collapse the page table.
1333  *
1334  * Note that following race exists:
1335  * (1) khugepaged calls khugepaged_collapse_pte_mapped_thps() for mm_struct A,
1336  *     emptying the A's ->pte_mapped_thp[] array.
1337  * (2) MADV_COLLAPSE collapses some file extent with target mm_struct B, and
1338  *     retract_page_tables() finds a VMA in mm_struct A mapping the same extent
1339  *     (at virtual address X) and adds an entry (for X) into mm_struct A's
1340  *     ->pte-mapped_thp[] array.
1341  * (3) khugepaged calls khugepaged_collapse_scan_file() for mm_struct A at X,
1342  *     sees a pte-mapped THP (SCAN_PTE_MAPPED_HUGEPAGE) and adds an entry
1343  *     (for X) into mm_struct A's ->pte-mapped_thp[] array.
1344  * Thus, it's possible the same address is added multiple times for the same
1345  * mm_struct.  Should this happen, we'll simply attempt
1346  * collapse_pte_mapped_thp() multiple times for the same address, under the same
1347  * exclusive mmap_lock, and assuming the first call is successful, subsequent
1348  * attempts will return quickly (without grabbing any additional locks) when
1349  * a huge pmd is found in find_pmd_or_thp_or_none().  Since this is a cheap
1350  * check, and since this is a rare occurrence, the cost of preventing this
1351  * "multiple-add" is thought to be more expensive than just handling it, should
1352  * it occur.
1353  */
1354 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
1355                                           unsigned long addr)
1356 {
1357         struct khugepaged_mm_slot *mm_slot;
1358         struct mm_slot *slot;
1359         bool ret = false;
1360
1361         VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
1362
1363         spin_lock(&khugepaged_mm_lock);
1364         slot = mm_slot_lookup(mm_slots_hash, mm);
1365         mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
1366         if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) {
1367                 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
1368                 ret = true;
1369         }
1370         spin_unlock(&khugepaged_mm_lock);
1371         return ret;
1372 }
1373
1374 /* hpage must be locked, and mmap_lock must be held in write */
1375 static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1376                         pmd_t *pmdp, struct page *hpage)
1377 {
1378         struct vm_fault vmf = {
1379                 .vma = vma,
1380                 .address = addr,
1381                 .flags = 0,
1382                 .pmd = pmdp,
1383         };
1384
1385         VM_BUG_ON(!PageTransHuge(hpage));
1386         mmap_assert_write_locked(vma->vm_mm);
1387
1388         if (do_set_pmd(&vmf, hpage))
1389                 return SCAN_FAIL;
1390
1391         get_page(hpage);
1392         return SCAN_SUCCEED;
1393 }
1394
1395 /*
1396  * A note about locking:
1397  * Trying to take the page table spinlocks would be useless here because those
1398  * are only used to synchronize:
1399  *
1400  *  - modifying terminal entries (ones that point to a data page, not to another
1401  *    page table)
1402  *  - installing *new* non-terminal entries
1403  *
1404  * Instead, we need roughly the same kind of protection as free_pgtables() or
1405  * mm_take_all_locks() (but only for a single VMA):
1406  * The mmap lock together with this VMA's rmap locks covers all paths towards
1407  * the page table entries we're messing with here, except for hardware page
1408  * table walks and lockless_pages_from_mm().
1409  */
1410 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1411                                   unsigned long addr, pmd_t *pmdp)
1412 {
1413         pmd_t pmd;
1414         struct mmu_notifier_range range;
1415
1416         mmap_assert_write_locked(mm);
1417         if (vma->vm_file)
1418                 lockdep_assert_held_write(&vma->vm_file->f_mapping->i_mmap_rwsem);
1419         /*
1420          * All anon_vmas attached to the VMA have the same root and are
1421          * therefore locked by the same lock.
1422          */
1423         if (vma->anon_vma)
1424                 lockdep_assert_held_write(&vma->anon_vma->root->rwsem);
1425
1426         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm, addr,
1427                                 addr + HPAGE_PMD_SIZE);
1428         mmu_notifier_invalidate_range_start(&range);
1429         pmd = pmdp_collapse_flush(vma, addr, pmdp);
1430         tlb_remove_table_sync_one();
1431         mmu_notifier_invalidate_range_end(&range);
1432         mm_dec_nr_ptes(mm);
1433         page_table_check_pte_clear_range(mm, addr, pmd);
1434         pte_free(mm, pmd_pgtable(pmd));
1435 }
1436
1437 /**
1438  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1439  * address haddr.
1440  *
1441  * @mm: process address space where collapse happens
1442  * @addr: THP collapse address
1443  * @install_pmd: If a huge PMD should be installed
1444  *
1445  * This function checks whether all the PTEs in the PMD are pointing to the
1446  * right THP. If so, retract the page table so the THP can refault in with
1447  * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1448  */
1449 int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1450                             bool install_pmd)
1451 {
1452         unsigned long haddr = addr & HPAGE_PMD_MASK;
1453         struct vm_area_struct *vma = vma_lookup(mm, haddr);
1454         struct page *hpage;
1455         pte_t *start_pte, *pte;
1456         pmd_t *pmd;
1457         spinlock_t *ptl;
1458         int count = 0, result = SCAN_FAIL;
1459         int i;
1460
1461         mmap_assert_write_locked(mm);
1462
1463         /* Fast check before locking page if already PMD-mapped */
1464         result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1465         if (result == SCAN_PMD_MAPPED)
1466                 return result;
1467
1468         if (!vma || !vma->vm_file ||
1469             !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1470                 return SCAN_VMA_CHECK;
1471
1472         /*
1473          * If we are here, we've succeeded in replacing all the native pages
1474          * in the page cache with a single hugepage. If a mm were to fault-in
1475          * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1476          * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1477          * analogously elide sysfs THP settings here.
1478          */
1479         if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
1480                 return SCAN_VMA_CHECK;
1481
1482         /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1483         if (userfaultfd_wp(vma))
1484                 return SCAN_PTE_UFFD_WP;
1485
1486         hpage = find_lock_page(vma->vm_file->f_mapping,
1487                                linear_page_index(vma, haddr));
1488         if (!hpage)
1489                 return SCAN_PAGE_NULL;
1490
1491         if (!PageHead(hpage)) {
1492                 result = SCAN_FAIL;
1493                 goto drop_hpage;
1494         }
1495
1496         if (compound_order(hpage) != HPAGE_PMD_ORDER) {
1497                 result = SCAN_PAGE_COMPOUND;
1498                 goto drop_hpage;
1499         }
1500
1501         switch (result) {
1502         case SCAN_SUCCEED:
1503                 break;
1504         case SCAN_PMD_NONE:
1505                 /*
1506                  * In MADV_COLLAPSE path, possible race with khugepaged where
1507                  * all pte entries have been removed and pmd cleared.  If so,
1508                  * skip all the pte checks and just update the pmd mapping.
1509                  */
1510                 goto maybe_install_pmd;
1511         default:
1512                 goto drop_hpage;
1513         }
1514
1515         /*
1516          * We need to lock the mapping so that from here on, only GUP-fast and
1517          * hardware page walks can access the parts of the page tables that
1518          * we're operating on.
1519          * See collapse_and_free_pmd().
1520          */
1521         i_mmap_lock_write(vma->vm_file->f_mapping);
1522
1523         /*
1524          * This spinlock should be unnecessary: Nobody else should be accessing
1525          * the page tables under spinlock protection here, only
1526          * lockless_pages_from_mm() and the hardware page walker can access page
1527          * tables while all the high-level locks are held in write mode.
1528          */
1529         start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1530         result = SCAN_FAIL;
1531
1532         /* step 1: check all mapped PTEs are to the right huge page */
1533         for (i = 0, addr = haddr, pte = start_pte;
1534              i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1535                 struct page *page;
1536
1537                 /* empty pte, skip */
1538                 if (pte_none(*pte))
1539                         continue;
1540
1541                 /* page swapped out, abort */
1542                 if (!pte_present(*pte)) {
1543                         result = SCAN_PTE_NON_PRESENT;
1544                         goto abort;
1545                 }
1546
1547                 page = vm_normal_page(vma, addr, *pte);
1548                 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1549                         page = NULL;
1550                 /*
1551                  * Note that uprobe, debugger, or MAP_PRIVATE may change the
1552                  * page table, but the new page will not be a subpage of hpage.
1553                  */
1554                 if (hpage + i != page)
1555                         goto abort;
1556                 count++;
1557         }
1558
1559         /* step 2: adjust rmap */
1560         for (i = 0, addr = haddr, pte = start_pte;
1561              i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1562                 struct page *page;
1563
1564                 if (pte_none(*pte))
1565                         continue;
1566                 page = vm_normal_page(vma, addr, *pte);
1567                 if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1568                         goto abort;
1569                 page_remove_rmap(page, vma, false);
1570         }
1571
1572         pte_unmap_unlock(start_pte, ptl);
1573
1574         /* step 3: set proper refcount and mm_counters. */
1575         if (count) {
1576                 page_ref_sub(hpage, count);
1577                 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
1578         }
1579
1580         /* step 4: remove pte entries */
1581         /* we make no change to anon, but protect concurrent anon page lookup */
1582         if (vma->anon_vma)
1583                 anon_vma_lock_write(vma->anon_vma);
1584
1585         collapse_and_free_pmd(mm, vma, haddr, pmd);
1586
1587         if (vma->anon_vma)
1588                 anon_vma_unlock_write(vma->anon_vma);
1589         i_mmap_unlock_write(vma->vm_file->f_mapping);
1590
1591 maybe_install_pmd:
1592         /* step 5: install pmd entry */
1593         result = install_pmd
1594                         ? set_huge_pmd(vma, haddr, pmd, hpage)
1595                         : SCAN_SUCCEED;
1596
1597 drop_hpage:
1598         unlock_page(hpage);
1599         put_page(hpage);
1600         return result;
1601
1602 abort:
1603         pte_unmap_unlock(start_pte, ptl);
1604         i_mmap_unlock_write(vma->vm_file->f_mapping);
1605         goto drop_hpage;
1606 }
1607
1608 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
1609 {
1610         struct mm_slot *slot = &mm_slot->slot;
1611         struct mm_struct *mm = slot->mm;
1612         int i;
1613
1614         if (likely(mm_slot->nr_pte_mapped_thp == 0))
1615                 return;
1616
1617         if (!mmap_write_trylock(mm))
1618                 return;
1619
1620         if (unlikely(hpage_collapse_test_exit(mm)))
1621                 goto out;
1622
1623         for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
1624                 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i], false);
1625
1626 out:
1627         mm_slot->nr_pte_mapped_thp = 0;
1628         mmap_write_unlock(mm);
1629 }
1630
1631 static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff,
1632                                struct mm_struct *target_mm,
1633                                unsigned long target_addr, struct page *hpage,
1634                                struct collapse_control *cc)
1635 {
1636         struct vm_area_struct *vma;
1637         int target_result = SCAN_FAIL;
1638
1639         i_mmap_lock_write(mapping);
1640         vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1641                 int result = SCAN_FAIL;
1642                 struct mm_struct *mm = NULL;
1643                 unsigned long addr = 0;
1644                 pmd_t *pmd;
1645                 bool is_target = false;
1646
1647                 /*
1648                  * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1649                  * got written to. These VMAs are likely not worth investing
1650                  * mmap_write_lock(mm) as PMD-mapping is likely to be split
1651                  * later.
1652                  *
1653                  * Note that vma->anon_vma check is racy: it can be set up after
1654                  * the check but before we took mmap_lock by the fault path.
1655                  * But page lock would prevent establishing any new ptes of the
1656                  * page, so we are safe.
1657                  *
1658                  * An alternative would be drop the check, but check that page
1659                  * table is clear before calling pmdp_collapse_flush() under
1660                  * ptl. It has higher chance to recover THP for the VMA, but
1661                  * has higher cost too. It would also probably require locking
1662                  * the anon_vma.
1663                  */
1664                 if (READ_ONCE(vma->anon_vma)) {
1665                         result = SCAN_PAGE_ANON;
1666                         goto next;
1667                 }
1668                 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1669                 if (addr & ~HPAGE_PMD_MASK ||
1670                     vma->vm_end < addr + HPAGE_PMD_SIZE) {
1671                         result = SCAN_VMA_CHECK;
1672                         goto next;
1673                 }
1674                 mm = vma->vm_mm;
1675                 is_target = mm == target_mm && addr == target_addr;
1676                 result = find_pmd_or_thp_or_none(mm, addr, &pmd);
1677                 if (result != SCAN_SUCCEED)
1678                         goto next;
1679                 /*
1680                  * We need exclusive mmap_lock to retract page table.
1681                  *
1682                  * We use trylock due to lock inversion: we need to acquire
1683                  * mmap_lock while holding page lock. Fault path does it in
1684                  * reverse order. Trylock is a way to avoid deadlock.
1685                  *
1686                  * Also, it's not MADV_COLLAPSE's job to collapse other
1687                  * mappings - let khugepaged take care of them later.
1688                  */
1689                 result = SCAN_PTE_MAPPED_HUGEPAGE;
1690                 if ((cc->is_khugepaged || is_target) &&
1691                     mmap_write_trylock(mm)) {
1692                         /*
1693                          * Re-check whether we have an ->anon_vma, because
1694                          * collapse_and_free_pmd() requires that either no
1695                          * ->anon_vma exists or the anon_vma is locked.
1696                          * We already checked ->anon_vma above, but that check
1697                          * is racy because ->anon_vma can be populated under the
1698                          * mmap lock in read mode.
1699                          */
1700                         if (vma->anon_vma) {
1701                                 result = SCAN_PAGE_ANON;
1702                                 goto unlock_next;
1703                         }
1704                         /*
1705                          * When a vma is registered with uffd-wp, we can't
1706                          * recycle the pmd pgtable because there can be pte
1707                          * markers installed.  Skip it only, so the rest mm/vma
1708                          * can still have the same file mapped hugely, however
1709                          * it'll always mapped in small page size for uffd-wp
1710                          * registered ranges.
1711                          */
1712                         if (hpage_collapse_test_exit(mm)) {
1713                                 result = SCAN_ANY_PROCESS;
1714                                 goto unlock_next;
1715                         }
1716                         if (userfaultfd_wp(vma)) {
1717                                 result = SCAN_PTE_UFFD_WP;
1718                                 goto unlock_next;
1719                         }
1720                         collapse_and_free_pmd(mm, vma, addr, pmd);
1721                         if (!cc->is_khugepaged && is_target)
1722                                 result = set_huge_pmd(vma, addr, pmd, hpage);
1723                         else
1724                                 result = SCAN_SUCCEED;
1725
1726 unlock_next:
1727                         mmap_write_unlock(mm);
1728                         goto next;
1729                 }
1730                 /*
1731                  * Calling context will handle target mm/addr. Otherwise, let
1732                  * khugepaged try again later.
1733                  */
1734                 if (!is_target) {
1735                         khugepaged_add_pte_mapped_thp(mm, addr);
1736                         continue;
1737                 }
1738 next:
1739                 if (is_target)
1740                         target_result = result;
1741         }
1742         i_mmap_unlock_write(mapping);
1743         return target_result;
1744 }
1745
1746 /**
1747  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1748  *
1749  * @mm: process address space where collapse happens
1750  * @addr: virtual collapse start address
1751  * @file: file that collapse on
1752  * @start: collapse start address
1753  * @cc: collapse context and scratchpad
1754  *
1755  * Basic scheme is simple, details are more complex:
1756  *  - allocate and lock a new huge page;
1757  *  - scan page cache replacing old pages with the new one
1758  *    + swap/gup in pages if necessary;
1759  *    + fill in gaps;
1760  *    + keep old pages around in case rollback is required;
1761  *  - if replacing succeeds:
1762  *    + copy data over;
1763  *    + free old pages;
1764  *    + unlock huge page;
1765  *  - if replacing failed;
1766  *    + put all pages back and unfreeze them;
1767  *    + restore gaps in the page cache;
1768  *    + unlock and free huge page;
1769  */
1770 static int collapse_file(struct mm_struct *mm, unsigned long addr,
1771                          struct file *file, pgoff_t start,
1772                          struct collapse_control *cc)
1773 {
1774         struct address_space *mapping = file->f_mapping;
1775         struct page *hpage;
1776         pgoff_t index, end = start + HPAGE_PMD_NR;
1777         LIST_HEAD(pagelist);
1778         XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1779         int nr_none = 0, result = SCAN_SUCCEED;
1780         bool is_shmem = shmem_file(file);
1781         int nr;
1782
1783         VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1784         VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1785
1786         result = alloc_charge_hpage(&hpage, mm, cc);
1787         if (result != SCAN_SUCCEED)
1788                 goto out;
1789
1790         /*
1791          * Ensure we have slots for all the pages in the range.  This is
1792          * almost certainly a no-op because most of the pages must be present
1793          */
1794         do {
1795                 xas_lock_irq(&xas);
1796                 xas_create_range(&xas);
1797                 if (!xas_error(&xas))
1798                         break;
1799                 xas_unlock_irq(&xas);
1800                 if (!xas_nomem(&xas, GFP_KERNEL)) {
1801                         result = SCAN_FAIL;
1802                         goto out;
1803                 }
1804         } while (1);
1805
1806         __SetPageLocked(hpage);
1807         if (is_shmem)
1808                 __SetPageSwapBacked(hpage);
1809         hpage->index = start;
1810         hpage->mapping = mapping;
1811
1812         /*
1813          * At this point the hpage is locked and not up-to-date.
1814          * It's safe to insert it into the page cache, because nobody would
1815          * be able to map it or use it in another way until we unlock it.
1816          */
1817
1818         xas_set(&xas, start);
1819         for (index = start; index < end; index++) {
1820                 struct page *page = xas_next(&xas);
1821
1822                 VM_BUG_ON(index != xas.xa_index);
1823                 if (is_shmem) {
1824                         if (!page) {
1825                                 /*
1826                                  * Stop if extent has been truncated or
1827                                  * hole-punched, and is now completely
1828                                  * empty.
1829                                  */
1830                                 if (index == start) {
1831                                         if (!xas_next_entry(&xas, end - 1)) {
1832                                                 result = SCAN_TRUNCATED;
1833                                                 goto xa_locked;
1834                                         }
1835                                         xas_set(&xas, index);
1836                                 }
1837                                 if (!shmem_charge(mapping->host, 1)) {
1838                                         result = SCAN_FAIL;
1839                                         goto xa_locked;
1840                                 }
1841                                 xas_store(&xas, hpage);
1842                                 nr_none++;
1843                                 continue;
1844                         }
1845
1846                         if (xa_is_value(page) || !PageUptodate(page)) {
1847                                 struct folio *folio;
1848
1849                                 xas_unlock_irq(&xas);
1850                                 /* swap in or instantiate fallocated page */
1851                                 if (shmem_get_folio(mapping->host, index,
1852                                                 &folio, SGP_NOALLOC)) {
1853                                         result = SCAN_FAIL;
1854                                         goto xa_unlocked;
1855                                 }
1856                                 page = folio_file_page(folio, index);
1857                         } else if (trylock_page(page)) {
1858                                 get_page(page);
1859                                 xas_unlock_irq(&xas);
1860                         } else {
1861                                 result = SCAN_PAGE_LOCK;
1862                                 goto xa_locked;
1863                         }
1864                 } else {        /* !is_shmem */
1865                         if (!page || xa_is_value(page)) {
1866                                 xas_unlock_irq(&xas);
1867                                 page_cache_sync_readahead(mapping, &file->f_ra,
1868                                                           file, index,
1869                                                           end - index);
1870                                 /* drain pagevecs to help isolate_lru_page() */
1871                                 lru_add_drain();
1872                                 page = find_lock_page(mapping, index);
1873                                 if (unlikely(page == NULL)) {
1874                                         result = SCAN_FAIL;
1875                                         goto xa_unlocked;
1876                                 }
1877                         } else if (PageDirty(page)) {
1878                                 /*
1879                                  * khugepaged only works on read-only fd,
1880                                  * so this page is dirty because it hasn't
1881                                  * been flushed since first write. There
1882                                  * won't be new dirty pages.
1883                                  *
1884                                  * Trigger async flush here and hope the
1885                                  * writeback is done when khugepaged
1886                                  * revisits this page.
1887                                  *
1888                                  * This is a one-off situation. We are not
1889                                  * forcing writeback in loop.
1890                                  */
1891                                 xas_unlock_irq(&xas);
1892                                 filemap_flush(mapping);
1893                                 result = SCAN_FAIL;
1894                                 goto xa_unlocked;
1895                         } else if (PageWriteback(page)) {
1896                                 xas_unlock_irq(&xas);
1897                                 result = SCAN_FAIL;
1898                                 goto xa_unlocked;
1899                         } else if (trylock_page(page)) {
1900                                 get_page(page);
1901                                 xas_unlock_irq(&xas);
1902                         } else {
1903                                 result = SCAN_PAGE_LOCK;
1904                                 goto xa_locked;
1905                         }
1906                 }
1907
1908                 /*
1909                  * The page must be locked, so we can drop the i_pages lock
1910                  * without racing with truncate.
1911                  */
1912                 VM_BUG_ON_PAGE(!PageLocked(page), page);
1913
1914                 /* make sure the page is up to date */
1915                 if (unlikely(!PageUptodate(page))) {
1916                         result = SCAN_FAIL;
1917                         goto out_unlock;
1918                 }
1919
1920                 /*
1921                  * If file was truncated then extended, or hole-punched, before
1922                  * we locked the first page, then a THP might be there already.
1923                  * This will be discovered on the first iteration.
1924                  */
1925                 if (PageTransCompound(page)) {
1926                         struct page *head = compound_head(page);
1927
1928                         result = compound_order(head) == HPAGE_PMD_ORDER &&
1929                                         head->index == start
1930                                         /* Maybe PMD-mapped */
1931                                         ? SCAN_PTE_MAPPED_HUGEPAGE
1932                                         : SCAN_PAGE_COMPOUND;
1933                         goto out_unlock;
1934                 }
1935
1936                 if (page_mapping(page) != mapping) {
1937                         result = SCAN_TRUNCATED;
1938                         goto out_unlock;
1939                 }
1940
1941                 if (!is_shmem && (PageDirty(page) ||
1942                                   PageWriteback(page))) {
1943                         /*
1944                          * khugepaged only works on read-only fd, so this
1945                          * page is dirty because it hasn't been flushed
1946                          * since first write.
1947                          */
1948                         result = SCAN_FAIL;
1949                         goto out_unlock;
1950                 }
1951
1952                 if (isolate_lru_page(page)) {
1953                         result = SCAN_DEL_PAGE_LRU;
1954                         goto out_unlock;
1955                 }
1956
1957                 if (page_has_private(page) &&
1958                     !try_to_release_page(page, GFP_KERNEL)) {
1959                         result = SCAN_PAGE_HAS_PRIVATE;
1960                         putback_lru_page(page);
1961                         goto out_unlock;
1962                 }
1963
1964                 if (page_mapped(page))
1965                         try_to_unmap(page_folio(page),
1966                                         TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1967
1968                 xas_lock_irq(&xas);
1969                 xas_set(&xas, index);
1970
1971                 VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1972
1973                 /*
1974                  * The page is expected to have page_count() == 3:
1975                  *  - we hold a pin on it;
1976                  *  - one reference from page cache;
1977                  *  - one from isolate_lru_page;
1978                  */
1979                 if (!page_ref_freeze(page, 3)) {
1980                         result = SCAN_PAGE_COUNT;
1981                         xas_unlock_irq(&xas);
1982                         putback_lru_page(page);
1983                         goto out_unlock;
1984                 }
1985
1986                 /*
1987                  * Add the page to the list to be able to undo the collapse if
1988                  * something go wrong.
1989                  */
1990                 list_add_tail(&page->lru, &pagelist);
1991
1992                 /* Finally, replace with the new page. */
1993                 xas_store(&xas, hpage);
1994                 continue;
1995 out_unlock:
1996                 unlock_page(page);
1997                 put_page(page);
1998                 goto xa_unlocked;
1999         }
2000         nr = thp_nr_pages(hpage);
2001
2002         if (is_shmem)
2003                 __mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
2004         else {
2005                 __mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
2006                 filemap_nr_thps_inc(mapping);
2007                 /*
2008                  * Paired with smp_mb() in do_dentry_open() to ensure
2009                  * i_writecount is up to date and the update to nr_thps is
2010                  * visible. Ensures the page cache will be truncated if the
2011                  * file is opened writable.
2012                  */
2013                 smp_mb();
2014                 if (inode_is_open_for_write(mapping->host)) {
2015                         result = SCAN_FAIL;
2016                         __mod_lruvec_page_state(hpage, NR_FILE_THPS, -nr);
2017                         filemap_nr_thps_dec(mapping);
2018                         goto xa_locked;
2019                 }
2020         }
2021
2022         if (nr_none) {
2023                 __mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
2024                 /* nr_none is always 0 for non-shmem. */
2025                 __mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2026         }
2027
2028         /* Join all the small entries into a single multi-index entry */
2029         xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2030         xas_store(&xas, hpage);
2031 xa_locked:
2032         xas_unlock_irq(&xas);
2033 xa_unlocked:
2034
2035         /*
2036          * If collapse is successful, flush must be done now before copying.
2037          * If collapse is unsuccessful, does flush actually need to be done?
2038          * Do it anyway, to clear the state.
2039          */
2040         try_to_unmap_flush();
2041
2042         if (result == SCAN_SUCCEED) {
2043                 struct page *page, *tmp;
2044
2045                 /*
2046                  * Replacing old pages with new one has succeeded, now we
2047                  * need to copy the content and free the old pages.
2048                  */
2049                 index = start;
2050                 list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2051                         while (index < page->index) {
2052                                 clear_highpage(hpage + (index % HPAGE_PMD_NR));
2053                                 index++;
2054                         }
2055                         copy_highpage(hpage + (page->index % HPAGE_PMD_NR),
2056                                       page);
2057                         list_del(&page->lru);
2058                         page->mapping = NULL;
2059                         page_ref_unfreeze(page, 1);
2060                         ClearPageActive(page);
2061                         ClearPageUnevictable(page);
2062                         unlock_page(page);
2063                         put_page(page);
2064                         index++;
2065                 }
2066                 while (index < end) {
2067                         clear_highpage(hpage + (index % HPAGE_PMD_NR));
2068                         index++;
2069                 }
2070
2071                 SetPageUptodate(hpage);
2072                 page_ref_add(hpage, HPAGE_PMD_NR - 1);
2073                 if (is_shmem)
2074                         set_page_dirty(hpage);
2075                 lru_cache_add(hpage);
2076
2077                 /*
2078                  * Remove pte page tables, so we can re-fault the page as huge.
2079                  */
2080                 result = retract_page_tables(mapping, start, mm, addr, hpage,
2081                                              cc);
2082                 unlock_page(hpage);
2083                 hpage = NULL;
2084         } else {
2085                 struct page *page;
2086
2087                 /* Something went wrong: roll back page cache changes */
2088                 xas_lock_irq(&xas);
2089                 if (nr_none) {
2090                         mapping->nrpages -= nr_none;
2091                         shmem_uncharge(mapping->host, nr_none);
2092                 }
2093
2094                 xas_set(&xas, start);
2095                 xas_for_each(&xas, page, end - 1) {
2096                         page = list_first_entry_or_null(&pagelist,
2097                                         struct page, lru);
2098                         if (!page || xas.xa_index < page->index) {
2099                                 if (!nr_none)
2100                                         break;
2101                                 nr_none--;
2102                                 /* Put holes back where they were */
2103                                 xas_store(&xas, NULL);
2104                                 continue;
2105                         }
2106
2107                         VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2108
2109                         /* Unfreeze the page. */
2110                         list_del(&page->lru);
2111                         page_ref_unfreeze(page, 2);
2112                         xas_store(&xas, page);
2113                         xas_pause(&xas);
2114                         xas_unlock_irq(&xas);
2115                         unlock_page(page);
2116                         putback_lru_page(page);
2117                         xas_lock_irq(&xas);
2118                 }
2119                 VM_BUG_ON(nr_none);
2120                 xas_unlock_irq(&xas);
2121
2122                 hpage->mapping = NULL;
2123         }
2124
2125         if (hpage)
2126                 unlock_page(hpage);
2127 out:
2128         VM_BUG_ON(!list_empty(&pagelist));
2129         if (hpage) {
2130                 mem_cgroup_uncharge(page_folio(hpage));
2131                 put_page(hpage);
2132         }
2133         /* TODO: tracepoints */
2134         return result;
2135 }
2136
2137 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2138                                     struct file *file, pgoff_t start,
2139                                     struct collapse_control *cc)
2140 {
2141         struct page *page = NULL;
2142         struct address_space *mapping = file->f_mapping;
2143         XA_STATE(xas, &mapping->i_pages, start);
2144         int present, swap;
2145         int node = NUMA_NO_NODE;
2146         int result = SCAN_SUCCEED;
2147
2148         present = 0;
2149         swap = 0;
2150         memset(cc->node_load, 0, sizeof(cc->node_load));
2151         nodes_clear(cc->alloc_nmask);
2152         rcu_read_lock();
2153         xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
2154                 if (xas_retry(&xas, page))
2155                         continue;
2156
2157                 if (xa_is_value(page)) {
2158                         ++swap;
2159                         if (cc->is_khugepaged &&
2160                             swap > khugepaged_max_ptes_swap) {
2161                                 result = SCAN_EXCEED_SWAP_PTE;
2162                                 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2163                                 break;
2164                         }
2165                         continue;
2166                 }
2167
2168                 /*
2169                  * TODO: khugepaged should compact smaller compound pages
2170                  * into a PMD sized page
2171                  */
2172                 if (PageTransCompound(page)) {
2173                         struct page *head = compound_head(page);
2174
2175                         result = compound_order(head) == HPAGE_PMD_ORDER &&
2176                                         head->index == start
2177                                         /* Maybe PMD-mapped */
2178                                         ? SCAN_PTE_MAPPED_HUGEPAGE
2179                                         : SCAN_PAGE_COMPOUND;
2180                         /*
2181                          * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2182                          * by the caller won't touch the page cache, and so
2183                          * it's safe to skip LRU and refcount checks before
2184                          * returning.
2185                          */
2186                         break;
2187                 }
2188
2189                 node = page_to_nid(page);
2190                 if (hpage_collapse_scan_abort(node, cc)) {
2191                         result = SCAN_SCAN_ABORT;
2192                         break;
2193                 }
2194                 cc->node_load[node]++;
2195
2196                 if (!PageLRU(page)) {
2197                         result = SCAN_PAGE_LRU;
2198                         break;
2199                 }
2200
2201                 if (page_count(page) !=
2202                     1 + page_mapcount(page) + page_has_private(page)) {
2203                         result = SCAN_PAGE_COUNT;
2204                         break;
2205                 }
2206
2207                 /*
2208                  * We probably should check if the page is referenced here, but
2209                  * nobody would transfer pte_young() to PageReferenced() for us.
2210                  * And rmap walk here is just too costly...
2211                  */
2212
2213                 present++;
2214
2215                 if (need_resched()) {
2216                         xas_pause(&xas);
2217                         cond_resched_rcu();
2218                 }
2219         }
2220         rcu_read_unlock();
2221
2222         if (result == SCAN_SUCCEED) {
2223                 if (cc->is_khugepaged &&
2224                     present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2225                         result = SCAN_EXCEED_NONE_PTE;
2226                         count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2227                 } else {
2228                         result = collapse_file(mm, addr, file, start, cc);
2229                 }
2230         }
2231
2232         trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
2233         return result;
2234 }
2235 #else
2236 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2237                                     struct file *file, pgoff_t start,
2238                                     struct collapse_control *cc)
2239 {
2240         BUILD_BUG();
2241 }
2242
2243 static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
2244 {
2245 }
2246
2247 static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
2248                                           unsigned long addr)
2249 {
2250         return false;
2251 }
2252 #endif
2253
2254 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2255                                             struct collapse_control *cc)
2256         __releases(&khugepaged_mm_lock)
2257         __acquires(&khugepaged_mm_lock)
2258 {
2259         struct vma_iterator vmi;
2260         struct khugepaged_mm_slot *mm_slot;
2261         struct mm_slot *slot;
2262         struct mm_struct *mm;
2263         struct vm_area_struct *vma;
2264         int progress = 0;
2265
2266         VM_BUG_ON(!pages);
2267         lockdep_assert_held(&khugepaged_mm_lock);
2268         *result = SCAN_FAIL;
2269
2270         if (khugepaged_scan.mm_slot) {
2271                 mm_slot = khugepaged_scan.mm_slot;
2272                 slot = &mm_slot->slot;
2273         } else {
2274                 slot = list_entry(khugepaged_scan.mm_head.next,
2275                                      struct mm_slot, mm_node);
2276                 mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2277                 khugepaged_scan.address = 0;
2278                 khugepaged_scan.mm_slot = mm_slot;
2279         }
2280         spin_unlock(&khugepaged_mm_lock);
2281         khugepaged_collapse_pte_mapped_thps(mm_slot);
2282
2283         mm = slot->mm;
2284         /*
2285          * Don't wait for semaphore (to avoid long wait times).  Just move to
2286          * the next mm on the list.
2287          */
2288         vma = NULL;
2289         if (unlikely(!mmap_read_trylock(mm)))
2290                 goto breakouterloop_mmap_lock;
2291
2292         progress++;
2293         if (unlikely(hpage_collapse_test_exit(mm)))
2294                 goto breakouterloop;
2295
2296         vma_iter_init(&vmi, mm, khugepaged_scan.address);
2297         for_each_vma(vmi, vma) {
2298                 unsigned long hstart, hend;
2299
2300                 cond_resched();
2301                 if (unlikely(hpage_collapse_test_exit(mm))) {
2302                         progress++;
2303                         break;
2304                 }
2305                 if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2306 skip:
2307                         progress++;
2308                         continue;
2309                 }
2310                 hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2311                 hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2312                 if (khugepaged_scan.address > hend)
2313                         goto skip;
2314                 if (khugepaged_scan.address < hstart)
2315                         khugepaged_scan.address = hstart;
2316                 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2317
2318                 while (khugepaged_scan.address < hend) {
2319                         bool mmap_locked = true;
2320
2321                         cond_resched();
2322                         if (unlikely(hpage_collapse_test_exit(mm)))
2323                                 goto breakouterloop;
2324
2325                         VM_BUG_ON(khugepaged_scan.address < hstart ||
2326                                   khugepaged_scan.address + HPAGE_PMD_SIZE >
2327                                   hend);
2328                         if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2329                                 struct file *file = get_file(vma->vm_file);
2330                                 pgoff_t pgoff = linear_page_index(vma,
2331                                                 khugepaged_scan.address);
2332
2333                                 mmap_read_unlock(mm);
2334                                 *result = hpage_collapse_scan_file(mm,
2335                                                                    khugepaged_scan.address,
2336                                                                    file, pgoff, cc);
2337                                 mmap_locked = false;
2338                                 fput(file);
2339                         } else {
2340                                 *result = hpage_collapse_scan_pmd(mm, vma,
2341                                                                   khugepaged_scan.address,
2342                                                                   &mmap_locked,
2343                                                                   cc);
2344                         }
2345                         switch (*result) {
2346                         case SCAN_PTE_MAPPED_HUGEPAGE: {
2347                                 pmd_t *pmd;
2348
2349                                 *result = find_pmd_or_thp_or_none(mm,
2350                                                                   khugepaged_scan.address,
2351                                                                   &pmd);
2352                                 if (*result != SCAN_SUCCEED)
2353                                         break;
2354                                 if (!khugepaged_add_pte_mapped_thp(mm,
2355                                                                    khugepaged_scan.address))
2356                                         break;
2357                         } fallthrough;
2358                         case SCAN_SUCCEED:
2359                                 ++khugepaged_pages_collapsed;
2360                                 break;
2361                         default:
2362                                 break;
2363                         }
2364
2365                         /* move to next address */
2366                         khugepaged_scan.address += HPAGE_PMD_SIZE;
2367                         progress += HPAGE_PMD_NR;
2368                         if (!mmap_locked)
2369                                 /*
2370                                  * We released mmap_lock so break loop.  Note
2371                                  * that we drop mmap_lock before all hugepage
2372                                  * allocations, so if allocation fails, we are
2373                                  * guaranteed to break here and report the
2374                                  * correct result back to caller.
2375                                  */
2376                                 goto breakouterloop_mmap_lock;
2377                         if (progress >= pages)
2378                                 goto breakouterloop;
2379                 }
2380         }
2381 breakouterloop:
2382         mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2383 breakouterloop_mmap_lock:
2384
2385         spin_lock(&khugepaged_mm_lock);
2386         VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2387         /*
2388          * Release the current mm_slot if this mm is about to die, or
2389          * if we scanned all vmas of this mm.
2390          */
2391         if (hpage_collapse_test_exit(mm) || !vma) {
2392                 /*
2393                  * Make sure that if mm_users is reaching zero while
2394                  * khugepaged runs here, khugepaged_exit will find
2395                  * mm_slot not pointing to the exiting mm.
2396                  */
2397                 if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2398                         slot = list_entry(slot->mm_node.next,
2399                                           struct mm_slot, mm_node);
2400                         khugepaged_scan.mm_slot =
2401                                 mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2402                         khugepaged_scan.address = 0;
2403                 } else {
2404                         khugepaged_scan.mm_slot = NULL;
2405                         khugepaged_full_scans++;
2406                 }
2407
2408                 collect_mm_slot(mm_slot);
2409         }
2410
2411         return progress;
2412 }
2413
2414 static int khugepaged_has_work(void)
2415 {
2416         return !list_empty(&khugepaged_scan.mm_head) &&
2417                 hugepage_flags_enabled();
2418 }
2419
2420 static int khugepaged_wait_event(void)
2421 {
2422         return !list_empty(&khugepaged_scan.mm_head) ||
2423                 kthread_should_stop();
2424 }
2425
2426 static void khugepaged_do_scan(struct collapse_control *cc)
2427 {
2428         unsigned int progress = 0, pass_through_head = 0;
2429         unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2430         bool wait = true;
2431         int result = SCAN_SUCCEED;
2432
2433         lru_add_drain_all();
2434
2435         while (true) {
2436                 cond_resched();
2437
2438                 if (unlikely(kthread_should_stop() || try_to_freeze()))
2439                         break;
2440
2441                 spin_lock(&khugepaged_mm_lock);
2442                 if (!khugepaged_scan.mm_slot)
2443                         pass_through_head++;
2444                 if (khugepaged_has_work() &&
2445                     pass_through_head < 2)
2446                         progress += khugepaged_scan_mm_slot(pages - progress,
2447                                                             &result, cc);
2448                 else
2449                         progress = pages;
2450                 spin_unlock(&khugepaged_mm_lock);
2451
2452                 if (progress >= pages)
2453                         break;
2454
2455                 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2456                         /*
2457                          * If fail to allocate the first time, try to sleep for
2458                          * a while.  When hit again, cancel the scan.
2459                          */
2460                         if (!wait)
2461                                 break;
2462                         wait = false;
2463                         khugepaged_alloc_sleep();
2464                 }
2465         }
2466 }
2467
2468 static bool khugepaged_should_wakeup(void)
2469 {
2470         return kthread_should_stop() ||
2471                time_after_eq(jiffies, khugepaged_sleep_expire);
2472 }
2473
2474 static void khugepaged_wait_work(void)
2475 {
2476         if (khugepaged_has_work()) {
2477                 const unsigned long scan_sleep_jiffies =
2478                         msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2479
2480                 if (!scan_sleep_jiffies)
2481                         return;
2482
2483                 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2484                 wait_event_freezable_timeout(khugepaged_wait,
2485                                              khugepaged_should_wakeup(),
2486                                              scan_sleep_jiffies);
2487                 return;
2488         }
2489
2490         if (hugepage_flags_enabled())
2491                 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2492 }
2493
2494 static int khugepaged(void *none)
2495 {
2496         struct khugepaged_mm_slot *mm_slot;
2497
2498         set_freezable();
2499         set_user_nice(current, MAX_NICE);
2500
2501         while (!kthread_should_stop()) {
2502                 khugepaged_do_scan(&khugepaged_collapse_control);
2503                 khugepaged_wait_work();
2504         }
2505
2506         spin_lock(&khugepaged_mm_lock);
2507         mm_slot = khugepaged_scan.mm_slot;
2508         khugepaged_scan.mm_slot = NULL;
2509         if (mm_slot)
2510                 collect_mm_slot(mm_slot);
2511         spin_unlock(&khugepaged_mm_lock);
2512         return 0;
2513 }
2514
2515 static void set_recommended_min_free_kbytes(void)
2516 {
2517         struct zone *zone;
2518         int nr_zones = 0;
2519         unsigned long recommended_min;
2520
2521         if (!hugepage_flags_enabled()) {
2522                 calculate_min_free_kbytes();
2523                 goto update_wmarks;
2524         }
2525
2526         for_each_populated_zone(zone) {
2527                 /*
2528                  * We don't need to worry about fragmentation of
2529                  * ZONE_MOVABLE since it only has movable pages.
2530                  */
2531                 if (zone_idx(zone) > gfp_zone(GFP_USER))
2532                         continue;
2533
2534                 nr_zones++;
2535         }
2536
2537         /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2538         recommended_min = pageblock_nr_pages * nr_zones * 2;
2539
2540         /*
2541          * Make sure that on average at least two pageblocks are almost free
2542          * of another type, one for a migratetype to fall back to and a
2543          * second to avoid subsequent fallbacks of other types There are 3
2544          * MIGRATE_TYPES we care about.
2545          */
2546         recommended_min += pageblock_nr_pages * nr_zones *
2547                            MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2548
2549         /* don't ever allow to reserve more than 5% of the lowmem */
2550         recommended_min = min(recommended_min,
2551                               (unsigned long) nr_free_buffer_pages() / 20);
2552         recommended_min <<= (PAGE_SHIFT-10);
2553
2554         if (recommended_min > min_free_kbytes) {
2555                 if (user_min_free_kbytes >= 0)
2556                         pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2557                                 min_free_kbytes, recommended_min);
2558
2559                 min_free_kbytes = recommended_min;
2560         }
2561
2562 update_wmarks:
2563         setup_per_zone_wmarks();
2564 }
2565
2566 int start_stop_khugepaged(void)
2567 {
2568         int err = 0;
2569
2570         mutex_lock(&khugepaged_mutex);
2571         if (hugepage_flags_enabled()) {
2572                 if (!khugepaged_thread)
2573                         khugepaged_thread = kthread_run(khugepaged, NULL,
2574                                                         "khugepaged");
2575                 if (IS_ERR(khugepaged_thread)) {
2576                         pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2577                         err = PTR_ERR(khugepaged_thread);
2578                         khugepaged_thread = NULL;
2579                         goto fail;
2580                 }
2581
2582                 if (!list_empty(&khugepaged_scan.mm_head))
2583                         wake_up_interruptible(&khugepaged_wait);
2584         } else if (khugepaged_thread) {
2585                 kthread_stop(khugepaged_thread);
2586                 khugepaged_thread = NULL;
2587         }
2588         set_recommended_min_free_kbytes();
2589 fail:
2590         mutex_unlock(&khugepaged_mutex);
2591         return err;
2592 }
2593
2594 void khugepaged_min_free_kbytes_update(void)
2595 {
2596         mutex_lock(&khugepaged_mutex);
2597         if (hugepage_flags_enabled() && khugepaged_thread)
2598                 set_recommended_min_free_kbytes();
2599         mutex_unlock(&khugepaged_mutex);
2600 }
2601
2602 static int madvise_collapse_errno(enum scan_result r)
2603 {
2604         /*
2605          * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2606          * actionable feedback to caller, so they may take an appropriate
2607          * fallback measure depending on the nature of the failure.
2608          */
2609         switch (r) {
2610         case SCAN_ALLOC_HUGE_PAGE_FAIL:
2611                 return -ENOMEM;
2612         case SCAN_CGROUP_CHARGE_FAIL:
2613                 return -EBUSY;
2614         /* Resource temporary unavailable - trying again might succeed */
2615         case SCAN_PAGE_COUNT:
2616         case SCAN_PAGE_LOCK:
2617         case SCAN_PAGE_LRU:
2618         case SCAN_DEL_PAGE_LRU:
2619                 return -EAGAIN;
2620         /*
2621          * Other: Trying again likely not to succeed / error intrinsic to
2622          * specified memory range. khugepaged likely won't be able to collapse
2623          * either.
2624          */
2625         default:
2626                 return -EINVAL;
2627         }
2628 }
2629
2630 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2631                      unsigned long start, unsigned long end)
2632 {
2633         struct collapse_control *cc;
2634         struct mm_struct *mm = vma->vm_mm;
2635         unsigned long hstart, hend, addr;
2636         int thps = 0, last_fail = SCAN_FAIL;
2637         bool mmap_locked = true;
2638
2639         BUG_ON(vma->vm_start > start);
2640         BUG_ON(vma->vm_end < end);
2641
2642         *prev = vma;
2643
2644         if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
2645                 return -EINVAL;
2646
2647         cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2648         if (!cc)
2649                 return -ENOMEM;
2650         cc->is_khugepaged = false;
2651
2652         mmgrab(mm);
2653         lru_add_drain_all();
2654
2655         hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2656         hend = end & HPAGE_PMD_MASK;
2657
2658         for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2659                 int result = SCAN_FAIL;
2660
2661                 if (!mmap_locked) {
2662                         cond_resched();
2663                         mmap_read_lock(mm);
2664                         mmap_locked = true;
2665                         result = hugepage_vma_revalidate(mm, addr, false, &vma,
2666                                                          cc);
2667                         if (result  != SCAN_SUCCEED) {
2668                                 last_fail = result;
2669                                 goto out_nolock;
2670                         }
2671
2672                         hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
2673                 }
2674                 mmap_assert_locked(mm);
2675                 memset(cc->node_load, 0, sizeof(cc->node_load));
2676                 nodes_clear(cc->alloc_nmask);
2677                 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2678                         struct file *file = get_file(vma->vm_file);
2679                         pgoff_t pgoff = linear_page_index(vma, addr);
2680
2681                         mmap_read_unlock(mm);
2682                         mmap_locked = false;
2683                         result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2684                                                           cc);
2685                         fput(file);
2686                 } else {
2687                         result = hpage_collapse_scan_pmd(mm, vma, addr,
2688                                                          &mmap_locked, cc);
2689                 }
2690                 if (!mmap_locked)
2691                         *prev = NULL;  /* Tell caller we dropped mmap_lock */
2692
2693 handle_result:
2694                 switch (result) {
2695                 case SCAN_SUCCEED:
2696                 case SCAN_PMD_MAPPED:
2697                         ++thps;
2698                         break;
2699                 case SCAN_PTE_MAPPED_HUGEPAGE:
2700                         BUG_ON(mmap_locked);
2701                         BUG_ON(*prev);
2702                         mmap_write_lock(mm);
2703                         result = collapse_pte_mapped_thp(mm, addr, true);
2704                         mmap_write_unlock(mm);
2705                         goto handle_result;
2706                 /* Whitelisted set of results where continuing OK */
2707                 case SCAN_PMD_NULL:
2708                 case SCAN_PTE_NON_PRESENT:
2709                 case SCAN_PTE_UFFD_WP:
2710                 case SCAN_PAGE_RO:
2711                 case SCAN_LACK_REFERENCED_PAGE:
2712                 case SCAN_PAGE_NULL:
2713                 case SCAN_PAGE_COUNT:
2714                 case SCAN_PAGE_LOCK:
2715                 case SCAN_PAGE_COMPOUND:
2716                 case SCAN_PAGE_LRU:
2717                 case SCAN_DEL_PAGE_LRU:
2718                         last_fail = result;
2719                         break;
2720                 default:
2721                         last_fail = result;
2722                         /* Other error, exit */
2723                         goto out_maybelock;
2724                 }
2725         }
2726
2727 out_maybelock:
2728         /* Caller expects us to hold mmap_lock on return */
2729         if (!mmap_locked)
2730                 mmap_read_lock(mm);
2731 out_nolock:
2732         mmap_assert_locked(mm);
2733         mmdrop(mm);
2734         kfree(cc);
2735
2736         return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2737                         : madvise_collapse_errno(last_fail);
2738 }