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