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