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