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 		     unsigned long *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 			  unsigned long 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 	if (!pmd_present(pmde))
945 		return SCAN_PMD_NULL;
946 	if (pmd_trans_huge(pmde))
947 		return SCAN_PMD_MAPPED;
948 	if (pmd_devmap(pmde))
949 		return SCAN_PMD_NULL;
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 haddr, pmd_t *pmd,
990 				       int referenced)
991 {
992 	int swapped_in = 0;
993 	vm_fault_t ret = 0;
994 	unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
995 	int result;
996 	pte_t *pte = NULL;
997 	spinlock_t *ptl;
998 
999 	for (address = haddr; address < end; address += PAGE_SIZE) {
1000 		struct vm_fault vmf = {
1001 			.vma = vma,
1002 			.address = address,
1003 			.pgoff = linear_page_index(vma, address),
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, address, &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 	result = check_pmd_still_valid(mm, address, pmd);
1159 	if (result != SCAN_SUCCEED)
1160 		goto out_up_write;
1161 
1162 	vma_start_write(vma);
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 address, 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 _address;
1266 	spinlock_t *ptl;
1267 	int node = NUMA_NO_NODE, unmapped = 0;
1268 	bool writable = false;
1269 
1270 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1271 
1272 	result = find_pmd_or_thp_or_none(mm, address, &pmd);
1273 	if (result != SCAN_SUCCEED)
1274 		goto out;
1275 
1276 	memset(cc->node_load, 0, sizeof(cc->node_load));
1277 	nodes_clear(cc->alloc_nmask);
1278 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1279 	if (!pte) {
1280 		result = SCAN_PMD_NULL;
1281 		goto out;
1282 	}
1283 
1284 	for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1285 	     _pte++, _address += PAGE_SIZE) {
1286 		pte_t pteval = ptep_get(_pte);
1287 		if (is_swap_pte(pteval)) {
1288 			++unmapped;
1289 			if (!cc->is_khugepaged ||
1290 			    unmapped <= khugepaged_max_ptes_swap) {
1291 				/*
1292 				 * Always be strict with uffd-wp
1293 				 * enabled swap entries.  Please see
1294 				 * comment below for pte_uffd_wp().
1295 				 */
1296 				if (pte_swp_uffd_wp_any(pteval)) {
1297 					result = SCAN_PTE_UFFD_WP;
1298 					goto out_unmap;
1299 				}
1300 				continue;
1301 			} else {
1302 				result = SCAN_EXCEED_SWAP_PTE;
1303 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1304 				goto out_unmap;
1305 			}
1306 		}
1307 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1308 			++none_or_zero;
1309 			if (!userfaultfd_armed(vma) &&
1310 			    (!cc->is_khugepaged ||
1311 			     none_or_zero <= khugepaged_max_ptes_none)) {
1312 				continue;
1313 			} else {
1314 				result = SCAN_EXCEED_NONE_PTE;
1315 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1316 				goto out_unmap;
1317 			}
1318 		}
1319 		if (pte_uffd_wp(pteval)) {
1320 			/*
1321 			 * Don't collapse the page if any of the small
1322 			 * PTEs are armed with uffd write protection.
1323 			 * Here we can also mark the new huge pmd as
1324 			 * write protected if any of the small ones is
1325 			 * marked but that could bring unknown
1326 			 * userfault messages that falls outside of
1327 			 * the registered range.  So, just be simple.
1328 			 */
1329 			result = SCAN_PTE_UFFD_WP;
1330 			goto out_unmap;
1331 		}
1332 		if (pte_write(pteval))
1333 			writable = true;
1334 
1335 		page = vm_normal_page(vma, _address, pteval);
1336 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1337 			result = SCAN_PAGE_NULL;
1338 			goto out_unmap;
1339 		}
1340 		folio = page_folio(page);
1341 
1342 		if (!folio_test_anon(folio)) {
1343 			result = SCAN_PAGE_ANON;
1344 			goto out_unmap;
1345 		}
1346 
1347 		/*
1348 		 * We treat a single page as shared if any part of the THP
1349 		 * is shared.
1350 		 */
1351 		if (folio_maybe_mapped_shared(folio)) {
1352 			++shared;
1353 			if (cc->is_khugepaged &&
1354 			    shared > khugepaged_max_ptes_shared) {
1355 				result = SCAN_EXCEED_SHARED_PTE;
1356 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1357 				goto out_unmap;
1358 			}
1359 		}
1360 
1361 		/*
1362 		 * Record which node the original page is from and save this
1363 		 * information to cc->node_load[].
1364 		 * Khugepaged will allocate hugepage from the node has the max
1365 		 * hit record.
1366 		 */
1367 		node = folio_nid(folio);
1368 		if (hpage_collapse_scan_abort(node, cc)) {
1369 			result = SCAN_SCAN_ABORT;
1370 			goto out_unmap;
1371 		}
1372 		cc->node_load[node]++;
1373 		if (!folio_test_lru(folio)) {
1374 			result = SCAN_PAGE_LRU;
1375 			goto out_unmap;
1376 		}
1377 		if (folio_test_locked(folio)) {
1378 			result = SCAN_PAGE_LOCK;
1379 			goto out_unmap;
1380 		}
1381 
1382 		/*
1383 		 * Check if the page has any GUP (or other external) pins.
1384 		 *
1385 		 * Here the check may be racy:
1386 		 * it may see folio_mapcount() > folio_ref_count().
1387 		 * But such case is ephemeral we could always retry collapse
1388 		 * later.  However it may report false positive if the page
1389 		 * has excessive GUP pins (i.e. 512).  Anyway the same check
1390 		 * will be done again later the risk seems low.
1391 		 */
1392 		if (folio_expected_ref_count(folio) != folio_ref_count(folio)) {
1393 			result = SCAN_PAGE_COUNT;
1394 			goto out_unmap;
1395 		}
1396 
1397 		/*
1398 		 * If collapse was initiated by khugepaged, check that there is
1399 		 * enough young pte to justify collapsing the page
1400 		 */
1401 		if (cc->is_khugepaged &&
1402 		    (pte_young(pteval) || folio_test_young(folio) ||
1403 		     folio_test_referenced(folio) || mmu_notifier_test_young(vma->vm_mm,
1404 								     address)))
1405 			referenced++;
1406 	}
1407 	if (!writable) {
1408 		result = SCAN_PAGE_RO;
1409 	} else if (cc->is_khugepaged &&
1410 		   (!referenced ||
1411 		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1412 		result = SCAN_LACK_REFERENCED_PAGE;
1413 	} else {
1414 		result = SCAN_SUCCEED;
1415 	}
1416 out_unmap:
1417 	pte_unmap_unlock(pte, ptl);
1418 	if (result == SCAN_SUCCEED) {
1419 		result = collapse_huge_page(mm, address, referenced,
1420 					    unmapped, cc);
1421 		/* collapse_huge_page will return with the mmap_lock released */
1422 		*mmap_locked = false;
1423 	}
1424 out:
1425 	trace_mm_khugepaged_scan_pmd(mm, folio, writable, referenced,
1426 				     none_or_zero, result, unmapped);
1427 	return result;
1428 }
1429 
1430 static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1431 {
1432 	struct mm_slot *slot = &mm_slot->slot;
1433 	struct mm_struct *mm = slot->mm;
1434 
1435 	lockdep_assert_held(&khugepaged_mm_lock);
1436 
1437 	if (hpage_collapse_test_exit(mm)) {
1438 		/* free mm_slot */
1439 		hash_del(&slot->hash);
1440 		list_del(&slot->mm_node);
1441 
1442 		/*
1443 		 * Not strictly needed because the mm exited already.
1444 		 *
1445 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1446 		 */
1447 
1448 		/* khugepaged_mm_lock actually not necessary for the below */
1449 		mm_slot_free(mm_slot_cache, mm_slot);
1450 		mmdrop(mm);
1451 	}
1452 }
1453 
1454 /* folio must be locked, and mmap_lock must be held */
1455 static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1456 			pmd_t *pmdp, struct folio *folio, struct page *page)
1457 {
1458 	struct vm_fault vmf = {
1459 		.vma = vma,
1460 		.address = addr,
1461 		.flags = 0,
1462 		.pmd = pmdp,
1463 	};
1464 
1465 	mmap_assert_locked(vma->vm_mm);
1466 
1467 	if (do_set_pmd(&vmf, folio, page))
1468 		return SCAN_FAIL;
1469 
1470 	folio_get(folio);
1471 	return SCAN_SUCCEED;
1472 }
1473 
1474 /**
1475  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1476  * address haddr.
1477  *
1478  * @mm: process address space where collapse happens
1479  * @addr: THP collapse address
1480  * @install_pmd: If a huge PMD should be installed
1481  *
1482  * This function checks whether all the PTEs in the PMD are pointing to the
1483  * right THP. If so, retract the page table so the THP can refault in with
1484  * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1485  */
1486 int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1487 			    bool install_pmd)
1488 {
1489 	struct mmu_notifier_range range;
1490 	bool notified = false;
1491 	unsigned long haddr = addr & HPAGE_PMD_MASK;
1492 	struct vm_area_struct *vma = vma_lookup(mm, haddr);
1493 	struct folio *folio;
1494 	pte_t *start_pte, *pte;
1495 	pmd_t *pmd, pgt_pmd;
1496 	spinlock_t *pml = NULL, *ptl;
1497 	int nr_ptes = 0, result = SCAN_FAIL;
1498 	int i;
1499 
1500 	mmap_assert_locked(mm);
1501 
1502 	/* First check VMA found, in case page tables are being torn down */
1503 	if (!vma || !vma->vm_file ||
1504 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1505 		return SCAN_VMA_CHECK;
1506 
1507 	/* Fast check before locking page if already PMD-mapped */
1508 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1509 	if (result == SCAN_PMD_MAPPED)
1510 		return result;
1511 
1512 	/*
1513 	 * If we are here, we've succeeded in replacing all the native pages
1514 	 * in the page cache with a single hugepage. If a mm were to fault-in
1515 	 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1516 	 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1517 	 * analogously elide sysfs THP settings here.
1518 	 */
1519 	if (!thp_vma_allowable_order(vma, vma->vm_flags, 0, PMD_ORDER))
1520 		return SCAN_VMA_CHECK;
1521 
1522 	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1523 	if (userfaultfd_wp(vma))
1524 		return SCAN_PTE_UFFD_WP;
1525 
1526 	folio = filemap_lock_folio(vma->vm_file->f_mapping,
1527 			       linear_page_index(vma, haddr));
1528 	if (IS_ERR(folio))
1529 		return SCAN_PAGE_NULL;
1530 
1531 	if (folio_order(folio) != HPAGE_PMD_ORDER) {
1532 		result = SCAN_PAGE_COMPOUND;
1533 		goto drop_folio;
1534 	}
1535 
1536 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1537 	switch (result) {
1538 	case SCAN_SUCCEED:
1539 		break;
1540 	case SCAN_PMD_NONE:
1541 		/*
1542 		 * All pte entries have been removed and pmd cleared.
1543 		 * Skip all the pte checks and just update the pmd mapping.
1544 		 */
1545 		goto maybe_install_pmd;
1546 	default:
1547 		goto drop_folio;
1548 	}
1549 
1550 	result = SCAN_FAIL;
1551 	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1552 	if (!start_pte)		/* mmap_lock + page lock should prevent this */
1553 		goto drop_folio;
1554 
1555 	/* step 1: check all mapped PTEs are to the right huge page */
1556 	for (i = 0, addr = haddr, pte = start_pte;
1557 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1558 		struct page *page;
1559 		pte_t ptent = ptep_get(pte);
1560 
1561 		/* empty pte, skip */
1562 		if (pte_none(ptent))
1563 			continue;
1564 
1565 		/* page swapped out, abort */
1566 		if (!pte_present(ptent)) {
1567 			result = SCAN_PTE_NON_PRESENT;
1568 			goto abort;
1569 		}
1570 
1571 		page = vm_normal_page(vma, addr, ptent);
1572 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1573 			page = NULL;
1574 		/*
1575 		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1576 		 * page table, but the new page will not be a subpage of hpage.
1577 		 */
1578 		if (folio_page(folio, i) != page)
1579 			goto abort;
1580 	}
1581 
1582 	pte_unmap_unlock(start_pte, ptl);
1583 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1584 				haddr, haddr + HPAGE_PMD_SIZE);
1585 	mmu_notifier_invalidate_range_start(&range);
1586 	notified = true;
1587 
1588 	/*
1589 	 * pmd_lock covers a wider range than ptl, and (if split from mm's
1590 	 * page_table_lock) ptl nests inside pml. The less time we hold pml,
1591 	 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA
1592 	 * inserts a valid as-if-COWed PTE without even looking up page cache.
1593 	 * So page lock of folio does not protect from it, so we must not drop
1594 	 * ptl before pgt_pmd is removed, so uffd private needs pml taken now.
1595 	 */
1596 	if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED))
1597 		pml = pmd_lock(mm, pmd);
1598 
1599 	start_pte = pte_offset_map_rw_nolock(mm, pmd, haddr, &pgt_pmd, &ptl);
1600 	if (!start_pte)		/* mmap_lock + page lock should prevent this */
1601 		goto abort;
1602 	if (!pml)
1603 		spin_lock(ptl);
1604 	else if (ptl != pml)
1605 		spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1606 
1607 	if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd))))
1608 		goto abort;
1609 
1610 	/* step 2: clear page table and adjust rmap */
1611 	for (i = 0, addr = haddr, pte = start_pte;
1612 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1613 		struct page *page;
1614 		pte_t ptent = ptep_get(pte);
1615 
1616 		if (pte_none(ptent))
1617 			continue;
1618 		/*
1619 		 * We dropped ptl after the first scan, to do the mmu_notifier:
1620 		 * page lock stops more PTEs of the folio being faulted in, but
1621 		 * does not stop write faults COWing anon copies from existing
1622 		 * PTEs; and does not stop those being swapped out or migrated.
1623 		 */
1624 		if (!pte_present(ptent)) {
1625 			result = SCAN_PTE_NON_PRESENT;
1626 			goto abort;
1627 		}
1628 		page = vm_normal_page(vma, addr, ptent);
1629 		if (folio_page(folio, i) != page)
1630 			goto abort;
1631 
1632 		/*
1633 		 * Must clear entry, or a racing truncate may re-remove it.
1634 		 * TLB flush can be left until pmdp_collapse_flush() does it.
1635 		 * PTE dirty? Shmem page is already dirty; file is read-only.
1636 		 */
1637 		ptep_clear(mm, addr, pte);
1638 		folio_remove_rmap_pte(folio, page, vma);
1639 		nr_ptes++;
1640 	}
1641 
1642 	if (!pml)
1643 		spin_unlock(ptl);
1644 
1645 	/* step 3: set proper refcount and mm_counters. */
1646 	if (nr_ptes) {
1647 		folio_ref_sub(folio, nr_ptes);
1648 		add_mm_counter(mm, mm_counter_file(folio), -nr_ptes);
1649 	}
1650 
1651 	/* step 4: remove empty page table */
1652 	if (!pml) {
1653 		pml = pmd_lock(mm, pmd);
1654 		if (ptl != pml) {
1655 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1656 			if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) {
1657 				flush_tlb_mm(mm);
1658 				goto unlock;
1659 			}
1660 		}
1661 	}
1662 	pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd);
1663 	pmdp_get_lockless_sync();
1664 	pte_unmap_unlock(start_pte, ptl);
1665 	if (ptl != pml)
1666 		spin_unlock(pml);
1667 
1668 	mmu_notifier_invalidate_range_end(&range);
1669 
1670 	mm_dec_nr_ptes(mm);
1671 	page_table_check_pte_clear_range(mm, haddr, pgt_pmd);
1672 	pte_free_defer(mm, pmd_pgtable(pgt_pmd));
1673 
1674 maybe_install_pmd:
1675 	/* step 5: install pmd entry */
1676 	result = install_pmd
1677 			? set_huge_pmd(vma, haddr, pmd, folio, &folio->page)
1678 			: SCAN_SUCCEED;
1679 	goto drop_folio;
1680 abort:
1681 	if (nr_ptes) {
1682 		flush_tlb_mm(mm);
1683 		folio_ref_sub(folio, nr_ptes);
1684 		add_mm_counter(mm, mm_counter_file(folio), -nr_ptes);
1685 	}
1686 unlock:
1687 	if (start_pte)
1688 		pte_unmap_unlock(start_pte, ptl);
1689 	if (pml && pml != ptl)
1690 		spin_unlock(pml);
1691 	if (notified)
1692 		mmu_notifier_invalidate_range_end(&range);
1693 drop_folio:
1694 	folio_unlock(folio);
1695 	folio_put(folio);
1696 	return result;
1697 }
1698 
1699 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1700 {
1701 	struct vm_area_struct *vma;
1702 
1703 	i_mmap_lock_read(mapping);
1704 	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1705 		struct mmu_notifier_range range;
1706 		struct mm_struct *mm;
1707 		unsigned long addr;
1708 		pmd_t *pmd, pgt_pmd;
1709 		spinlock_t *pml;
1710 		spinlock_t *ptl;
1711 		bool success = false;
1712 
1713 		/*
1714 		 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1715 		 * got written to. These VMAs are likely not worth removing
1716 		 * page tables from, as PMD-mapping is likely to be split later.
1717 		 */
1718 		if (READ_ONCE(vma->anon_vma))
1719 			continue;
1720 
1721 		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1722 		if (addr & ~HPAGE_PMD_MASK ||
1723 		    vma->vm_end < addr + HPAGE_PMD_SIZE)
1724 			continue;
1725 
1726 		mm = vma->vm_mm;
1727 		if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED)
1728 			continue;
1729 
1730 		if (hpage_collapse_test_exit(mm))
1731 			continue;
1732 		/*
1733 		 * When a vma is registered with uffd-wp, we cannot recycle
1734 		 * the page table because there may be pte markers installed.
1735 		 * Other vmas can still have the same file mapped hugely, but
1736 		 * skip this one: it will always be mapped in small page size
1737 		 * for uffd-wp registered ranges.
1738 		 */
1739 		if (userfaultfd_wp(vma))
1740 			continue;
1741 
1742 		/* PTEs were notified when unmapped; but now for the PMD? */
1743 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1744 					addr, addr + HPAGE_PMD_SIZE);
1745 		mmu_notifier_invalidate_range_start(&range);
1746 
1747 		pml = pmd_lock(mm, pmd);
1748 		/*
1749 		 * The lock of new_folio is still held, we will be blocked in
1750 		 * the page fault path, which prevents the pte entries from
1751 		 * being set again. So even though the old empty PTE page may be
1752 		 * concurrently freed and a new PTE page is filled into the pmd
1753 		 * entry, it is still empty and can be removed.
1754 		 *
1755 		 * So here we only need to recheck if the state of pmd entry
1756 		 * still meets our requirements, rather than checking pmd_same()
1757 		 * like elsewhere.
1758 		 */
1759 		if (check_pmd_state(pmd) != SCAN_SUCCEED)
1760 			goto drop_pml;
1761 		ptl = pte_lockptr(mm, pmd);
1762 		if (ptl != pml)
1763 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1764 
1765 		/*
1766 		 * Huge page lock is still held, so normally the page table
1767 		 * must remain empty; and we have already skipped anon_vma
1768 		 * and userfaultfd_wp() vmas.  But since the mmap_lock is not
1769 		 * held, it is still possible for a racing userfaultfd_ioctl()
1770 		 * to have inserted ptes or markers.  Now that we hold ptlock,
1771 		 * repeating the anon_vma check protects from one category,
1772 		 * and repeating the userfaultfd_wp() check from another.
1773 		 */
1774 		if (likely(!vma->anon_vma && !userfaultfd_wp(vma))) {
1775 			pgt_pmd = pmdp_collapse_flush(vma, addr, pmd);
1776 			pmdp_get_lockless_sync();
1777 			success = true;
1778 		}
1779 
1780 		if (ptl != pml)
1781 			spin_unlock(ptl);
1782 drop_pml:
1783 		spin_unlock(pml);
1784 
1785 		mmu_notifier_invalidate_range_end(&range);
1786 
1787 		if (success) {
1788 			mm_dec_nr_ptes(mm);
1789 			page_table_check_pte_clear_range(mm, addr, pgt_pmd);
1790 			pte_free_defer(mm, pmd_pgtable(pgt_pmd));
1791 		}
1792 	}
1793 	i_mmap_unlock_read(mapping);
1794 }
1795 
1796 /**
1797  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1798  *
1799  * @mm: process address space where collapse happens
1800  * @addr: virtual collapse start address
1801  * @file: file that collapse on
1802  * @start: collapse start address
1803  * @cc: collapse context and scratchpad
1804  *
1805  * Basic scheme is simple, details are more complex:
1806  *  - allocate and lock a new huge page;
1807  *  - scan page cache, locking old pages
1808  *    + swap/gup in pages if necessary;
1809  *  - copy data to new page
1810  *  - handle shmem holes
1811  *    + re-validate that holes weren't filled by someone else
1812  *    + check for userfaultfd
1813  *  - finalize updates to the page cache;
1814  *  - if replacing succeeds:
1815  *    + unlock huge page;
1816  *    + free old pages;
1817  *  - if replacing failed;
1818  *    + unlock old pages
1819  *    + unlock and free huge page;
1820  */
1821 static int collapse_file(struct mm_struct *mm, unsigned long addr,
1822 			 struct file *file, pgoff_t start,
1823 			 struct collapse_control *cc)
1824 {
1825 	struct address_space *mapping = file->f_mapping;
1826 	struct page *dst;
1827 	struct folio *folio, *tmp, *new_folio;
1828 	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1829 	LIST_HEAD(pagelist);
1830 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1831 	int nr_none = 0, result = SCAN_SUCCEED;
1832 	bool is_shmem = shmem_file(file);
1833 
1834 	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1835 	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1836 
1837 	result = alloc_charge_folio(&new_folio, mm, cc);
1838 	if (result != SCAN_SUCCEED)
1839 		goto out;
1840 
1841 	mapping_set_update(&xas, mapping);
1842 
1843 	__folio_set_locked(new_folio);
1844 	if (is_shmem)
1845 		__folio_set_swapbacked(new_folio);
1846 	new_folio->index = start;
1847 	new_folio->mapping = mapping;
1848 
1849 	/*
1850 	 * Ensure we have slots for all the pages in the range.  This is
1851 	 * almost certainly a no-op because most of the pages must be present
1852 	 */
1853 	do {
1854 		xas_lock_irq(&xas);
1855 		xas_create_range(&xas);
1856 		if (!xas_error(&xas))
1857 			break;
1858 		xas_unlock_irq(&xas);
1859 		if (!xas_nomem(&xas, GFP_KERNEL)) {
1860 			result = SCAN_FAIL;
1861 			goto rollback;
1862 		}
1863 	} while (1);
1864 
1865 	for (index = start; index < end;) {
1866 		xas_set(&xas, index);
1867 		folio = xas_load(&xas);
1868 
1869 		VM_BUG_ON(index != xas.xa_index);
1870 		if (is_shmem) {
1871 			if (!folio) {
1872 				/*
1873 				 * Stop if extent has been truncated or
1874 				 * hole-punched, and is now completely
1875 				 * empty.
1876 				 */
1877 				if (index == start) {
1878 					if (!xas_next_entry(&xas, end - 1)) {
1879 						result = SCAN_TRUNCATED;
1880 						goto xa_locked;
1881 					}
1882 				}
1883 				nr_none++;
1884 				index++;
1885 				continue;
1886 			}
1887 
1888 			if (xa_is_value(folio) || !folio_test_uptodate(folio)) {
1889 				xas_unlock_irq(&xas);
1890 				/* swap in or instantiate fallocated page */
1891 				if (shmem_get_folio(mapping->host, index, 0,
1892 						&folio, SGP_NOALLOC)) {
1893 					result = SCAN_FAIL;
1894 					goto xa_unlocked;
1895 				}
1896 				/* drain lru cache to help folio_isolate_lru() */
1897 				lru_add_drain();
1898 			} else if (folio_trylock(folio)) {
1899 				folio_get(folio);
1900 				xas_unlock_irq(&xas);
1901 			} else {
1902 				result = SCAN_PAGE_LOCK;
1903 				goto xa_locked;
1904 			}
1905 		} else {	/* !is_shmem */
1906 			if (!folio || xa_is_value(folio)) {
1907 				xas_unlock_irq(&xas);
1908 				page_cache_sync_readahead(mapping, &file->f_ra,
1909 							  file, index,
1910 							  end - index);
1911 				/* drain lru cache to help folio_isolate_lru() */
1912 				lru_add_drain();
1913 				folio = filemap_lock_folio(mapping, index);
1914 				if (IS_ERR(folio)) {
1915 					result = SCAN_FAIL;
1916 					goto xa_unlocked;
1917 				}
1918 			} else if (folio_test_dirty(folio)) {
1919 				/*
1920 				 * khugepaged only works on read-only fd,
1921 				 * so this page is dirty because it hasn't
1922 				 * been flushed since first write. There
1923 				 * won't be new dirty pages.
1924 				 *
1925 				 * Trigger async flush here and hope the
1926 				 * writeback is done when khugepaged
1927 				 * revisits this page.
1928 				 *
1929 				 * This is a one-off situation. We are not
1930 				 * forcing writeback in loop.
1931 				 */
1932 				xas_unlock_irq(&xas);
1933 				filemap_flush(mapping);
1934 				result = SCAN_FAIL;
1935 				goto xa_unlocked;
1936 			} else if (folio_test_writeback(folio)) {
1937 				xas_unlock_irq(&xas);
1938 				result = SCAN_FAIL;
1939 				goto xa_unlocked;
1940 			} else if (folio_trylock(folio)) {
1941 				folio_get(folio);
1942 				xas_unlock_irq(&xas);
1943 			} else {
1944 				result = SCAN_PAGE_LOCK;
1945 				goto xa_locked;
1946 			}
1947 		}
1948 
1949 		/*
1950 		 * The folio must be locked, so we can drop the i_pages lock
1951 		 * without racing with truncate.
1952 		 */
1953 		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1954 
1955 		/* make sure the folio is up to date */
1956 		if (unlikely(!folio_test_uptodate(folio))) {
1957 			result = SCAN_FAIL;
1958 			goto out_unlock;
1959 		}
1960 
1961 		/*
1962 		 * If file was truncated then extended, or hole-punched, before
1963 		 * we locked the first folio, then a THP might be there already.
1964 		 * This will be discovered on the first iteration.
1965 		 */
1966 		if (folio_order(folio) == HPAGE_PMD_ORDER &&
1967 		    folio->index == start) {
1968 			/* Maybe PMD-mapped */
1969 			result = SCAN_PTE_MAPPED_HUGEPAGE;
1970 			goto out_unlock;
1971 		}
1972 
1973 		if (folio_mapping(folio) != mapping) {
1974 			result = SCAN_TRUNCATED;
1975 			goto out_unlock;
1976 		}
1977 
1978 		if (!is_shmem && (folio_test_dirty(folio) ||
1979 				  folio_test_writeback(folio))) {
1980 			/*
1981 			 * khugepaged only works on read-only fd, so this
1982 			 * folio is dirty because it hasn't been flushed
1983 			 * since first write.
1984 			 */
1985 			result = SCAN_FAIL;
1986 			goto out_unlock;
1987 		}
1988 
1989 		if (!folio_isolate_lru(folio)) {
1990 			result = SCAN_DEL_PAGE_LRU;
1991 			goto out_unlock;
1992 		}
1993 
1994 		if (!filemap_release_folio(folio, GFP_KERNEL)) {
1995 			result = SCAN_PAGE_HAS_PRIVATE;
1996 			folio_putback_lru(folio);
1997 			goto out_unlock;
1998 		}
1999 
2000 		if (folio_mapped(folio))
2001 			try_to_unmap(folio,
2002 					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
2003 
2004 		xas_lock_irq(&xas);
2005 
2006 		VM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio);
2007 
2008 		/*
2009 		 * We control 2 + nr_pages references to the folio:
2010 		 *  - we hold a pin on it;
2011 		 *  - nr_pages reference from page cache;
2012 		 *  - one from lru_isolate_folio;
2013 		 * If those are the only references, then any new usage
2014 		 * of the folio will have to fetch it from the page
2015 		 * cache. That requires locking the folio to handle
2016 		 * truncate, so any new usage will be blocked until we
2017 		 * unlock folio after collapse/during rollback.
2018 		 */
2019 		if (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) {
2020 			result = SCAN_PAGE_COUNT;
2021 			xas_unlock_irq(&xas);
2022 			folio_putback_lru(folio);
2023 			goto out_unlock;
2024 		}
2025 
2026 		/*
2027 		 * Accumulate the folios that are being collapsed.
2028 		 */
2029 		list_add_tail(&folio->lru, &pagelist);
2030 		index += folio_nr_pages(folio);
2031 		continue;
2032 out_unlock:
2033 		folio_unlock(folio);
2034 		folio_put(folio);
2035 		goto xa_unlocked;
2036 	}
2037 
2038 	if (!is_shmem) {
2039 		filemap_nr_thps_inc(mapping);
2040 		/*
2041 		 * Paired with the fence in do_dentry_open() -> get_write_access()
2042 		 * to ensure i_writecount is up to date and the update to nr_thps
2043 		 * is visible. Ensures the page cache will be truncated if the
2044 		 * file is opened writable.
2045 		 */
2046 		smp_mb();
2047 		if (inode_is_open_for_write(mapping->host)) {
2048 			result = SCAN_FAIL;
2049 			filemap_nr_thps_dec(mapping);
2050 		}
2051 	}
2052 
2053 xa_locked:
2054 	xas_unlock_irq(&xas);
2055 xa_unlocked:
2056 
2057 	/*
2058 	 * If collapse is successful, flush must be done now before copying.
2059 	 * If collapse is unsuccessful, does flush actually need to be done?
2060 	 * Do it anyway, to clear the state.
2061 	 */
2062 	try_to_unmap_flush();
2063 
2064 	if (result == SCAN_SUCCEED && nr_none &&
2065 	    !shmem_charge(mapping->host, nr_none))
2066 		result = SCAN_FAIL;
2067 	if (result != SCAN_SUCCEED) {
2068 		nr_none = 0;
2069 		goto rollback;
2070 	}
2071 
2072 	/*
2073 	 * The old folios are locked, so they won't change anymore.
2074 	 */
2075 	index = start;
2076 	dst = folio_page(new_folio, 0);
2077 	list_for_each_entry(folio, &pagelist, lru) {
2078 		int i, nr_pages = folio_nr_pages(folio);
2079 
2080 		while (index < folio->index) {
2081 			clear_highpage(dst);
2082 			index++;
2083 			dst++;
2084 		}
2085 
2086 		for (i = 0; i < nr_pages; i++) {
2087 			if (copy_mc_highpage(dst, folio_page(folio, i)) > 0) {
2088 				result = SCAN_COPY_MC;
2089 				goto rollback;
2090 			}
2091 			index++;
2092 			dst++;
2093 		}
2094 	}
2095 	while (index < end) {
2096 		clear_highpage(dst);
2097 		index++;
2098 		dst++;
2099 	}
2100 
2101 	if (nr_none) {
2102 		struct vm_area_struct *vma;
2103 		int nr_none_check = 0;
2104 
2105 		i_mmap_lock_read(mapping);
2106 		xas_lock_irq(&xas);
2107 
2108 		xas_set(&xas, start);
2109 		for (index = start; index < end; index++) {
2110 			if (!xas_next(&xas)) {
2111 				xas_store(&xas, XA_RETRY_ENTRY);
2112 				if (xas_error(&xas)) {
2113 					result = SCAN_STORE_FAILED;
2114 					goto immap_locked;
2115 				}
2116 				nr_none_check++;
2117 			}
2118 		}
2119 
2120 		if (nr_none != nr_none_check) {
2121 			result = SCAN_PAGE_FILLED;
2122 			goto immap_locked;
2123 		}
2124 
2125 		/*
2126 		 * If userspace observed a missing page in a VMA with
2127 		 * a MODE_MISSING userfaultfd, then it might expect a
2128 		 * UFFD_EVENT_PAGEFAULT for that page. If so, we need to
2129 		 * roll back to avoid suppressing such an event. Since
2130 		 * wp/minor userfaultfds don't give userspace any
2131 		 * guarantees that the kernel doesn't fill a missing
2132 		 * page with a zero page, so they don't matter here.
2133 		 *
2134 		 * Any userfaultfds registered after this point will
2135 		 * not be able to observe any missing pages due to the
2136 		 * previously inserted retry entries.
2137 		 */
2138 		vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2139 			if (userfaultfd_missing(vma)) {
2140 				result = SCAN_EXCEED_NONE_PTE;
2141 				goto immap_locked;
2142 			}
2143 		}
2144 
2145 immap_locked:
2146 		i_mmap_unlock_read(mapping);
2147 		if (result != SCAN_SUCCEED) {
2148 			xas_set(&xas, start);
2149 			for (index = start; index < end; index++) {
2150 				if (xas_next(&xas) == XA_RETRY_ENTRY)
2151 					xas_store(&xas, NULL);
2152 			}
2153 
2154 			xas_unlock_irq(&xas);
2155 			goto rollback;
2156 		}
2157 	} else {
2158 		xas_lock_irq(&xas);
2159 	}
2160 
2161 	if (is_shmem)
2162 		__lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
2163 	else
2164 		__lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);
2165 
2166 	if (nr_none) {
2167 		__lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, nr_none);
2168 		/* nr_none is always 0 for non-shmem. */
2169 		__lruvec_stat_mod_folio(new_folio, NR_SHMEM, nr_none);
2170 	}
2171 
2172 	/*
2173 	 * Mark new_folio as uptodate before inserting it into the
2174 	 * page cache so that it isn't mistaken for an fallocated but
2175 	 * unwritten page.
2176 	 */
2177 	folio_mark_uptodate(new_folio);
2178 	folio_ref_add(new_folio, HPAGE_PMD_NR - 1);
2179 
2180 	if (is_shmem)
2181 		folio_mark_dirty(new_folio);
2182 	folio_add_lru(new_folio);
2183 
2184 	/* Join all the small entries into a single multi-index entry. */
2185 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2186 	xas_store(&xas, new_folio);
2187 	WARN_ON_ONCE(xas_error(&xas));
2188 	xas_unlock_irq(&xas);
2189 
2190 	/*
2191 	 * Remove pte page tables, so we can re-fault the page as huge.
2192 	 * If MADV_COLLAPSE, adjust result to call collapse_pte_mapped_thp().
2193 	 */
2194 	retract_page_tables(mapping, start);
2195 	if (cc && !cc->is_khugepaged)
2196 		result = SCAN_PTE_MAPPED_HUGEPAGE;
2197 	folio_unlock(new_folio);
2198 
2199 	/*
2200 	 * The collapse has succeeded, so free the old folios.
2201 	 */
2202 	list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
2203 		list_del(&folio->lru);
2204 		folio->mapping = NULL;
2205 		folio_clear_active(folio);
2206 		folio_clear_unevictable(folio);
2207 		folio_unlock(folio);
2208 		folio_put_refs(folio, 2 + folio_nr_pages(folio));
2209 	}
2210 
2211 	goto out;
2212 
2213 rollback:
2214 	/* Something went wrong: roll back page cache changes */
2215 	if (nr_none) {
2216 		xas_lock_irq(&xas);
2217 		mapping->nrpages -= nr_none;
2218 		xas_unlock_irq(&xas);
2219 		shmem_uncharge(mapping->host, nr_none);
2220 	}
2221 
2222 	list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
2223 		list_del(&folio->lru);
2224 		folio_unlock(folio);
2225 		folio_putback_lru(folio);
2226 		folio_put(folio);
2227 	}
2228 	/*
2229 	 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
2230 	 * file only. This undo is not needed unless failure is
2231 	 * due to SCAN_COPY_MC.
2232 	 */
2233 	if (!is_shmem && result == SCAN_COPY_MC) {
2234 		filemap_nr_thps_dec(mapping);
2235 		/*
2236 		 * Paired with the fence in do_dentry_open() -> get_write_access()
2237 		 * to ensure the update to nr_thps is visible.
2238 		 */
2239 		smp_mb();
2240 	}
2241 
2242 	new_folio->mapping = NULL;
2243 
2244 	folio_unlock(new_folio);
2245 	folio_put(new_folio);
2246 out:
2247 	VM_BUG_ON(!list_empty(&pagelist));
2248 	trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
2249 	return result;
2250 }
2251 
2252 static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2253 				    struct file *file, pgoff_t start,
2254 				    struct collapse_control *cc)
2255 {
2256 	struct folio *folio = NULL;
2257 	struct address_space *mapping = file->f_mapping;
2258 	XA_STATE(xas, &mapping->i_pages, start);
2259 	int present, swap;
2260 	int node = NUMA_NO_NODE;
2261 	int result = SCAN_SUCCEED;
2262 
2263 	present = 0;
2264 	swap = 0;
2265 	memset(cc->node_load, 0, sizeof(cc->node_load));
2266 	nodes_clear(cc->alloc_nmask);
2267 	rcu_read_lock();
2268 	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
2269 		if (xas_retry(&xas, folio))
2270 			continue;
2271 
2272 		if (xa_is_value(folio)) {
2273 			swap += 1 << xas_get_order(&xas);
2274 			if (cc->is_khugepaged &&
2275 			    swap > khugepaged_max_ptes_swap) {
2276 				result = SCAN_EXCEED_SWAP_PTE;
2277 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2278 				break;
2279 			}
2280 			continue;
2281 		}
2282 
2283 		if (!folio_try_get(folio)) {
2284 			xas_reset(&xas);
2285 			continue;
2286 		}
2287 
2288 		if (unlikely(folio != xas_reload(&xas))) {
2289 			folio_put(folio);
2290 			xas_reset(&xas);
2291 			continue;
2292 		}
2293 
2294 		if (folio_order(folio) == HPAGE_PMD_ORDER &&
2295 		    folio->index == start) {
2296 			/* Maybe PMD-mapped */
2297 			result = SCAN_PTE_MAPPED_HUGEPAGE;
2298 			/*
2299 			 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2300 			 * by the caller won't touch the page cache, and so
2301 			 * it's safe to skip LRU and refcount checks before
2302 			 * returning.
2303 			 */
2304 			folio_put(folio);
2305 			break;
2306 		}
2307 
2308 		node = folio_nid(folio);
2309 		if (hpage_collapse_scan_abort(node, cc)) {
2310 			result = SCAN_SCAN_ABORT;
2311 			folio_put(folio);
2312 			break;
2313 		}
2314 		cc->node_load[node]++;
2315 
2316 		if (!folio_test_lru(folio)) {
2317 			result = SCAN_PAGE_LRU;
2318 			folio_put(folio);
2319 			break;
2320 		}
2321 
2322 		if (folio_expected_ref_count(folio) + 1 != folio_ref_count(folio)) {
2323 			result = SCAN_PAGE_COUNT;
2324 			folio_put(folio);
2325 			break;
2326 		}
2327 
2328 		/*
2329 		 * We probably should check if the folio is referenced
2330 		 * here, but nobody would transfer pte_young() to
2331 		 * folio_test_referenced() for us.  And rmap walk here
2332 		 * is just too costly...
2333 		 */
2334 
2335 		present += folio_nr_pages(folio);
2336 		folio_put(folio);
2337 
2338 		if (need_resched()) {
2339 			xas_pause(&xas);
2340 			cond_resched_rcu();
2341 		}
2342 	}
2343 	rcu_read_unlock();
2344 
2345 	if (result == SCAN_SUCCEED) {
2346 		if (cc->is_khugepaged &&
2347 		    present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2348 			result = SCAN_EXCEED_NONE_PTE;
2349 			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2350 		} else {
2351 			result = collapse_file(mm, addr, file, start, cc);
2352 		}
2353 	}
2354 
2355 	trace_mm_khugepaged_scan_file(mm, folio, file, present, swap, result);
2356 	return result;
2357 }
2358 
2359 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2360 					    struct collapse_control *cc)
2361 	__releases(&khugepaged_mm_lock)
2362 	__acquires(&khugepaged_mm_lock)
2363 {
2364 	struct vma_iterator vmi;
2365 	struct khugepaged_mm_slot *mm_slot;
2366 	struct mm_slot *slot;
2367 	struct mm_struct *mm;
2368 	struct vm_area_struct *vma;
2369 	int progress = 0;
2370 
2371 	VM_BUG_ON(!pages);
2372 	lockdep_assert_held(&khugepaged_mm_lock);
2373 	*result = SCAN_FAIL;
2374 
2375 	if (khugepaged_scan.mm_slot) {
2376 		mm_slot = khugepaged_scan.mm_slot;
2377 		slot = &mm_slot->slot;
2378 	} else {
2379 		slot = list_entry(khugepaged_scan.mm_head.next,
2380 				     struct mm_slot, mm_node);
2381 		mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2382 		khugepaged_scan.address = 0;
2383 		khugepaged_scan.mm_slot = mm_slot;
2384 	}
2385 	spin_unlock(&khugepaged_mm_lock);
2386 
2387 	mm = slot->mm;
2388 	/*
2389 	 * Don't wait for semaphore (to avoid long wait times).  Just move to
2390 	 * the next mm on the list.
2391 	 */
2392 	vma = NULL;
2393 	if (unlikely(!mmap_read_trylock(mm)))
2394 		goto breakouterloop_mmap_lock;
2395 
2396 	progress++;
2397 	if (unlikely(hpage_collapse_test_exit_or_disable(mm)))
2398 		goto breakouterloop;
2399 
2400 	vma_iter_init(&vmi, mm, khugepaged_scan.address);
2401 	for_each_vma(vmi, vma) {
2402 		unsigned long hstart, hend;
2403 
2404 		cond_resched();
2405 		if (unlikely(hpage_collapse_test_exit_or_disable(mm))) {
2406 			progress++;
2407 			break;
2408 		}
2409 		if (!thp_vma_allowable_order(vma, vma->vm_flags,
2410 					TVA_ENFORCE_SYSFS, PMD_ORDER)) {
2411 skip:
2412 			progress++;
2413 			continue;
2414 		}
2415 		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2416 		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2417 		if (khugepaged_scan.address > hend)
2418 			goto skip;
2419 		if (khugepaged_scan.address < hstart)
2420 			khugepaged_scan.address = hstart;
2421 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2422 
2423 		while (khugepaged_scan.address < hend) {
2424 			bool mmap_locked = true;
2425 
2426 			cond_resched();
2427 			if (unlikely(hpage_collapse_test_exit_or_disable(mm)))
2428 				goto breakouterloop;
2429 
2430 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2431 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2432 				  hend);
2433 			if (!vma_is_anonymous(vma)) {
2434 				struct file *file = get_file(vma->vm_file);
2435 				pgoff_t pgoff = linear_page_index(vma,
2436 						khugepaged_scan.address);
2437 
2438 				mmap_read_unlock(mm);
2439 				mmap_locked = false;
2440 				*result = hpage_collapse_scan_file(mm,
2441 					khugepaged_scan.address, file, pgoff, cc);
2442 				fput(file);
2443 				if (*result == SCAN_PTE_MAPPED_HUGEPAGE) {
2444 					mmap_read_lock(mm);
2445 					if (hpage_collapse_test_exit_or_disable(mm))
2446 						goto breakouterloop;
2447 					*result = collapse_pte_mapped_thp(mm,
2448 						khugepaged_scan.address, false);
2449 					if (*result == SCAN_PMD_MAPPED)
2450 						*result = SCAN_SUCCEED;
2451 					mmap_read_unlock(mm);
2452 				}
2453 			} else {
2454 				*result = hpage_collapse_scan_pmd(mm, vma,
2455 					khugepaged_scan.address, &mmap_locked, cc);
2456 			}
2457 
2458 			if (*result == SCAN_SUCCEED)
2459 				++khugepaged_pages_collapsed;
2460 
2461 			/* move to next address */
2462 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2463 			progress += HPAGE_PMD_NR;
2464 			if (!mmap_locked)
2465 				/*
2466 				 * We released mmap_lock so break loop.  Note
2467 				 * that we drop mmap_lock before all hugepage
2468 				 * allocations, so if allocation fails, we are
2469 				 * guaranteed to break here and report the
2470 				 * correct result back to caller.
2471 				 */
2472 				goto breakouterloop_mmap_lock;
2473 			if (progress >= pages)
2474 				goto breakouterloop;
2475 		}
2476 	}
2477 breakouterloop:
2478 	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2479 breakouterloop_mmap_lock:
2480 
2481 	spin_lock(&khugepaged_mm_lock);
2482 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2483 	/*
2484 	 * Release the current mm_slot if this mm is about to die, or
2485 	 * if we scanned all vmas of this mm.
2486 	 */
2487 	if (hpage_collapse_test_exit(mm) || !vma) {
2488 		/*
2489 		 * Make sure that if mm_users is reaching zero while
2490 		 * khugepaged runs here, khugepaged_exit will find
2491 		 * mm_slot not pointing to the exiting mm.
2492 		 */
2493 		if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2494 			slot = list_entry(slot->mm_node.next,
2495 					  struct mm_slot, mm_node);
2496 			khugepaged_scan.mm_slot =
2497 				mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2498 			khugepaged_scan.address = 0;
2499 		} else {
2500 			khugepaged_scan.mm_slot = NULL;
2501 			khugepaged_full_scans++;
2502 		}
2503 
2504 		collect_mm_slot(mm_slot);
2505 	}
2506 
2507 	return progress;
2508 }
2509 
2510 static int khugepaged_has_work(void)
2511 {
2512 	return !list_empty(&khugepaged_scan.mm_head) && hugepage_pmd_enabled();
2513 }
2514 
2515 static int khugepaged_wait_event(void)
2516 {
2517 	return !list_empty(&khugepaged_scan.mm_head) ||
2518 		kthread_should_stop();
2519 }
2520 
2521 static void khugepaged_do_scan(struct collapse_control *cc)
2522 {
2523 	unsigned int progress = 0, pass_through_head = 0;
2524 	unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2525 	bool wait = true;
2526 	int result = SCAN_SUCCEED;
2527 
2528 	lru_add_drain_all();
2529 
2530 	while (true) {
2531 		cond_resched();
2532 
2533 		if (unlikely(kthread_should_stop()))
2534 			break;
2535 
2536 		spin_lock(&khugepaged_mm_lock);
2537 		if (!khugepaged_scan.mm_slot)
2538 			pass_through_head++;
2539 		if (khugepaged_has_work() &&
2540 		    pass_through_head < 2)
2541 			progress += khugepaged_scan_mm_slot(pages - progress,
2542 							    &result, cc);
2543 		else
2544 			progress = pages;
2545 		spin_unlock(&khugepaged_mm_lock);
2546 
2547 		if (progress >= pages)
2548 			break;
2549 
2550 		if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2551 			/*
2552 			 * If fail to allocate the first time, try to sleep for
2553 			 * a while.  When hit again, cancel the scan.
2554 			 */
2555 			if (!wait)
2556 				break;
2557 			wait = false;
2558 			khugepaged_alloc_sleep();
2559 		}
2560 	}
2561 }
2562 
2563 static bool khugepaged_should_wakeup(void)
2564 {
2565 	return kthread_should_stop() ||
2566 	       time_after_eq(jiffies, khugepaged_sleep_expire);
2567 }
2568 
2569 static void khugepaged_wait_work(void)
2570 {
2571 	if (khugepaged_has_work()) {
2572 		const unsigned long scan_sleep_jiffies =
2573 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2574 
2575 		if (!scan_sleep_jiffies)
2576 			return;
2577 
2578 		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2579 		wait_event_freezable_timeout(khugepaged_wait,
2580 					     khugepaged_should_wakeup(),
2581 					     scan_sleep_jiffies);
2582 		return;
2583 	}
2584 
2585 	if (hugepage_pmd_enabled())
2586 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2587 }
2588 
2589 static int khugepaged(void *none)
2590 {
2591 	struct khugepaged_mm_slot *mm_slot;
2592 
2593 	set_freezable();
2594 	set_user_nice(current, MAX_NICE);
2595 
2596 	while (!kthread_should_stop()) {
2597 		khugepaged_do_scan(&khugepaged_collapse_control);
2598 		khugepaged_wait_work();
2599 	}
2600 
2601 	spin_lock(&khugepaged_mm_lock);
2602 	mm_slot = khugepaged_scan.mm_slot;
2603 	khugepaged_scan.mm_slot = NULL;
2604 	if (mm_slot)
2605 		collect_mm_slot(mm_slot);
2606 	spin_unlock(&khugepaged_mm_lock);
2607 	return 0;
2608 }
2609 
2610 static void set_recommended_min_free_kbytes(void)
2611 {
2612 	struct zone *zone;
2613 	int nr_zones = 0;
2614 	unsigned long recommended_min;
2615 
2616 	if (!hugepage_pmd_enabled()) {
2617 		calculate_min_free_kbytes();
2618 		goto update_wmarks;
2619 	}
2620 
2621 	for_each_populated_zone(zone) {
2622 		/*
2623 		 * We don't need to worry about fragmentation of
2624 		 * ZONE_MOVABLE since it only has movable pages.
2625 		 */
2626 		if (zone_idx(zone) > gfp_zone(GFP_USER))
2627 			continue;
2628 
2629 		nr_zones++;
2630 	}
2631 
2632 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2633 	recommended_min = pageblock_nr_pages * nr_zones * 2;
2634 
2635 	/*
2636 	 * Make sure that on average at least two pageblocks are almost free
2637 	 * of another type, one for a migratetype to fall back to and a
2638 	 * second to avoid subsequent fallbacks of other types There are 3
2639 	 * MIGRATE_TYPES we care about.
2640 	 */
2641 	recommended_min += pageblock_nr_pages * nr_zones *
2642 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2643 
2644 	/* don't ever allow to reserve more than 5% of the lowmem */
2645 	recommended_min = min(recommended_min,
2646 			      (unsigned long) nr_free_buffer_pages() / 20);
2647 	recommended_min <<= (PAGE_SHIFT-10);
2648 
2649 	if (recommended_min > min_free_kbytes) {
2650 		if (user_min_free_kbytes >= 0)
2651 			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2652 				min_free_kbytes, recommended_min);
2653 
2654 		min_free_kbytes = recommended_min;
2655 	}
2656 
2657 update_wmarks:
2658 	setup_per_zone_wmarks();
2659 }
2660 
2661 int start_stop_khugepaged(void)
2662 {
2663 	int err = 0;
2664 
2665 	mutex_lock(&khugepaged_mutex);
2666 	if (hugepage_pmd_enabled()) {
2667 		if (!khugepaged_thread)
2668 			khugepaged_thread = kthread_run(khugepaged, NULL,
2669 							"khugepaged");
2670 		if (IS_ERR(khugepaged_thread)) {
2671 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2672 			err = PTR_ERR(khugepaged_thread);
2673 			khugepaged_thread = NULL;
2674 			goto fail;
2675 		}
2676 
2677 		if (!list_empty(&khugepaged_scan.mm_head))
2678 			wake_up_interruptible(&khugepaged_wait);
2679 	} else if (khugepaged_thread) {
2680 		kthread_stop(khugepaged_thread);
2681 		khugepaged_thread = NULL;
2682 	}
2683 	set_recommended_min_free_kbytes();
2684 fail:
2685 	mutex_unlock(&khugepaged_mutex);
2686 	return err;
2687 }
2688 
2689 void khugepaged_min_free_kbytes_update(void)
2690 {
2691 	mutex_lock(&khugepaged_mutex);
2692 	if (hugepage_pmd_enabled() && khugepaged_thread)
2693 		set_recommended_min_free_kbytes();
2694 	mutex_unlock(&khugepaged_mutex);
2695 }
2696 
2697 bool current_is_khugepaged(void)
2698 {
2699 	return kthread_func(current) == khugepaged;
2700 }
2701 
2702 static int madvise_collapse_errno(enum scan_result r)
2703 {
2704 	/*
2705 	 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2706 	 * actionable feedback to caller, so they may take an appropriate
2707 	 * fallback measure depending on the nature of the failure.
2708 	 */
2709 	switch (r) {
2710 	case SCAN_ALLOC_HUGE_PAGE_FAIL:
2711 		return -ENOMEM;
2712 	case SCAN_CGROUP_CHARGE_FAIL:
2713 	case SCAN_EXCEED_NONE_PTE:
2714 		return -EBUSY;
2715 	/* Resource temporary unavailable - trying again might succeed */
2716 	case SCAN_PAGE_COUNT:
2717 	case SCAN_PAGE_LOCK:
2718 	case SCAN_PAGE_LRU:
2719 	case SCAN_DEL_PAGE_LRU:
2720 	case SCAN_PAGE_FILLED:
2721 		return -EAGAIN;
2722 	/*
2723 	 * Other: Trying again likely not to succeed / error intrinsic to
2724 	 * specified memory range. khugepaged likely won't be able to collapse
2725 	 * either.
2726 	 */
2727 	default:
2728 		return -EINVAL;
2729 	}
2730 }
2731 
2732 int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2733 		     unsigned long start, unsigned long end)
2734 {
2735 	struct collapse_control *cc;
2736 	struct mm_struct *mm = vma->vm_mm;
2737 	unsigned long hstart, hend, addr;
2738 	int thps = 0, last_fail = SCAN_FAIL;
2739 	bool mmap_locked = true;
2740 
2741 	BUG_ON(vma->vm_start > start);
2742 	BUG_ON(vma->vm_end < end);
2743 
2744 	*prev = vma;
2745 
2746 	if (!thp_vma_allowable_order(vma, vma->vm_flags, 0, PMD_ORDER))
2747 		return -EINVAL;
2748 
2749 	cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2750 	if (!cc)
2751 		return -ENOMEM;
2752 	cc->is_khugepaged = false;
2753 
2754 	mmgrab(mm);
2755 	lru_add_drain_all();
2756 
2757 	hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2758 	hend = end & HPAGE_PMD_MASK;
2759 
2760 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2761 		int result = SCAN_FAIL;
2762 
2763 		if (!mmap_locked) {
2764 			cond_resched();
2765 			mmap_read_lock(mm);
2766 			mmap_locked = true;
2767 			result = hugepage_vma_revalidate(mm, addr, false, &vma,
2768 							 cc);
2769 			if (result  != SCAN_SUCCEED) {
2770 				last_fail = result;
2771 				goto out_nolock;
2772 			}
2773 
2774 			hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
2775 		}
2776 		mmap_assert_locked(mm);
2777 		memset(cc->node_load, 0, sizeof(cc->node_load));
2778 		nodes_clear(cc->alloc_nmask);
2779 		if (!vma_is_anonymous(vma)) {
2780 			struct file *file = get_file(vma->vm_file);
2781 			pgoff_t pgoff = linear_page_index(vma, addr);
2782 
2783 			mmap_read_unlock(mm);
2784 			mmap_locked = false;
2785 			result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2786 							  cc);
2787 			fput(file);
2788 		} else {
2789 			result = hpage_collapse_scan_pmd(mm, vma, addr,
2790 							 &mmap_locked, cc);
2791 		}
2792 		if (!mmap_locked)
2793 			*prev = NULL;  /* Tell caller we dropped mmap_lock */
2794 
2795 handle_result:
2796 		switch (result) {
2797 		case SCAN_SUCCEED:
2798 		case SCAN_PMD_MAPPED:
2799 			++thps;
2800 			break;
2801 		case SCAN_PTE_MAPPED_HUGEPAGE:
2802 			BUG_ON(mmap_locked);
2803 			BUG_ON(*prev);
2804 			mmap_read_lock(mm);
2805 			result = collapse_pte_mapped_thp(mm, addr, true);
2806 			mmap_read_unlock(mm);
2807 			goto handle_result;
2808 		/* Whitelisted set of results where continuing OK */
2809 		case SCAN_PMD_NULL:
2810 		case SCAN_PTE_NON_PRESENT:
2811 		case SCAN_PTE_UFFD_WP:
2812 		case SCAN_PAGE_RO:
2813 		case SCAN_LACK_REFERENCED_PAGE:
2814 		case SCAN_PAGE_NULL:
2815 		case SCAN_PAGE_COUNT:
2816 		case SCAN_PAGE_LOCK:
2817 		case SCAN_PAGE_COMPOUND:
2818 		case SCAN_PAGE_LRU:
2819 		case SCAN_DEL_PAGE_LRU:
2820 			last_fail = result;
2821 			break;
2822 		default:
2823 			last_fail = result;
2824 			/* Other error, exit */
2825 			goto out_maybelock;
2826 		}
2827 	}
2828 
2829 out_maybelock:
2830 	/* Caller expects us to hold mmap_lock on return */
2831 	if (!mmap_locked)
2832 		mmap_read_lock(mm);
2833 out_nolock:
2834 	mmap_assert_locked(mm);
2835 	mmdrop(mm);
2836 	kfree(cc);
2837 
2838 	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2839 			: madvise_collapse_errno(last_fail);
2840 }
2841