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