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