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