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