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