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