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