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