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