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