a47b45d8ff6418ee01da71936a998a8fb8d8e10d
[pandora-kernel.git] / mm / huge_memory.c
1 /*
2  *  Copyright (C) 2009  Red Hat, Inc.
3  *
4  *  This work is licensed under the terms of the GNU GPL, version 2. See
5  *  the COPYING file in the top-level directory.
6  */
7
8 #include <linux/mm.h>
9 #include <linux/sched.h>
10 #include <linux/highmem.h>
11 #include <linux/hugetlb.h>
12 #include <linux/mmu_notifier.h>
13 #include <linux/rmap.h>
14 #include <linux/swap.h>
15 #include <linux/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                 mm->nr_ptes++;
646                 spin_unlock(&mm->page_table_lock);
647         }
648
649         return ret;
650 }
651
652 static inline gfp_t alloc_hugepage_gfpmask(int defrag, gfp_t extra_gfp)
653 {
654         return (GFP_TRANSHUGE & ~(defrag ? 0 : __GFP_WAIT)) | extra_gfp;
655 }
656
657 static inline struct page *alloc_hugepage_vma(int defrag,
658                                               struct vm_area_struct *vma,
659                                               unsigned long haddr, int nd,
660                                               gfp_t extra_gfp)
661 {
662         return alloc_pages_vma(alloc_hugepage_gfpmask(defrag, extra_gfp),
663                                HPAGE_PMD_ORDER, vma, haddr, nd);
664 }
665
666 #ifndef CONFIG_NUMA
667 static inline struct page *alloc_hugepage(int defrag)
668 {
669         return alloc_pages(alloc_hugepage_gfpmask(defrag, 0),
670                            HPAGE_PMD_ORDER);
671 }
672 #endif
673
674 int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
675                                unsigned long address, pmd_t *pmd,
676                                unsigned int flags)
677 {
678         struct page *page;
679         unsigned long haddr = address & HPAGE_PMD_MASK;
680         pte_t *pte;
681
682         if (haddr >= vma->vm_start && haddr + HPAGE_PMD_SIZE <= vma->vm_end) {
683                 if (unlikely(anon_vma_prepare(vma)))
684                         return VM_FAULT_OOM;
685                 if (unlikely(khugepaged_enter(vma)))
686                         return VM_FAULT_OOM;
687                 page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
688                                           vma, haddr, numa_node_id(), 0);
689                 if (unlikely(!page)) {
690                         count_vm_event(THP_FAULT_FALLBACK);
691                         goto out;
692                 }
693                 count_vm_event(THP_FAULT_ALLOC);
694                 if (unlikely(mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))) {
695                         put_page(page);
696                         goto out;
697                 }
698
699                 return __do_huge_pmd_anonymous_page(mm, vma, haddr, pmd, page);
700         }
701 out:
702         /*
703          * Use __pte_alloc instead of pte_alloc_map, because we can't
704          * run pte_offset_map on the pmd, if an huge pmd could
705          * materialize from under us from a different thread.
706          */
707         if (unlikely(__pte_alloc(mm, vma, pmd, address)))
708                 return VM_FAULT_OOM;
709         /* if an huge pmd materialized from under us just retry later */
710         if (unlikely(pmd_trans_huge(*pmd)))
711                 return 0;
712         /*
713          * A regular pmd is established and it can't morph into a huge pmd
714          * from under us anymore at this point because we hold the mmap_sem
715          * read mode and khugepaged takes it in write mode. So now it's
716          * safe to run pte_offset_map().
717          */
718         pte = pte_offset_map(pmd, address);
719         return handle_pte_fault(mm, vma, address, pte, pmd, flags);
720 }
721
722 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
723                   pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
724                   struct vm_area_struct *vma)
725 {
726         struct page *src_page;
727         pmd_t pmd;
728         pgtable_t pgtable;
729         int ret;
730
731         ret = -ENOMEM;
732         pgtable = pte_alloc_one(dst_mm, addr);
733         if (unlikely(!pgtable))
734                 goto out;
735
736         spin_lock(&dst_mm->page_table_lock);
737         spin_lock_nested(&src_mm->page_table_lock, SINGLE_DEPTH_NESTING);
738
739         ret = -EAGAIN;
740         pmd = *src_pmd;
741         if (unlikely(!pmd_trans_huge(pmd))) {
742                 pte_free(dst_mm, pgtable);
743                 goto out_unlock;
744         }
745         if (unlikely(pmd_trans_splitting(pmd))) {
746                 /* split huge page running from under us */
747                 spin_unlock(&src_mm->page_table_lock);
748                 spin_unlock(&dst_mm->page_table_lock);
749                 pte_free(dst_mm, pgtable);
750
751                 wait_split_huge_page(vma->anon_vma, src_pmd); /* src_vma */
752                 goto out;
753         }
754         src_page = pmd_page(pmd);
755         VM_BUG_ON(!PageHead(src_page));
756         get_page(src_page);
757         page_dup_rmap(src_page);
758         add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
759
760         pmdp_set_wrprotect(src_mm, addr, src_pmd);
761         pmd = pmd_mkold(pmd_wrprotect(pmd));
762         set_pmd_at(dst_mm, addr, dst_pmd, pmd);
763         prepare_pmd_huge_pte(pgtable, dst_mm);
764         dst_mm->nr_ptes++;
765
766         ret = 0;
767 out_unlock:
768         spin_unlock(&src_mm->page_table_lock);
769         spin_unlock(&dst_mm->page_table_lock);
770 out:
771         return ret;
772 }
773
774 /* no "address" argument so destroys page coloring of some arch */
775 pgtable_t get_pmd_huge_pte(struct mm_struct *mm)
776 {
777         pgtable_t pgtable;
778
779         assert_spin_locked(&mm->page_table_lock);
780
781         /* FIFO */
782         pgtable = mm->pmd_huge_pte;
783         if (list_empty(&pgtable->lru))
784                 mm->pmd_huge_pte = NULL;
785         else {
786                 mm->pmd_huge_pte = list_entry(pgtable->lru.next,
787                                               struct page, lru);
788                 list_del(&pgtable->lru);
789         }
790         return pgtable;
791 }
792
793 static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
794                                         struct vm_area_struct *vma,
795                                         unsigned long address,
796                                         pmd_t *pmd, pmd_t orig_pmd,
797                                         struct page *page,
798                                         unsigned long haddr)
799 {
800         pgtable_t pgtable;
801         pmd_t _pmd;
802         int ret = 0, i;
803         struct page **pages;
804
805         pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
806                         GFP_KERNEL);
807         if (unlikely(!pages)) {
808                 ret |= VM_FAULT_OOM;
809                 goto out;
810         }
811
812         for (i = 0; i < HPAGE_PMD_NR; i++) {
813                 pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
814                                                __GFP_OTHER_NODE,
815                                                vma, address, page_to_nid(page));
816                 if (unlikely(!pages[i] ||
817                              mem_cgroup_newpage_charge(pages[i], mm,
818                                                        GFP_KERNEL))) {
819                         if (pages[i])
820                                 put_page(pages[i]);
821                         mem_cgroup_uncharge_start();
822                         while (--i >= 0) {
823                                 mem_cgroup_uncharge_page(pages[i]);
824                                 put_page(pages[i]);
825                         }
826                         mem_cgroup_uncharge_end();
827                         kfree(pages);
828                         ret |= VM_FAULT_OOM;
829                         goto out;
830                 }
831         }
832
833         for (i = 0; i < HPAGE_PMD_NR; i++) {
834                 copy_user_highpage(pages[i], page + i,
835                                    haddr + PAGE_SIZE * i, vma);
836                 __SetPageUptodate(pages[i]);
837                 cond_resched();
838         }
839
840         spin_lock(&mm->page_table_lock);
841         if (unlikely(!pmd_same(*pmd, orig_pmd)))
842                 goto out_free_pages;
843         VM_BUG_ON(!PageHead(page));
844
845         pmdp_clear_flush_notify(vma, haddr, pmd);
846         /* leave pmd empty until pte is filled */
847
848         pgtable = get_pmd_huge_pte(mm);
849         pmd_populate(mm, &_pmd, pgtable);
850
851         for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
852                 pte_t *pte, entry;
853                 entry = mk_pte(pages[i], vma->vm_page_prot);
854                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
855                 page_add_new_anon_rmap(pages[i], vma, haddr);
856                 pte = pte_offset_map(&_pmd, haddr);
857                 VM_BUG_ON(!pte_none(*pte));
858                 set_pte_at(mm, haddr, pte, entry);
859                 pte_unmap(pte);
860         }
861         kfree(pages);
862
863         smp_wmb(); /* make pte visible before pmd */
864         pmd_populate(mm, pmd, pgtable);
865         page_remove_rmap(page);
866         spin_unlock(&mm->page_table_lock);
867
868         ret |= VM_FAULT_WRITE;
869         put_page(page);
870
871 out:
872         return ret;
873
874 out_free_pages:
875         spin_unlock(&mm->page_table_lock);
876         mem_cgroup_uncharge_start();
877         for (i = 0; i < HPAGE_PMD_NR; i++) {
878                 mem_cgroup_uncharge_page(pages[i]);
879                 put_page(pages[i]);
880         }
881         mem_cgroup_uncharge_end();
882         kfree(pages);
883         goto out;
884 }
885
886 int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
887                         unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
888 {
889         int ret = 0;
890         struct page *page, *new_page;
891         unsigned long haddr;
892
893         VM_BUG_ON(!vma->anon_vma);
894         spin_lock(&mm->page_table_lock);
895         if (unlikely(!pmd_same(*pmd, orig_pmd)))
896                 goto out_unlock;
897
898         page = pmd_page(orig_pmd);
899         VM_BUG_ON(!PageCompound(page) || !PageHead(page));
900         haddr = address & HPAGE_PMD_MASK;
901         if (page_mapcount(page) == 1) {
902                 pmd_t entry;
903                 entry = pmd_mkyoung(orig_pmd);
904                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
905                 if (pmdp_set_access_flags(vma, haddr, pmd, entry,  1))
906                         update_mmu_cache(vma, address, pmd);
907                 ret |= VM_FAULT_WRITE;
908                 goto out_unlock;
909         }
910         get_page(page);
911         spin_unlock(&mm->page_table_lock);
912
913         if (transparent_hugepage_enabled(vma) &&
914             !transparent_hugepage_debug_cow())
915                 new_page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
916                                               vma, haddr, numa_node_id(), 0);
917         else
918                 new_page = NULL;
919
920         if (unlikely(!new_page)) {
921                 count_vm_event(THP_FAULT_FALLBACK);
922                 ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
923                                                    pmd, orig_pmd, page, haddr);
924                 if (ret & VM_FAULT_OOM)
925                         split_huge_page(page);
926                 put_page(page);
927                 goto out;
928         }
929         count_vm_event(THP_FAULT_ALLOC);
930
931         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
932                 put_page(new_page);
933                 split_huge_page(page);
934                 put_page(page);
935                 ret |= VM_FAULT_OOM;
936                 goto out;
937         }
938
939         copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
940         __SetPageUptodate(new_page);
941
942         spin_lock(&mm->page_table_lock);
943         put_page(page);
944         if (unlikely(!pmd_same(*pmd, orig_pmd))) {
945                 mem_cgroup_uncharge_page(new_page);
946                 put_page(new_page);
947         } else {
948                 pmd_t entry;
949                 VM_BUG_ON(!PageHead(page));
950                 entry = mk_pmd(new_page, vma->vm_page_prot);
951                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
952                 entry = pmd_mkhuge(entry);
953                 pmdp_clear_flush_notify(vma, haddr, pmd);
954                 page_add_new_anon_rmap(new_page, vma, haddr);
955                 set_pmd_at(mm, haddr, pmd, entry);
956                 update_mmu_cache(vma, address, pmd);
957                 page_remove_rmap(page);
958                 put_page(page);
959                 ret |= VM_FAULT_WRITE;
960         }
961 out_unlock:
962         spin_unlock(&mm->page_table_lock);
963 out:
964         return ret;
965 }
966
967 struct page *follow_trans_huge_pmd(struct mm_struct *mm,
968                                    unsigned long addr,
969                                    pmd_t *pmd,
970                                    unsigned int flags)
971 {
972         struct page *page = NULL;
973
974         assert_spin_locked(&mm->page_table_lock);
975
976         if (flags & FOLL_WRITE && !pmd_write(*pmd))
977                 goto out;
978
979         page = pmd_page(*pmd);
980         VM_BUG_ON(!PageHead(page));
981         if (flags & FOLL_TOUCH) {
982                 pmd_t _pmd;
983                 /*
984                  * We should set the dirty bit only for FOLL_WRITE but
985                  * for now the dirty bit in the pmd is meaningless.
986                  * And if the dirty bit will become meaningful and
987                  * we'll only set it with FOLL_WRITE, an atomic
988                  * set_bit will be required on the pmd to set the
989                  * young bit, instead of the current set_pmd_at.
990                  */
991                 _pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
992                 set_pmd_at(mm, addr & HPAGE_PMD_MASK, pmd, _pmd);
993         }
994         page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
995         VM_BUG_ON(!PageCompound(page));
996         if (flags & FOLL_GET)
997                 get_page_foll(page);
998
999 out:
1000         return page;
1001 }
1002
1003 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1004                  pmd_t *pmd)
1005 {
1006         int ret = 0;
1007
1008         spin_lock(&tlb->mm->page_table_lock);
1009         if (likely(pmd_trans_huge(*pmd))) {
1010                 if (unlikely(pmd_trans_splitting(*pmd))) {
1011                         spin_unlock(&tlb->mm->page_table_lock);
1012                         wait_split_huge_page(vma->anon_vma,
1013                                              pmd);
1014                 } else {
1015                         struct page *page;
1016                         pgtable_t pgtable;
1017                         pgtable = get_pmd_huge_pte(tlb->mm);
1018                         page = pmd_page(*pmd);
1019                         pmd_clear(pmd);
1020                         page_remove_rmap(page);
1021                         VM_BUG_ON(page_mapcount(page) < 0);
1022                         add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1023                         VM_BUG_ON(!PageHead(page));
1024                         tlb->mm->nr_ptes--;
1025                         spin_unlock(&tlb->mm->page_table_lock);
1026                         tlb_remove_page(tlb, page);
1027                         pte_free(tlb->mm, pgtable);
1028                         ret = 1;
1029                 }
1030         } else
1031                 spin_unlock(&tlb->mm->page_table_lock);
1032
1033         return ret;
1034 }
1035
1036 int mincore_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1037                 unsigned long addr, unsigned long end,
1038                 unsigned char *vec)
1039 {
1040         int ret = 0;
1041
1042         spin_lock(&vma->vm_mm->page_table_lock);
1043         if (likely(pmd_trans_huge(*pmd))) {
1044                 ret = !pmd_trans_splitting(*pmd);
1045                 spin_unlock(&vma->vm_mm->page_table_lock);
1046                 if (unlikely(!ret))
1047                         wait_split_huge_page(vma->anon_vma, pmd);
1048                 else {
1049                         /*
1050                          * All logical pages in the range are present
1051                          * if backed by a huge page.
1052                          */
1053                         memset(vec, 1, (end - addr) >> PAGE_SHIFT);
1054                 }
1055         } else
1056                 spin_unlock(&vma->vm_mm->page_table_lock);
1057
1058         return ret;
1059 }
1060
1061 int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1062                   unsigned long old_addr,
1063                   unsigned long new_addr, unsigned long old_end,
1064                   pmd_t *old_pmd, pmd_t *new_pmd)
1065 {
1066         int ret = 0;
1067         pmd_t pmd;
1068
1069         struct mm_struct *mm = vma->vm_mm;
1070
1071         if ((old_addr & ~HPAGE_PMD_MASK) ||
1072             (new_addr & ~HPAGE_PMD_MASK) ||
1073             old_end - old_addr < HPAGE_PMD_SIZE ||
1074             (new_vma->vm_flags & VM_NOHUGEPAGE))
1075                 goto out;
1076
1077         /*
1078          * The destination pmd shouldn't be established, free_pgtables()
1079          * should have release it.
1080          */
1081         if (WARN_ON(!pmd_none(*new_pmd))) {
1082                 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1083                 goto out;
1084         }
1085
1086         spin_lock(&mm->page_table_lock);
1087         if (likely(pmd_trans_huge(*old_pmd))) {
1088                 if (pmd_trans_splitting(*old_pmd)) {
1089                         spin_unlock(&mm->page_table_lock);
1090                         wait_split_huge_page(vma->anon_vma, old_pmd);
1091                         ret = -1;
1092                 } else {
1093                         pmd = pmdp_get_and_clear(mm, old_addr, old_pmd);
1094                         VM_BUG_ON(!pmd_none(*new_pmd));
1095                         set_pmd_at(mm, new_addr, new_pmd, pmd);
1096                         spin_unlock(&mm->page_table_lock);
1097                         ret = 1;
1098                 }
1099         } else {
1100                 spin_unlock(&mm->page_table_lock);
1101         }
1102 out:
1103         return ret;
1104 }
1105
1106 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1107                 unsigned long addr, pgprot_t newprot)
1108 {
1109         struct mm_struct *mm = vma->vm_mm;
1110         int ret = 0;
1111
1112         spin_lock(&mm->page_table_lock);
1113         if (likely(pmd_trans_huge(*pmd))) {
1114                 if (unlikely(pmd_trans_splitting(*pmd))) {
1115                         spin_unlock(&mm->page_table_lock);
1116                         wait_split_huge_page(vma->anon_vma, pmd);
1117                 } else {
1118                         pmd_t entry;
1119
1120                         entry = pmdp_get_and_clear(mm, addr, pmd);
1121                         entry = pmd_modify(entry, newprot);
1122                         set_pmd_at(mm, addr, pmd, entry);
1123                         spin_unlock(&vma->vm_mm->page_table_lock);
1124                         flush_tlb_range(vma, addr, addr + HPAGE_PMD_SIZE);
1125                         ret = 1;
1126                 }
1127         } else
1128                 spin_unlock(&vma->vm_mm->page_table_lock);
1129
1130         return ret;
1131 }
1132
1133 pmd_t *page_check_address_pmd(struct page *page,
1134                               struct mm_struct *mm,
1135                               unsigned long address,
1136                               enum page_check_address_pmd_flag flag)
1137 {
1138         pgd_t *pgd;
1139         pud_t *pud;
1140         pmd_t *pmd, *ret = NULL;
1141
1142         if (address & ~HPAGE_PMD_MASK)
1143                 goto out;
1144
1145         pgd = pgd_offset(mm, address);
1146         if (!pgd_present(*pgd))
1147                 goto out;
1148
1149         pud = pud_offset(pgd, address);
1150         if (!pud_present(*pud))
1151                 goto out;
1152
1153         pmd = pmd_offset(pud, address);
1154         if (pmd_none(*pmd))
1155                 goto out;
1156         if (pmd_page(*pmd) != page)
1157                 goto out;
1158         /*
1159          * split_vma() may create temporary aliased mappings. There is
1160          * no risk as long as all huge pmd are found and have their
1161          * splitting bit set before __split_huge_page_refcount
1162          * runs. Finding the same huge pmd more than once during the
1163          * same rmap walk is not a problem.
1164          */
1165         if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1166             pmd_trans_splitting(*pmd))
1167                 goto out;
1168         if (pmd_trans_huge(*pmd)) {
1169                 VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1170                           !pmd_trans_splitting(*pmd));
1171                 ret = pmd;
1172         }
1173 out:
1174         return ret;
1175 }
1176
1177 static int __split_huge_page_splitting(struct page *page,
1178                                        struct vm_area_struct *vma,
1179                                        unsigned long address)
1180 {
1181         struct mm_struct *mm = vma->vm_mm;
1182         pmd_t *pmd;
1183         int ret = 0;
1184
1185         spin_lock(&mm->page_table_lock);
1186         pmd = page_check_address_pmd(page, mm, address,
1187                                      PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
1188         if (pmd) {
1189                 /*
1190                  * We can't temporarily set the pmd to null in order
1191                  * to split it, the pmd must remain marked huge at all
1192                  * times or the VM won't take the pmd_trans_huge paths
1193                  * and it won't wait on the anon_vma->root->mutex to
1194                  * serialize against split_huge_page*.
1195                  */
1196                 pmdp_splitting_flush_notify(vma, address, pmd);
1197                 ret = 1;
1198         }
1199         spin_unlock(&mm->page_table_lock);
1200
1201         return ret;
1202 }
1203
1204 static void __split_huge_page_refcount(struct page *page)
1205 {
1206         int i;
1207         unsigned long head_index = page->index;
1208         struct zone *zone = page_zone(page);
1209         int zonestat;
1210         int tail_count = 0;
1211
1212         /* prevent PageLRU to go away from under us, and freeze lru stats */
1213         spin_lock_irq(&zone->lru_lock);
1214         compound_lock(page);
1215
1216         for (i = 1; i < HPAGE_PMD_NR; i++) {
1217                 struct page *page_tail = page + i;
1218
1219                 /* tail_page->_mapcount cannot change */
1220                 BUG_ON(page_mapcount(page_tail) < 0);
1221                 tail_count += page_mapcount(page_tail);
1222                 /* check for overflow */
1223                 BUG_ON(tail_count < 0);
1224                 BUG_ON(atomic_read(&page_tail->_count) != 0);
1225                 /*
1226                  * tail_page->_count is zero and not changing from
1227                  * under us. But get_page_unless_zero() may be running
1228                  * from under us on the tail_page. If we used
1229                  * atomic_set() below instead of atomic_add(), we
1230                  * would then run atomic_set() concurrently with
1231                  * get_page_unless_zero(), and atomic_set() is
1232                  * implemented in C not using locked ops. spin_unlock
1233                  * on x86 sometime uses locked ops because of PPro
1234                  * errata 66, 92, so unless somebody can guarantee
1235                  * atomic_set() here would be safe on all archs (and
1236                  * not only on x86), it's safer to use atomic_add().
1237                  */
1238                 atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1239                            &page_tail->_count);
1240
1241                 /* after clearing PageTail the gup refcount can be released */
1242                 smp_mb();
1243
1244                 /*
1245                  * retain hwpoison flag of the poisoned tail page:
1246                  *   fix for the unsuitable process killed on Guest Machine(KVM)
1247                  *   by the memory-failure.
1248                  */
1249                 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP | __PG_HWPOISON;
1250                 page_tail->flags |= (page->flags &
1251                                      ((1L << PG_referenced) |
1252                                       (1L << PG_swapbacked) |
1253                                       (1L << PG_mlocked) |
1254                                       (1L << PG_uptodate)));
1255                 page_tail->flags |= (1L << PG_dirty);
1256
1257                 /* clear PageTail before overwriting first_page */
1258                 smp_wmb();
1259
1260                 /*
1261                  * __split_huge_page_splitting() already set the
1262                  * splitting bit in all pmd that could map this
1263                  * hugepage, that will ensure no CPU can alter the
1264                  * mapcount on the head page. The mapcount is only
1265                  * accounted in the head page and it has to be
1266                  * transferred to all tail pages in the below code. So
1267                  * for this code to be safe, the split the mapcount
1268                  * can't change. But that doesn't mean userland can't
1269                  * keep changing and reading the page contents while
1270                  * we transfer the mapcount, so the pmd splitting
1271                  * status is achieved setting a reserved bit in the
1272                  * pmd, not by clearing the present bit.
1273                 */
1274                 page_tail->_mapcount = page->_mapcount;
1275
1276                 BUG_ON(page_tail->mapping);
1277                 page_tail->mapping = page->mapping;
1278
1279                 page_tail->index = ++head_index;
1280
1281                 BUG_ON(!PageAnon(page_tail));
1282                 BUG_ON(!PageUptodate(page_tail));
1283                 BUG_ON(!PageDirty(page_tail));
1284                 BUG_ON(!PageSwapBacked(page_tail));
1285
1286                 mem_cgroup_split_huge_fixup(page, page_tail);
1287
1288                 lru_add_page_tail(zone, page, page_tail);
1289         }
1290         atomic_sub(tail_count, &page->_count);
1291         BUG_ON(atomic_read(&page->_count) <= 0);
1292
1293         __dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
1294         __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1295
1296         /*
1297          * A hugepage counts for HPAGE_PMD_NR pages on the LRU statistics,
1298          * so adjust those appropriately if this page is on the LRU.
1299          */
1300         if (PageLRU(page)) {
1301                 zonestat = NR_LRU_BASE + page_lru(page);
1302                 __mod_zone_page_state(zone, zonestat, -(HPAGE_PMD_NR-1));
1303         }
1304
1305         ClearPageCompound(page);
1306         compound_unlock(page);
1307         spin_unlock_irq(&zone->lru_lock);
1308
1309         for (i = 1; i < HPAGE_PMD_NR; i++) {
1310                 struct page *page_tail = page + i;
1311                 BUG_ON(page_count(page_tail) <= 0);
1312                 /*
1313                  * Tail pages may be freed if there wasn't any mapping
1314                  * like if add_to_swap() is running on a lru page that
1315                  * had its mapping zapped. And freeing these pages
1316                  * requires taking the lru_lock so we do the put_page
1317                  * of the tail pages after the split is complete.
1318                  */
1319                 put_page(page_tail);
1320         }
1321
1322         /*
1323          * Only the head page (now become a regular page) is required
1324          * to be pinned by the caller.
1325          */
1326         BUG_ON(page_count(page) <= 0);
1327 }
1328
1329 static int __split_huge_page_map(struct page *page,
1330                                  struct vm_area_struct *vma,
1331                                  unsigned long address)
1332 {
1333         struct mm_struct *mm = vma->vm_mm;
1334         pmd_t *pmd, _pmd;
1335         int ret = 0, i;
1336         pgtable_t pgtable;
1337         unsigned long haddr;
1338
1339         spin_lock(&mm->page_table_lock);
1340         pmd = page_check_address_pmd(page, mm, address,
1341                                      PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1342         if (pmd) {
1343                 pgtable = get_pmd_huge_pte(mm);
1344                 pmd_populate(mm, &_pmd, pgtable);
1345
1346                 for (i = 0, haddr = address; i < HPAGE_PMD_NR;
1347                      i++, haddr += PAGE_SIZE) {
1348                         pte_t *pte, entry;
1349                         BUG_ON(PageCompound(page+i));
1350                         entry = mk_pte(page + i, vma->vm_page_prot);
1351                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1352                         if (!pmd_write(*pmd))
1353                                 entry = pte_wrprotect(entry);
1354                         else
1355                                 BUG_ON(page_mapcount(page) != 1);
1356                         if (!pmd_young(*pmd))
1357                                 entry = pte_mkold(entry);
1358                         pte = pte_offset_map(&_pmd, haddr);
1359                         BUG_ON(!pte_none(*pte));
1360                         set_pte_at(mm, haddr, pte, entry);
1361                         pte_unmap(pte);
1362                 }
1363
1364                 smp_wmb(); /* make pte visible before pmd */
1365                 /*
1366                  * Up to this point the pmd is present and huge and
1367                  * userland has the whole access to the hugepage
1368                  * during the split (which happens in place). If we
1369                  * overwrite the pmd with the not-huge version
1370                  * pointing to the pte here (which of course we could
1371                  * if all CPUs were bug free), userland could trigger
1372                  * a small page size TLB miss on the small sized TLB
1373                  * while the hugepage TLB entry is still established
1374                  * in the huge TLB. Some CPU doesn't like that. See
1375                  * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1376                  * Erratum 383 on page 93. Intel should be safe but is
1377                  * also warns that it's only safe if the permission
1378                  * and cache attributes of the two entries loaded in
1379                  * the two TLB is identical (which should be the case
1380                  * here). But it is generally safer to never allow
1381                  * small and huge TLB entries for the same virtual
1382                  * address to be loaded simultaneously. So instead of
1383                  * doing "pmd_populate(); flush_tlb_range();" we first
1384                  * mark the current pmd notpresent (atomically because
1385                  * here the pmd_trans_huge and pmd_trans_splitting
1386                  * must remain set at all times on the pmd until the
1387                  * split is complete for this pmd), then we flush the
1388                  * SMP TLB and finally we write the non-huge version
1389                  * of the pmd entry with pmd_populate.
1390                  */
1391                 set_pmd_at(mm, address, pmd, pmd_mknotpresent(*pmd));
1392                 flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
1393                 pmd_populate(mm, pmd, pgtable);
1394                 ret = 1;
1395         }
1396         spin_unlock(&mm->page_table_lock);
1397
1398         return ret;
1399 }
1400
1401 /* must be called with anon_vma->root->mutex hold */
1402 static void __split_huge_page(struct page *page,
1403                               struct anon_vma *anon_vma)
1404 {
1405         int mapcount, mapcount2;
1406         struct anon_vma_chain *avc;
1407
1408         BUG_ON(!PageHead(page));
1409         BUG_ON(PageTail(page));
1410
1411         mapcount = 0;
1412         list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1413                 struct vm_area_struct *vma = avc->vma;
1414                 unsigned long addr = vma_address(page, vma);
1415                 BUG_ON(is_vma_temporary_stack(vma));
1416                 if (addr == -EFAULT)
1417                         continue;
1418                 mapcount += __split_huge_page_splitting(page, vma, addr);
1419         }
1420         /*
1421          * It is critical that new vmas are added to the tail of the
1422          * anon_vma list. This guarantes that if copy_huge_pmd() runs
1423          * and establishes a child pmd before
1424          * __split_huge_page_splitting() freezes the parent pmd (so if
1425          * we fail to prevent copy_huge_pmd() from running until the
1426          * whole __split_huge_page() is complete), we will still see
1427          * the newly established pmd of the child later during the
1428          * walk, to be able to set it as pmd_trans_splitting too.
1429          */
1430         if (mapcount != page_mapcount(page))
1431                 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1432                        mapcount, page_mapcount(page));
1433         BUG_ON(mapcount != page_mapcount(page));
1434
1435         __split_huge_page_refcount(page);
1436
1437         mapcount2 = 0;
1438         list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1439                 struct vm_area_struct *vma = avc->vma;
1440                 unsigned long addr = vma_address(page, vma);
1441                 BUG_ON(is_vma_temporary_stack(vma));
1442                 if (addr == -EFAULT)
1443                         continue;
1444                 mapcount2 += __split_huge_page_map(page, vma, addr);
1445         }
1446         if (mapcount != mapcount2)
1447                 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1448                        mapcount, mapcount2, page_mapcount(page));
1449         BUG_ON(mapcount != mapcount2);
1450 }
1451
1452 int split_huge_page(struct page *page)
1453 {
1454         struct anon_vma *anon_vma;
1455         int ret = 1;
1456
1457         BUG_ON(!PageAnon(page));
1458         anon_vma = page_lock_anon_vma(page);
1459         if (!anon_vma)
1460                 goto out;
1461         ret = 0;
1462         if (!PageCompound(page))
1463                 goto out_unlock;
1464
1465         BUG_ON(!PageSwapBacked(page));
1466         __split_huge_page(page, anon_vma);
1467         count_vm_event(THP_SPLIT);
1468
1469         BUG_ON(PageCompound(page));
1470 out_unlock:
1471         page_unlock_anon_vma(anon_vma);
1472 out:
1473         return ret;
1474 }
1475
1476 #define VM_NO_THP (VM_SPECIAL|VM_INSERTPAGE|VM_MIXEDMAP|VM_SAO| \
1477                    VM_HUGETLB|VM_SHARED|VM_MAYSHARE)
1478
1479 int hugepage_madvise(struct vm_area_struct *vma,
1480                      unsigned long *vm_flags, int advice)
1481 {
1482         switch (advice) {
1483         case MADV_HUGEPAGE:
1484                 /*
1485                  * Be somewhat over-protective like KSM for now!
1486                  */
1487                 if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
1488                         return -EINVAL;
1489                 *vm_flags &= ~VM_NOHUGEPAGE;
1490                 *vm_flags |= VM_HUGEPAGE;
1491                 /*
1492                  * If the vma become good for khugepaged to scan,
1493                  * register it here without waiting a page fault that
1494                  * may not happen any time soon.
1495                  */
1496                 if (unlikely(khugepaged_enter_vma_merge(vma)))
1497                         return -ENOMEM;
1498                 break;
1499         case MADV_NOHUGEPAGE:
1500                 /*
1501                  * Be somewhat over-protective like KSM for now!
1502                  */
1503                 if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
1504                         return -EINVAL;
1505                 *vm_flags &= ~VM_HUGEPAGE;
1506                 *vm_flags |= VM_NOHUGEPAGE;
1507                 /*
1508                  * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1509                  * this vma even if we leave the mm registered in khugepaged if
1510                  * it got registered before VM_NOHUGEPAGE was set.
1511                  */
1512                 break;
1513         }
1514
1515         return 0;
1516 }
1517
1518 static int __init khugepaged_slab_init(void)
1519 {
1520         mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1521                                           sizeof(struct mm_slot),
1522                                           __alignof__(struct mm_slot), 0, NULL);
1523         if (!mm_slot_cache)
1524                 return -ENOMEM;
1525
1526         return 0;
1527 }
1528
1529 static void __init khugepaged_slab_free(void)
1530 {
1531         kmem_cache_destroy(mm_slot_cache);
1532         mm_slot_cache = NULL;
1533 }
1534
1535 static inline struct mm_slot *alloc_mm_slot(void)
1536 {
1537         if (!mm_slot_cache)     /* initialization failed */
1538                 return NULL;
1539         return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1540 }
1541
1542 static inline void free_mm_slot(struct mm_slot *mm_slot)
1543 {
1544         kmem_cache_free(mm_slot_cache, mm_slot);
1545 }
1546
1547 static int __init mm_slots_hash_init(void)
1548 {
1549         mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1550                                 GFP_KERNEL);
1551         if (!mm_slots_hash)
1552                 return -ENOMEM;
1553         return 0;
1554 }
1555
1556 #if 0
1557 static void __init mm_slots_hash_free(void)
1558 {
1559         kfree(mm_slots_hash);
1560         mm_slots_hash = NULL;
1561 }
1562 #endif
1563
1564 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1565 {
1566         struct mm_slot *mm_slot;
1567         struct hlist_head *bucket;
1568         struct hlist_node *node;
1569
1570         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1571                                 % MM_SLOTS_HASH_HEADS];
1572         hlist_for_each_entry(mm_slot, node, bucket, hash) {
1573                 if (mm == mm_slot->mm)
1574                         return mm_slot;
1575         }
1576         return NULL;
1577 }
1578
1579 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1580                                     struct mm_slot *mm_slot)
1581 {
1582         struct hlist_head *bucket;
1583
1584         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1585                                 % MM_SLOTS_HASH_HEADS];
1586         mm_slot->mm = mm;
1587         hlist_add_head(&mm_slot->hash, bucket);
1588 }
1589
1590 static inline int khugepaged_test_exit(struct mm_struct *mm)
1591 {
1592         return atomic_read(&mm->mm_users) == 0;
1593 }
1594
1595 int __khugepaged_enter(struct mm_struct *mm)
1596 {
1597         struct mm_slot *mm_slot;
1598         int wakeup;
1599
1600         mm_slot = alloc_mm_slot();
1601         if (!mm_slot)
1602                 return -ENOMEM;
1603
1604         /* __khugepaged_exit() must not run from under us */
1605         VM_BUG_ON(khugepaged_test_exit(mm));
1606         if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1607                 free_mm_slot(mm_slot);
1608                 return 0;
1609         }
1610
1611         spin_lock(&khugepaged_mm_lock);
1612         insert_to_mm_slots_hash(mm, mm_slot);
1613         /*
1614          * Insert just behind the scanning cursor, to let the area settle
1615          * down a little.
1616          */
1617         wakeup = list_empty(&khugepaged_scan.mm_head);
1618         list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1619         spin_unlock(&khugepaged_mm_lock);
1620
1621         atomic_inc(&mm->mm_count);
1622         if (wakeup)
1623                 wake_up_interruptible(&khugepaged_wait);
1624
1625         return 0;
1626 }
1627
1628 int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
1629 {
1630         unsigned long hstart, hend;
1631         if (!vma->anon_vma)
1632                 /*
1633                  * Not yet faulted in so we will register later in the
1634                  * page fault if needed.
1635                  */
1636                 return 0;
1637         if (vma->vm_ops)
1638                 /* khugepaged not yet working on file or special mappings */
1639                 return 0;
1640         /*
1641          * If is_pfn_mapping() is true is_learn_pfn_mapping() must be
1642          * true too, verify it here.
1643          */
1644         VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP);
1645         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1646         hend = vma->vm_end & HPAGE_PMD_MASK;
1647         if (hstart < hend)
1648                 return khugepaged_enter(vma);
1649         return 0;
1650 }
1651
1652 void __khugepaged_exit(struct mm_struct *mm)
1653 {
1654         struct mm_slot *mm_slot;
1655         int free = 0;
1656
1657         spin_lock(&khugepaged_mm_lock);
1658         mm_slot = get_mm_slot(mm);
1659         if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1660                 hlist_del(&mm_slot->hash);
1661                 list_del(&mm_slot->mm_node);
1662                 free = 1;
1663         }
1664         spin_unlock(&khugepaged_mm_lock);
1665
1666         if (free) {
1667                 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1668                 free_mm_slot(mm_slot);
1669                 mmdrop(mm);
1670         } else if (mm_slot) {
1671                 /*
1672                  * This is required to serialize against
1673                  * khugepaged_test_exit() (which is guaranteed to run
1674                  * under mmap sem read mode). Stop here (after we
1675                  * return all pagetables will be destroyed) until
1676                  * khugepaged has finished working on the pagetables
1677                  * under the mmap_sem.
1678                  */
1679                 down_write(&mm->mmap_sem);
1680                 up_write(&mm->mmap_sem);
1681         }
1682 }
1683
1684 static void release_pte_page(struct page *page)
1685 {
1686         /* 0 stands for page_is_file_cache(page) == false */
1687         dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1688         unlock_page(page);
1689         putback_lru_page(page);
1690 }
1691
1692 static void release_pte_pages(pte_t *pte, pte_t *_pte)
1693 {
1694         while (--_pte >= pte) {
1695                 pte_t pteval = *_pte;
1696                 if (!pte_none(pteval))
1697                         release_pte_page(pte_page(pteval));
1698         }
1699 }
1700
1701 static void release_all_pte_pages(pte_t *pte)
1702 {
1703         release_pte_pages(pte, pte + HPAGE_PMD_NR);
1704 }
1705
1706 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1707                                         unsigned long address,
1708                                         pte_t *pte)
1709 {
1710         struct page *page;
1711         pte_t *_pte;
1712         int referenced = 0, isolated = 0, none = 0;
1713         for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1714              _pte++, address += PAGE_SIZE) {
1715                 pte_t pteval = *_pte;
1716                 if (pte_none(pteval)) {
1717                         if (++none <= khugepaged_max_ptes_none)
1718                                 continue;
1719                         else {
1720                                 release_pte_pages(pte, _pte);
1721                                 goto out;
1722                         }
1723                 }
1724                 if (!pte_present(pteval) || !pte_write(pteval)) {
1725                         release_pte_pages(pte, _pte);
1726                         goto out;
1727                 }
1728                 page = vm_normal_page(vma, address, pteval);
1729                 if (unlikely(!page)) {
1730                         release_pte_pages(pte, _pte);
1731                         goto out;
1732                 }
1733                 VM_BUG_ON(PageCompound(page));
1734                 BUG_ON(!PageAnon(page));
1735                 VM_BUG_ON(!PageSwapBacked(page));
1736
1737                 /* cannot use mapcount: can't collapse if there's a gup pin */
1738                 if (page_count(page) != 1) {
1739                         release_pte_pages(pte, _pte);
1740                         goto out;
1741                 }
1742                 /*
1743                  * We can do it before isolate_lru_page because the
1744                  * page can't be freed from under us. NOTE: PG_lock
1745                  * is needed to serialize against split_huge_page
1746                  * when invoked from the VM.
1747                  */
1748                 if (!trylock_page(page)) {
1749                         release_pte_pages(pte, _pte);
1750                         goto out;
1751                 }
1752                 /*
1753                  * Isolate the page to avoid collapsing an hugepage
1754                  * currently in use by the VM.
1755                  */
1756                 if (isolate_lru_page(page)) {
1757                         unlock_page(page);
1758                         release_pte_pages(pte, _pte);
1759                         goto out;
1760                 }
1761                 /* 0 stands for page_is_file_cache(page) == false */
1762                 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1763                 VM_BUG_ON(!PageLocked(page));
1764                 VM_BUG_ON(PageLRU(page));
1765
1766                 /* If there is no mapped pte young don't collapse the page */
1767                 if (pte_young(pteval) || PageReferenced(page) ||
1768                     mmu_notifier_test_young(vma->vm_mm, address))
1769                         referenced = 1;
1770         }
1771         if (unlikely(!referenced))
1772                 release_all_pte_pages(pte);
1773         else
1774                 isolated = 1;
1775 out:
1776         return isolated;
1777 }
1778
1779 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1780                                       struct vm_area_struct *vma,
1781                                       unsigned long address,
1782                                       spinlock_t *ptl)
1783 {
1784         pte_t *_pte;
1785         for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1786                 pte_t pteval = *_pte;
1787                 struct page *src_page;
1788
1789                 if (pte_none(pteval)) {
1790                         clear_user_highpage(page, address);
1791                         add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1792                 } else {
1793                         src_page = pte_page(pteval);
1794                         copy_user_highpage(page, src_page, address, vma);
1795                         VM_BUG_ON(page_mapcount(src_page) != 1);
1796                         VM_BUG_ON(page_count(src_page) != 2);
1797                         release_pte_page(src_page);
1798                         /*
1799                          * ptl mostly unnecessary, but preempt has to
1800                          * be disabled to update the per-cpu stats
1801                          * inside page_remove_rmap().
1802                          */
1803                         spin_lock(ptl);
1804                         /*
1805                          * paravirt calls inside pte_clear here are
1806                          * superfluous.
1807                          */
1808                         pte_clear(vma->vm_mm, address, _pte);
1809                         page_remove_rmap(src_page);
1810                         spin_unlock(ptl);
1811                         free_page_and_swap_cache(src_page);
1812                 }
1813
1814                 address += PAGE_SIZE;
1815                 page++;
1816         }
1817 }
1818
1819 static void collapse_huge_page(struct mm_struct *mm,
1820                                unsigned long address,
1821                                struct page **hpage,
1822                                struct vm_area_struct *vma,
1823                                int node)
1824 {
1825         pgd_t *pgd;
1826         pud_t *pud;
1827         pmd_t *pmd, _pmd;
1828         pte_t *pte;
1829         pgtable_t pgtable;
1830         struct page *new_page;
1831         spinlock_t *ptl;
1832         int isolated;
1833         unsigned long hstart, hend;
1834
1835         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1836 #ifndef CONFIG_NUMA
1837         up_read(&mm->mmap_sem);
1838         VM_BUG_ON(!*hpage);
1839         new_page = *hpage;
1840 #else
1841         VM_BUG_ON(*hpage);
1842         /*
1843          * Allocate the page while the vma is still valid and under
1844          * the mmap_sem read mode so there is no memory allocation
1845          * later when we take the mmap_sem in write mode. This is more
1846          * friendly behavior (OTOH it may actually hide bugs) to
1847          * filesystems in userland with daemons allocating memory in
1848          * the userland I/O paths.  Allocating memory with the
1849          * mmap_sem in read mode is good idea also to allow greater
1850          * scalability.
1851          */
1852         new_page = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
1853                                       node, __GFP_OTHER_NODE);
1854
1855         /*
1856          * After allocating the hugepage, release the mmap_sem read lock in
1857          * preparation for taking it in write mode.
1858          */
1859         up_read(&mm->mmap_sem);
1860         if (unlikely(!new_page)) {
1861                 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1862                 *hpage = ERR_PTR(-ENOMEM);
1863                 return;
1864         }
1865 #endif
1866
1867         count_vm_event(THP_COLLAPSE_ALLOC);
1868         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
1869 #ifdef CONFIG_NUMA
1870                 put_page(new_page);
1871 #endif
1872                 return;
1873         }
1874
1875         /*
1876          * Prevent all access to pagetables with the exception of
1877          * gup_fast later hanlded by the ptep_clear_flush and the VM
1878          * handled by the anon_vma lock + PG_lock.
1879          */
1880         down_write(&mm->mmap_sem);
1881         if (unlikely(khugepaged_test_exit(mm)))
1882                 goto out;
1883
1884         vma = find_vma(mm, address);
1885         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1886         hend = vma->vm_end & HPAGE_PMD_MASK;
1887         if (address < hstart || address + HPAGE_PMD_SIZE > hend)
1888                 goto out;
1889
1890         if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
1891             (vma->vm_flags & VM_NOHUGEPAGE))
1892                 goto out;
1893
1894         if (!vma->anon_vma || vma->vm_ops)
1895                 goto out;
1896         if (is_vma_temporary_stack(vma))
1897                 goto out;
1898         /*
1899          * If is_pfn_mapping() is true is_learn_pfn_mapping() must be
1900          * true too, verify it here.
1901          */
1902         VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP);
1903
1904         pgd = pgd_offset(mm, address);
1905         if (!pgd_present(*pgd))
1906                 goto out;
1907
1908         pud = pud_offset(pgd, address);
1909         if (!pud_present(*pud))
1910                 goto out;
1911
1912         pmd = pmd_offset(pud, address);
1913         /* pmd can't go away or become huge under us */
1914         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
1915                 goto out;
1916
1917         anon_vma_lock(vma->anon_vma);
1918
1919         pte = pte_offset_map(pmd, address);
1920         ptl = pte_lockptr(mm, pmd);
1921
1922         spin_lock(&mm->page_table_lock); /* probably unnecessary */
1923         /*
1924          * After this gup_fast can't run anymore. This also removes
1925          * any huge TLB entry from the CPU so we won't allow
1926          * huge and small TLB entries for the same virtual address
1927          * to avoid the risk of CPU bugs in that area.
1928          */
1929         _pmd = pmdp_clear_flush_notify(vma, address, pmd);
1930         spin_unlock(&mm->page_table_lock);
1931
1932         spin_lock(ptl);
1933         isolated = __collapse_huge_page_isolate(vma, address, pte);
1934         spin_unlock(ptl);
1935
1936         if (unlikely(!isolated)) {
1937                 pte_unmap(pte);
1938                 spin_lock(&mm->page_table_lock);
1939                 BUG_ON(!pmd_none(*pmd));
1940                 set_pmd_at(mm, address, pmd, _pmd);
1941                 spin_unlock(&mm->page_table_lock);
1942                 anon_vma_unlock(vma->anon_vma);
1943                 goto out;
1944         }
1945
1946         /*
1947          * All pages are isolated and locked so anon_vma rmap
1948          * can't run anymore.
1949          */
1950         anon_vma_unlock(vma->anon_vma);
1951
1952         __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
1953         pte_unmap(pte);
1954         __SetPageUptodate(new_page);
1955         pgtable = pmd_pgtable(_pmd);
1956         VM_BUG_ON(page_count(pgtable) != 1);
1957         VM_BUG_ON(page_mapcount(pgtable) != 0);
1958
1959         _pmd = mk_pmd(new_page, vma->vm_page_prot);
1960         _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1961         _pmd = pmd_mkhuge(_pmd);
1962
1963         /*
1964          * spin_lock() below is not the equivalent of smp_wmb(), so
1965          * this is needed to avoid the copy_huge_page writes to become
1966          * visible after the set_pmd_at() write.
1967          */
1968         smp_wmb();
1969
1970         spin_lock(&mm->page_table_lock);
1971         BUG_ON(!pmd_none(*pmd));
1972         page_add_new_anon_rmap(new_page, vma, address);
1973         set_pmd_at(mm, address, pmd, _pmd);
1974         update_mmu_cache(vma, address, pmd);
1975         prepare_pmd_huge_pte(pgtable, mm);
1976         spin_unlock(&mm->page_table_lock);
1977
1978 #ifndef CONFIG_NUMA
1979         *hpage = NULL;
1980 #endif
1981         khugepaged_pages_collapsed++;
1982 out_up_write:
1983         up_write(&mm->mmap_sem);
1984         return;
1985
1986 out:
1987         mem_cgroup_uncharge_page(new_page);
1988 #ifdef CONFIG_NUMA
1989         put_page(new_page);
1990 #endif
1991         goto out_up_write;
1992 }
1993
1994 static int khugepaged_scan_pmd(struct mm_struct *mm,
1995                                struct vm_area_struct *vma,
1996                                unsigned long address,
1997                                struct page **hpage)
1998 {
1999         pgd_t *pgd;
2000         pud_t *pud;
2001         pmd_t *pmd;
2002         pte_t *pte, *_pte;
2003         int ret = 0, referenced = 0, none = 0;
2004         struct page *page;
2005         unsigned long _address;
2006         spinlock_t *ptl;
2007         int node = -1;
2008
2009         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2010
2011         pgd = pgd_offset(mm, address);
2012         if (!pgd_present(*pgd))
2013                 goto out;
2014
2015         pud = pud_offset(pgd, address);
2016         if (!pud_present(*pud))
2017                 goto out;
2018
2019         pmd = pmd_offset(pud, address);
2020         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
2021                 goto out;
2022
2023         pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2024         for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2025              _pte++, _address += PAGE_SIZE) {
2026                 pte_t pteval = *_pte;
2027                 if (pte_none(pteval)) {
2028                         if (++none <= khugepaged_max_ptes_none)
2029                                 continue;
2030                         else
2031                                 goto out_unmap;
2032                 }
2033                 if (!pte_present(pteval) || !pte_write(pteval))
2034                         goto out_unmap;
2035                 page = vm_normal_page(vma, _address, pteval);
2036                 if (unlikely(!page))
2037                         goto out_unmap;
2038                 /*
2039                  * Chose the node of the first page. This could
2040                  * be more sophisticated and look at more pages,
2041                  * but isn't for now.
2042                  */
2043                 if (node == -1)
2044                         node = page_to_nid(page);
2045                 VM_BUG_ON(PageCompound(page));
2046                 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2047                         goto out_unmap;
2048                 /* cannot use mapcount: can't collapse if there's a gup pin */
2049                 if (page_count(page) != 1)
2050                         goto out_unmap;
2051                 if (pte_young(pteval) || PageReferenced(page) ||
2052                     mmu_notifier_test_young(vma->vm_mm, address))
2053                         referenced = 1;
2054         }
2055         if (referenced)
2056                 ret = 1;
2057 out_unmap:
2058         pte_unmap_unlock(pte, ptl);
2059         if (ret)
2060                 /* collapse_huge_page will return with the mmap_sem released */
2061                 collapse_huge_page(mm, address, hpage, vma, node);
2062 out:
2063         return ret;
2064 }
2065
2066 static void collect_mm_slot(struct mm_slot *mm_slot)
2067 {
2068         struct mm_struct *mm = mm_slot->mm;
2069
2070         VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2071
2072         if (khugepaged_test_exit(mm)) {
2073                 /* free mm_slot */
2074                 hlist_del(&mm_slot->hash);
2075                 list_del(&mm_slot->mm_node);
2076
2077                 /*
2078                  * Not strictly needed because the mm exited already.
2079                  *
2080                  * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2081                  */
2082
2083                 /* khugepaged_mm_lock actually not necessary for the below */
2084                 free_mm_slot(mm_slot);
2085                 mmdrop(mm);
2086         }
2087 }
2088
2089 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2090                                             struct page **hpage)
2091         __releases(&khugepaged_mm_lock)
2092         __acquires(&khugepaged_mm_lock)
2093 {
2094         struct mm_slot *mm_slot;
2095         struct mm_struct *mm;
2096         struct vm_area_struct *vma;
2097         int progress = 0;
2098
2099         VM_BUG_ON(!pages);
2100         VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2101
2102         if (khugepaged_scan.mm_slot)
2103                 mm_slot = khugepaged_scan.mm_slot;
2104         else {
2105                 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2106                                      struct mm_slot, mm_node);
2107                 khugepaged_scan.address = 0;
2108                 khugepaged_scan.mm_slot = mm_slot;
2109         }
2110         spin_unlock(&khugepaged_mm_lock);
2111
2112         mm = mm_slot->mm;
2113         down_read(&mm->mmap_sem);
2114         if (unlikely(khugepaged_test_exit(mm)))
2115                 vma = NULL;
2116         else
2117                 vma = find_vma(mm, khugepaged_scan.address);
2118
2119         progress++;
2120         for (; vma; vma = vma->vm_next) {
2121                 unsigned long hstart, hend;
2122
2123                 cond_resched();
2124                 if (unlikely(khugepaged_test_exit(mm))) {
2125                         progress++;
2126                         break;
2127                 }
2128
2129                 if ((!(vma->vm_flags & VM_HUGEPAGE) &&
2130                      !khugepaged_always()) ||
2131                     (vma->vm_flags & VM_NOHUGEPAGE)) {
2132                 skip:
2133                         progress++;
2134                         continue;
2135                 }
2136                 if (!vma->anon_vma || vma->vm_ops)
2137                         goto skip;
2138                 if (is_vma_temporary_stack(vma))
2139                         goto skip;
2140                 /*
2141                  * If is_pfn_mapping() is true is_learn_pfn_mapping()
2142                  * must be true too, verify it here.
2143                  */
2144                 VM_BUG_ON(is_linear_pfn_mapping(vma) ||
2145                           vma->vm_flags & VM_NO_THP);
2146
2147                 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2148                 hend = vma->vm_end & HPAGE_PMD_MASK;
2149                 if (hstart >= hend)
2150                         goto skip;
2151                 if (khugepaged_scan.address > hend)
2152                         goto skip;
2153                 if (khugepaged_scan.address < hstart)
2154                         khugepaged_scan.address = hstart;
2155                 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2156
2157                 while (khugepaged_scan.address < hend) {
2158                         int ret;
2159                         cond_resched();
2160                         if (unlikely(khugepaged_test_exit(mm)))
2161                                 goto breakouterloop;
2162
2163                         VM_BUG_ON(khugepaged_scan.address < hstart ||
2164                                   khugepaged_scan.address + HPAGE_PMD_SIZE >
2165                                   hend);
2166                         ret = khugepaged_scan_pmd(mm, vma,
2167                                                   khugepaged_scan.address,
2168                                                   hpage);
2169                         /* move to next address */
2170                         khugepaged_scan.address += HPAGE_PMD_SIZE;
2171                         progress += HPAGE_PMD_NR;
2172                         if (ret)
2173                                 /* we released mmap_sem so break loop */
2174                                 goto breakouterloop_mmap_sem;
2175                         if (progress >= pages)
2176                                 goto breakouterloop;
2177                 }
2178         }
2179 breakouterloop:
2180         up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2181 breakouterloop_mmap_sem:
2182
2183         spin_lock(&khugepaged_mm_lock);
2184         VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2185         /*
2186          * Release the current mm_slot if this mm is about to die, or
2187          * if we scanned all vmas of this mm.
2188          */
2189         if (khugepaged_test_exit(mm) || !vma) {
2190                 /*
2191                  * Make sure that if mm_users is reaching zero while
2192                  * khugepaged runs here, khugepaged_exit will find
2193                  * mm_slot not pointing to the exiting mm.
2194                  */
2195                 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2196                         khugepaged_scan.mm_slot = list_entry(
2197                                 mm_slot->mm_node.next,
2198                                 struct mm_slot, mm_node);
2199                         khugepaged_scan.address = 0;
2200                 } else {
2201                         khugepaged_scan.mm_slot = NULL;
2202                         khugepaged_full_scans++;
2203                 }
2204
2205                 collect_mm_slot(mm_slot);
2206         }
2207
2208         return progress;
2209 }
2210
2211 static int khugepaged_has_work(void)
2212 {
2213         return !list_empty(&khugepaged_scan.mm_head) &&
2214                 khugepaged_enabled();
2215 }
2216
2217 static int khugepaged_wait_event(void)
2218 {
2219         return !list_empty(&khugepaged_scan.mm_head) ||
2220                 !khugepaged_enabled();
2221 }
2222
2223 static void khugepaged_do_scan(struct page **hpage)
2224 {
2225         unsigned int progress = 0, pass_through_head = 0;
2226         unsigned int pages = khugepaged_pages_to_scan;
2227
2228         barrier(); /* write khugepaged_pages_to_scan to local stack */
2229
2230         while (progress < pages) {
2231                 cond_resched();
2232
2233 #ifndef CONFIG_NUMA
2234                 if (!*hpage) {
2235                         *hpage = alloc_hugepage(khugepaged_defrag());
2236                         if (unlikely(!*hpage)) {
2237                                 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2238                                 break;
2239                         }
2240                         count_vm_event(THP_COLLAPSE_ALLOC);
2241                 }
2242 #else
2243                 if (IS_ERR(*hpage))
2244                         break;
2245 #endif
2246
2247                 if (unlikely(kthread_should_stop() || freezing(current)))
2248                         break;
2249
2250                 spin_lock(&khugepaged_mm_lock);
2251                 if (!khugepaged_scan.mm_slot)
2252                         pass_through_head++;
2253                 if (khugepaged_has_work() &&
2254                     pass_through_head < 2)
2255                         progress += khugepaged_scan_mm_slot(pages - progress,
2256                                                             hpage);
2257                 else
2258                         progress = pages;
2259                 spin_unlock(&khugepaged_mm_lock);
2260         }
2261 }
2262
2263 static void khugepaged_alloc_sleep(void)
2264 {
2265         wait_event_freezable_timeout(khugepaged_wait, false,
2266                         msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
2267 }
2268
2269 #ifndef CONFIG_NUMA
2270 static struct page *khugepaged_alloc_hugepage(void)
2271 {
2272         struct page *hpage;
2273
2274         do {
2275                 hpage = alloc_hugepage(khugepaged_defrag());
2276                 if (!hpage) {
2277                         count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2278                         khugepaged_alloc_sleep();
2279                 } else
2280                         count_vm_event(THP_COLLAPSE_ALLOC);
2281         } while (unlikely(!hpage) &&
2282                  likely(khugepaged_enabled()));
2283         return hpage;
2284 }
2285 #endif
2286
2287 static void khugepaged_loop(void)
2288 {
2289         struct page *hpage;
2290
2291 #ifdef CONFIG_NUMA
2292         hpage = NULL;
2293 #endif
2294         while (likely(khugepaged_enabled())) {
2295 #ifndef CONFIG_NUMA
2296                 hpage = khugepaged_alloc_hugepage();
2297                 if (unlikely(!hpage))
2298                         break;
2299 #else
2300                 if (IS_ERR(hpage)) {
2301                         khugepaged_alloc_sleep();
2302                         hpage = NULL;
2303                 }
2304 #endif
2305
2306                 khugepaged_do_scan(&hpage);
2307 #ifndef CONFIG_NUMA
2308                 if (hpage)
2309                         put_page(hpage);
2310 #endif
2311                 try_to_freeze();
2312                 if (unlikely(kthread_should_stop()))
2313                         break;
2314                 if (khugepaged_has_work()) {
2315                         if (!khugepaged_scan_sleep_millisecs)
2316                                 continue;
2317                         wait_event_freezable_timeout(khugepaged_wait, false,
2318                             msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2319                 } else if (khugepaged_enabled())
2320                         wait_event_freezable(khugepaged_wait,
2321                                              khugepaged_wait_event());
2322         }
2323 }
2324
2325 static int khugepaged(void *none)
2326 {
2327         struct mm_slot *mm_slot;
2328
2329         set_freezable();
2330         set_user_nice(current, 19);
2331
2332         /* serialize with start_khugepaged() */
2333         mutex_lock(&khugepaged_mutex);
2334
2335         for (;;) {
2336                 mutex_unlock(&khugepaged_mutex);
2337                 VM_BUG_ON(khugepaged_thread != current);
2338                 khugepaged_loop();
2339                 VM_BUG_ON(khugepaged_thread != current);
2340
2341                 mutex_lock(&khugepaged_mutex);
2342                 if (!khugepaged_enabled())
2343                         break;
2344                 if (unlikely(kthread_should_stop()))
2345                         break;
2346         }
2347
2348         spin_lock(&khugepaged_mm_lock);
2349         mm_slot = khugepaged_scan.mm_slot;
2350         khugepaged_scan.mm_slot = NULL;
2351         if (mm_slot)
2352                 collect_mm_slot(mm_slot);
2353         spin_unlock(&khugepaged_mm_lock);
2354
2355         khugepaged_thread = NULL;
2356         mutex_unlock(&khugepaged_mutex);
2357
2358         return 0;
2359 }
2360
2361 void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2362 {
2363         struct page *page;
2364
2365         spin_lock(&mm->page_table_lock);
2366         if (unlikely(!pmd_trans_huge(*pmd))) {
2367                 spin_unlock(&mm->page_table_lock);
2368                 return;
2369         }
2370         page = pmd_page(*pmd);
2371         VM_BUG_ON(!page_count(page));
2372         get_page(page);
2373         spin_unlock(&mm->page_table_lock);
2374
2375         split_huge_page(page);
2376
2377         put_page(page);
2378         BUG_ON(pmd_trans_huge(*pmd));
2379 }
2380
2381 static void split_huge_page_address(struct mm_struct *mm,
2382                                     unsigned long address)
2383 {
2384         pgd_t *pgd;
2385         pud_t *pud;
2386         pmd_t *pmd;
2387
2388         VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
2389
2390         pgd = pgd_offset(mm, address);
2391         if (!pgd_present(*pgd))
2392                 return;
2393
2394         pud = pud_offset(pgd, address);
2395         if (!pud_present(*pud))
2396                 return;
2397
2398         pmd = pmd_offset(pud, address);
2399         if (!pmd_present(*pmd))
2400                 return;
2401         /*
2402          * Caller holds the mmap_sem write mode, so a huge pmd cannot
2403          * materialize from under us.
2404          */
2405         split_huge_page_pmd(mm, pmd);
2406 }
2407
2408 void __vma_adjust_trans_huge(struct vm_area_struct *vma,
2409                              unsigned long start,
2410                              unsigned long end,
2411                              long adjust_next)
2412 {
2413         /*
2414          * If the new start 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 (start & ~HPAGE_PMD_MASK &&
2419             (start & HPAGE_PMD_MASK) >= vma->vm_start &&
2420             (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2421                 split_huge_page_address(vma->vm_mm, start);
2422
2423         /*
2424          * If the new end address isn't hpage aligned and it could
2425          * previously contain an hugepage: check if we need to split
2426          * an huge pmd.
2427          */
2428         if (end & ~HPAGE_PMD_MASK &&
2429             (end & HPAGE_PMD_MASK) >= vma->vm_start &&
2430             (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2431                 split_huge_page_address(vma->vm_mm, end);
2432
2433         /*
2434          * If we're also updating the vma->vm_next->vm_start, if the new
2435          * vm_next->vm_start isn't page aligned and it could previously
2436          * contain an hugepage: check if we need to split an huge pmd.
2437          */
2438         if (adjust_next > 0) {
2439                 struct vm_area_struct *next = vma->vm_next;
2440                 unsigned long nstart = next->vm_start;
2441                 nstart += adjust_next << PAGE_SHIFT;
2442                 if (nstart & ~HPAGE_PMD_MASK &&
2443                     (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
2444                     (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
2445                         split_huge_page_address(next->vm_mm, nstart);
2446         }
2447 }