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