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