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