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