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