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