blob: 8978c1bf91e45c16a14d8a8a99f33f5d19e4054e [file] [log] [blame]
yuezonghe824eb0c2024-06-27 02:32:26 -07001/*
2 * Copyright (C) 2009 Red Hat, Inc.
3 *
4 * This work is licensed under the terms of the GNU GPL, version 2. See
5 * the COPYING file in the top-level directory.
6 */
7
8#include <linux/mm.h>
9#include <linux/sched.h>
10#include <linux/highmem.h>
11#include <linux/hugetlb.h>
12#include <linux/mmu_notifier.h>
13#include <linux/rmap.h>
14#include <linux/swap.h>
15#include <linux/mm_inline.h>
16#include <linux/kthread.h>
17#include <linux/khugepaged.h>
18#include <linux/freezer.h>
19#include <linux/mman.h>
20#include <asm/tlb.h>
21#include <asm/pgalloc.h>
22#include "internal.h"
23
24/*
25 * By default transparent hugepage support is enabled for all mappings
26 * and khugepaged scans all mappings. Defrag is only invoked by
27 * khugepaged hugepage allocations and by page faults inside
28 * MADV_HUGEPAGE regions to avoid the risk of slowing down short lived
29 * allocations.
30 */
31unsigned long transparent_hugepage_flags __read_mostly =
32#ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
33 (1<<TRANSPARENT_HUGEPAGE_FLAG)|
34#endif
35#ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
36 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
37#endif
38 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_FLAG)|
39 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
40
41/* default scan 8*512 pte (or vmas) every 30 second */
42static unsigned int khugepaged_pages_to_scan __read_mostly = HPAGE_PMD_NR*8;
43static unsigned int khugepaged_pages_collapsed;
44static unsigned int khugepaged_full_scans;
45static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
46/* during fragmentation poll the hugepage allocator once every minute */
47static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
48static struct task_struct *khugepaged_thread __read_mostly;
49static DEFINE_MUTEX(khugepaged_mutex);
50static DEFINE_SPINLOCK(khugepaged_mm_lock);
51static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
52/*
53 * default collapse hugepages if there is at least one pte mapped like
54 * it would have happened if the vma was large enough during page
55 * fault.
56 */
57static unsigned int khugepaged_max_ptes_none __read_mostly = HPAGE_PMD_NR-1;
58
59static int khugepaged(void *none);
60static int mm_slots_hash_init(void);
61static int khugepaged_slab_init(void);
62static void khugepaged_slab_free(void);
63
64#define MM_SLOTS_HASH_HEADS 1024
65static struct hlist_head *mm_slots_hash __read_mostly;
66static struct kmem_cache *mm_slot_cache __read_mostly;
67
68/**
69 * struct mm_slot - hash lookup from mm to mm_slot
70 * @hash: hash collision list
71 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
72 * @mm: the mm that this information is valid for
73 */
74struct mm_slot {
75 struct hlist_node hash;
76 struct list_head mm_node;
77 struct mm_struct *mm;
78};
79
80/**
81 * struct khugepaged_scan - cursor for scanning
82 * @mm_head: the head of the mm list to scan
83 * @mm_slot: the current mm_slot we are scanning
84 * @address: the next address inside that to be scanned
85 *
86 * There is only the one khugepaged_scan instance of this cursor structure.
87 */
88struct khugepaged_scan {
89 struct list_head mm_head;
90 struct mm_slot *mm_slot;
91 unsigned long address;
92};
93static struct khugepaged_scan khugepaged_scan = {
94 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
95};
96
97
98static int set_recommended_min_free_kbytes(void)
99{
100 struct zone *zone;
101 int nr_zones = 0;
102 unsigned long recommended_min;
103 extern int min_free_kbytes;
104
105 if (!test_bit(TRANSPARENT_HUGEPAGE_FLAG,
106 &transparent_hugepage_flags) &&
107 !test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
108 &transparent_hugepage_flags))
109 return 0;
110
111 for_each_populated_zone(zone)
112 nr_zones++;
113
114 /* Make sure at least 2 hugepages are free for MIGRATE_RESERVE */
115 recommended_min = pageblock_nr_pages * nr_zones * 2;
116
117 /*
118 * Make sure that on average at least two pageblocks are almost free
119 * of another type, one for a migratetype to fall back to and a
120 * second to avoid subsequent fallbacks of other types There are 3
121 * MIGRATE_TYPES we care about.
122 */
123 recommended_min += pageblock_nr_pages * nr_zones *
124 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
125
126 /* don't ever allow to reserve more than 5% of the lowmem */
127 recommended_min = min(recommended_min,
128 (unsigned long) nr_free_buffer_pages() / 20);
129 recommended_min <<= (PAGE_SHIFT-10);
130
131 if (recommended_min > min_free_kbytes)
132 min_free_kbytes = recommended_min;
133 setup_per_zone_wmarks();
134 return 0;
135}
136late_initcall(set_recommended_min_free_kbytes);
137
138static int start_khugepaged(void)
139{
140 int err = 0;
141 if (khugepaged_enabled()) {
142 int wakeup;
143 if (unlikely(!mm_slot_cache || !mm_slots_hash)) {
144 err = -ENOMEM;
145 goto out;
146 }
147 mutex_lock(&khugepaged_mutex);
148 if (!khugepaged_thread)
149 khugepaged_thread = kthread_run(khugepaged, NULL,
150 "khugepaged");
151 if (unlikely(IS_ERR(khugepaged_thread))) {
152 printk(KERN_ERR
153 "khugepaged: kthread_run(khugepaged) failed\n");
154 err = PTR_ERR(khugepaged_thread);
155 khugepaged_thread = NULL;
156 }
157 wakeup = !list_empty(&khugepaged_scan.mm_head);
158 mutex_unlock(&khugepaged_mutex);
159 if (wakeup)
160 wake_up_interruptible(&khugepaged_wait);
161
162 set_recommended_min_free_kbytes();
163 } else
164 /* wakeup to exit */
165 wake_up_interruptible(&khugepaged_wait);
166out:
167 return err;
168}
169
170#ifdef CONFIG_SYSFS
171
172static ssize_t double_flag_show(struct kobject *kobj,
173 struct kobj_attribute *attr, char *buf,
174 enum transparent_hugepage_flag enabled,
175 enum transparent_hugepage_flag req_madv)
176{
177 if (test_bit(enabled, &transparent_hugepage_flags)) {
178 VM_BUG_ON(test_bit(req_madv, &transparent_hugepage_flags));
179 return sprintf(buf, "[always] madvise never\n");
180 } else if (test_bit(req_madv, &transparent_hugepage_flags))
181 return sprintf(buf, "always [madvise] never\n");
182 else
183 return sprintf(buf, "always madvise [never]\n");
184}
185static ssize_t double_flag_store(struct kobject *kobj,
186 struct kobj_attribute *attr,
187 const char *buf, size_t count,
188 enum transparent_hugepage_flag enabled,
189 enum transparent_hugepage_flag req_madv)
190{
191 if (!memcmp("always", buf,
192 min(sizeof("always")-1, count))) {
193 set_bit(enabled, &transparent_hugepage_flags);
194 clear_bit(req_madv, &transparent_hugepage_flags);
195 } else if (!memcmp("madvise", buf,
196 min(sizeof("madvise")-1, count))) {
197 clear_bit(enabled, &transparent_hugepage_flags);
198 set_bit(req_madv, &transparent_hugepage_flags);
199 } else if (!memcmp("never", buf,
200 min(sizeof("never")-1, count))) {
201 clear_bit(enabled, &transparent_hugepage_flags);
202 clear_bit(req_madv, &transparent_hugepage_flags);
203 } else
204 return -EINVAL;
205
206 return count;
207}
208
209static ssize_t enabled_show(struct kobject *kobj,
210 struct kobj_attribute *attr, char *buf)
211{
212 return double_flag_show(kobj, attr, buf,
213 TRANSPARENT_HUGEPAGE_FLAG,
214 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
215}
216static ssize_t enabled_store(struct kobject *kobj,
217 struct kobj_attribute *attr,
218 const char *buf, size_t count)
219{
220 ssize_t ret;
221
222 ret = double_flag_store(kobj, attr, buf, count,
223 TRANSPARENT_HUGEPAGE_FLAG,
224 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
225
226 if (ret > 0) {
227 int err = start_khugepaged();
228 if (err)
229 ret = err;
230 }
231
232 if (ret > 0 &&
233 (test_bit(TRANSPARENT_HUGEPAGE_FLAG,
234 &transparent_hugepage_flags) ||
235 test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
236 &transparent_hugepage_flags)))
237 set_recommended_min_free_kbytes();
238
239 return ret;
240}
241static struct kobj_attribute enabled_attr =
242 __ATTR(enabled, 0644, enabled_show, enabled_store);
243
244static ssize_t single_flag_show(struct kobject *kobj,
245 struct kobj_attribute *attr, char *buf,
246 enum transparent_hugepage_flag flag)
247{
248 return sprintf(buf, "%d\n",
249 !!test_bit(flag, &transparent_hugepage_flags));
250}
251
252static ssize_t single_flag_store(struct kobject *kobj,
253 struct kobj_attribute *attr,
254 const char *buf, size_t count,
255 enum transparent_hugepage_flag flag)
256{
257 unsigned long value;
258 int ret;
259
260 ret = kstrtoul(buf, 10, &value);
261 if (ret < 0)
262 return ret;
263 if (value > 1)
264 return -EINVAL;
265
266 if (value)
267 set_bit(flag, &transparent_hugepage_flags);
268 else
269 clear_bit(flag, &transparent_hugepage_flags);
270
271 return count;
272}
273
274/*
275 * Currently defrag only disables __GFP_NOWAIT for allocation. A blind
276 * __GFP_REPEAT is too aggressive, it's never worth swapping tons of
277 * memory just to allocate one more hugepage.
278 */
279static ssize_t defrag_show(struct kobject *kobj,
280 struct kobj_attribute *attr, char *buf)
281{
282 return double_flag_show(kobj, attr, buf,
283 TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
284 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
285}
286static ssize_t defrag_store(struct kobject *kobj,
287 struct kobj_attribute *attr,
288 const char *buf, size_t count)
289{
290 return double_flag_store(kobj, attr, buf, count,
291 TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
292 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
293}
294static struct kobj_attribute defrag_attr =
295 __ATTR(defrag, 0644, defrag_show, defrag_store);
296
297#ifdef CONFIG_DEBUG_VM
298static ssize_t debug_cow_show(struct kobject *kobj,
299 struct kobj_attribute *attr, char *buf)
300{
301 return single_flag_show(kobj, attr, buf,
302 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
303}
304static ssize_t debug_cow_store(struct kobject *kobj,
305 struct kobj_attribute *attr,
306 const char *buf, size_t count)
307{
308 return single_flag_store(kobj, attr, buf, count,
309 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
310}
311static struct kobj_attribute debug_cow_attr =
312 __ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
313#endif /* CONFIG_DEBUG_VM */
314
315static struct attribute *hugepage_attr[] = {
316 &enabled_attr.attr,
317 &defrag_attr.attr,
318#ifdef CONFIG_DEBUG_VM
319 &debug_cow_attr.attr,
320#endif
321 NULL,
322};
323
324static struct attribute_group hugepage_attr_group = {
325 .attrs = hugepage_attr,
326};
327
328static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
329 struct kobj_attribute *attr,
330 char *buf)
331{
332 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
333}
334
335static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
336 struct kobj_attribute *attr,
337 const char *buf, size_t count)
338{
339 unsigned long msecs;
340 int err;
341
342 err = strict_strtoul(buf, 10, &msecs);
343 if (err || msecs > UINT_MAX)
344 return -EINVAL;
345
346 khugepaged_scan_sleep_millisecs = msecs;
347 wake_up_interruptible(&khugepaged_wait);
348
349 return count;
350}
351static struct kobj_attribute scan_sleep_millisecs_attr =
352 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
353 scan_sleep_millisecs_store);
354
355static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
356 struct kobj_attribute *attr,
357 char *buf)
358{
359 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
360}
361
362static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
363 struct kobj_attribute *attr,
364 const char *buf, size_t count)
365{
366 unsigned long msecs;
367 int err;
368
369 err = strict_strtoul(buf, 10, &msecs);
370 if (err || msecs > UINT_MAX)
371 return -EINVAL;
372
373 khugepaged_alloc_sleep_millisecs = msecs;
374 wake_up_interruptible(&khugepaged_wait);
375
376 return count;
377}
378static struct kobj_attribute alloc_sleep_millisecs_attr =
379 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
380 alloc_sleep_millisecs_store);
381
382static ssize_t pages_to_scan_show(struct kobject *kobj,
383 struct kobj_attribute *attr,
384 char *buf)
385{
386 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
387}
388static ssize_t pages_to_scan_store(struct kobject *kobj,
389 struct kobj_attribute *attr,
390 const char *buf, size_t count)
391{
392 int err;
393 unsigned long pages;
394
395 err = strict_strtoul(buf, 10, &pages);
396 if (err || !pages || pages > UINT_MAX)
397 return -EINVAL;
398
399 khugepaged_pages_to_scan = pages;
400
401 return count;
402}
403static struct kobj_attribute pages_to_scan_attr =
404 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
405 pages_to_scan_store);
406
407static ssize_t pages_collapsed_show(struct kobject *kobj,
408 struct kobj_attribute *attr,
409 char *buf)
410{
411 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
412}
413static struct kobj_attribute pages_collapsed_attr =
414 __ATTR_RO(pages_collapsed);
415
416static ssize_t full_scans_show(struct kobject *kobj,
417 struct kobj_attribute *attr,
418 char *buf)
419{
420 return sprintf(buf, "%u\n", khugepaged_full_scans);
421}
422static struct kobj_attribute full_scans_attr =
423 __ATTR_RO(full_scans);
424
425static ssize_t khugepaged_defrag_show(struct kobject *kobj,
426 struct kobj_attribute *attr, char *buf)
427{
428 return single_flag_show(kobj, attr, buf,
429 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
430}
431static ssize_t khugepaged_defrag_store(struct kobject *kobj,
432 struct kobj_attribute *attr,
433 const char *buf, size_t count)
434{
435 return single_flag_store(kobj, attr, buf, count,
436 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
437}
438static struct kobj_attribute khugepaged_defrag_attr =
439 __ATTR(defrag, 0644, khugepaged_defrag_show,
440 khugepaged_defrag_store);
441
442/*
443 * max_ptes_none controls if khugepaged should collapse hugepages over
444 * any unmapped ptes in turn potentially increasing the memory
445 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
446 * reduce the available free memory in the system as it
447 * runs. Increasing max_ptes_none will instead potentially reduce the
448 * free memory in the system during the khugepaged scan.
449 */
450static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
451 struct kobj_attribute *attr,
452 char *buf)
453{
454 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
455}
456static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
457 struct kobj_attribute *attr,
458 const char *buf, size_t count)
459{
460 int err;
461 unsigned long max_ptes_none;
462
463 err = strict_strtoul(buf, 10, &max_ptes_none);
464 if (err || max_ptes_none > HPAGE_PMD_NR-1)
465 return -EINVAL;
466
467 khugepaged_max_ptes_none = max_ptes_none;
468
469 return count;
470}
471static struct kobj_attribute khugepaged_max_ptes_none_attr =
472 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
473 khugepaged_max_ptes_none_store);
474
475static struct attribute *khugepaged_attr[] = {
476 &khugepaged_defrag_attr.attr,
477 &khugepaged_max_ptes_none_attr.attr,
478 &pages_to_scan_attr.attr,
479 &pages_collapsed_attr.attr,
480 &full_scans_attr.attr,
481 &scan_sleep_millisecs_attr.attr,
482 &alloc_sleep_millisecs_attr.attr,
483 NULL,
484};
485
486static struct attribute_group khugepaged_attr_group = {
487 .attrs = khugepaged_attr,
488 .name = "khugepaged",
489};
490
491static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
492{
493 int err;
494
495 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
496 if (unlikely(!*hugepage_kobj)) {
497 printk(KERN_ERR "hugepage: failed kobject create\n");
498 return -ENOMEM;
499 }
500
501 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
502 if (err) {
503 printk(KERN_ERR "hugepage: failed register hugeage group\n");
504 goto delete_obj;
505 }
506
507 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
508 if (err) {
509 printk(KERN_ERR "hugepage: failed register hugeage group\n");
510 goto remove_hp_group;
511 }
512
513 return 0;
514
515remove_hp_group:
516 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
517delete_obj:
518 kobject_put(*hugepage_kobj);
519 return err;
520}
521
522static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
523{
524 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
525 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
526 kobject_put(hugepage_kobj);
527}
528#else
529static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
530{
531 return 0;
532}
533
534static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
535{
536}
537#endif /* CONFIG_SYSFS */
538
539static int __init hugepage_init(void)
540{
541 int err;
542 struct kobject *hugepage_kobj;
543
544 if (!has_transparent_hugepage()) {
545 transparent_hugepage_flags = 0;
546 return -EINVAL;
547 }
548
549 err = hugepage_init_sysfs(&hugepage_kobj);
550 if (err)
551 return err;
552
553 err = khugepaged_slab_init();
554 if (err)
555 goto out;
556
557 err = mm_slots_hash_init();
558 if (err) {
559 khugepaged_slab_free();
560 goto out;
561 }
562
563 /*
564 * By default disable transparent hugepages on smaller systems,
565 * where the extra memory used could hurt more than TLB overhead
566 * is likely to save. The admin can still enable it through /sys.
567 */
568 if (totalram_pages < (512 << (20 - PAGE_SHIFT)))
569 transparent_hugepage_flags = 0;
570
571 start_khugepaged();
572
573 set_recommended_min_free_kbytes();
574
575 return 0;
576out:
577 hugepage_exit_sysfs(hugepage_kobj);
578 return err;
579}
580module_init(hugepage_init)
581
582static int __init setup_transparent_hugepage(char *str)
583{
584 int ret = 0;
585 if (!str)
586 goto out;
587 if (!strcmp(str, "always")) {
588 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
589 &transparent_hugepage_flags);
590 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
591 &transparent_hugepage_flags);
592 ret = 1;
593 } else if (!strcmp(str, "madvise")) {
594 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
595 &transparent_hugepage_flags);
596 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
597 &transparent_hugepage_flags);
598 ret = 1;
599 } else if (!strcmp(str, "never")) {
600 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
601 &transparent_hugepage_flags);
602 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
603 &transparent_hugepage_flags);
604 ret = 1;
605 }
606out:
607 if (!ret)
608 printk(KERN_WARNING
609 "transparent_hugepage= cannot parse, ignored\n");
610 return ret;
611}
612__setup("transparent_hugepage=", setup_transparent_hugepage);
613
614static void prepare_pmd_huge_pte(pgtable_t pgtable,
615 struct mm_struct *mm)
616{
617 assert_spin_locked(&mm->page_table_lock);
618
619 /* FIFO */
620 if (!mm->pmd_huge_pte)
621 INIT_LIST_HEAD(&pgtable->lru);
622 else
623 list_add(&pgtable->lru, &mm->pmd_huge_pte->lru);
624 mm->pmd_huge_pte = pgtable;
625}
626
627static inline pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
628{
629 if (likely(vma->vm_flags & VM_WRITE))
630 pmd = pmd_mkwrite(pmd);
631 return pmd;
632}
633
634static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
635 struct vm_area_struct *vma,
636 unsigned long haddr, pmd_t *pmd,
637 struct page *page)
638{
639 int ret = 0;
640 pgtable_t pgtable;
641
642 VM_BUG_ON(!PageCompound(page));
643 pgtable = pte_alloc_one(mm, haddr);
644 if (unlikely(!pgtable)) {
645 mem_cgroup_uncharge_page(page);
646 put_page(page);
647 return VM_FAULT_OOM;
648 }
649
650 clear_huge_page(page, haddr, HPAGE_PMD_NR);
651 __SetPageUptodate(page);
652
653 spin_lock(&mm->page_table_lock);
654 if (unlikely(!pmd_none(*pmd))) {
655 spin_unlock(&mm->page_table_lock);
656 mem_cgroup_uncharge_page(page);
657 put_page(page);
658 pte_free(mm, pgtable);
659 } else {
660 pmd_t entry;
661 entry = mk_pmd(page, vma->vm_page_prot);
662 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
663 entry = pmd_mkhuge(entry);
664 /*
665 * The spinlocking to take the lru_lock inside
666 * page_add_new_anon_rmap() acts as a full memory
667 * barrier to be sure clear_huge_page writes become
668 * visible after the set_pmd_at() write.
669 */
670 page_add_new_anon_rmap(page, vma, haddr);
671 set_pmd_at(mm, haddr, pmd, entry);
672 prepare_pmd_huge_pte(pgtable, mm);
673 add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
674 mm->nr_ptes++;
675 spin_unlock(&mm->page_table_lock);
676 }
677
678 return ret;
679}
680
681static inline gfp_t alloc_hugepage_gfpmask(int defrag, gfp_t extra_gfp)
682{
683 return (GFP_TRANSHUGE & ~(defrag ? 0 : __GFP_WAIT)) | extra_gfp;
684}
685
686static inline struct page *alloc_hugepage_vma(int defrag,
687 struct vm_area_struct *vma,
688 unsigned long haddr, int nd,
689 gfp_t extra_gfp)
690{
691 return alloc_pages_vma(alloc_hugepage_gfpmask(defrag, extra_gfp),
692 HPAGE_PMD_ORDER, vma, haddr, nd);
693}
694
695#ifndef CONFIG_NUMA
696static inline struct page *alloc_hugepage(int defrag)
697{
698 return alloc_pages(alloc_hugepage_gfpmask(defrag, 0),
699 HPAGE_PMD_ORDER);
700}
701#endif
702
703int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
704 unsigned long address, pmd_t *pmd,
705 unsigned int flags)
706{
707 struct page *page;
708 unsigned long haddr = address & HPAGE_PMD_MASK;
709 pte_t *pte;
710
711 if (haddr >= vma->vm_start && haddr + HPAGE_PMD_SIZE <= vma->vm_end) {
712 if (unlikely(anon_vma_prepare(vma)))
713 return VM_FAULT_OOM;
714 if (unlikely(khugepaged_enter(vma, vma->vm_flags)))
715 return VM_FAULT_OOM;
716 page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
717 vma, haddr, numa_node_id(), 0);
718 if (unlikely(!page)) {
719 count_vm_event(THP_FAULT_FALLBACK);
720 goto out;
721 }
722 count_vm_event(THP_FAULT_ALLOC);
723 if (unlikely(mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))) {
724 put_page(page);
725 goto out;
726 }
727
728 return __do_huge_pmd_anonymous_page(mm, vma, haddr, pmd, page);
729 }
730out:
731 /*
732 * Use __pte_alloc instead of pte_alloc_map, because we can't
733 * run pte_offset_map on the pmd, if an huge pmd could
734 * materialize from under us from a different thread.
735 */
736 if (unlikely(__pte_alloc(mm, vma, pmd, address)))
737 return VM_FAULT_OOM;
738 /* if an huge pmd materialized from under us just retry later */
739 if (unlikely(pmd_trans_huge(*pmd)))
740 return 0;
741 /*
742 * A regular pmd is established and it can't morph into a huge pmd
743 * from under us anymore at this point because we hold the mmap_sem
744 * read mode and khugepaged takes it in write mode. So now it's
745 * safe to run pte_offset_map().
746 */
747 pte = pte_offset_map(pmd, address);
748 return handle_pte_fault(mm, vma, address, pte, pmd, flags);
749}
750
751int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
752 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
753 struct vm_area_struct *vma)
754{
755 struct page *src_page;
756 pmd_t pmd;
757 pgtable_t pgtable;
758 int ret;
759
760 ret = -ENOMEM;
761 pgtable = pte_alloc_one(dst_mm, addr);
762 if (unlikely(!pgtable))
763 goto out;
764
765 spin_lock(&dst_mm->page_table_lock);
766 spin_lock_nested(&src_mm->page_table_lock, SINGLE_DEPTH_NESTING);
767
768 ret = -EAGAIN;
769 pmd = *src_pmd;
770 if (unlikely(!pmd_trans_huge(pmd))) {
771 pte_free(dst_mm, pgtable);
772 goto out_unlock;
773 }
774 if (unlikely(pmd_trans_splitting(pmd))) {
775 /* split huge page running from under us */
776 spin_unlock(&src_mm->page_table_lock);
777 spin_unlock(&dst_mm->page_table_lock);
778 pte_free(dst_mm, pgtable);
779
780 wait_split_huge_page(vma->anon_vma, src_pmd); /* src_vma */
781 goto out;
782 }
783 src_page = pmd_page(pmd);
784 VM_BUG_ON(!PageHead(src_page));
785 get_page(src_page);
786 page_dup_rmap(src_page);
787 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
788
789 pmdp_set_wrprotect(src_mm, addr, src_pmd);
790 pmd = pmd_mkold(pmd_wrprotect(pmd));
791 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
792 prepare_pmd_huge_pte(pgtable, dst_mm);
793 dst_mm->nr_ptes++;
794
795 ret = 0;
796out_unlock:
797 spin_unlock(&src_mm->page_table_lock);
798 spin_unlock(&dst_mm->page_table_lock);
799out:
800 return ret;
801}
802
803/* no "address" argument so destroys page coloring of some arch */
804pgtable_t get_pmd_huge_pte(struct mm_struct *mm)
805{
806 pgtable_t pgtable;
807
808 assert_spin_locked(&mm->page_table_lock);
809
810 /* FIFO */
811 pgtable = mm->pmd_huge_pte;
812 if (list_empty(&pgtable->lru))
813 mm->pmd_huge_pte = NULL;
814 else {
815 mm->pmd_huge_pte = list_entry(pgtable->lru.next,
816 struct page, lru);
817 list_del(&pgtable->lru);
818 }
819 return pgtable;
820}
821
822static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
823 struct vm_area_struct *vma,
824 unsigned long address,
825 pmd_t *pmd, pmd_t orig_pmd,
826 struct page *page,
827 unsigned long haddr)
828{
829 pgtable_t pgtable;
830 pmd_t _pmd;
831 int ret = 0, i;
832 struct page **pages;
833
834 pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
835 GFP_KERNEL);
836 if (unlikely(!pages)) {
837 ret |= VM_FAULT_OOM;
838 goto out;
839 }
840
841 for (i = 0; i < HPAGE_PMD_NR; i++) {
842 pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
843 __GFP_OTHER_NODE,
844 vma, address, page_to_nid(page));
845 if (unlikely(!pages[i] ||
846 mem_cgroup_newpage_charge(pages[i], mm,
847 GFP_KERNEL))) {
848 if (pages[i])
849 put_page(pages[i]);
850 mem_cgroup_uncharge_start();
851 while (--i >= 0) {
852 mem_cgroup_uncharge_page(pages[i]);
853 put_page(pages[i]);
854 }
855 mem_cgroup_uncharge_end();
856 kfree(pages);
857 ret |= VM_FAULT_OOM;
858 goto out;
859 }
860 }
861
862 for (i = 0; i < HPAGE_PMD_NR; i++) {
863 copy_user_highpage(pages[i], page + i,
864 haddr + PAGE_SIZE * i, vma);
865 __SetPageUptodate(pages[i]);
866 cond_resched();
867 }
868
869 spin_lock(&mm->page_table_lock);
870 if (unlikely(!pmd_same(*pmd, orig_pmd)))
871 goto out_free_pages;
872 VM_BUG_ON(!PageHead(page));
873
874 pmdp_clear_flush_notify(vma, haddr, pmd);
875 /* leave pmd empty until pte is filled */
876
877 pgtable = get_pmd_huge_pte(mm);
878 pmd_populate(mm, &_pmd, pgtable);
879
880 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
881 pte_t *pte, entry;
882 entry = mk_pte(pages[i], vma->vm_page_prot);
883 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
884 page_add_new_anon_rmap(pages[i], vma, haddr);
885 pte = pte_offset_map(&_pmd, haddr);
886 VM_BUG_ON(!pte_none(*pte));
887 set_pte_at(mm, haddr, pte, entry);
888 pte_unmap(pte);
889 }
890 kfree(pages);
891
892 smp_wmb(); /* make pte visible before pmd */
893 pmd_populate(mm, pmd, pgtable);
894 page_remove_rmap(page);
895 spin_unlock(&mm->page_table_lock);
896
897 ret |= VM_FAULT_WRITE;
898 put_page(page);
899
900out:
901 return ret;
902
903out_free_pages:
904 spin_unlock(&mm->page_table_lock);
905 mem_cgroup_uncharge_start();
906 for (i = 0; i < HPAGE_PMD_NR; i++) {
907 mem_cgroup_uncharge_page(pages[i]);
908 put_page(pages[i]);
909 }
910 mem_cgroup_uncharge_end();
911 kfree(pages);
912 goto out;
913}
914
915int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
916 unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
917{
918 int ret = 0;
919 struct page *page, *new_page;
920 unsigned long haddr;
921
922 VM_BUG_ON(!vma->anon_vma);
923 spin_lock(&mm->page_table_lock);
924 if (unlikely(!pmd_same(*pmd, orig_pmd)))
925 goto out_unlock;
926
927 page = pmd_page(orig_pmd);
928 VM_BUG_ON(!PageCompound(page) || !PageHead(page));
929 haddr = address & HPAGE_PMD_MASK;
930 if (page_mapcount(page) == 1) {
931 pmd_t entry;
932 entry = pmd_mkyoung(orig_pmd);
933 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
934 if (pmdp_set_access_flags(vma, haddr, pmd, entry, 1))
935 update_mmu_cache(vma, address, entry);
936 ret |= VM_FAULT_WRITE;
937 goto out_unlock;
938 }
939 get_page(page);
940 spin_unlock(&mm->page_table_lock);
941
942 if (transparent_hugepage_enabled(vma) &&
943 !transparent_hugepage_debug_cow())
944 new_page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
945 vma, haddr, numa_node_id(), 0);
946 else
947 new_page = NULL;
948
949 if (unlikely(!new_page)) {
950 count_vm_event(THP_FAULT_FALLBACK);
951 ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
952 pmd, orig_pmd, page, haddr);
953 if (ret & VM_FAULT_OOM)
954 split_huge_page(page);
955 put_page(page);
956 goto out;
957 }
958 count_vm_event(THP_FAULT_ALLOC);
959
960 if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
961 put_page(new_page);
962 split_huge_page(page);
963 put_page(page);
964 ret |= VM_FAULT_OOM;
965 goto out;
966 }
967
968 copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
969 __SetPageUptodate(new_page);
970
971 spin_lock(&mm->page_table_lock);
972 put_page(page);
973 if (unlikely(!pmd_same(*pmd, orig_pmd))) {
974 mem_cgroup_uncharge_page(new_page);
975 put_page(new_page);
976 } else {
977 pmd_t entry;
978 VM_BUG_ON(!PageHead(page));
979 entry = mk_pmd(new_page, vma->vm_page_prot);
980 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
981 entry = pmd_mkhuge(entry);
982 pmdp_clear_flush_notify(vma, haddr, pmd);
983 page_add_new_anon_rmap(new_page, vma, haddr);
984 set_pmd_at(mm, haddr, pmd, entry);
985 update_mmu_cache(vma, address, entry);
986 page_remove_rmap(page);
987 put_page(page);
988 ret |= VM_FAULT_WRITE;
989 }
990out_unlock:
991 spin_unlock(&mm->page_table_lock);
992out:
993 return ret;
994}
995
996struct page *follow_trans_huge_pmd(struct mm_struct *mm,
997 unsigned long addr,
998 pmd_t *pmd,
999 unsigned int flags)
1000{
1001 struct page *page = NULL;
1002
1003 assert_spin_locked(&mm->page_table_lock);
1004
1005 if (flags & FOLL_WRITE && !pmd_write(*pmd))
1006 goto out;
1007
1008 page = pmd_page(*pmd);
1009 VM_BUG_ON(!PageHead(page));
1010 if (flags & FOLL_TOUCH) {
1011 pmd_t _pmd;
1012 /*
1013 * We should set the dirty bit only for FOLL_WRITE but
1014 * for now the dirty bit in the pmd is meaningless.
1015 * And if the dirty bit will become meaningful and
1016 * we'll only set it with FOLL_WRITE, an atomic
1017 * set_bit will be required on the pmd to set the
1018 * young bit, instead of the current set_pmd_at.
1019 */
1020 _pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
1021 set_pmd_at(mm, addr & HPAGE_PMD_MASK, pmd, _pmd);
1022 }
1023 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1024 VM_BUG_ON(!PageCompound(page));
1025 if (flags & FOLL_GET)
1026 get_page_foll(page);
1027
1028out:
1029 return page;
1030}
1031
1032int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1033 pmd_t *pmd, unsigned long addr)
1034{
1035 int ret = 0;
1036
1037 if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1038 struct page *page;
1039 pgtable_t pgtable;
1040 pgtable = get_pmd_huge_pte(tlb->mm);
1041 page = pmd_page(*pmd);
1042 pmd_clear(pmd);
1043 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1044 page_remove_rmap(page);
1045 VM_BUG_ON(page_mapcount(page) < 0);
1046 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1047 VM_BUG_ON(!PageHead(page));
1048 tlb->mm->nr_ptes--;
1049 spin_unlock(&tlb->mm->page_table_lock);
1050 tlb_remove_page(tlb, page);
1051 pte_free(tlb->mm, pgtable);
1052 ret = 1;
1053 }
1054 return ret;
1055}
1056
1057int mincore_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1058 unsigned long addr, unsigned long end,
1059 unsigned char *vec)
1060{
1061 int ret = 0;
1062
1063 if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1064 /*
1065 * All logical pages in the range are present
1066 * if backed by a huge page.
1067 */
1068 spin_unlock(&vma->vm_mm->page_table_lock);
1069 memset(vec, 1, (end - addr) >> PAGE_SHIFT);
1070 ret = 1;
1071 }
1072
1073 return ret;
1074}
1075
1076int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1077 unsigned long old_addr,
1078 unsigned long new_addr, unsigned long old_end,
1079 pmd_t *old_pmd, pmd_t *new_pmd)
1080{
1081 int ret = 0;
1082 pmd_t pmd;
1083
1084 struct mm_struct *mm = vma->vm_mm;
1085
1086 if ((old_addr & ~HPAGE_PMD_MASK) ||
1087 (new_addr & ~HPAGE_PMD_MASK) ||
1088 old_end - old_addr < HPAGE_PMD_SIZE ||
1089 (new_vma->vm_flags & VM_NOHUGEPAGE))
1090 goto out;
1091
1092 /*
1093 * The destination pmd shouldn't be established, free_pgtables()
1094 * should have release it.
1095 */
1096 if (WARN_ON(!pmd_none(*new_pmd))) {
1097 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1098 goto out;
1099 }
1100
1101 ret = __pmd_trans_huge_lock(old_pmd, vma);
1102 if (ret == 1) {
1103 pmd = pmdp_get_and_clear(mm, old_addr, old_pmd);
1104 VM_BUG_ON(!pmd_none(*new_pmd));
1105 set_pmd_at(mm, new_addr, new_pmd, pmd);
1106 spin_unlock(&mm->page_table_lock);
1107 }
1108out:
1109 return ret;
1110}
1111
1112int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1113 unsigned long addr, pgprot_t newprot)
1114{
1115 struct mm_struct *mm = vma->vm_mm;
1116 int ret = 0;
1117
1118 if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1119 pmd_t entry;
1120 entry = pmdp_get_and_clear(mm, addr, pmd);
1121 entry = pmd_modify(entry, newprot);
1122 set_pmd_at(mm, addr, pmd, entry);
1123 spin_unlock(&vma->vm_mm->page_table_lock);
1124 ret = 1;
1125 }
1126
1127 return ret;
1128}
1129
1130/*
1131 * Returns 1 if a given pmd maps a stable (not under splitting) thp.
1132 * Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
1133 *
1134 * Note that if it returns 1, this routine returns without unlocking page
1135 * table locks. So callers must unlock them.
1136 */
1137int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1138{
1139 spin_lock(&vma->vm_mm->page_table_lock);
1140 if (likely(pmd_trans_huge(*pmd))) {
1141 if (unlikely(pmd_trans_splitting(*pmd))) {
1142 spin_unlock(&vma->vm_mm->page_table_lock);
1143 wait_split_huge_page(vma->anon_vma, pmd);
1144 return -1;
1145 } else {
1146 /* Thp mapped by 'pmd' is stable, so we can
1147 * handle it as it is. */
1148 return 1;
1149 }
1150 }
1151 spin_unlock(&vma->vm_mm->page_table_lock);
1152 return 0;
1153}
1154
1155pmd_t *page_check_address_pmd(struct page *page,
1156 struct mm_struct *mm,
1157 unsigned long address,
1158 enum page_check_address_pmd_flag flag)
1159{
1160 pgd_t *pgd;
1161 pud_t *pud;
1162 pmd_t *pmd, *ret = NULL;
1163
1164 if (address & ~HPAGE_PMD_MASK)
1165 goto out;
1166
1167 pgd = pgd_offset(mm, address);
1168 if (!pgd_present(*pgd))
1169 goto out;
1170
1171 pud = pud_offset(pgd, address);
1172 if (!pud_present(*pud))
1173 goto out;
1174
1175 pmd = pmd_offset(pud, address);
1176 if (pmd_none(*pmd))
1177 goto out;
1178 if (pmd_page(*pmd) != page)
1179 goto out;
1180 /*
1181 * split_vma() may create temporary aliased mappings. There is
1182 * no risk as long as all huge pmd are found and have their
1183 * splitting bit set before __split_huge_page_refcount
1184 * runs. Finding the same huge pmd more than once during the
1185 * same rmap walk is not a problem.
1186 */
1187 if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1188 pmd_trans_splitting(*pmd))
1189 goto out;
1190 if (pmd_trans_huge(*pmd)) {
1191 VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1192 !pmd_trans_splitting(*pmd));
1193 ret = pmd;
1194 }
1195out:
1196 return ret;
1197}
1198
1199static int __split_huge_page_splitting(struct page *page,
1200 struct vm_area_struct *vma,
1201 unsigned long address)
1202{
1203 struct mm_struct *mm = vma->vm_mm;
1204 pmd_t *pmd;
1205 int ret = 0;
1206
1207 spin_lock(&mm->page_table_lock);
1208 pmd = page_check_address_pmd(page, mm, address,
1209 PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
1210 if (pmd) {
1211 /*
1212 * We can't temporarily set the pmd to null in order
1213 * to split it, the pmd must remain marked huge at all
1214 * times or the VM won't take the pmd_trans_huge paths
1215 * and it won't wait on the anon_vma->root->mutex to
1216 * serialize against split_huge_page*.
1217 */
1218 pmdp_splitting_flush_notify(vma, address, pmd);
1219 ret = 1;
1220 }
1221 spin_unlock(&mm->page_table_lock);
1222
1223 return ret;
1224}
1225
1226static void __split_huge_page_refcount(struct page *page)
1227{
1228 int i;
1229 struct zone *zone = page_zone(page);
1230 int tail_count = 0;
1231
1232 /* prevent PageLRU to go away from under us, and freeze lru stats */
1233 spin_lock_irq(&zone->lru_lock);
1234 compound_lock(page);
1235 /* complete memcg works before add pages to LRU */
1236 mem_cgroup_split_huge_fixup(page);
1237
1238 for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
1239 struct page *page_tail = page + i;
1240
1241 /* tail_page->_mapcount cannot change */
1242 BUG_ON(page_mapcount(page_tail) < 0);
1243 tail_count += page_mapcount(page_tail);
1244 /* check for overflow */
1245 BUG_ON(tail_count < 0);
1246 BUG_ON(atomic_read(&page_tail->_count) != 0);
1247 /*
1248 * tail_page->_count is zero and not changing from
1249 * under us. But get_page_unless_zero() may be running
1250 * from under us on the tail_page. If we used
1251 * atomic_set() below instead of atomic_add(), we
1252 * would then run atomic_set() concurrently with
1253 * get_page_unless_zero(), and atomic_set() is
1254 * implemented in C not using locked ops. spin_unlock
1255 * on x86 sometime uses locked ops because of PPro
1256 * errata 66, 92, so unless somebody can guarantee
1257 * atomic_set() here would be safe on all archs (and
1258 * not only on x86), it's safer to use atomic_add().
1259 */
1260 atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1261 &page_tail->_count);
1262
1263 /* after clearing PageTail the gup refcount can be released */
1264 smp_mb();
1265
1266 /*
1267 * retain hwpoison flag of the poisoned tail page:
1268 * fix for the unsuitable process killed on Guest Machine(KVM)
1269 * by the memory-failure.
1270 */
1271 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP | __PG_HWPOISON;
1272 page_tail->flags |= (page->flags &
1273 ((1L << PG_referenced) |
1274 (1L << PG_swapbacked) |
1275 (1L << PG_mlocked) |
1276 (1L << PG_uptodate)));
1277 page_tail->flags |= (1L << PG_dirty);
1278
1279 /* clear PageTail before overwriting first_page */
1280 smp_wmb();
1281
1282 /*
1283 * __split_huge_page_splitting() already set the
1284 * splitting bit in all pmd that could map this
1285 * hugepage, that will ensure no CPU can alter the
1286 * mapcount on the head page. The mapcount is only
1287 * accounted in the head page and it has to be
1288 * transferred to all tail pages in the below code. So
1289 * for this code to be safe, the split the mapcount
1290 * can't change. But that doesn't mean userland can't
1291 * keep changing and reading the page contents while
1292 * we transfer the mapcount, so the pmd splitting
1293 * status is achieved setting a reserved bit in the
1294 * pmd, not by clearing the present bit.
1295 */
1296 page_tail->_mapcount = page->_mapcount;
1297
1298 BUG_ON(page_tail->mapping);
1299 page_tail->mapping = page->mapping;
1300
1301 page_tail->index = page->index + i;
1302
1303 BUG_ON(!PageAnon(page_tail));
1304 BUG_ON(!PageUptodate(page_tail));
1305 BUG_ON(!PageDirty(page_tail));
1306 BUG_ON(!PageSwapBacked(page_tail));
1307
1308
1309 lru_add_page_tail(zone, page, page_tail);
1310 }
1311 atomic_sub(tail_count, &page->_count);
1312 BUG_ON(atomic_read(&page->_count) <= 0);
1313
1314 __dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
1315 __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1316
1317 ClearPageCompound(page);
1318 compound_unlock(page);
1319 spin_unlock_irq(&zone->lru_lock);
1320
1321 for (i = 1; i < HPAGE_PMD_NR; i++) {
1322 struct page *page_tail = page + i;
1323 BUG_ON(page_count(page_tail) <= 0);
1324 /*
1325 * Tail pages may be freed if there wasn't any mapping
1326 * like if add_to_swap() is running on a lru page that
1327 * had its mapping zapped. And freeing these pages
1328 * requires taking the lru_lock so we do the put_page
1329 * of the tail pages after the split is complete.
1330 */
1331 put_page(page_tail);
1332 }
1333
1334 /*
1335 * Only the head page (now become a regular page) is required
1336 * to be pinned by the caller.
1337 */
1338 BUG_ON(page_count(page) <= 0);
1339}
1340
1341static int __split_huge_page_map(struct page *page,
1342 struct vm_area_struct *vma,
1343 unsigned long address)
1344{
1345 struct mm_struct *mm = vma->vm_mm;
1346 pmd_t *pmd, _pmd;
1347 int ret = 0, i;
1348 pgtable_t pgtable;
1349 unsigned long haddr;
1350
1351 spin_lock(&mm->page_table_lock);
1352 pmd = page_check_address_pmd(page, mm, address,
1353 PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1354 if (pmd) {
1355 pgtable = get_pmd_huge_pte(mm);
1356 pmd_populate(mm, &_pmd, pgtable);
1357
1358 for (i = 0, haddr = address; i < HPAGE_PMD_NR;
1359 i++, haddr += PAGE_SIZE) {
1360 pte_t *pte, entry;
1361 BUG_ON(PageCompound(page+i));
1362 entry = mk_pte(page + i, vma->vm_page_prot);
1363 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1364 if (!pmd_write(*pmd))
1365 entry = pte_wrprotect(entry);
1366 else
1367 BUG_ON(page_mapcount(page) != 1);
1368 if (!pmd_young(*pmd))
1369 entry = pte_mkold(entry);
1370 pte = pte_offset_map(&_pmd, haddr);
1371 BUG_ON(!pte_none(*pte));
1372 set_pte_at(mm, haddr, pte, entry);
1373 pte_unmap(pte);
1374 }
1375
1376 smp_wmb(); /* make pte visible before pmd */
1377 /*
1378 * Up to this point the pmd is present and huge and
1379 * userland has the whole access to the hugepage
1380 * during the split (which happens in place). If we
1381 * overwrite the pmd with the not-huge version
1382 * pointing to the pte here (which of course we could
1383 * if all CPUs were bug free), userland could trigger
1384 * a small page size TLB miss on the small sized TLB
1385 * while the hugepage TLB entry is still established
1386 * in the huge TLB. Some CPU doesn't like that. See
1387 * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1388 * Erratum 383 on page 93. Intel should be safe but is
1389 * also warns that it's only safe if the permission
1390 * and cache attributes of the two entries loaded in
1391 * the two TLB is identical (which should be the case
1392 * here). But it is generally safer to never allow
1393 * small and huge TLB entries for the same virtual
1394 * address to be loaded simultaneously. So instead of
1395 * doing "pmd_populate(); flush_tlb_range();" we first
1396 * mark the current pmd notpresent (atomically because
1397 * here the pmd_trans_huge and pmd_trans_splitting
1398 * must remain set at all times on the pmd until the
1399 * split is complete for this pmd), then we flush the
1400 * SMP TLB and finally we write the non-huge version
1401 * of the pmd entry with pmd_populate.
1402 */
1403 set_pmd_at(mm, address, pmd, pmd_mknotpresent(*pmd));
1404 flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
1405 pmd_populate(mm, pmd, pgtable);
1406 ret = 1;
1407 }
1408 spin_unlock(&mm->page_table_lock);
1409
1410 return ret;
1411}
1412
1413/* must be called with anon_vma->root->mutex hold */
1414static void __split_huge_page(struct page *page,
1415 struct anon_vma *anon_vma)
1416{
1417 int mapcount, mapcount2;
1418 struct anon_vma_chain *avc;
1419
1420 BUG_ON(!PageHead(page));
1421 BUG_ON(PageTail(page));
1422
1423 mapcount = 0;
1424 list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1425 struct vm_area_struct *vma = avc->vma;
1426 unsigned long addr = vma_address(page, vma);
1427 BUG_ON(is_vma_temporary_stack(vma));
1428 if (addr == -EFAULT)
1429 continue;
1430 mapcount += __split_huge_page_splitting(page, vma, addr);
1431 }
1432 /*
1433 * It is critical that new vmas are added to the tail of the
1434 * anon_vma list. This guarantes that if copy_huge_pmd() runs
1435 * and establishes a child pmd before
1436 * __split_huge_page_splitting() freezes the parent pmd (so if
1437 * we fail to prevent copy_huge_pmd() from running until the
1438 * whole __split_huge_page() is complete), we will still see
1439 * the newly established pmd of the child later during the
1440 * walk, to be able to set it as pmd_trans_splitting too.
1441 */
1442 if (mapcount != page_mapcount(page))
1443 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1444 mapcount, page_mapcount(page));
1445 BUG_ON(mapcount != page_mapcount(page));
1446
1447 __split_huge_page_refcount(page);
1448
1449 mapcount2 = 0;
1450 list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1451 struct vm_area_struct *vma = avc->vma;
1452 unsigned long addr = vma_address(page, vma);
1453 BUG_ON(is_vma_temporary_stack(vma));
1454 if (addr == -EFAULT)
1455 continue;
1456 mapcount2 += __split_huge_page_map(page, vma, addr);
1457 }
1458 if (mapcount != mapcount2)
1459 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1460 mapcount, mapcount2, page_mapcount(page));
1461 BUG_ON(mapcount != mapcount2);
1462}
1463
1464int split_huge_page(struct page *page)
1465{
1466 struct anon_vma *anon_vma;
1467 int ret = 1;
1468
1469 BUG_ON(!PageAnon(page));
1470 anon_vma = page_lock_anon_vma(page);
1471 if (!anon_vma)
1472 goto out;
1473 ret = 0;
1474 if (!PageCompound(page))
1475 goto out_unlock;
1476
1477 BUG_ON(!PageSwapBacked(page));
1478 __split_huge_page(page, anon_vma);
1479 count_vm_event(THP_SPLIT);
1480
1481 BUG_ON(PageCompound(page));
1482out_unlock:
1483 page_unlock_anon_vma(anon_vma);
1484out:
1485 return ret;
1486}
1487
1488#define VM_NO_THP (VM_SPECIAL|VM_INSERTPAGE|VM_MIXEDMAP|VM_SAO| \
1489 VM_HUGETLB|VM_SHARED|VM_MAYSHARE)
1490
1491int hugepage_madvise(struct vm_area_struct *vma,
1492 unsigned long *vm_flags, int advice)
1493{
1494 switch (advice) {
1495 case MADV_HUGEPAGE:
1496 /*
1497 * Be somewhat over-protective like KSM for now!
1498 */
1499 if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
1500 return -EINVAL;
1501 *vm_flags &= ~VM_NOHUGEPAGE;
1502 *vm_flags |= VM_HUGEPAGE;
1503 /*
1504 * If the vma become good for khugepaged to scan,
1505 * register it here without waiting a page fault that
1506 * may not happen any time soon.
1507 */
1508 if (unlikely(khugepaged_enter_vma_merge(vma, *vm_flags)))
1509 return -ENOMEM;
1510 break;
1511 case MADV_NOHUGEPAGE:
1512 /*
1513 * Be somewhat over-protective like KSM for now!
1514 */
1515 if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
1516 return -EINVAL;
1517 *vm_flags &= ~VM_HUGEPAGE;
1518 *vm_flags |= VM_NOHUGEPAGE;
1519 /*
1520 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1521 * this vma even if we leave the mm registered in khugepaged if
1522 * it got registered before VM_NOHUGEPAGE was set.
1523 */
1524 break;
1525 }
1526
1527 return 0;
1528}
1529
1530static int __init khugepaged_slab_init(void)
1531{
1532 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1533 sizeof(struct mm_slot),
1534 __alignof__(struct mm_slot), 0, NULL);
1535 if (!mm_slot_cache)
1536 return -ENOMEM;
1537
1538 return 0;
1539}
1540
1541static void __init khugepaged_slab_free(void)
1542{
1543 kmem_cache_destroy(mm_slot_cache);
1544 mm_slot_cache = NULL;
1545}
1546
1547static inline struct mm_slot *alloc_mm_slot(void)
1548{
1549 if (!mm_slot_cache) /* initialization failed */
1550 return NULL;
1551 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1552}
1553
1554static inline void free_mm_slot(struct mm_slot *mm_slot)
1555{
1556 kmem_cache_free(mm_slot_cache, mm_slot);
1557}
1558
1559static int __init mm_slots_hash_init(void)
1560{
1561 mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1562 GFP_KERNEL);
1563 if (!mm_slots_hash)
1564 return -ENOMEM;
1565 return 0;
1566}
1567
1568#if 0
1569static void __init mm_slots_hash_free(void)
1570{
1571 kfree(mm_slots_hash);
1572 mm_slots_hash = NULL;
1573}
1574#endif
1575
1576static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1577{
1578 struct mm_slot *mm_slot;
1579 struct hlist_head *bucket;
1580 struct hlist_node *node;
1581
1582 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1583 % MM_SLOTS_HASH_HEADS];
1584 hlist_for_each_entry(mm_slot, node, bucket, hash) {
1585 if (mm == mm_slot->mm)
1586 return mm_slot;
1587 }
1588 return NULL;
1589}
1590
1591static void insert_to_mm_slots_hash(struct mm_struct *mm,
1592 struct mm_slot *mm_slot)
1593{
1594 struct hlist_head *bucket;
1595
1596 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1597 % MM_SLOTS_HASH_HEADS];
1598 mm_slot->mm = mm;
1599 hlist_add_head(&mm_slot->hash, bucket);
1600}
1601
1602static inline int khugepaged_test_exit(struct mm_struct *mm)
1603{
1604 return atomic_read(&mm->mm_users) == 0;
1605}
1606
1607int __khugepaged_enter(struct mm_struct *mm)
1608{
1609 struct mm_slot *mm_slot;
1610 int wakeup;
1611
1612 mm_slot = alloc_mm_slot();
1613 if (!mm_slot)
1614 return -ENOMEM;
1615
1616 /* __khugepaged_exit() must not run from under us */
1617 VM_BUG_ON(khugepaged_test_exit(mm));
1618 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1619 free_mm_slot(mm_slot);
1620 return 0;
1621 }
1622
1623 spin_lock(&khugepaged_mm_lock);
1624 insert_to_mm_slots_hash(mm, mm_slot);
1625 /*
1626 * Insert just behind the scanning cursor, to let the area settle
1627 * down a little.
1628 */
1629 wakeup = list_empty(&khugepaged_scan.mm_head);
1630 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1631 spin_unlock(&khugepaged_mm_lock);
1632
1633 atomic_inc(&mm->mm_count);
1634 if (wakeup)
1635 wake_up_interruptible(&khugepaged_wait);
1636
1637 return 0;
1638}
1639
1640int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
1641 unsigned long vm_flags)
1642{
1643 unsigned long hstart, hend;
1644 if (!vma->anon_vma)
1645 /*
1646 * Not yet faulted in so we will register later in the
1647 * page fault if needed.
1648 */
1649 return 0;
1650 if (vma->vm_ops)
1651 /* khugepaged not yet working on file or special mappings */
1652 return 0;
1653 /*
1654 * If is_pfn_mapping() is true is_learn_pfn_mapping() must be
1655 * true too, verify it here.
1656 */
1657 VM_BUG_ON(is_linear_pfn_mapping(vma) || vm_flags & VM_NO_THP);
1658 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1659 hend = vma->vm_end & HPAGE_PMD_MASK;
1660 if (hstart < hend)
1661 return khugepaged_enter(vma, vm_flags);
1662 return 0;
1663}
1664
1665void __khugepaged_exit(struct mm_struct *mm)
1666{
1667 struct mm_slot *mm_slot;
1668 int free = 0;
1669
1670 spin_lock(&khugepaged_mm_lock);
1671 mm_slot = get_mm_slot(mm);
1672 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1673 hlist_del(&mm_slot->hash);
1674 list_del(&mm_slot->mm_node);
1675 free = 1;
1676 }
1677 spin_unlock(&khugepaged_mm_lock);
1678
1679 if (free) {
1680 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1681 free_mm_slot(mm_slot);
1682 mmdrop(mm);
1683 } else if (mm_slot) {
1684 /*
1685 * This is required to serialize against
1686 * khugepaged_test_exit() (which is guaranteed to run
1687 * under mmap sem read mode). Stop here (after we
1688 * return all pagetables will be destroyed) until
1689 * khugepaged has finished working on the pagetables
1690 * under the mmap_sem.
1691 */
1692 down_write(&mm->mmap_sem);
1693 up_write(&mm->mmap_sem);
1694 }
1695}
1696
1697static void release_pte_page(struct page *page)
1698{
1699 /* 0 stands for page_is_file_cache(page) == false */
1700 dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1701 unlock_page(page);
1702 putback_lru_page(page);
1703}
1704
1705static void release_pte_pages(pte_t *pte, pte_t *_pte)
1706{
1707 while (--_pte >= pte) {
1708 pte_t pteval = *_pte;
1709 if (!pte_none(pteval))
1710 release_pte_page(pte_page(pteval));
1711 }
1712}
1713
1714static void release_all_pte_pages(pte_t *pte)
1715{
1716 release_pte_pages(pte, pte + HPAGE_PMD_NR);
1717}
1718
1719static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1720 unsigned long address,
1721 pte_t *pte)
1722{
1723 struct page *page;
1724 pte_t *_pte;
1725 int referenced = 0, isolated = 0, none = 0;
1726 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1727 _pte++, address += PAGE_SIZE) {
1728 pte_t pteval = *_pte;
1729 if (pte_none(pteval)) {
1730 if (++none <= khugepaged_max_ptes_none)
1731 continue;
1732 else {
1733 release_pte_pages(pte, _pte);
1734 goto out;
1735 }
1736 }
1737 if (!pte_present(pteval) || !pte_write(pteval)) {
1738 release_pte_pages(pte, _pte);
1739 goto out;
1740 }
1741 page = vm_normal_page(vma, address, pteval);
1742 if (unlikely(!page)) {
1743 release_pte_pages(pte, _pte);
1744 goto out;
1745 }
1746 VM_BUG_ON(PageCompound(page));
1747 BUG_ON(!PageAnon(page));
1748 VM_BUG_ON(!PageSwapBacked(page));
1749
1750 /* cannot use mapcount: can't collapse if there's a gup pin */
1751 if (page_count(page) != 1) {
1752 release_pte_pages(pte, _pte);
1753 goto out;
1754 }
1755 /*
1756 * We can do it before isolate_lru_page because the
1757 * page can't be freed from under us. NOTE: PG_lock
1758 * is needed to serialize against split_huge_page
1759 * when invoked from the VM.
1760 */
1761 if (!trylock_page(page)) {
1762 release_pte_pages(pte, _pte);
1763 goto out;
1764 }
1765 /*
1766 * Isolate the page to avoid collapsing an hugepage
1767 * currently in use by the VM.
1768 */
1769 if (isolate_lru_page(page)) {
1770 unlock_page(page);
1771 release_pte_pages(pte, _pte);
1772 goto out;
1773 }
1774 /* 0 stands for page_is_file_cache(page) == false */
1775 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1776 VM_BUG_ON(!PageLocked(page));
1777 VM_BUG_ON(PageLRU(page));
1778
1779 /* If there is no mapped pte young don't collapse the page */
1780 if (pte_young(pteval) || PageReferenced(page) ||
1781 mmu_notifier_test_young(vma->vm_mm, address))
1782 referenced = 1;
1783 }
1784 if (unlikely(!referenced))
1785 release_all_pte_pages(pte);
1786 else
1787 isolated = 1;
1788out:
1789 return isolated;
1790}
1791
1792static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1793 struct vm_area_struct *vma,
1794 unsigned long address,
1795 spinlock_t *ptl)
1796{
1797 pte_t *_pte;
1798 for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1799 pte_t pteval = *_pte;
1800 struct page *src_page;
1801
1802 if (pte_none(pteval)) {
1803 clear_user_highpage(page, address);
1804 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1805 } else {
1806 src_page = pte_page(pteval);
1807 copy_user_highpage(page, src_page, address, vma);
1808 VM_BUG_ON(page_mapcount(src_page) != 1);
1809 VM_BUG_ON(page_count(src_page) != 2);
1810 release_pte_page(src_page);
1811 /*
1812 * ptl mostly unnecessary, but preempt has to
1813 * be disabled to update the per-cpu stats
1814 * inside page_remove_rmap().
1815 */
1816 spin_lock(ptl);
1817 /*
1818 * paravirt calls inside pte_clear here are
1819 * superfluous.
1820 */
1821 pte_clear(vma->vm_mm, address, _pte);
1822 page_remove_rmap(src_page);
1823 spin_unlock(ptl);
1824 free_page_and_swap_cache(src_page);
1825 }
1826
1827 address += PAGE_SIZE;
1828 page++;
1829 }
1830}
1831
1832static void collapse_huge_page(struct mm_struct *mm,
1833 unsigned long address,
1834 struct page **hpage,
1835 struct vm_area_struct *vma,
1836 int node)
1837{
1838 pgd_t *pgd;
1839 pud_t *pud;
1840 pmd_t *pmd, _pmd;
1841 pte_t *pte;
1842 pgtable_t pgtable;
1843 struct page *new_page;
1844 spinlock_t *ptl;
1845 int isolated;
1846 unsigned long hstart, hend;
1847
1848 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1849#ifndef CONFIG_NUMA
1850 up_read(&mm->mmap_sem);
1851 VM_BUG_ON(!*hpage);
1852 new_page = *hpage;
1853#else
1854 VM_BUG_ON(*hpage);
1855 /*
1856 * Allocate the page while the vma is still valid and under
1857 * the mmap_sem read mode so there is no memory allocation
1858 * later when we take the mmap_sem in write mode. This is more
1859 * friendly behavior (OTOH it may actually hide bugs) to
1860 * filesystems in userland with daemons allocating memory in
1861 * the userland I/O paths. Allocating memory with the
1862 * mmap_sem in read mode is good idea also to allow greater
1863 * scalability.
1864 */
1865 new_page = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
1866 node, __GFP_OTHER_NODE);
1867
1868 /*
1869 * After allocating the hugepage, release the mmap_sem read lock in
1870 * preparation for taking it in write mode.
1871 */
1872 up_read(&mm->mmap_sem);
1873 if (unlikely(!new_page)) {
1874 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1875 *hpage = ERR_PTR(-ENOMEM);
1876 return;
1877 }
1878#endif
1879
1880 count_vm_event(THP_COLLAPSE_ALLOC);
1881 if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
1882#ifdef CONFIG_NUMA
1883 put_page(new_page);
1884#endif
1885 return;
1886 }
1887
1888 /*
1889 * Prevent all access to pagetables with the exception of
1890 * gup_fast later hanlded by the ptep_clear_flush and the VM
1891 * handled by the anon_vma lock + PG_lock.
1892 */
1893 down_write(&mm->mmap_sem);
1894 if (unlikely(khugepaged_test_exit(mm)))
1895 goto out;
1896
1897 vma = find_vma(mm, address);
1898 if (!vma)
1899 goto out;
1900 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1901 hend = vma->vm_end & HPAGE_PMD_MASK;
1902 if (address < hstart || address + HPAGE_PMD_SIZE > hend)
1903 goto out;
1904
1905 if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
1906 (vma->vm_flags & VM_NOHUGEPAGE))
1907 goto out;
1908
1909 if (!vma->anon_vma || vma->vm_ops)
1910 goto out;
1911 if (is_vma_temporary_stack(vma))
1912 goto out;
1913 /*
1914 * If is_pfn_mapping() is true is_learn_pfn_mapping() must be
1915 * true too, verify it here.
1916 */
1917 VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP);
1918
1919 pgd = pgd_offset(mm, address);
1920 if (!pgd_present(*pgd))
1921 goto out;
1922
1923 pud = pud_offset(pgd, address);
1924 if (!pud_present(*pud))
1925 goto out;
1926
1927 pmd = pmd_offset(pud, address);
1928 /* pmd can't go away or become huge under us */
1929 if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
1930 goto out;
1931
1932 anon_vma_lock(vma->anon_vma);
1933
1934 pte = pte_offset_map(pmd, address);
1935 ptl = pte_lockptr(mm, pmd);
1936
1937 spin_lock(&mm->page_table_lock); /* probably unnecessary */
1938 /*
1939 * After this gup_fast can't run anymore. This also removes
1940 * any huge TLB entry from the CPU so we won't allow
1941 * huge and small TLB entries for the same virtual address
1942 * to avoid the risk of CPU bugs in that area.
1943 */
1944 _pmd = pmdp_clear_flush_notify(vma, address, pmd);
1945 spin_unlock(&mm->page_table_lock);
1946
1947 spin_lock(ptl);
1948 isolated = __collapse_huge_page_isolate(vma, address, pte);
1949 spin_unlock(ptl);
1950
1951 if (unlikely(!isolated)) {
1952 pte_unmap(pte);
1953 spin_lock(&mm->page_table_lock);
1954 BUG_ON(!pmd_none(*pmd));
1955 /*
1956 * We can only use set_pmd_at when establishing
1957 * hugepmds and never for establishing regular pmds that
1958 * points to regular pagetables. Use pmd_populate for that
1959 */
1960 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1961 spin_unlock(&mm->page_table_lock);
1962 anon_vma_unlock(vma->anon_vma);
1963 goto out;
1964 }
1965
1966 /*
1967 * All pages are isolated and locked so anon_vma rmap
1968 * can't run anymore.
1969 */
1970 anon_vma_unlock(vma->anon_vma);
1971
1972 __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
1973 pte_unmap(pte);
1974 __SetPageUptodate(new_page);
1975 pgtable = pmd_pgtable(_pmd);
1976 VM_BUG_ON(page_count(pgtable) != 1);
1977 VM_BUG_ON(page_mapcount(pgtable) != 0);
1978
1979 _pmd = mk_pmd(new_page, vma->vm_page_prot);
1980 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1981 _pmd = pmd_mkhuge(_pmd);
1982
1983 /*
1984 * spin_lock() below is not the equivalent of smp_wmb(), so
1985 * this is needed to avoid the copy_huge_page writes to become
1986 * visible after the set_pmd_at() write.
1987 */
1988 smp_wmb();
1989
1990 spin_lock(&mm->page_table_lock);
1991 BUG_ON(!pmd_none(*pmd));
1992 page_add_new_anon_rmap(new_page, vma, address);
1993 set_pmd_at(mm, address, pmd, _pmd);
1994 update_mmu_cache(vma, address, _pmd);
1995 prepare_pmd_huge_pte(pgtable, mm);
1996 spin_unlock(&mm->page_table_lock);
1997
1998#ifndef CONFIG_NUMA
1999 *hpage = NULL;
2000#endif
2001 khugepaged_pages_collapsed++;
2002out_up_write:
2003 up_write(&mm->mmap_sem);
2004 return;
2005
2006out:
2007 mem_cgroup_uncharge_page(new_page);
2008#ifdef CONFIG_NUMA
2009 put_page(new_page);
2010#endif
2011 goto out_up_write;
2012}
2013
2014static int khugepaged_scan_pmd(struct mm_struct *mm,
2015 struct vm_area_struct *vma,
2016 unsigned long address,
2017 struct page **hpage)
2018{
2019 pgd_t *pgd;
2020 pud_t *pud;
2021 pmd_t *pmd;
2022 pte_t *pte, *_pte;
2023 int ret = 0, referenced = 0, none = 0;
2024 struct page *page;
2025 unsigned long _address;
2026 spinlock_t *ptl;
2027 int node = -1;
2028
2029 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2030
2031 pgd = pgd_offset(mm, address);
2032 if (!pgd_present(*pgd))
2033 goto out;
2034
2035 pud = pud_offset(pgd, address);
2036 if (!pud_present(*pud))
2037 goto out;
2038
2039 pmd = pmd_offset(pud, address);
2040 if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
2041 goto out;
2042
2043 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2044 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2045 _pte++, _address += PAGE_SIZE) {
2046 pte_t pteval = *_pte;
2047 if (pte_none(pteval)) {
2048 if (++none <= khugepaged_max_ptes_none)
2049 continue;
2050 else
2051 goto out_unmap;
2052 }
2053 if (!pte_present(pteval) || !pte_write(pteval))
2054 goto out_unmap;
2055 page = vm_normal_page(vma, _address, pteval);
2056 if (unlikely(!page))
2057 goto out_unmap;
2058 /*
2059 * Chose the node of the first page. This could
2060 * be more sophisticated and look at more pages,
2061 * but isn't for now.
2062 */
2063 if (node == -1)
2064 node = page_to_nid(page);
2065 VM_BUG_ON(PageCompound(page));
2066 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2067 goto out_unmap;
2068 /* cannot use mapcount: can't collapse if there's a gup pin */
2069 if (page_count(page) != 1)
2070 goto out_unmap;
2071 if (pte_young(pteval) || PageReferenced(page) ||
2072 mmu_notifier_test_young(vma->vm_mm, address))
2073 referenced = 1;
2074 }
2075 if (referenced)
2076 ret = 1;
2077out_unmap:
2078 pte_unmap_unlock(pte, ptl);
2079 if (ret)
2080 /* collapse_huge_page will return with the mmap_sem released */
2081 collapse_huge_page(mm, address, hpage, vma, node);
2082out:
2083 return ret;
2084}
2085
2086static void collect_mm_slot(struct mm_slot *mm_slot)
2087{
2088 struct mm_struct *mm = mm_slot->mm;
2089
2090 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2091
2092 if (khugepaged_test_exit(mm)) {
2093 /* free mm_slot */
2094 hlist_del(&mm_slot->hash);
2095 list_del(&mm_slot->mm_node);
2096
2097 /*
2098 * Not strictly needed because the mm exited already.
2099 *
2100 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2101 */
2102
2103 /* khugepaged_mm_lock actually not necessary for the below */
2104 free_mm_slot(mm_slot);
2105 mmdrop(mm);
2106 }
2107}
2108
2109static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2110 struct page **hpage)
2111 __releases(&khugepaged_mm_lock)
2112 __acquires(&khugepaged_mm_lock)
2113{
2114 struct mm_slot *mm_slot;
2115 struct mm_struct *mm;
2116 struct vm_area_struct *vma;
2117 int progress = 0;
2118
2119 VM_BUG_ON(!pages);
2120 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2121
2122 if (khugepaged_scan.mm_slot)
2123 mm_slot = khugepaged_scan.mm_slot;
2124 else {
2125 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2126 struct mm_slot, mm_node);
2127 khugepaged_scan.address = 0;
2128 khugepaged_scan.mm_slot = mm_slot;
2129 }
2130 spin_unlock(&khugepaged_mm_lock);
2131
2132 mm = mm_slot->mm;
2133 down_read(&mm->mmap_sem);
2134 if (unlikely(khugepaged_test_exit(mm)))
2135 vma = NULL;
2136 else
2137 vma = find_vma(mm, khugepaged_scan.address);
2138
2139 progress++;
2140 for (; vma; vma = vma->vm_next) {
2141 unsigned long hstart, hend;
2142
2143 cond_resched();
2144 if (unlikely(khugepaged_test_exit(mm))) {
2145 progress++;
2146 break;
2147 }
2148
2149 if ((!(vma->vm_flags & VM_HUGEPAGE) &&
2150 !khugepaged_always()) ||
2151 (vma->vm_flags & VM_NOHUGEPAGE)) {
2152 skip:
2153 progress++;
2154 continue;
2155 }
2156 if (!vma->anon_vma || vma->vm_ops)
2157 goto skip;
2158 if (is_vma_temporary_stack(vma))
2159 goto skip;
2160 /*
2161 * If is_pfn_mapping() is true is_learn_pfn_mapping()
2162 * must be true too, verify it here.
2163 */
2164 VM_BUG_ON(is_linear_pfn_mapping(vma) ||
2165 vma->vm_flags & VM_NO_THP);
2166
2167 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2168 hend = vma->vm_end & HPAGE_PMD_MASK;
2169 if (hstart >= hend)
2170 goto skip;
2171 if (khugepaged_scan.address > hend)
2172 goto skip;
2173 if (khugepaged_scan.address < hstart)
2174 khugepaged_scan.address = hstart;
2175 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2176
2177 while (khugepaged_scan.address < hend) {
2178 int ret;
2179 cond_resched();
2180 if (unlikely(khugepaged_test_exit(mm)))
2181 goto breakouterloop;
2182
2183 VM_BUG_ON(khugepaged_scan.address < hstart ||
2184 khugepaged_scan.address + HPAGE_PMD_SIZE >
2185 hend);
2186 ret = khugepaged_scan_pmd(mm, vma,
2187 khugepaged_scan.address,
2188 hpage);
2189 /* move to next address */
2190 khugepaged_scan.address += HPAGE_PMD_SIZE;
2191 progress += HPAGE_PMD_NR;
2192 if (ret)
2193 /* we released mmap_sem so break loop */
2194 goto breakouterloop_mmap_sem;
2195 if (progress >= pages)
2196 goto breakouterloop;
2197 }
2198 }
2199breakouterloop:
2200 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2201breakouterloop_mmap_sem:
2202
2203 spin_lock(&khugepaged_mm_lock);
2204 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2205 /*
2206 * Release the current mm_slot if this mm is about to die, or
2207 * if we scanned all vmas of this mm.
2208 */
2209 if (khugepaged_test_exit(mm) || !vma) {
2210 /*
2211 * Make sure that if mm_users is reaching zero while
2212 * khugepaged runs here, khugepaged_exit will find
2213 * mm_slot not pointing to the exiting mm.
2214 */
2215 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2216 khugepaged_scan.mm_slot = list_entry(
2217 mm_slot->mm_node.next,
2218 struct mm_slot, mm_node);
2219 khugepaged_scan.address = 0;
2220 } else {
2221 khugepaged_scan.mm_slot = NULL;
2222 khugepaged_full_scans++;
2223 }
2224
2225 collect_mm_slot(mm_slot);
2226 }
2227
2228 return progress;
2229}
2230
2231static int khugepaged_has_work(void)
2232{
2233 return !list_empty(&khugepaged_scan.mm_head) &&
2234 khugepaged_enabled();
2235}
2236
2237static int khugepaged_wait_event(void)
2238{
2239 return !list_empty(&khugepaged_scan.mm_head) ||
2240 !khugepaged_enabled();
2241}
2242
2243static void khugepaged_do_scan(struct page **hpage)
2244{
2245 unsigned int progress = 0, pass_through_head = 0;
2246 unsigned int pages = khugepaged_pages_to_scan;
2247
2248 barrier(); /* write khugepaged_pages_to_scan to local stack */
2249
2250 while (progress < pages) {
2251 cond_resched();
2252
2253#ifndef CONFIG_NUMA
2254 if (!*hpage) {
2255 *hpage = alloc_hugepage(khugepaged_defrag());
2256 if (unlikely(!*hpage)) {
2257 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2258 break;
2259 }
2260 count_vm_event(THP_COLLAPSE_ALLOC);
2261 }
2262#else
2263 if (IS_ERR(*hpage))
2264 break;
2265#endif
2266
2267 if (unlikely(kthread_should_stop() || freezing(current)))
2268 break;
2269
2270 spin_lock(&khugepaged_mm_lock);
2271 if (!khugepaged_scan.mm_slot)
2272 pass_through_head++;
2273 if (khugepaged_has_work() &&
2274 pass_through_head < 2)
2275 progress += khugepaged_scan_mm_slot(pages - progress,
2276 hpage);
2277 else
2278 progress = pages;
2279 spin_unlock(&khugepaged_mm_lock);
2280 }
2281}
2282
2283static void khugepaged_alloc_sleep(void)
2284{
2285 wait_event_freezable_timeout(khugepaged_wait, false,
2286 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
2287}
2288
2289#ifndef CONFIG_NUMA
2290static struct page *khugepaged_alloc_hugepage(void)
2291{
2292 struct page *hpage;
2293
2294 do {
2295 hpage = alloc_hugepage(khugepaged_defrag());
2296 if (!hpage) {
2297 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2298 khugepaged_alloc_sleep();
2299 } else
2300 count_vm_event(THP_COLLAPSE_ALLOC);
2301 } while (unlikely(!hpage) &&
2302 likely(khugepaged_enabled()));
2303 return hpage;
2304}
2305#endif
2306
2307static void khugepaged_loop(void)
2308{
2309 struct page *hpage;
2310
2311#ifdef CONFIG_NUMA
2312 hpage = NULL;
2313#endif
2314 while (likely(khugepaged_enabled())) {
2315#ifndef CONFIG_NUMA
2316 hpage = khugepaged_alloc_hugepage();
2317 if (unlikely(!hpage))
2318 break;
2319#else
2320 if (IS_ERR(hpage)) {
2321 khugepaged_alloc_sleep();
2322 hpage = NULL;
2323 }
2324#endif
2325
2326 khugepaged_do_scan(&hpage);
2327#ifndef CONFIG_NUMA
2328 if (hpage)
2329 put_page(hpage);
2330#endif
2331 try_to_freeze();
2332 if (unlikely(kthread_should_stop()))
2333 break;
2334 if (khugepaged_has_work()) {
2335 if (!khugepaged_scan_sleep_millisecs)
2336 continue;
2337 wait_event_freezable_timeout(khugepaged_wait, false,
2338 msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2339 } else if (khugepaged_enabled())
2340 wait_event_freezable(khugepaged_wait,
2341 khugepaged_wait_event());
2342 }
2343}
2344
2345static int khugepaged(void *none)
2346{
2347 struct mm_slot *mm_slot;
2348
2349 set_freezable();
2350 set_user_nice(current, 19);
2351
2352 /* serialize with start_khugepaged() */
2353 mutex_lock(&khugepaged_mutex);
2354
2355 for (;;) {
2356 mutex_unlock(&khugepaged_mutex);
2357 VM_BUG_ON(khugepaged_thread != current);
2358 khugepaged_loop();
2359 VM_BUG_ON(khugepaged_thread != current);
2360
2361 mutex_lock(&khugepaged_mutex);
2362 if (!khugepaged_enabled())
2363 break;
2364 if (unlikely(kthread_should_stop()))
2365 break;
2366 }
2367
2368 spin_lock(&khugepaged_mm_lock);
2369 mm_slot = khugepaged_scan.mm_slot;
2370 khugepaged_scan.mm_slot = NULL;
2371 if (mm_slot)
2372 collect_mm_slot(mm_slot);
2373 spin_unlock(&khugepaged_mm_lock);
2374
2375 khugepaged_thread = NULL;
2376 mutex_unlock(&khugepaged_mutex);
2377
2378 return 0;
2379}
2380
2381void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2382{
2383 struct page *page;
2384
2385 spin_lock(&mm->page_table_lock);
2386 if (unlikely(!pmd_trans_huge(*pmd))) {
2387 spin_unlock(&mm->page_table_lock);
2388 return;
2389 }
2390 page = pmd_page(*pmd);
2391 VM_BUG_ON(!page_count(page));
2392 get_page(page);
2393 spin_unlock(&mm->page_table_lock);
2394
2395 split_huge_page(page);
2396
2397 put_page(page);
2398 BUG_ON(pmd_trans_huge(*pmd));
2399}
2400
2401static void split_huge_page_address(struct mm_struct *mm,
2402 unsigned long address)
2403{
2404 pgd_t *pgd;
2405 pud_t *pud;
2406 pmd_t *pmd;
2407
2408 VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
2409
2410 pgd = pgd_offset(mm, address);
2411 if (!pgd_present(*pgd))
2412 return;
2413
2414 pud = pud_offset(pgd, address);
2415 if (!pud_present(*pud))
2416 return;
2417
2418 pmd = pmd_offset(pud, address);
2419 if (!pmd_present(*pmd))
2420 return;
2421 /*
2422 * Caller holds the mmap_sem write mode, so a huge pmd cannot
2423 * materialize from under us.
2424 */
2425 split_huge_page_pmd(mm, pmd);
2426}
2427
2428void __vma_adjust_trans_huge(struct vm_area_struct *vma,
2429 unsigned long start,
2430 unsigned long end,
2431 long adjust_next)
2432{
2433 /*
2434 * If the new start address isn't hpage aligned and it could
2435 * previously contain an hugepage: check if we need to split
2436 * an huge pmd.
2437 */
2438 if (start & ~HPAGE_PMD_MASK &&
2439 (start & HPAGE_PMD_MASK) >= vma->vm_start &&
2440 (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2441 split_huge_page_address(vma->vm_mm, start);
2442
2443 /*
2444 * If the new end address isn't hpage aligned and it could
2445 * previously contain an hugepage: check if we need to split
2446 * an huge pmd.
2447 */
2448 if (end & ~HPAGE_PMD_MASK &&
2449 (end & HPAGE_PMD_MASK) >= vma->vm_start &&
2450 (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2451 split_huge_page_address(vma->vm_mm, end);
2452
2453 /*
2454 * If we're also updating the vma->vm_next->vm_start, if the new
2455 * vm_next->vm_start isn't page aligned and it could previously
2456 * contain an hugepage: check if we need to split an huge pmd.
2457 */
2458 if (adjust_next > 0) {
2459 struct vm_area_struct *next = vma->vm_next;
2460 unsigned long nstart = next->vm_start;
2461 nstart += adjust_next << PAGE_SHIFT;
2462 if (nstart & ~HPAGE_PMD_MASK &&
2463 (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
2464 (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
2465 split_huge_page_address(next->vm_mm, nstart);
2466 }
2467}