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