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