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