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