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