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