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