mm: numa: Add fault driven placement and migration
[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 static inline 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 = NULL;
1027         unsigned long haddr = addr & HPAGE_PMD_MASK;
1028         int target_nid;
1029
1030         spin_lock(&mm->page_table_lock);
1031         if (unlikely(!pmd_same(pmd, *pmdp)))
1032                 goto out_unlock;
1033
1034         page = pmd_page(pmd);
1035         get_page(page);
1036         spin_unlock(&mm->page_table_lock);
1037
1038         target_nid = mpol_misplaced(page, vma, haddr);
1039         if (target_nid == -1)
1040                 goto clear_pmdnuma;
1041
1042         /*
1043          * Due to lacking code to migrate thp pages, we'll split
1044          * (which preserves the special PROT_NONE) and re-take the
1045          * fault on the normal pages.
1046          */
1047         split_huge_page(page);
1048         put_page(page);
1049
1050         return 0;
1051
1052 clear_pmdnuma:
1053         spin_lock(&mm->page_table_lock);
1054         if (unlikely(!pmd_same(pmd, *pmdp)))
1055                 goto out_unlock;
1056
1057         pmd = pmd_mknonnuma(pmd);
1058         set_pmd_at(mm, haddr, pmdp, pmd);
1059         VM_BUG_ON(pmd_numa(*pmdp));
1060         update_mmu_cache_pmd(vma, addr, pmdp);
1061
1062 out_unlock:
1063         spin_unlock(&mm->page_table_lock);
1064         if (page) {
1065                 put_page(page);
1066                 task_numa_fault(numa_node_id(), HPAGE_PMD_NR);
1067         }
1068         return 0;
1069 }
1070
1071 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1072                  pmd_t *pmd, unsigned long addr)
1073 {
1074         int ret = 0;
1075
1076         if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1077                 struct page *page;
1078                 pgtable_t pgtable;
1079                 pmd_t orig_pmd;
1080                 pgtable = pgtable_trans_huge_withdraw(tlb->mm);
1081                 orig_pmd = pmdp_get_and_clear(tlb->mm, addr, pmd);
1082                 page = pmd_page(orig_pmd);
1083                 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1084                 page_remove_rmap(page);
1085                 VM_BUG_ON(page_mapcount(page) < 0);
1086                 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1087                 VM_BUG_ON(!PageHead(page));
1088                 tlb->mm->nr_ptes--;
1089                 spin_unlock(&tlb->mm->page_table_lock);
1090                 tlb_remove_page(tlb, page);
1091                 pte_free(tlb->mm, pgtable);
1092                 ret = 1;
1093         }
1094         return ret;
1095 }
1096
1097 int mincore_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1098                 unsigned long addr, unsigned long end,
1099                 unsigned char *vec)
1100 {
1101         int ret = 0;
1102
1103         if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1104                 /*
1105                  * All logical pages in the range are present
1106                  * if backed by a huge page.
1107                  */
1108                 spin_unlock(&vma->vm_mm->page_table_lock);
1109                 memset(vec, 1, (end - addr) >> PAGE_SHIFT);
1110                 ret = 1;
1111         }
1112
1113         return ret;
1114 }
1115
1116 int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1117                   unsigned long old_addr,
1118                   unsigned long new_addr, unsigned long old_end,
1119                   pmd_t *old_pmd, pmd_t *new_pmd)
1120 {
1121         int ret = 0;
1122         pmd_t pmd;
1123
1124         struct mm_struct *mm = vma->vm_mm;
1125
1126         if ((old_addr & ~HPAGE_PMD_MASK) ||
1127             (new_addr & ~HPAGE_PMD_MASK) ||
1128             old_end - old_addr < HPAGE_PMD_SIZE ||
1129             (new_vma->vm_flags & VM_NOHUGEPAGE))
1130                 goto out;
1131
1132         /*
1133          * The destination pmd shouldn't be established, free_pgtables()
1134          * should have release it.
1135          */
1136         if (WARN_ON(!pmd_none(*new_pmd))) {
1137                 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1138                 goto out;
1139         }
1140
1141         ret = __pmd_trans_huge_lock(old_pmd, vma);
1142         if (ret == 1) {
1143                 pmd = pmdp_get_and_clear(mm, old_addr, old_pmd);
1144                 VM_BUG_ON(!pmd_none(*new_pmd));
1145                 set_pmd_at(mm, new_addr, new_pmd, pmd);
1146                 spin_unlock(&mm->page_table_lock);
1147         }
1148 out:
1149         return ret;
1150 }
1151
1152 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1153                 unsigned long addr, pgprot_t newprot, int prot_numa)
1154 {
1155         struct mm_struct *mm = vma->vm_mm;
1156         int ret = 0;
1157
1158         if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1159                 pmd_t entry;
1160                 entry = pmdp_get_and_clear(mm, addr, pmd);
1161                 if (!prot_numa)
1162                         entry = pmd_modify(entry, newprot);
1163                 else {
1164                         struct page *page = pmd_page(*pmd);
1165
1166                         /* only check non-shared pages */
1167                         if (page_mapcount(page) == 1 &&
1168                             !pmd_numa(*pmd)) {
1169                                 entry = pmd_mknuma(entry);
1170                         }
1171                 }
1172                 set_pmd_at(mm, addr, pmd, entry);
1173                 spin_unlock(&vma->vm_mm->page_table_lock);
1174                 ret = 1;
1175         }
1176
1177         return ret;
1178 }
1179
1180 /*
1181  * Returns 1 if a given pmd maps a stable (not under splitting) thp.
1182  * Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
1183  *
1184  * Note that if it returns 1, this routine returns without unlocking page
1185  * table locks. So callers must unlock them.
1186  */
1187 int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1188 {
1189         spin_lock(&vma->vm_mm->page_table_lock);
1190         if (likely(pmd_trans_huge(*pmd))) {
1191                 if (unlikely(pmd_trans_splitting(*pmd))) {
1192                         spin_unlock(&vma->vm_mm->page_table_lock);
1193                         wait_split_huge_page(vma->anon_vma, pmd);
1194                         return -1;
1195                 } else {
1196                         /* Thp mapped by 'pmd' is stable, so we can
1197                          * handle it as it is. */
1198                         return 1;
1199                 }
1200         }
1201         spin_unlock(&vma->vm_mm->page_table_lock);
1202         return 0;
1203 }
1204
1205 pmd_t *page_check_address_pmd(struct page *page,
1206                               struct mm_struct *mm,
1207                               unsigned long address,
1208                               enum page_check_address_pmd_flag flag)
1209 {
1210         pgd_t *pgd;
1211         pud_t *pud;
1212         pmd_t *pmd, *ret = NULL;
1213
1214         if (address & ~HPAGE_PMD_MASK)
1215                 goto out;
1216
1217         pgd = pgd_offset(mm, address);
1218         if (!pgd_present(*pgd))
1219                 goto out;
1220
1221         pud = pud_offset(pgd, address);
1222         if (!pud_present(*pud))
1223                 goto out;
1224
1225         pmd = pmd_offset(pud, address);
1226         if (pmd_none(*pmd))
1227                 goto out;
1228         if (pmd_page(*pmd) != page)
1229                 goto out;
1230         /*
1231          * split_vma() may create temporary aliased mappings. There is
1232          * no risk as long as all huge pmd are found and have their
1233          * splitting bit set before __split_huge_page_refcount
1234          * runs. Finding the same huge pmd more than once during the
1235          * same rmap walk is not a problem.
1236          */
1237         if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1238             pmd_trans_splitting(*pmd))
1239                 goto out;
1240         if (pmd_trans_huge(*pmd)) {
1241                 VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1242                           !pmd_trans_splitting(*pmd));
1243                 ret = pmd;
1244         }
1245 out:
1246         return ret;
1247 }
1248
1249 static int __split_huge_page_splitting(struct page *page,
1250                                        struct vm_area_struct *vma,
1251                                        unsigned long address)
1252 {
1253         struct mm_struct *mm = vma->vm_mm;
1254         pmd_t *pmd;
1255         int ret = 0;
1256         /* For mmu_notifiers */
1257         const unsigned long mmun_start = address;
1258         const unsigned long mmun_end   = address + HPAGE_PMD_SIZE;
1259
1260         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1261         spin_lock(&mm->page_table_lock);
1262         pmd = page_check_address_pmd(page, mm, address,
1263                                      PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
1264         if (pmd) {
1265                 /*
1266                  * We can't temporarily set the pmd to null in order
1267                  * to split it, the pmd must remain marked huge at all
1268                  * times or the VM won't take the pmd_trans_huge paths
1269                  * and it won't wait on the anon_vma->root->mutex to
1270                  * serialize against split_huge_page*.
1271                  */
1272                 pmdp_splitting_flush(vma, address, pmd);
1273                 ret = 1;
1274         }
1275         spin_unlock(&mm->page_table_lock);
1276         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1277
1278         return ret;
1279 }
1280
1281 static void __split_huge_page_refcount(struct page *page)
1282 {
1283         int i;
1284         struct zone *zone = page_zone(page);
1285         struct lruvec *lruvec;
1286         int tail_count = 0;
1287
1288         /* prevent PageLRU to go away from under us, and freeze lru stats */
1289         spin_lock_irq(&zone->lru_lock);
1290         lruvec = mem_cgroup_page_lruvec(page, zone);
1291
1292         compound_lock(page);
1293         /* complete memcg works before add pages to LRU */
1294         mem_cgroup_split_huge_fixup(page);
1295
1296         for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
1297                 struct page *page_tail = page + i;
1298
1299                 /* tail_page->_mapcount cannot change */
1300                 BUG_ON(page_mapcount(page_tail) < 0);
1301                 tail_count += page_mapcount(page_tail);
1302                 /* check for overflow */
1303                 BUG_ON(tail_count < 0);
1304                 BUG_ON(atomic_read(&page_tail->_count) != 0);
1305                 /*
1306                  * tail_page->_count is zero and not changing from
1307                  * under us. But get_page_unless_zero() may be running
1308                  * from under us on the tail_page. If we used
1309                  * atomic_set() below instead of atomic_add(), we
1310                  * would then run atomic_set() concurrently with
1311                  * get_page_unless_zero(), and atomic_set() is
1312                  * implemented in C not using locked ops. spin_unlock
1313                  * on x86 sometime uses locked ops because of PPro
1314                  * errata 66, 92, so unless somebody can guarantee
1315                  * atomic_set() here would be safe on all archs (and
1316                  * not only on x86), it's safer to use atomic_add().
1317                  */
1318                 atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1319                            &page_tail->_count);
1320
1321                 /* after clearing PageTail the gup refcount can be released */
1322                 smp_mb();
1323
1324                 /*
1325                  * retain hwpoison flag of the poisoned tail page:
1326                  *   fix for the unsuitable process killed on Guest Machine(KVM)
1327                  *   by the memory-failure.
1328                  */
1329                 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP | __PG_HWPOISON;
1330                 page_tail->flags |= (page->flags &
1331                                      ((1L << PG_referenced) |
1332                                       (1L << PG_swapbacked) |
1333                                       (1L << PG_mlocked) |
1334                                       (1L << PG_uptodate)));
1335                 page_tail->flags |= (1L << PG_dirty);
1336
1337                 /* clear PageTail before overwriting first_page */
1338                 smp_wmb();
1339
1340                 /*
1341                  * __split_huge_page_splitting() already set the
1342                  * splitting bit in all pmd that could map this
1343                  * hugepage, that will ensure no CPU can alter the
1344                  * mapcount on the head page. The mapcount is only
1345                  * accounted in the head page and it has to be
1346                  * transferred to all tail pages in the below code. So
1347                  * for this code to be safe, the split the mapcount
1348                  * can't change. But that doesn't mean userland can't
1349                  * keep changing and reading the page contents while
1350                  * we transfer the mapcount, so the pmd splitting
1351                  * status is achieved setting a reserved bit in the
1352                  * pmd, not by clearing the present bit.
1353                 */
1354                 page_tail->_mapcount = page->_mapcount;
1355
1356                 BUG_ON(page_tail->mapping);
1357                 page_tail->mapping = page->mapping;
1358
1359                 page_tail->index = page->index + i;
1360
1361                 BUG_ON(!PageAnon(page_tail));
1362                 BUG_ON(!PageUptodate(page_tail));
1363                 BUG_ON(!PageDirty(page_tail));
1364                 BUG_ON(!PageSwapBacked(page_tail));
1365
1366                 lru_add_page_tail(page, page_tail, lruvec);
1367         }
1368         atomic_sub(tail_count, &page->_count);
1369         BUG_ON(atomic_read(&page->_count) <= 0);
1370
1371         __mod_zone_page_state(zone, NR_ANON_TRANSPARENT_HUGEPAGES, -1);
1372         __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1373
1374         ClearPageCompound(page);
1375         compound_unlock(page);
1376         spin_unlock_irq(&zone->lru_lock);
1377
1378         for (i = 1; i < HPAGE_PMD_NR; i++) {
1379                 struct page *page_tail = page + i;
1380                 BUG_ON(page_count(page_tail) <= 0);
1381                 /*
1382                  * Tail pages may be freed if there wasn't any mapping
1383                  * like if add_to_swap() is running on a lru page that
1384                  * had its mapping zapped. And freeing these pages
1385                  * requires taking the lru_lock so we do the put_page
1386                  * of the tail pages after the split is complete.
1387                  */
1388                 put_page(page_tail);
1389         }
1390
1391         /*
1392          * Only the head page (now become a regular page) is required
1393          * to be pinned by the caller.
1394          */
1395         BUG_ON(page_count(page) <= 0);
1396 }
1397
1398 static int __split_huge_page_map(struct page *page,
1399                                  struct vm_area_struct *vma,
1400                                  unsigned long address)
1401 {
1402         struct mm_struct *mm = vma->vm_mm;
1403         pmd_t *pmd, _pmd;
1404         int ret = 0, i;
1405         pgtable_t pgtable;
1406         unsigned long haddr;
1407
1408         spin_lock(&mm->page_table_lock);
1409         pmd = page_check_address_pmd(page, mm, address,
1410                                      PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1411         if (pmd) {
1412                 pgtable = pgtable_trans_huge_withdraw(mm);
1413                 pmd_populate(mm, &_pmd, pgtable);
1414
1415                 haddr = address;
1416                 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1417                         pte_t *pte, entry;
1418                         BUG_ON(PageCompound(page+i));
1419                         entry = mk_pte(page + i, vma->vm_page_prot);
1420                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1421                         if (!pmd_write(*pmd))
1422                                 entry = pte_wrprotect(entry);
1423                         else
1424                                 BUG_ON(page_mapcount(page) != 1);
1425                         if (!pmd_young(*pmd))
1426                                 entry = pte_mkold(entry);
1427                         if (pmd_numa(*pmd))
1428                                 entry = pte_mknuma(entry);
1429                         pte = pte_offset_map(&_pmd, haddr);
1430                         BUG_ON(!pte_none(*pte));
1431                         set_pte_at(mm, haddr, pte, entry);
1432                         pte_unmap(pte);
1433                 }
1434
1435                 smp_wmb(); /* make pte visible before pmd */
1436                 /*
1437                  * Up to this point the pmd is present and huge and
1438                  * userland has the whole access to the hugepage
1439                  * during the split (which happens in place). If we
1440                  * overwrite the pmd with the not-huge version
1441                  * pointing to the pte here (which of course we could
1442                  * if all CPUs were bug free), userland could trigger
1443                  * a small page size TLB miss on the small sized TLB
1444                  * while the hugepage TLB entry is still established
1445                  * in the huge TLB. Some CPU doesn't like that. See
1446                  * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1447                  * Erratum 383 on page 93. Intel should be safe but is
1448                  * also warns that it's only safe if the permission
1449                  * and cache attributes of the two entries loaded in
1450                  * the two TLB is identical (which should be the case
1451                  * here). But it is generally safer to never allow
1452                  * small and huge TLB entries for the same virtual
1453                  * address to be loaded simultaneously. So instead of
1454                  * doing "pmd_populate(); flush_tlb_range();" we first
1455                  * mark the current pmd notpresent (atomically because
1456                  * here the pmd_trans_huge and pmd_trans_splitting
1457                  * must remain set at all times on the pmd until the
1458                  * split is complete for this pmd), then we flush the
1459                  * SMP TLB and finally we write the non-huge version
1460                  * of the pmd entry with pmd_populate.
1461                  */
1462                 pmdp_invalidate(vma, address, pmd);
1463                 pmd_populate(mm, pmd, pgtable);
1464                 ret = 1;
1465         }
1466         spin_unlock(&mm->page_table_lock);
1467
1468         return ret;
1469 }
1470
1471 /* must be called with anon_vma->root->mutex hold */
1472 static void __split_huge_page(struct page *page,
1473                               struct anon_vma *anon_vma)
1474 {
1475         int mapcount, mapcount2;
1476         pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
1477         struct anon_vma_chain *avc;
1478
1479         BUG_ON(!PageHead(page));
1480         BUG_ON(PageTail(page));
1481
1482         mapcount = 0;
1483         anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1484                 struct vm_area_struct *vma = avc->vma;
1485                 unsigned long addr = vma_address(page, vma);
1486                 BUG_ON(is_vma_temporary_stack(vma));
1487                 mapcount += __split_huge_page_splitting(page, vma, addr);
1488         }
1489         /*
1490          * It is critical that new vmas are added to the tail of the
1491          * anon_vma list. This guarantes that if copy_huge_pmd() runs
1492          * and establishes a child pmd before
1493          * __split_huge_page_splitting() freezes the parent pmd (so if
1494          * we fail to prevent copy_huge_pmd() from running until the
1495          * whole __split_huge_page() is complete), we will still see
1496          * the newly established pmd of the child later during the
1497          * walk, to be able to set it as pmd_trans_splitting too.
1498          */
1499         if (mapcount != page_mapcount(page))
1500                 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1501                        mapcount, page_mapcount(page));
1502         BUG_ON(mapcount != page_mapcount(page));
1503
1504         __split_huge_page_refcount(page);
1505
1506         mapcount2 = 0;
1507         anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1508                 struct vm_area_struct *vma = avc->vma;
1509                 unsigned long addr = vma_address(page, vma);
1510                 BUG_ON(is_vma_temporary_stack(vma));
1511                 mapcount2 += __split_huge_page_map(page, vma, addr);
1512         }
1513         if (mapcount != mapcount2)
1514                 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1515                        mapcount, mapcount2, page_mapcount(page));
1516         BUG_ON(mapcount != mapcount2);
1517 }
1518
1519 int split_huge_page(struct page *page)
1520 {
1521         struct anon_vma *anon_vma;
1522         int ret = 1;
1523
1524         BUG_ON(!PageAnon(page));
1525         anon_vma = page_lock_anon_vma(page);
1526         if (!anon_vma)
1527                 goto out;
1528         ret = 0;
1529         if (!PageCompound(page))
1530                 goto out_unlock;
1531
1532         BUG_ON(!PageSwapBacked(page));
1533         __split_huge_page(page, anon_vma);
1534         count_vm_event(THP_SPLIT);
1535
1536         BUG_ON(PageCompound(page));
1537 out_unlock:
1538         page_unlock_anon_vma(anon_vma);
1539 out:
1540         return ret;
1541 }
1542
1543 #define VM_NO_THP (VM_SPECIAL|VM_MIXEDMAP|VM_HUGETLB|VM_SHARED|VM_MAYSHARE)
1544
1545 int hugepage_madvise(struct vm_area_struct *vma,
1546                      unsigned long *vm_flags, int advice)
1547 {
1548         struct mm_struct *mm = vma->vm_mm;
1549
1550         switch (advice) {
1551         case MADV_HUGEPAGE:
1552                 /*
1553                  * Be somewhat over-protective like KSM for now!
1554                  */
1555                 if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
1556                         return -EINVAL;
1557                 if (mm->def_flags & VM_NOHUGEPAGE)
1558                         return -EINVAL;
1559                 *vm_flags &= ~VM_NOHUGEPAGE;
1560                 *vm_flags |= VM_HUGEPAGE;
1561                 /*
1562                  * If the vma become good for khugepaged to scan,
1563                  * register it here without waiting a page fault that
1564                  * may not happen any time soon.
1565                  */
1566                 if (unlikely(khugepaged_enter_vma_merge(vma)))
1567                         return -ENOMEM;
1568                 break;
1569         case MADV_NOHUGEPAGE:
1570                 /*
1571                  * Be somewhat over-protective like KSM for now!
1572                  */
1573                 if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
1574                         return -EINVAL;
1575                 *vm_flags &= ~VM_HUGEPAGE;
1576                 *vm_flags |= VM_NOHUGEPAGE;
1577                 /*
1578                  * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1579                  * this vma even if we leave the mm registered in khugepaged if
1580                  * it got registered before VM_NOHUGEPAGE was set.
1581                  */
1582                 break;
1583         }
1584
1585         return 0;
1586 }
1587
1588 static int __init khugepaged_slab_init(void)
1589 {
1590         mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1591                                           sizeof(struct mm_slot),
1592                                           __alignof__(struct mm_slot), 0, NULL);
1593         if (!mm_slot_cache)
1594                 return -ENOMEM;
1595
1596         return 0;
1597 }
1598
1599 static void __init khugepaged_slab_free(void)
1600 {
1601         kmem_cache_destroy(mm_slot_cache);
1602         mm_slot_cache = NULL;
1603 }
1604
1605 static inline struct mm_slot *alloc_mm_slot(void)
1606 {
1607         if (!mm_slot_cache)     /* initialization failed */
1608                 return NULL;
1609         return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1610 }
1611
1612 static inline void free_mm_slot(struct mm_slot *mm_slot)
1613 {
1614         kmem_cache_free(mm_slot_cache, mm_slot);
1615 }
1616
1617 static int __init mm_slots_hash_init(void)
1618 {
1619         mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1620                                 GFP_KERNEL);
1621         if (!mm_slots_hash)
1622                 return -ENOMEM;
1623         return 0;
1624 }
1625
1626 #if 0
1627 static void __init mm_slots_hash_free(void)
1628 {
1629         kfree(mm_slots_hash);
1630         mm_slots_hash = NULL;
1631 }
1632 #endif
1633
1634 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1635 {
1636         struct mm_slot *mm_slot;
1637         struct hlist_head *bucket;
1638         struct hlist_node *node;
1639
1640         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1641                                 % MM_SLOTS_HASH_HEADS];
1642         hlist_for_each_entry(mm_slot, node, bucket, hash) {
1643                 if (mm == mm_slot->mm)
1644                         return mm_slot;
1645         }
1646         return NULL;
1647 }
1648
1649 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1650                                     struct mm_slot *mm_slot)
1651 {
1652         struct hlist_head *bucket;
1653
1654         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1655                                 % MM_SLOTS_HASH_HEADS];
1656         mm_slot->mm = mm;
1657         hlist_add_head(&mm_slot->hash, bucket);
1658 }
1659
1660 static inline int khugepaged_test_exit(struct mm_struct *mm)
1661 {
1662         return atomic_read(&mm->mm_users) == 0;
1663 }
1664
1665 int __khugepaged_enter(struct mm_struct *mm)
1666 {
1667         struct mm_slot *mm_slot;
1668         int wakeup;
1669
1670         mm_slot = alloc_mm_slot();
1671         if (!mm_slot)
1672                 return -ENOMEM;
1673
1674         /* __khugepaged_exit() must not run from under us */
1675         VM_BUG_ON(khugepaged_test_exit(mm));
1676         if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1677                 free_mm_slot(mm_slot);
1678                 return 0;
1679         }
1680
1681         spin_lock(&khugepaged_mm_lock);
1682         insert_to_mm_slots_hash(mm, mm_slot);
1683         /*
1684          * Insert just behind the scanning cursor, to let the area settle
1685          * down a little.
1686          */
1687         wakeup = list_empty(&khugepaged_scan.mm_head);
1688         list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1689         spin_unlock(&khugepaged_mm_lock);
1690
1691         atomic_inc(&mm->mm_count);
1692         if (wakeup)
1693                 wake_up_interruptible(&khugepaged_wait);
1694
1695         return 0;
1696 }
1697
1698 int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
1699 {
1700         unsigned long hstart, hend;
1701         if (!vma->anon_vma)
1702                 /*
1703                  * Not yet faulted in so we will register later in the
1704                  * page fault if needed.
1705                  */
1706                 return 0;
1707         if (vma->vm_ops)
1708                 /* khugepaged not yet working on file or special mappings */
1709                 return 0;
1710         VM_BUG_ON(vma->vm_flags & VM_NO_THP);
1711         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1712         hend = vma->vm_end & HPAGE_PMD_MASK;
1713         if (hstart < hend)
1714                 return khugepaged_enter(vma);
1715         return 0;
1716 }
1717
1718 void __khugepaged_exit(struct mm_struct *mm)
1719 {
1720         struct mm_slot *mm_slot;
1721         int free = 0;
1722
1723         spin_lock(&khugepaged_mm_lock);
1724         mm_slot = get_mm_slot(mm);
1725         if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1726                 hlist_del(&mm_slot->hash);
1727                 list_del(&mm_slot->mm_node);
1728                 free = 1;
1729         }
1730         spin_unlock(&khugepaged_mm_lock);
1731
1732         if (free) {
1733                 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1734                 free_mm_slot(mm_slot);
1735                 mmdrop(mm);
1736         } else if (mm_slot) {
1737                 /*
1738                  * This is required to serialize against
1739                  * khugepaged_test_exit() (which is guaranteed to run
1740                  * under mmap sem read mode). Stop here (after we
1741                  * return all pagetables will be destroyed) until
1742                  * khugepaged has finished working on the pagetables
1743                  * under the mmap_sem.
1744                  */
1745                 down_write(&mm->mmap_sem);
1746                 up_write(&mm->mmap_sem);
1747         }
1748 }
1749
1750 static void release_pte_page(struct page *page)
1751 {
1752         /* 0 stands for page_is_file_cache(page) == false */
1753         dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1754         unlock_page(page);
1755         putback_lru_page(page);
1756 }
1757
1758 static void release_pte_pages(pte_t *pte, pte_t *_pte)
1759 {
1760         while (--_pte >= pte) {
1761                 pte_t pteval = *_pte;
1762                 if (!pte_none(pteval))
1763                         release_pte_page(pte_page(pteval));
1764         }
1765 }
1766
1767 static void release_all_pte_pages(pte_t *pte)
1768 {
1769         release_pte_pages(pte, pte + HPAGE_PMD_NR);
1770 }
1771
1772 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1773                                         unsigned long address,
1774                                         pte_t *pte)
1775 {
1776         struct page *page;
1777         pte_t *_pte;
1778         int referenced = 0, isolated = 0, none = 0;
1779         for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1780              _pte++, address += PAGE_SIZE) {
1781                 pte_t pteval = *_pte;
1782                 if (pte_none(pteval)) {
1783                         if (++none <= khugepaged_max_ptes_none)
1784                                 continue;
1785                         else {
1786                                 release_pte_pages(pte, _pte);
1787                                 goto out;
1788                         }
1789                 }
1790                 if (!pte_present(pteval) || !pte_write(pteval)) {
1791                         release_pte_pages(pte, _pte);
1792                         goto out;
1793                 }
1794                 page = vm_normal_page(vma, address, pteval);
1795                 if (unlikely(!page)) {
1796                         release_pte_pages(pte, _pte);
1797                         goto out;
1798                 }
1799                 VM_BUG_ON(PageCompound(page));
1800                 BUG_ON(!PageAnon(page));
1801                 VM_BUG_ON(!PageSwapBacked(page));
1802
1803                 /* cannot use mapcount: can't collapse if there's a gup pin */
1804                 if (page_count(page) != 1) {
1805                         release_pte_pages(pte, _pte);
1806                         goto out;
1807                 }
1808                 /*
1809                  * We can do it before isolate_lru_page because the
1810                  * page can't be freed from under us. NOTE: PG_lock
1811                  * is needed to serialize against split_huge_page
1812                  * when invoked from the VM.
1813                  */
1814                 if (!trylock_page(page)) {
1815                         release_pte_pages(pte, _pte);
1816                         goto out;
1817                 }
1818                 /*
1819                  * Isolate the page to avoid collapsing an hugepage
1820                  * currently in use by the VM.
1821                  */
1822                 if (isolate_lru_page(page)) {
1823                         unlock_page(page);
1824                         release_pte_pages(pte, _pte);
1825                         goto out;
1826                 }
1827                 /* 0 stands for page_is_file_cache(page) == false */
1828                 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1829                 VM_BUG_ON(!PageLocked(page));
1830                 VM_BUG_ON(PageLRU(page));
1831
1832                 /* If there is no mapped pte young don't collapse the page */
1833                 if (pte_young(pteval) || PageReferenced(page) ||
1834                     mmu_notifier_test_young(vma->vm_mm, address))
1835                         referenced = 1;
1836         }
1837         if (unlikely(!referenced))
1838                 release_all_pte_pages(pte);
1839         else
1840                 isolated = 1;
1841 out:
1842         return isolated;
1843 }
1844
1845 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1846                                       struct vm_area_struct *vma,
1847                                       unsigned long address,
1848                                       spinlock_t *ptl)
1849 {
1850         pte_t *_pte;
1851         for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1852                 pte_t pteval = *_pte;
1853                 struct page *src_page;
1854
1855                 if (pte_none(pteval)) {
1856                         clear_user_highpage(page, address);
1857                         add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1858                 } else {
1859                         src_page = pte_page(pteval);
1860                         copy_user_highpage(page, src_page, address, vma);
1861                         VM_BUG_ON(page_mapcount(src_page) != 1);
1862                         release_pte_page(src_page);
1863                         /*
1864                          * ptl mostly unnecessary, but preempt has to
1865                          * be disabled to update the per-cpu stats
1866                          * inside page_remove_rmap().
1867                          */
1868                         spin_lock(ptl);
1869                         /*
1870                          * paravirt calls inside pte_clear here are
1871                          * superfluous.
1872                          */
1873                         pte_clear(vma->vm_mm, address, _pte);
1874                         page_remove_rmap(src_page);
1875                         spin_unlock(ptl);
1876                         free_page_and_swap_cache(src_page);
1877                 }
1878
1879                 address += PAGE_SIZE;
1880                 page++;
1881         }
1882 }
1883
1884 static void khugepaged_alloc_sleep(void)
1885 {
1886         wait_event_freezable_timeout(khugepaged_wait, false,
1887                         msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
1888 }
1889
1890 #ifdef CONFIG_NUMA
1891 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
1892 {
1893         if (IS_ERR(*hpage)) {
1894                 if (!*wait)
1895                         return false;
1896
1897                 *wait = false;
1898                 *hpage = NULL;
1899                 khugepaged_alloc_sleep();
1900         } else if (*hpage) {
1901                 put_page(*hpage);
1902                 *hpage = NULL;
1903         }
1904
1905         return true;
1906 }
1907
1908 static struct page
1909 *khugepaged_alloc_page(struct page **hpage, struct mm_struct *mm,
1910                        struct vm_area_struct *vma, unsigned long address,
1911                        int node)
1912 {
1913         VM_BUG_ON(*hpage);
1914         /*
1915          * Allocate the page while the vma is still valid and under
1916          * the mmap_sem read mode so there is no memory allocation
1917          * later when we take the mmap_sem in write mode. This is more
1918          * friendly behavior (OTOH it may actually hide bugs) to
1919          * filesystems in userland with daemons allocating memory in
1920          * the userland I/O paths.  Allocating memory with the
1921          * mmap_sem in read mode is good idea also to allow greater
1922          * scalability.
1923          */
1924         *hpage  = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
1925                                       node, __GFP_OTHER_NODE);
1926
1927         /*
1928          * After allocating the hugepage, release the mmap_sem read lock in
1929          * preparation for taking it in write mode.
1930          */
1931         up_read(&mm->mmap_sem);
1932         if (unlikely(!*hpage)) {
1933                 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1934                 *hpage = ERR_PTR(-ENOMEM);
1935                 return NULL;
1936         }
1937
1938         count_vm_event(THP_COLLAPSE_ALLOC);
1939         return *hpage;
1940 }
1941 #else
1942 static struct page *khugepaged_alloc_hugepage(bool *wait)
1943 {
1944         struct page *hpage;
1945
1946         do {
1947                 hpage = alloc_hugepage(khugepaged_defrag());
1948                 if (!hpage) {
1949                         count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1950                         if (!*wait)
1951                                 return NULL;
1952
1953                         *wait = false;
1954                         khugepaged_alloc_sleep();
1955                 } else
1956                         count_vm_event(THP_COLLAPSE_ALLOC);
1957         } while (unlikely(!hpage) && likely(khugepaged_enabled()));
1958
1959         return hpage;
1960 }
1961
1962 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
1963 {
1964         if (!*hpage)
1965                 *hpage = khugepaged_alloc_hugepage(wait);
1966
1967         if (unlikely(!*hpage))
1968                 return false;
1969
1970         return true;
1971 }
1972
1973 static struct page
1974 *khugepaged_alloc_page(struct page **hpage, struct mm_struct *mm,
1975                        struct vm_area_struct *vma, unsigned long address,
1976                        int node)
1977 {
1978         up_read(&mm->mmap_sem);
1979         VM_BUG_ON(!*hpage);
1980         return  *hpage;
1981 }
1982 #endif
1983
1984 static void collapse_huge_page(struct mm_struct *mm,
1985                                    unsigned long address,
1986                                    struct page **hpage,
1987                                    struct vm_area_struct *vma,
1988                                    int node)
1989 {
1990         pgd_t *pgd;
1991         pud_t *pud;
1992         pmd_t *pmd, _pmd;
1993         pte_t *pte;
1994         pgtable_t pgtable;
1995         struct page *new_page;
1996         spinlock_t *ptl;
1997         int isolated;
1998         unsigned long hstart, hend;
1999         unsigned long mmun_start;       /* For mmu_notifiers */
2000         unsigned long mmun_end;         /* For mmu_notifiers */
2001
2002         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2003
2004         /* release the mmap_sem read lock. */
2005         new_page = khugepaged_alloc_page(hpage, mm, vma, address, node);
2006         if (!new_page)
2007                 return;
2008
2009         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL)))
2010                 return;
2011
2012         /*
2013          * Prevent all access to pagetables with the exception of
2014          * gup_fast later hanlded by the ptep_clear_flush and the VM
2015          * handled by the anon_vma lock + PG_lock.
2016          */
2017         down_write(&mm->mmap_sem);
2018         if (unlikely(khugepaged_test_exit(mm)))
2019                 goto out;
2020
2021         vma = find_vma(mm, address);
2022         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2023         hend = vma->vm_end & HPAGE_PMD_MASK;
2024         if (address < hstart || address + HPAGE_PMD_SIZE > hend)
2025                 goto out;
2026
2027         if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
2028             (vma->vm_flags & VM_NOHUGEPAGE))
2029                 goto out;
2030
2031         if (!vma->anon_vma || vma->vm_ops)
2032                 goto out;
2033         if (is_vma_temporary_stack(vma))
2034                 goto out;
2035         VM_BUG_ON(vma->vm_flags & VM_NO_THP);
2036
2037         pgd = pgd_offset(mm, address);
2038         if (!pgd_present(*pgd))
2039                 goto out;
2040
2041         pud = pud_offset(pgd, address);
2042         if (!pud_present(*pud))
2043                 goto out;
2044
2045         pmd = pmd_offset(pud, address);
2046         /* pmd can't go away or become huge under us */
2047         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
2048                 goto out;
2049
2050         anon_vma_lock(vma->anon_vma);
2051
2052         pte = pte_offset_map(pmd, address);
2053         ptl = pte_lockptr(mm, pmd);
2054
2055         mmun_start = address;
2056         mmun_end   = address + HPAGE_PMD_SIZE;
2057         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2058         spin_lock(&mm->page_table_lock); /* probably unnecessary */
2059         /*
2060          * After this gup_fast can't run anymore. This also removes
2061          * any huge TLB entry from the CPU so we won't allow
2062          * huge and small TLB entries for the same virtual address
2063          * to avoid the risk of CPU bugs in that area.
2064          */
2065         _pmd = pmdp_clear_flush(vma, address, pmd);
2066         spin_unlock(&mm->page_table_lock);
2067         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2068
2069         spin_lock(ptl);
2070         isolated = __collapse_huge_page_isolate(vma, address, pte);
2071         spin_unlock(ptl);
2072
2073         if (unlikely(!isolated)) {
2074                 pte_unmap(pte);
2075                 spin_lock(&mm->page_table_lock);
2076                 BUG_ON(!pmd_none(*pmd));
2077                 set_pmd_at(mm, address, pmd, _pmd);
2078                 spin_unlock(&mm->page_table_lock);
2079                 anon_vma_unlock(vma->anon_vma);
2080                 goto out;
2081         }
2082
2083         /*
2084          * All pages are isolated and locked so anon_vma rmap
2085          * can't run anymore.
2086          */
2087         anon_vma_unlock(vma->anon_vma);
2088
2089         __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
2090         pte_unmap(pte);
2091         __SetPageUptodate(new_page);
2092         pgtable = pmd_pgtable(_pmd);
2093
2094         _pmd = mk_pmd(new_page, vma->vm_page_prot);
2095         _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
2096         _pmd = pmd_mkhuge(_pmd);
2097
2098         /*
2099          * spin_lock() below is not the equivalent of smp_wmb(), so
2100          * this is needed to avoid the copy_huge_page writes to become
2101          * visible after the set_pmd_at() write.
2102          */
2103         smp_wmb();
2104
2105         spin_lock(&mm->page_table_lock);
2106         BUG_ON(!pmd_none(*pmd));
2107         page_add_new_anon_rmap(new_page, vma, address);
2108         set_pmd_at(mm, address, pmd, _pmd);
2109         update_mmu_cache_pmd(vma, address, pmd);
2110         pgtable_trans_huge_deposit(mm, pgtable);
2111         spin_unlock(&mm->page_table_lock);
2112
2113         *hpage = NULL;
2114
2115         khugepaged_pages_collapsed++;
2116 out_up_write:
2117         up_write(&mm->mmap_sem);
2118         return;
2119
2120 out:
2121         mem_cgroup_uncharge_page(new_page);
2122         goto out_up_write;
2123 }
2124
2125 static int khugepaged_scan_pmd(struct mm_struct *mm,
2126                                struct vm_area_struct *vma,
2127                                unsigned long address,
2128                                struct page **hpage)
2129 {
2130         pgd_t *pgd;
2131         pud_t *pud;
2132         pmd_t *pmd;
2133         pte_t *pte, *_pte;
2134         int ret = 0, referenced = 0, none = 0;
2135         struct page *page;
2136         unsigned long _address;
2137         spinlock_t *ptl;
2138         int node = -1;
2139
2140         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2141
2142         pgd = pgd_offset(mm, address);
2143         if (!pgd_present(*pgd))
2144                 goto out;
2145
2146         pud = pud_offset(pgd, address);
2147         if (!pud_present(*pud))
2148                 goto out;
2149
2150         pmd = pmd_offset(pud, address);
2151         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
2152                 goto out;
2153
2154         pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2155         for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2156              _pte++, _address += PAGE_SIZE) {
2157                 pte_t pteval = *_pte;
2158                 if (pte_none(pteval)) {
2159                         if (++none <= khugepaged_max_ptes_none)
2160                                 continue;
2161                         else
2162                                 goto out_unmap;
2163                 }
2164                 if (!pte_present(pteval) || !pte_write(pteval))
2165                         goto out_unmap;
2166                 page = vm_normal_page(vma, _address, pteval);
2167                 if (unlikely(!page))
2168                         goto out_unmap;
2169                 /*
2170                  * Chose the node of the first page. This could
2171                  * be more sophisticated and look at more pages,
2172                  * but isn't for now.
2173                  */
2174                 if (node == -1)
2175                         node = page_to_nid(page);
2176                 VM_BUG_ON(PageCompound(page));
2177                 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2178                         goto out_unmap;
2179                 /* cannot use mapcount: can't collapse if there's a gup pin */
2180                 if (page_count(page) != 1)
2181                         goto out_unmap;
2182                 if (pte_young(pteval) || PageReferenced(page) ||
2183                     mmu_notifier_test_young(vma->vm_mm, address))
2184                         referenced = 1;
2185         }
2186         if (referenced)
2187                 ret = 1;
2188 out_unmap:
2189         pte_unmap_unlock(pte, ptl);
2190         if (ret)
2191                 /* collapse_huge_page will return with the mmap_sem released */
2192                 collapse_huge_page(mm, address, hpage, vma, node);
2193 out:
2194         return ret;
2195 }
2196
2197 static void collect_mm_slot(struct mm_slot *mm_slot)
2198 {
2199         struct mm_struct *mm = mm_slot->mm;
2200
2201         VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2202
2203         if (khugepaged_test_exit(mm)) {
2204                 /* free mm_slot */
2205                 hlist_del(&mm_slot->hash);
2206                 list_del(&mm_slot->mm_node);
2207
2208                 /*
2209                  * Not strictly needed because the mm exited already.
2210                  *
2211                  * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2212                  */
2213
2214                 /* khugepaged_mm_lock actually not necessary for the below */
2215                 free_mm_slot(mm_slot);
2216                 mmdrop(mm);
2217         }
2218 }
2219
2220 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2221                                             struct page **hpage)
2222         __releases(&khugepaged_mm_lock)
2223         __acquires(&khugepaged_mm_lock)
2224 {
2225         struct mm_slot *mm_slot;
2226         struct mm_struct *mm;
2227         struct vm_area_struct *vma;
2228         int progress = 0;
2229
2230         VM_BUG_ON(!pages);
2231         VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2232
2233         if (khugepaged_scan.mm_slot)
2234                 mm_slot = khugepaged_scan.mm_slot;
2235         else {
2236                 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2237                                      struct mm_slot, mm_node);
2238                 khugepaged_scan.address = 0;
2239                 khugepaged_scan.mm_slot = mm_slot;
2240         }
2241         spin_unlock(&khugepaged_mm_lock);
2242
2243         mm = mm_slot->mm;
2244         down_read(&mm->mmap_sem);
2245         if (unlikely(khugepaged_test_exit(mm)))
2246                 vma = NULL;
2247         else
2248                 vma = find_vma(mm, khugepaged_scan.address);
2249
2250         progress++;
2251         for (; vma; vma = vma->vm_next) {
2252                 unsigned long hstart, hend;
2253
2254                 cond_resched();
2255                 if (unlikely(khugepaged_test_exit(mm))) {
2256                         progress++;
2257                         break;
2258                 }
2259
2260                 if ((!(vma->vm_flags & VM_HUGEPAGE) &&
2261                      !khugepaged_always()) ||
2262                     (vma->vm_flags & VM_NOHUGEPAGE)) {
2263                 skip:
2264                         progress++;
2265                         continue;
2266                 }
2267                 if (!vma->anon_vma || vma->vm_ops)
2268                         goto skip;
2269                 if (is_vma_temporary_stack(vma))
2270                         goto skip;
2271                 VM_BUG_ON(vma->vm_flags & VM_NO_THP);
2272
2273                 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2274                 hend = vma->vm_end & HPAGE_PMD_MASK;
2275                 if (hstart >= hend)
2276                         goto skip;
2277                 if (khugepaged_scan.address > hend)
2278                         goto skip;
2279                 if (khugepaged_scan.address < hstart)
2280                         khugepaged_scan.address = hstart;
2281                 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2282
2283                 while (khugepaged_scan.address < hend) {
2284                         int ret;
2285                         cond_resched();
2286                         if (unlikely(khugepaged_test_exit(mm)))
2287                                 goto breakouterloop;
2288
2289                         VM_BUG_ON(khugepaged_scan.address < hstart ||
2290                                   khugepaged_scan.address + HPAGE_PMD_SIZE >
2291                                   hend);
2292                         ret = khugepaged_scan_pmd(mm, vma,
2293                                                   khugepaged_scan.address,
2294                                                   hpage);
2295                         /* move to next address */
2296                         khugepaged_scan.address += HPAGE_PMD_SIZE;
2297                         progress += HPAGE_PMD_NR;
2298                         if (ret)
2299                                 /* we released mmap_sem so break loop */
2300                                 goto breakouterloop_mmap_sem;
2301                         if (progress >= pages)
2302                                 goto breakouterloop;
2303                 }
2304         }
2305 breakouterloop:
2306         up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2307 breakouterloop_mmap_sem:
2308
2309         spin_lock(&khugepaged_mm_lock);
2310         VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2311         /*
2312          * Release the current mm_slot if this mm is about to die, or
2313          * if we scanned all vmas of this mm.
2314          */
2315         if (khugepaged_test_exit(mm) || !vma) {
2316                 /*
2317                  * Make sure that if mm_users is reaching zero while
2318                  * khugepaged runs here, khugepaged_exit will find
2319                  * mm_slot not pointing to the exiting mm.
2320                  */
2321                 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2322                         khugepaged_scan.mm_slot = list_entry(
2323                                 mm_slot->mm_node.next,
2324                                 struct mm_slot, mm_node);
2325                         khugepaged_scan.address = 0;
2326                 } else {
2327                         khugepaged_scan.mm_slot = NULL;
2328                         khugepaged_full_scans++;
2329                 }
2330
2331                 collect_mm_slot(mm_slot);
2332         }
2333
2334         return progress;
2335 }
2336
2337 static int khugepaged_has_work(void)
2338 {
2339         return !list_empty(&khugepaged_scan.mm_head) &&
2340                 khugepaged_enabled();
2341 }
2342
2343 static int khugepaged_wait_event(void)
2344 {
2345         return !list_empty(&khugepaged_scan.mm_head) ||
2346                 kthread_should_stop();
2347 }
2348
2349 static void khugepaged_do_scan(void)
2350 {
2351         struct page *hpage = NULL;
2352         unsigned int progress = 0, pass_through_head = 0;
2353         unsigned int pages = khugepaged_pages_to_scan;
2354         bool wait = true;
2355
2356         barrier(); /* write khugepaged_pages_to_scan to local stack */
2357
2358         while (progress < pages) {
2359                 if (!khugepaged_prealloc_page(&hpage, &wait))
2360                         break;
2361
2362                 cond_resched();
2363
2364                 if (unlikely(kthread_should_stop() || freezing(current)))
2365                         break;
2366
2367                 spin_lock(&khugepaged_mm_lock);
2368                 if (!khugepaged_scan.mm_slot)
2369                         pass_through_head++;
2370                 if (khugepaged_has_work() &&
2371                     pass_through_head < 2)
2372                         progress += khugepaged_scan_mm_slot(pages - progress,
2373                                                             &hpage);
2374                 else
2375                         progress = pages;
2376                 spin_unlock(&khugepaged_mm_lock);
2377         }
2378
2379         if (!IS_ERR_OR_NULL(hpage))
2380                 put_page(hpage);
2381 }
2382
2383 static void khugepaged_wait_work(void)
2384 {
2385         try_to_freeze();
2386
2387         if (khugepaged_has_work()) {
2388                 if (!khugepaged_scan_sleep_millisecs)
2389                         return;
2390
2391                 wait_event_freezable_timeout(khugepaged_wait,
2392                                              kthread_should_stop(),
2393                         msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2394                 return;
2395         }
2396
2397         if (khugepaged_enabled())
2398                 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2399 }
2400
2401 static int khugepaged(void *none)
2402 {
2403         struct mm_slot *mm_slot;
2404
2405         set_freezable();
2406         set_user_nice(current, 19);
2407
2408         while (!kthread_should_stop()) {
2409                 khugepaged_do_scan();
2410                 khugepaged_wait_work();
2411         }
2412
2413         spin_lock(&khugepaged_mm_lock);
2414         mm_slot = khugepaged_scan.mm_slot;
2415         khugepaged_scan.mm_slot = NULL;
2416         if (mm_slot)
2417                 collect_mm_slot(mm_slot);
2418         spin_unlock(&khugepaged_mm_lock);
2419         return 0;
2420 }
2421
2422 void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2423 {
2424         struct page *page;
2425
2426         spin_lock(&mm->page_table_lock);
2427         if (unlikely(!pmd_trans_huge(*pmd))) {
2428                 spin_unlock(&mm->page_table_lock);
2429                 return;
2430         }
2431         page = pmd_page(*pmd);
2432         VM_BUG_ON(!page_count(page));
2433         get_page(page);
2434         spin_unlock(&mm->page_table_lock);
2435
2436         split_huge_page(page);
2437
2438         put_page(page);
2439         BUG_ON(pmd_trans_huge(*pmd));
2440 }
2441
2442 static void split_huge_page_address(struct mm_struct *mm,
2443                                     unsigned long address)
2444 {
2445         pgd_t *pgd;
2446         pud_t *pud;
2447         pmd_t *pmd;
2448
2449         VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
2450
2451         pgd = pgd_offset(mm, address);
2452         if (!pgd_present(*pgd))
2453                 return;
2454
2455         pud = pud_offset(pgd, address);
2456         if (!pud_present(*pud))
2457                 return;
2458
2459         pmd = pmd_offset(pud, address);
2460         if (!pmd_present(*pmd))
2461                 return;
2462         /*
2463          * Caller holds the mmap_sem write mode, so a huge pmd cannot
2464          * materialize from under us.
2465          */
2466         split_huge_page_pmd(mm, pmd);
2467 }
2468
2469 void __vma_adjust_trans_huge(struct vm_area_struct *vma,
2470                              unsigned long start,
2471                              unsigned long end,
2472                              long adjust_next)
2473 {
2474         /*
2475          * If the new start address isn't hpage aligned and it could
2476          * previously contain an hugepage: check if we need to split
2477          * an huge pmd.
2478          */
2479         if (start & ~HPAGE_PMD_MASK &&
2480             (start & HPAGE_PMD_MASK) >= vma->vm_start &&
2481             (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2482                 split_huge_page_address(vma->vm_mm, start);
2483
2484         /*
2485          * If the new end address isn't hpage aligned and it could
2486          * previously contain an hugepage: check if we need to split
2487          * an huge pmd.
2488          */
2489         if (end & ~HPAGE_PMD_MASK &&
2490             (end & HPAGE_PMD_MASK) >= vma->vm_start &&
2491             (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2492                 split_huge_page_address(vma->vm_mm, end);
2493
2494         /*
2495          * If we're also updating the vma->vm_next->vm_start, if the new
2496          * vm_next->vm_start isn't page aligned and it could previously
2497          * contain an hugepage: check if we need to split an huge pmd.
2498          */
2499         if (adjust_next > 0) {
2500                 struct vm_area_struct *next = vma->vm_next;
2501                 unsigned long nstart = next->vm_start;
2502                 nstart += adjust_next << PAGE_SHIFT;
2503                 if (nstart & ~HPAGE_PMD_MASK &&
2504                     (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
2505                     (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
2506                         split_huge_page_address(next->vm_mm, nstart);
2507         }
2508 }