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