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