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