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