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