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