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