thp: fix anon memory statistics with transparent hugepages
[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         int zonestat;
1147
1148         /* prevent PageLRU to go away from under us, and freeze lru stats */
1149         spin_lock_irq(&zone->lru_lock);
1150         compound_lock(page);
1151
1152         for (i = 1; i < HPAGE_PMD_NR; i++) {
1153                 struct page *page_tail = page + i;
1154
1155                 /* tail_page->_count cannot change */
1156                 atomic_sub(atomic_read(&page_tail->_count), &page->_count);
1157                 BUG_ON(page_count(page) <= 0);
1158                 atomic_add(page_mapcount(page) + 1, &page_tail->_count);
1159                 BUG_ON(atomic_read(&page_tail->_count) <= 0);
1160
1161                 /* after clearing PageTail the gup refcount can be released */
1162                 smp_mb();
1163
1164                 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1165                 page_tail->flags |= (page->flags &
1166                                      ((1L << PG_referenced) |
1167                                       (1L << PG_swapbacked) |
1168                                       (1L << PG_mlocked) |
1169                                       (1L << PG_uptodate)));
1170                 page_tail->flags |= (1L << PG_dirty);
1171
1172                 /*
1173                  * 1) clear PageTail before overwriting first_page
1174                  * 2) clear PageTail before clearing PageHead for VM_BUG_ON
1175                  */
1176                 smp_wmb();
1177
1178                 /*
1179                  * __split_huge_page_splitting() already set the
1180                  * splitting bit in all pmd that could map this
1181                  * hugepage, that will ensure no CPU can alter the
1182                  * mapcount on the head page. The mapcount is only
1183                  * accounted in the head page and it has to be
1184                  * transferred to all tail pages in the below code. So
1185                  * for this code to be safe, the split the mapcount
1186                  * can't change. But that doesn't mean userland can't
1187                  * keep changing and reading the page contents while
1188                  * we transfer the mapcount, so the pmd splitting
1189                  * status is achieved setting a reserved bit in the
1190                  * pmd, not by clearing the present bit.
1191                 */
1192                 BUG_ON(page_mapcount(page_tail));
1193                 page_tail->_mapcount = page->_mapcount;
1194
1195                 BUG_ON(page_tail->mapping);
1196                 page_tail->mapping = page->mapping;
1197
1198                 page_tail->index = ++head_index;
1199
1200                 BUG_ON(!PageAnon(page_tail));
1201                 BUG_ON(!PageUptodate(page_tail));
1202                 BUG_ON(!PageDirty(page_tail));
1203                 BUG_ON(!PageSwapBacked(page_tail));
1204
1205                 lru_add_page_tail(zone, page, page_tail);
1206         }
1207
1208         __dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
1209         __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1210
1211         /*
1212          * A hugepage counts for HPAGE_PMD_NR pages on the LRU statistics,
1213          * so adjust those appropriately if this page is on the LRU.
1214          */
1215         if (PageLRU(page)) {
1216                 zonestat = NR_LRU_BASE + page_lru(page);
1217                 __mod_zone_page_state(zone, zonestat, -(HPAGE_PMD_NR-1));
1218         }
1219
1220         ClearPageCompound(page);
1221         compound_unlock(page);
1222         spin_unlock_irq(&zone->lru_lock);
1223
1224         for (i = 1; i < HPAGE_PMD_NR; i++) {
1225                 struct page *page_tail = page + i;
1226                 BUG_ON(page_count(page_tail) <= 0);
1227                 /*
1228                  * Tail pages may be freed if there wasn't any mapping
1229                  * like if add_to_swap() is running on a lru page that
1230                  * had its mapping zapped. And freeing these pages
1231                  * requires taking the lru_lock so we do the put_page
1232                  * of the tail pages after the split is complete.
1233                  */
1234                 put_page(page_tail);
1235         }
1236
1237         /*
1238          * Only the head page (now become a regular page) is required
1239          * to be pinned by the caller.
1240          */
1241         BUG_ON(page_count(page) <= 0);
1242 }
1243
1244 static int __split_huge_page_map(struct page *page,
1245                                  struct vm_area_struct *vma,
1246                                  unsigned long address)
1247 {
1248         struct mm_struct *mm = vma->vm_mm;
1249         pmd_t *pmd, _pmd;
1250         int ret = 0, i;
1251         pgtable_t pgtable;
1252         unsigned long haddr;
1253
1254         spin_lock(&mm->page_table_lock);
1255         pmd = page_check_address_pmd(page, mm, address,
1256                                      PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1257         if (pmd) {
1258                 pgtable = get_pmd_huge_pte(mm);
1259                 pmd_populate(mm, &_pmd, pgtable);
1260
1261                 for (i = 0, haddr = address; i < HPAGE_PMD_NR;
1262                      i++, haddr += PAGE_SIZE) {
1263                         pte_t *pte, entry;
1264                         BUG_ON(PageCompound(page+i));
1265                         entry = mk_pte(page + i, vma->vm_page_prot);
1266                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1267                         if (!pmd_write(*pmd))
1268                                 entry = pte_wrprotect(entry);
1269                         else
1270                                 BUG_ON(page_mapcount(page) != 1);
1271                         if (!pmd_young(*pmd))
1272                                 entry = pte_mkold(entry);
1273                         pte = pte_offset_map(&_pmd, haddr);
1274                         BUG_ON(!pte_none(*pte));
1275                         set_pte_at(mm, haddr, pte, entry);
1276                         pte_unmap(pte);
1277                 }
1278
1279                 mm->nr_ptes++;
1280                 smp_wmb(); /* make pte visible before pmd */
1281                 /*
1282                  * Up to this point the pmd is present and huge and
1283                  * userland has the whole access to the hugepage
1284                  * during the split (which happens in place). If we
1285                  * overwrite the pmd with the not-huge version
1286                  * pointing to the pte here (which of course we could
1287                  * if all CPUs were bug free), userland could trigger
1288                  * a small page size TLB miss on the small sized TLB
1289                  * while the hugepage TLB entry is still established
1290                  * in the huge TLB. Some CPU doesn't like that. See
1291                  * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1292                  * Erratum 383 on page 93. Intel should be safe but is
1293                  * also warns that it's only safe if the permission
1294                  * and cache attributes of the two entries loaded in
1295                  * the two TLB is identical (which should be the case
1296                  * here). But it is generally safer to never allow
1297                  * small and huge TLB entries for the same virtual
1298                  * address to be loaded simultaneously. So instead of
1299                  * doing "pmd_populate(); flush_tlb_range();" we first
1300                  * mark the current pmd notpresent (atomically because
1301                  * here the pmd_trans_huge and pmd_trans_splitting
1302                  * must remain set at all times on the pmd until the
1303                  * split is complete for this pmd), then we flush the
1304                  * SMP TLB and finally we write the non-huge version
1305                  * of the pmd entry with pmd_populate.
1306                  */
1307                 set_pmd_at(mm, address, pmd, pmd_mknotpresent(*pmd));
1308                 flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
1309                 pmd_populate(mm, pmd, pgtable);
1310                 ret = 1;
1311         }
1312         spin_unlock(&mm->page_table_lock);
1313
1314         return ret;
1315 }
1316
1317 /* must be called with anon_vma->root->lock hold */
1318 static void __split_huge_page(struct page *page,
1319                               struct anon_vma *anon_vma)
1320 {
1321         int mapcount, mapcount2;
1322         struct anon_vma_chain *avc;
1323
1324         BUG_ON(!PageHead(page));
1325         BUG_ON(PageTail(page));
1326
1327         mapcount = 0;
1328         list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1329                 struct vm_area_struct *vma = avc->vma;
1330                 unsigned long addr = vma_address(page, vma);
1331                 BUG_ON(is_vma_temporary_stack(vma));
1332                 if (addr == -EFAULT)
1333                         continue;
1334                 mapcount += __split_huge_page_splitting(page, vma, addr);
1335         }
1336         /*
1337          * It is critical that new vmas are added to the tail of the
1338          * anon_vma list. This guarantes that if copy_huge_pmd() runs
1339          * and establishes a child pmd before
1340          * __split_huge_page_splitting() freezes the parent pmd (so if
1341          * we fail to prevent copy_huge_pmd() from running until the
1342          * whole __split_huge_page() is complete), we will still see
1343          * the newly established pmd of the child later during the
1344          * walk, to be able to set it as pmd_trans_splitting too.
1345          */
1346         if (mapcount != page_mapcount(page))
1347                 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1348                        mapcount, page_mapcount(page));
1349         BUG_ON(mapcount != page_mapcount(page));
1350
1351         __split_huge_page_refcount(page);
1352
1353         mapcount2 = 0;
1354         list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1355                 struct vm_area_struct *vma = avc->vma;
1356                 unsigned long addr = vma_address(page, vma);
1357                 BUG_ON(is_vma_temporary_stack(vma));
1358                 if (addr == -EFAULT)
1359                         continue;
1360                 mapcount2 += __split_huge_page_map(page, vma, addr);
1361         }
1362         if (mapcount != mapcount2)
1363                 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1364                        mapcount, mapcount2, page_mapcount(page));
1365         BUG_ON(mapcount != mapcount2);
1366 }
1367
1368 int split_huge_page(struct page *page)
1369 {
1370         struct anon_vma *anon_vma;
1371         int ret = 1;
1372
1373         BUG_ON(!PageAnon(page));
1374         anon_vma = page_lock_anon_vma(page);
1375         if (!anon_vma)
1376                 goto out;
1377         ret = 0;
1378         if (!PageCompound(page))
1379                 goto out_unlock;
1380
1381         BUG_ON(!PageSwapBacked(page));
1382         __split_huge_page(page, anon_vma);
1383
1384         BUG_ON(PageCompound(page));
1385 out_unlock:
1386         page_unlock_anon_vma(anon_vma);
1387 out:
1388         return ret;
1389 }
1390
1391 int hugepage_madvise(unsigned long *vm_flags)
1392 {
1393         /*
1394          * Be somewhat over-protective like KSM for now!
1395          */
1396         if (*vm_flags & (VM_HUGEPAGE | VM_SHARED  | VM_MAYSHARE   |
1397                          VM_PFNMAP   | VM_IO      | VM_DONTEXPAND |
1398                          VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
1399                          VM_MIXEDMAP | VM_SAO))
1400                 return -EINVAL;
1401
1402         *vm_flags |= VM_HUGEPAGE;
1403
1404         return 0;
1405 }
1406
1407 static int __init khugepaged_slab_init(void)
1408 {
1409         mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1410                                           sizeof(struct mm_slot),
1411                                           __alignof__(struct mm_slot), 0, NULL);
1412         if (!mm_slot_cache)
1413                 return -ENOMEM;
1414
1415         return 0;
1416 }
1417
1418 static void __init khugepaged_slab_free(void)
1419 {
1420         kmem_cache_destroy(mm_slot_cache);
1421         mm_slot_cache = NULL;
1422 }
1423
1424 static inline struct mm_slot *alloc_mm_slot(void)
1425 {
1426         if (!mm_slot_cache)     /* initialization failed */
1427                 return NULL;
1428         return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1429 }
1430
1431 static inline void free_mm_slot(struct mm_slot *mm_slot)
1432 {
1433         kmem_cache_free(mm_slot_cache, mm_slot);
1434 }
1435
1436 static int __init mm_slots_hash_init(void)
1437 {
1438         mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1439                                 GFP_KERNEL);
1440         if (!mm_slots_hash)
1441                 return -ENOMEM;
1442         return 0;
1443 }
1444
1445 #if 0
1446 static void __init mm_slots_hash_free(void)
1447 {
1448         kfree(mm_slots_hash);
1449         mm_slots_hash = NULL;
1450 }
1451 #endif
1452
1453 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1454 {
1455         struct mm_slot *mm_slot;
1456         struct hlist_head *bucket;
1457         struct hlist_node *node;
1458
1459         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1460                                 % MM_SLOTS_HASH_HEADS];
1461         hlist_for_each_entry(mm_slot, node, bucket, hash) {
1462                 if (mm == mm_slot->mm)
1463                         return mm_slot;
1464         }
1465         return NULL;
1466 }
1467
1468 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1469                                     struct mm_slot *mm_slot)
1470 {
1471         struct hlist_head *bucket;
1472
1473         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1474                                 % MM_SLOTS_HASH_HEADS];
1475         mm_slot->mm = mm;
1476         hlist_add_head(&mm_slot->hash, bucket);
1477 }
1478
1479 static inline int khugepaged_test_exit(struct mm_struct *mm)
1480 {
1481         return atomic_read(&mm->mm_users) == 0;
1482 }
1483
1484 int __khugepaged_enter(struct mm_struct *mm)
1485 {
1486         struct mm_slot *mm_slot;
1487         int wakeup;
1488
1489         mm_slot = alloc_mm_slot();
1490         if (!mm_slot)
1491                 return -ENOMEM;
1492
1493         /* __khugepaged_exit() must not run from under us */
1494         VM_BUG_ON(khugepaged_test_exit(mm));
1495         if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1496                 free_mm_slot(mm_slot);
1497                 return 0;
1498         }
1499
1500         spin_lock(&khugepaged_mm_lock);
1501         insert_to_mm_slots_hash(mm, mm_slot);
1502         /*
1503          * Insert just behind the scanning cursor, to let the area settle
1504          * down a little.
1505          */
1506         wakeup = list_empty(&khugepaged_scan.mm_head);
1507         list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1508         spin_unlock(&khugepaged_mm_lock);
1509
1510         atomic_inc(&mm->mm_count);
1511         if (wakeup)
1512                 wake_up_interruptible(&khugepaged_wait);
1513
1514         return 0;
1515 }
1516
1517 int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
1518 {
1519         unsigned long hstart, hend;
1520         if (!vma->anon_vma)
1521                 /*
1522                  * Not yet faulted in so we will register later in the
1523                  * page fault if needed.
1524                  */
1525                 return 0;
1526         if (vma->vm_file || vma->vm_ops)
1527                 /* khugepaged not yet working on file or special mappings */
1528                 return 0;
1529         VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
1530         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1531         hend = vma->vm_end & HPAGE_PMD_MASK;
1532         if (hstart < hend)
1533                 return khugepaged_enter(vma);
1534         return 0;
1535 }
1536
1537 void __khugepaged_exit(struct mm_struct *mm)
1538 {
1539         struct mm_slot *mm_slot;
1540         int free = 0;
1541
1542         spin_lock(&khugepaged_mm_lock);
1543         mm_slot = get_mm_slot(mm);
1544         if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1545                 hlist_del(&mm_slot->hash);
1546                 list_del(&mm_slot->mm_node);
1547                 free = 1;
1548         }
1549
1550         if (free) {
1551                 spin_unlock(&khugepaged_mm_lock);
1552                 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1553                 free_mm_slot(mm_slot);
1554                 mmdrop(mm);
1555         } else if (mm_slot) {
1556                 spin_unlock(&khugepaged_mm_lock);
1557                 /*
1558                  * This is required to serialize against
1559                  * khugepaged_test_exit() (which is guaranteed to run
1560                  * under mmap sem read mode). Stop here (after we
1561                  * return all pagetables will be destroyed) until
1562                  * khugepaged has finished working on the pagetables
1563                  * under the mmap_sem.
1564                  */
1565                 down_write(&mm->mmap_sem);
1566                 up_write(&mm->mmap_sem);
1567         } else
1568                 spin_unlock(&khugepaged_mm_lock);
1569 }
1570
1571 static void release_pte_page(struct page *page)
1572 {
1573         /* 0 stands for page_is_file_cache(page) == false */
1574         dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1575         unlock_page(page);
1576         putback_lru_page(page);
1577 }
1578
1579 static void release_pte_pages(pte_t *pte, pte_t *_pte)
1580 {
1581         while (--_pte >= pte) {
1582                 pte_t pteval = *_pte;
1583                 if (!pte_none(pteval))
1584                         release_pte_page(pte_page(pteval));
1585         }
1586 }
1587
1588 static void release_all_pte_pages(pte_t *pte)
1589 {
1590         release_pte_pages(pte, pte + HPAGE_PMD_NR);
1591 }
1592
1593 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1594                                         unsigned long address,
1595                                         pte_t *pte)
1596 {
1597         struct page *page;
1598         pte_t *_pte;
1599         int referenced = 0, isolated = 0, none = 0;
1600         for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1601              _pte++, address += PAGE_SIZE) {
1602                 pte_t pteval = *_pte;
1603                 if (pte_none(pteval)) {
1604                         if (++none <= khugepaged_max_ptes_none)
1605                                 continue;
1606                         else {
1607                                 release_pte_pages(pte, _pte);
1608                                 goto out;
1609                         }
1610                 }
1611                 if (!pte_present(pteval) || !pte_write(pteval)) {
1612                         release_pte_pages(pte, _pte);
1613                         goto out;
1614                 }
1615                 page = vm_normal_page(vma, address, pteval);
1616                 if (unlikely(!page)) {
1617                         release_pte_pages(pte, _pte);
1618                         goto out;
1619                 }
1620                 VM_BUG_ON(PageCompound(page));
1621                 BUG_ON(!PageAnon(page));
1622                 VM_BUG_ON(!PageSwapBacked(page));
1623
1624                 /* cannot use mapcount: can't collapse if there's a gup pin */
1625                 if (page_count(page) != 1) {
1626                         release_pte_pages(pte, _pte);
1627                         goto out;
1628                 }
1629                 /*
1630                  * We can do it before isolate_lru_page because the
1631                  * page can't be freed from under us. NOTE: PG_lock
1632                  * is needed to serialize against split_huge_page
1633                  * when invoked from the VM.
1634                  */
1635                 if (!trylock_page(page)) {
1636                         release_pte_pages(pte, _pte);
1637                         goto out;
1638                 }
1639                 /*
1640                  * Isolate the page to avoid collapsing an hugepage
1641                  * currently in use by the VM.
1642                  */
1643                 if (isolate_lru_page(page)) {
1644                         unlock_page(page);
1645                         release_pte_pages(pte, _pte);
1646                         goto out;
1647                 }
1648                 /* 0 stands for page_is_file_cache(page) == false */
1649                 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1650                 VM_BUG_ON(!PageLocked(page));
1651                 VM_BUG_ON(PageLRU(page));
1652
1653                 /* If there is no mapped pte young don't collapse the page */
1654                 if (pte_young(pteval) || PageReferenced(page) ||
1655                     mmu_notifier_test_young(vma->vm_mm, address))
1656                         referenced = 1;
1657         }
1658         if (unlikely(!referenced))
1659                 release_all_pte_pages(pte);
1660         else
1661                 isolated = 1;
1662 out:
1663         return isolated;
1664 }
1665
1666 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1667                                       struct vm_area_struct *vma,
1668                                       unsigned long address,
1669                                       spinlock_t *ptl)
1670 {
1671         pte_t *_pte;
1672         for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1673                 pte_t pteval = *_pte;
1674                 struct page *src_page;
1675
1676                 if (pte_none(pteval)) {
1677                         clear_user_highpage(page, address);
1678                         add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1679                 } else {
1680                         src_page = pte_page(pteval);
1681                         copy_user_highpage(page, src_page, address, vma);
1682                         VM_BUG_ON(page_mapcount(src_page) != 1);
1683                         VM_BUG_ON(page_count(src_page) != 2);
1684                         release_pte_page(src_page);
1685                         /*
1686                          * ptl mostly unnecessary, but preempt has to
1687                          * be disabled to update the per-cpu stats
1688                          * inside page_remove_rmap().
1689                          */
1690                         spin_lock(ptl);
1691                         /*
1692                          * paravirt calls inside pte_clear here are
1693                          * superfluous.
1694                          */
1695                         pte_clear(vma->vm_mm, address, _pte);
1696                         page_remove_rmap(src_page);
1697                         spin_unlock(ptl);
1698                         free_page_and_swap_cache(src_page);
1699                 }
1700
1701                 address += PAGE_SIZE;
1702                 page++;
1703         }
1704 }
1705
1706 static void collapse_huge_page(struct mm_struct *mm,
1707                                unsigned long address,
1708                                struct page **hpage,
1709                                struct vm_area_struct *vma)
1710 {
1711         pgd_t *pgd;
1712         pud_t *pud;
1713         pmd_t *pmd, _pmd;
1714         pte_t *pte;
1715         pgtable_t pgtable;
1716         struct page *new_page;
1717         spinlock_t *ptl;
1718         int isolated;
1719         unsigned long hstart, hend;
1720
1721         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1722 #ifndef CONFIG_NUMA
1723         VM_BUG_ON(!*hpage);
1724         new_page = *hpage;
1725 #else
1726         VM_BUG_ON(*hpage);
1727         /*
1728          * Allocate the page while the vma is still valid and under
1729          * the mmap_sem read mode so there is no memory allocation
1730          * later when we take the mmap_sem in write mode. This is more
1731          * friendly behavior (OTOH it may actually hide bugs) to
1732          * filesystems in userland with daemons allocating memory in
1733          * the userland I/O paths.  Allocating memory with the
1734          * mmap_sem in read mode is good idea also to allow greater
1735          * scalability.
1736          */
1737         new_page = alloc_hugepage_vma(khugepaged_defrag(), vma, address);
1738         if (unlikely(!new_page)) {
1739                 up_read(&mm->mmap_sem);
1740                 *hpage = ERR_PTR(-ENOMEM);
1741                 return;
1742         }
1743 #endif
1744         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
1745                 up_read(&mm->mmap_sem);
1746                 put_page(new_page);
1747                 return;
1748         }
1749
1750         /* after allocating the hugepage upgrade to mmap_sem write mode */
1751         up_read(&mm->mmap_sem);
1752
1753         /*
1754          * Prevent all access to pagetables with the exception of
1755          * gup_fast later hanlded by the ptep_clear_flush and the VM
1756          * handled by the anon_vma lock + PG_lock.
1757          */
1758         down_write(&mm->mmap_sem);
1759         if (unlikely(khugepaged_test_exit(mm)))
1760                 goto out;
1761
1762         vma = find_vma(mm, address);
1763         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1764         hend = vma->vm_end & HPAGE_PMD_MASK;
1765         if (address < hstart || address + HPAGE_PMD_SIZE > hend)
1766                 goto out;
1767
1768         if (!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always())
1769                 goto out;
1770
1771         /* VM_PFNMAP vmas may have vm_ops null but vm_file set */
1772         if (!vma->anon_vma || vma->vm_ops || vma->vm_file)
1773                 goto out;
1774         VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
1775
1776         pgd = pgd_offset(mm, address);
1777         if (!pgd_present(*pgd))
1778                 goto out;
1779
1780         pud = pud_offset(pgd, address);
1781         if (!pud_present(*pud))
1782                 goto out;
1783
1784         pmd = pmd_offset(pud, address);
1785         /* pmd can't go away or become huge under us */
1786         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
1787                 goto out;
1788
1789         anon_vma_lock(vma->anon_vma);
1790
1791         pte = pte_offset_map(pmd, address);
1792         ptl = pte_lockptr(mm, pmd);
1793
1794         spin_lock(&mm->page_table_lock); /* probably unnecessary */
1795         /*
1796          * After this gup_fast can't run anymore. This also removes
1797          * any huge TLB entry from the CPU so we won't allow
1798          * huge and small TLB entries for the same virtual address
1799          * to avoid the risk of CPU bugs in that area.
1800          */
1801         _pmd = pmdp_clear_flush_notify(vma, address, pmd);
1802         spin_unlock(&mm->page_table_lock);
1803
1804         spin_lock(ptl);
1805         isolated = __collapse_huge_page_isolate(vma, address, pte);
1806         spin_unlock(ptl);
1807         pte_unmap(pte);
1808
1809         if (unlikely(!isolated)) {
1810                 spin_lock(&mm->page_table_lock);
1811                 BUG_ON(!pmd_none(*pmd));
1812                 set_pmd_at(mm, address, pmd, _pmd);
1813                 spin_unlock(&mm->page_table_lock);
1814                 anon_vma_unlock(vma->anon_vma);
1815                 mem_cgroup_uncharge_page(new_page);
1816                 goto out;
1817         }
1818
1819         /*
1820          * All pages are isolated and locked so anon_vma rmap
1821          * can't run anymore.
1822          */
1823         anon_vma_unlock(vma->anon_vma);
1824
1825         __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
1826         __SetPageUptodate(new_page);
1827         pgtable = pmd_pgtable(_pmd);
1828         VM_BUG_ON(page_count(pgtable) != 1);
1829         VM_BUG_ON(page_mapcount(pgtable) != 0);
1830
1831         _pmd = mk_pmd(new_page, vma->vm_page_prot);
1832         _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1833         _pmd = pmd_mkhuge(_pmd);
1834
1835         /*
1836          * spin_lock() below is not the equivalent of smp_wmb(), so
1837          * this is needed to avoid the copy_huge_page writes to become
1838          * visible after the set_pmd_at() write.
1839          */
1840         smp_wmb();
1841
1842         spin_lock(&mm->page_table_lock);
1843         BUG_ON(!pmd_none(*pmd));
1844         page_add_new_anon_rmap(new_page, vma, address);
1845         set_pmd_at(mm, address, pmd, _pmd);
1846         update_mmu_cache(vma, address, entry);
1847         prepare_pmd_huge_pte(pgtable, mm);
1848         mm->nr_ptes--;
1849         spin_unlock(&mm->page_table_lock);
1850
1851 #ifndef CONFIG_NUMA
1852         *hpage = NULL;
1853 #endif
1854         khugepaged_pages_collapsed++;
1855 out_up_write:
1856         up_write(&mm->mmap_sem);
1857         return;
1858
1859 out:
1860 #ifdef CONFIG_NUMA
1861         put_page(new_page);
1862 #endif
1863         goto out_up_write;
1864 }
1865
1866 static int khugepaged_scan_pmd(struct mm_struct *mm,
1867                                struct vm_area_struct *vma,
1868                                unsigned long address,
1869                                struct page **hpage)
1870 {
1871         pgd_t *pgd;
1872         pud_t *pud;
1873         pmd_t *pmd;
1874         pte_t *pte, *_pte;
1875         int ret = 0, referenced = 0, none = 0;
1876         struct page *page;
1877         unsigned long _address;
1878         spinlock_t *ptl;
1879
1880         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1881
1882         pgd = pgd_offset(mm, address);
1883         if (!pgd_present(*pgd))
1884                 goto out;
1885
1886         pud = pud_offset(pgd, address);
1887         if (!pud_present(*pud))
1888                 goto out;
1889
1890         pmd = pmd_offset(pud, address);
1891         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
1892                 goto out;
1893
1894         pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1895         for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1896              _pte++, _address += PAGE_SIZE) {
1897                 pte_t pteval = *_pte;
1898                 if (pte_none(pteval)) {
1899                         if (++none <= khugepaged_max_ptes_none)
1900                                 continue;
1901                         else
1902                                 goto out_unmap;
1903                 }
1904                 if (!pte_present(pteval) || !pte_write(pteval))
1905                         goto out_unmap;
1906                 page = vm_normal_page(vma, _address, pteval);
1907                 if (unlikely(!page))
1908                         goto out_unmap;
1909                 VM_BUG_ON(PageCompound(page));
1910                 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
1911                         goto out_unmap;
1912                 /* cannot use mapcount: can't collapse if there's a gup pin */
1913                 if (page_count(page) != 1)
1914                         goto out_unmap;
1915                 if (pte_young(pteval) || PageReferenced(page) ||
1916                     mmu_notifier_test_young(vma->vm_mm, address))
1917                         referenced = 1;
1918         }
1919         if (referenced)
1920                 ret = 1;
1921 out_unmap:
1922         pte_unmap_unlock(pte, ptl);
1923         if (ret)
1924                 /* collapse_huge_page will return with the mmap_sem released */
1925                 collapse_huge_page(mm, address, hpage, vma);
1926 out:
1927         return ret;
1928 }
1929
1930 static void collect_mm_slot(struct mm_slot *mm_slot)
1931 {
1932         struct mm_struct *mm = mm_slot->mm;
1933
1934         VM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock));
1935
1936         if (khugepaged_test_exit(mm)) {
1937                 /* free mm_slot */
1938                 hlist_del(&mm_slot->hash);
1939                 list_del(&mm_slot->mm_node);
1940
1941                 /*
1942                  * Not strictly needed because the mm exited already.
1943                  *
1944                  * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1945                  */
1946
1947                 /* khugepaged_mm_lock actually not necessary for the below */
1948                 free_mm_slot(mm_slot);
1949                 mmdrop(mm);
1950         }
1951 }
1952
1953 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
1954                                             struct page **hpage)
1955 {
1956         struct mm_slot *mm_slot;
1957         struct mm_struct *mm;
1958         struct vm_area_struct *vma;
1959         int progress = 0;
1960
1961         VM_BUG_ON(!pages);
1962         VM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock));
1963
1964         if (khugepaged_scan.mm_slot)
1965                 mm_slot = khugepaged_scan.mm_slot;
1966         else {
1967                 mm_slot = list_entry(khugepaged_scan.mm_head.next,
1968                                      struct mm_slot, mm_node);
1969                 khugepaged_scan.address = 0;
1970                 khugepaged_scan.mm_slot = mm_slot;
1971         }
1972         spin_unlock(&khugepaged_mm_lock);
1973
1974         mm = mm_slot->mm;
1975         down_read(&mm->mmap_sem);
1976         if (unlikely(khugepaged_test_exit(mm)))
1977                 vma = NULL;
1978         else
1979                 vma = find_vma(mm, khugepaged_scan.address);
1980
1981         progress++;
1982         for (; vma; vma = vma->vm_next) {
1983                 unsigned long hstart, hend;
1984
1985                 cond_resched();
1986                 if (unlikely(khugepaged_test_exit(mm))) {
1987                         progress++;
1988                         break;
1989                 }
1990
1991                 if (!(vma->vm_flags & VM_HUGEPAGE) &&
1992                     !khugepaged_always()) {
1993                         progress++;
1994                         continue;
1995                 }
1996
1997                 /* VM_PFNMAP vmas may have vm_ops null but vm_file set */
1998                 if (!vma->anon_vma || vma->vm_ops || vma->vm_file) {
1999                         khugepaged_scan.address = vma->vm_end;
2000                         progress++;
2001                         continue;
2002                 }
2003                 VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
2004
2005                 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2006                 hend = vma->vm_end & HPAGE_PMD_MASK;
2007                 if (hstart >= hend) {
2008                         progress++;
2009                         continue;
2010                 }
2011                 if (khugepaged_scan.address < hstart)
2012                         khugepaged_scan.address = hstart;
2013                 if (khugepaged_scan.address > hend) {
2014                         khugepaged_scan.address = hend + HPAGE_PMD_SIZE;
2015                         progress++;
2016                         continue;
2017                 }
2018                 BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2019
2020                 while (khugepaged_scan.address < hend) {
2021                         int ret;
2022                         cond_resched();
2023                         if (unlikely(khugepaged_test_exit(mm)))
2024                                 goto breakouterloop;
2025
2026                         VM_BUG_ON(khugepaged_scan.address < hstart ||
2027                                   khugepaged_scan.address + HPAGE_PMD_SIZE >
2028                                   hend);
2029                         ret = khugepaged_scan_pmd(mm, vma,
2030                                                   khugepaged_scan.address,
2031                                                   hpage);
2032                         /* move to next address */
2033                         khugepaged_scan.address += HPAGE_PMD_SIZE;
2034                         progress += HPAGE_PMD_NR;
2035                         if (ret)
2036                                 /* we released mmap_sem so break loop */
2037                                 goto breakouterloop_mmap_sem;
2038                         if (progress >= pages)
2039                                 goto breakouterloop;
2040                 }
2041         }
2042 breakouterloop:
2043         up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2044 breakouterloop_mmap_sem:
2045
2046         spin_lock(&khugepaged_mm_lock);
2047         BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2048         /*
2049          * Release the current mm_slot if this mm is about to die, or
2050          * if we scanned all vmas of this mm.
2051          */
2052         if (khugepaged_test_exit(mm) || !vma) {
2053                 /*
2054                  * Make sure that if mm_users is reaching zero while
2055                  * khugepaged runs here, khugepaged_exit will find
2056                  * mm_slot not pointing to the exiting mm.
2057                  */
2058                 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2059                         khugepaged_scan.mm_slot = list_entry(
2060                                 mm_slot->mm_node.next,
2061                                 struct mm_slot, mm_node);
2062                         khugepaged_scan.address = 0;
2063                 } else {
2064                         khugepaged_scan.mm_slot = NULL;
2065                         khugepaged_full_scans++;
2066                 }
2067
2068                 collect_mm_slot(mm_slot);
2069         }
2070
2071         return progress;
2072 }
2073
2074 static int khugepaged_has_work(void)
2075 {
2076         return !list_empty(&khugepaged_scan.mm_head) &&
2077                 khugepaged_enabled();
2078 }
2079
2080 static int khugepaged_wait_event(void)
2081 {
2082         return !list_empty(&khugepaged_scan.mm_head) ||
2083                 !khugepaged_enabled();
2084 }
2085
2086 static void khugepaged_do_scan(struct page **hpage)
2087 {
2088         unsigned int progress = 0, pass_through_head = 0;
2089         unsigned int pages = khugepaged_pages_to_scan;
2090
2091         barrier(); /* write khugepaged_pages_to_scan to local stack */
2092
2093         while (progress < pages) {
2094                 cond_resched();
2095
2096 #ifndef CONFIG_NUMA
2097                 if (!*hpage) {
2098                         *hpage = alloc_hugepage(khugepaged_defrag());
2099                         if (unlikely(!*hpage))
2100                                 break;
2101                 }
2102 #else
2103                 if (IS_ERR(*hpage))
2104                         break;
2105 #endif
2106
2107                 if (unlikely(kthread_should_stop() || freezing(current)))
2108                         break;
2109
2110                 spin_lock(&khugepaged_mm_lock);
2111                 if (!khugepaged_scan.mm_slot)
2112                         pass_through_head++;
2113                 if (khugepaged_has_work() &&
2114                     pass_through_head < 2)
2115                         progress += khugepaged_scan_mm_slot(pages - progress,
2116                                                             hpage);
2117                 else
2118                         progress = pages;
2119                 spin_unlock(&khugepaged_mm_lock);
2120         }
2121 }
2122
2123 static void khugepaged_alloc_sleep(void)
2124 {
2125         DEFINE_WAIT(wait);
2126         add_wait_queue(&khugepaged_wait, &wait);
2127         schedule_timeout_interruptible(
2128                 msecs_to_jiffies(
2129                         khugepaged_alloc_sleep_millisecs));
2130         remove_wait_queue(&khugepaged_wait, &wait);
2131 }
2132
2133 #ifndef CONFIG_NUMA
2134 static struct page *khugepaged_alloc_hugepage(void)
2135 {
2136         struct page *hpage;
2137
2138         do {
2139                 hpage = alloc_hugepage(khugepaged_defrag());
2140                 if (!hpage)
2141                         khugepaged_alloc_sleep();
2142         } while (unlikely(!hpage) &&
2143                  likely(khugepaged_enabled()));
2144         return hpage;
2145 }
2146 #endif
2147
2148 static void khugepaged_loop(void)
2149 {
2150         struct page *hpage;
2151
2152 #ifdef CONFIG_NUMA
2153         hpage = NULL;
2154 #endif
2155         while (likely(khugepaged_enabled())) {
2156 #ifndef CONFIG_NUMA
2157                 hpage = khugepaged_alloc_hugepage();
2158                 if (unlikely(!hpage))
2159                         break;
2160 #else
2161                 if (IS_ERR(hpage)) {
2162                         khugepaged_alloc_sleep();
2163                         hpage = NULL;
2164                 }
2165 #endif
2166
2167                 khugepaged_do_scan(&hpage);
2168 #ifndef CONFIG_NUMA
2169                 if (hpage)
2170                         put_page(hpage);
2171 #endif
2172                 try_to_freeze();
2173                 if (unlikely(kthread_should_stop()))
2174                         break;
2175                 if (khugepaged_has_work()) {
2176                         DEFINE_WAIT(wait);
2177                         if (!khugepaged_scan_sleep_millisecs)
2178                                 continue;
2179                         add_wait_queue(&khugepaged_wait, &wait);
2180                         schedule_timeout_interruptible(
2181                                 msecs_to_jiffies(
2182                                         khugepaged_scan_sleep_millisecs));
2183                         remove_wait_queue(&khugepaged_wait, &wait);
2184                 } else if (khugepaged_enabled())
2185                         wait_event_freezable(khugepaged_wait,
2186                                              khugepaged_wait_event());
2187         }
2188 }
2189
2190 static int khugepaged(void *none)
2191 {
2192         struct mm_slot *mm_slot;
2193
2194         set_freezable();
2195         set_user_nice(current, 19);
2196
2197         /* serialize with start_khugepaged() */
2198         mutex_lock(&khugepaged_mutex);
2199
2200         for (;;) {
2201                 mutex_unlock(&khugepaged_mutex);
2202                 BUG_ON(khugepaged_thread != current);
2203                 khugepaged_loop();
2204                 BUG_ON(khugepaged_thread != current);
2205
2206                 mutex_lock(&khugepaged_mutex);
2207                 if (!khugepaged_enabled())
2208                         break;
2209                 if (unlikely(kthread_should_stop()))
2210                         break;
2211         }
2212
2213         spin_lock(&khugepaged_mm_lock);
2214         mm_slot = khugepaged_scan.mm_slot;
2215         khugepaged_scan.mm_slot = NULL;
2216         if (mm_slot)
2217                 collect_mm_slot(mm_slot);
2218         spin_unlock(&khugepaged_mm_lock);
2219
2220         khugepaged_thread = NULL;
2221         mutex_unlock(&khugepaged_mutex);
2222
2223         return 0;
2224 }
2225
2226 void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2227 {
2228         struct page *page;
2229
2230         spin_lock(&mm->page_table_lock);
2231         if (unlikely(!pmd_trans_huge(*pmd))) {
2232                 spin_unlock(&mm->page_table_lock);
2233                 return;
2234         }
2235         page = pmd_page(*pmd);
2236         VM_BUG_ON(!page_count(page));
2237         get_page(page);
2238         spin_unlock(&mm->page_table_lock);
2239
2240         split_huge_page(page);
2241
2242         put_page(page);
2243         BUG_ON(pmd_trans_huge(*pmd));
2244 }
2245
2246 static void split_huge_page_address(struct mm_struct *mm,
2247                                     unsigned long address)
2248 {
2249         pgd_t *pgd;
2250         pud_t *pud;
2251         pmd_t *pmd;
2252
2253         VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
2254
2255         pgd = pgd_offset(mm, address);
2256         if (!pgd_present(*pgd))
2257                 return;
2258
2259         pud = pud_offset(pgd, address);
2260         if (!pud_present(*pud))
2261                 return;
2262
2263         pmd = pmd_offset(pud, address);
2264         if (!pmd_present(*pmd))
2265                 return;
2266         /*
2267          * Caller holds the mmap_sem write mode, so a huge pmd cannot
2268          * materialize from under us.
2269          */
2270         split_huge_page_pmd(mm, pmd);
2271 }
2272
2273 void __vma_adjust_trans_huge(struct vm_area_struct *vma,
2274                              unsigned long start,
2275                              unsigned long end,
2276                              long adjust_next)
2277 {
2278         /*
2279          * If the new start 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 (start & ~HPAGE_PMD_MASK &&
2284             (start & HPAGE_PMD_MASK) >= vma->vm_start &&
2285             (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2286                 split_huge_page_address(vma->vm_mm, start);
2287
2288         /*
2289          * If the new end address isn't hpage aligned and it could
2290          * previously contain an hugepage: check if we need to split
2291          * an huge pmd.
2292          */
2293         if (end & ~HPAGE_PMD_MASK &&
2294             (end & HPAGE_PMD_MASK) >= vma->vm_start &&
2295             (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2296                 split_huge_page_address(vma->vm_mm, end);
2297
2298         /*
2299          * If we're also updating the vma->vm_next->vm_start, if the new
2300          * vm_next->vm_start isn't page aligned and it could previously
2301          * contain an hugepage: check if we need to split an huge pmd.
2302          */
2303         if (adjust_next > 0) {
2304                 struct vm_area_struct *next = vma->vm_next;
2305                 unsigned long nstart = next->vm_start;
2306                 nstart += adjust_next << PAGE_SHIFT;
2307                 if (nstart & ~HPAGE_PMD_MASK &&
2308                     (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
2309                     (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
2310                         split_huge_page_address(next->vm_mm, nstart);
2311         }
2312 }