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