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