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