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