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