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