thp: mincore transparent hugepage support
[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 pmd_t *page_check_address_pmd(struct page *page,
952                               struct mm_struct *mm,
953                               unsigned long address,
954                               enum page_check_address_pmd_flag flag)
955 {
956         pgd_t *pgd;
957         pud_t *pud;
958         pmd_t *pmd, *ret = NULL;
959
960         if (address & ~HPAGE_PMD_MASK)
961                 goto out;
962
963         pgd = pgd_offset(mm, address);
964         if (!pgd_present(*pgd))
965                 goto out;
966
967         pud = pud_offset(pgd, address);
968         if (!pud_present(*pud))
969                 goto out;
970
971         pmd = pmd_offset(pud, address);
972         if (pmd_none(*pmd))
973                 goto out;
974         if (pmd_page(*pmd) != page)
975                 goto out;
976         VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
977                   pmd_trans_splitting(*pmd));
978         if (pmd_trans_huge(*pmd)) {
979                 VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
980                           !pmd_trans_splitting(*pmd));
981                 ret = pmd;
982         }
983 out:
984         return ret;
985 }
986
987 static int __split_huge_page_splitting(struct page *page,
988                                        struct vm_area_struct *vma,
989                                        unsigned long address)
990 {
991         struct mm_struct *mm = vma->vm_mm;
992         pmd_t *pmd;
993         int ret = 0;
994
995         spin_lock(&mm->page_table_lock);
996         pmd = page_check_address_pmd(page, mm, address,
997                                      PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
998         if (pmd) {
999                 /*
1000                  * We can't temporarily set the pmd to null in order
1001                  * to split it, the pmd must remain marked huge at all
1002                  * times or the VM won't take the pmd_trans_huge paths
1003                  * and it won't wait on the anon_vma->root->lock to
1004                  * serialize against split_huge_page*.
1005                  */
1006                 pmdp_splitting_flush_notify(vma, address, pmd);
1007                 ret = 1;
1008         }
1009         spin_unlock(&mm->page_table_lock);
1010
1011         return ret;
1012 }
1013
1014 static void __split_huge_page_refcount(struct page *page)
1015 {
1016         int i;
1017         unsigned long head_index = page->index;
1018         struct zone *zone = page_zone(page);
1019
1020         /* prevent PageLRU to go away from under us, and freeze lru stats */
1021         spin_lock_irq(&zone->lru_lock);
1022         compound_lock(page);
1023
1024         for (i = 1; i < HPAGE_PMD_NR; i++) {
1025                 struct page *page_tail = page + i;
1026
1027                 /* tail_page->_count cannot change */
1028                 atomic_sub(atomic_read(&page_tail->_count), &page->_count);
1029                 BUG_ON(page_count(page) <= 0);
1030                 atomic_add(page_mapcount(page) + 1, &page_tail->_count);
1031                 BUG_ON(atomic_read(&page_tail->_count) <= 0);
1032
1033                 /* after clearing PageTail the gup refcount can be released */
1034                 smp_mb();
1035
1036                 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1037                 page_tail->flags |= (page->flags &
1038                                      ((1L << PG_referenced) |
1039                                       (1L << PG_swapbacked) |
1040                                       (1L << PG_mlocked) |
1041                                       (1L << PG_uptodate)));
1042                 page_tail->flags |= (1L << PG_dirty);
1043
1044                 /*
1045                  * 1) clear PageTail before overwriting first_page
1046                  * 2) clear PageTail before clearing PageHead for VM_BUG_ON
1047                  */
1048                 smp_wmb();
1049
1050                 /*
1051                  * __split_huge_page_splitting() already set the
1052                  * splitting bit in all pmd that could map this
1053                  * hugepage, that will ensure no CPU can alter the
1054                  * mapcount on the head page. The mapcount is only
1055                  * accounted in the head page and it has to be
1056                  * transferred to all tail pages in the below code. So
1057                  * for this code to be safe, the split the mapcount
1058                  * can't change. But that doesn't mean userland can't
1059                  * keep changing and reading the page contents while
1060                  * we transfer the mapcount, so the pmd splitting
1061                  * status is achieved setting a reserved bit in the
1062                  * pmd, not by clearing the present bit.
1063                 */
1064                 BUG_ON(page_mapcount(page_tail));
1065                 page_tail->_mapcount = page->_mapcount;
1066
1067                 BUG_ON(page_tail->mapping);
1068                 page_tail->mapping = page->mapping;
1069
1070                 page_tail->index = ++head_index;
1071
1072                 BUG_ON(!PageAnon(page_tail));
1073                 BUG_ON(!PageUptodate(page_tail));
1074                 BUG_ON(!PageDirty(page_tail));
1075                 BUG_ON(!PageSwapBacked(page_tail));
1076
1077                 lru_add_page_tail(zone, page, page_tail);
1078         }
1079
1080         __dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
1081         __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1082
1083         ClearPageCompound(page);
1084         compound_unlock(page);
1085         spin_unlock_irq(&zone->lru_lock);
1086
1087         for (i = 1; i < HPAGE_PMD_NR; i++) {
1088                 struct page *page_tail = page + i;
1089                 BUG_ON(page_count(page_tail) <= 0);
1090                 /*
1091                  * Tail pages may be freed if there wasn't any mapping
1092                  * like if add_to_swap() is running on a lru page that
1093                  * had its mapping zapped. And freeing these pages
1094                  * requires taking the lru_lock so we do the put_page
1095                  * of the tail pages after the split is complete.
1096                  */
1097                 put_page(page_tail);
1098         }
1099
1100         /*
1101          * Only the head page (now become a regular page) is required
1102          * to be pinned by the caller.
1103          */
1104         BUG_ON(page_count(page) <= 0);
1105 }
1106
1107 static int __split_huge_page_map(struct page *page,
1108                                  struct vm_area_struct *vma,
1109                                  unsigned long address)
1110 {
1111         struct mm_struct *mm = vma->vm_mm;
1112         pmd_t *pmd, _pmd;
1113         int ret = 0, i;
1114         pgtable_t pgtable;
1115         unsigned long haddr;
1116
1117         spin_lock(&mm->page_table_lock);
1118         pmd = page_check_address_pmd(page, mm, address,
1119                                      PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1120         if (pmd) {
1121                 pgtable = get_pmd_huge_pte(mm);
1122                 pmd_populate(mm, &_pmd, pgtable);
1123
1124                 for (i = 0, haddr = address; i < HPAGE_PMD_NR;
1125                      i++, haddr += PAGE_SIZE) {
1126                         pte_t *pte, entry;
1127                         BUG_ON(PageCompound(page+i));
1128                         entry = mk_pte(page + i, vma->vm_page_prot);
1129                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1130                         if (!pmd_write(*pmd))
1131                                 entry = pte_wrprotect(entry);
1132                         else
1133                                 BUG_ON(page_mapcount(page) != 1);
1134                         if (!pmd_young(*pmd))
1135                                 entry = pte_mkold(entry);
1136                         pte = pte_offset_map(&_pmd, haddr);
1137                         BUG_ON(!pte_none(*pte));
1138                         set_pte_at(mm, haddr, pte, entry);
1139                         pte_unmap(pte);
1140                 }
1141
1142                 mm->nr_ptes++;
1143                 smp_wmb(); /* make pte visible before pmd */
1144                 /*
1145                  * Up to this point the pmd is present and huge and
1146                  * userland has the whole access to the hugepage
1147                  * during the split (which happens in place). If we
1148                  * overwrite the pmd with the not-huge version
1149                  * pointing to the pte here (which of course we could
1150                  * if all CPUs were bug free), userland could trigger
1151                  * a small page size TLB miss on the small sized TLB
1152                  * while the hugepage TLB entry is still established
1153                  * in the huge TLB. Some CPU doesn't like that. See
1154                  * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1155                  * Erratum 383 on page 93. Intel should be safe but is
1156                  * also warns that it's only safe if the permission
1157                  * and cache attributes of the two entries loaded in
1158                  * the two TLB is identical (which should be the case
1159                  * here). But it is generally safer to never allow
1160                  * small and huge TLB entries for the same virtual
1161                  * address to be loaded simultaneously. So instead of
1162                  * doing "pmd_populate(); flush_tlb_range();" we first
1163                  * mark the current pmd notpresent (atomically because
1164                  * here the pmd_trans_huge and pmd_trans_splitting
1165                  * must remain set at all times on the pmd until the
1166                  * split is complete for this pmd), then we flush the
1167                  * SMP TLB and finally we write the non-huge version
1168                  * of the pmd entry with pmd_populate.
1169                  */
1170                 set_pmd_at(mm, address, pmd, pmd_mknotpresent(*pmd));
1171                 flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
1172                 pmd_populate(mm, pmd, pgtable);
1173                 ret = 1;
1174         }
1175         spin_unlock(&mm->page_table_lock);
1176
1177         return ret;
1178 }
1179
1180 /* must be called with anon_vma->root->lock hold */
1181 static void __split_huge_page(struct page *page,
1182                               struct anon_vma *anon_vma)
1183 {
1184         int mapcount, mapcount2;
1185         struct anon_vma_chain *avc;
1186
1187         BUG_ON(!PageHead(page));
1188         BUG_ON(PageTail(page));
1189
1190         mapcount = 0;
1191         list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1192                 struct vm_area_struct *vma = avc->vma;
1193                 unsigned long addr = vma_address(page, vma);
1194                 BUG_ON(is_vma_temporary_stack(vma));
1195                 if (addr == -EFAULT)
1196                         continue;
1197                 mapcount += __split_huge_page_splitting(page, vma, addr);
1198         }
1199         /*
1200          * It is critical that new vmas are added to the tail of the
1201          * anon_vma list. This guarantes that if copy_huge_pmd() runs
1202          * and establishes a child pmd before
1203          * __split_huge_page_splitting() freezes the parent pmd (so if
1204          * we fail to prevent copy_huge_pmd() from running until the
1205          * whole __split_huge_page() is complete), we will still see
1206          * the newly established pmd of the child later during the
1207          * walk, to be able to set it as pmd_trans_splitting too.
1208          */
1209         if (mapcount != page_mapcount(page))
1210                 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1211                        mapcount, page_mapcount(page));
1212         BUG_ON(mapcount != page_mapcount(page));
1213
1214         __split_huge_page_refcount(page);
1215
1216         mapcount2 = 0;
1217         list_for_each_entry(avc, &anon_vma->head, same_anon_vma) {
1218                 struct vm_area_struct *vma = avc->vma;
1219                 unsigned long addr = vma_address(page, vma);
1220                 BUG_ON(is_vma_temporary_stack(vma));
1221                 if (addr == -EFAULT)
1222                         continue;
1223                 mapcount2 += __split_huge_page_map(page, vma, addr);
1224         }
1225         if (mapcount != mapcount2)
1226                 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1227                        mapcount, mapcount2, page_mapcount(page));
1228         BUG_ON(mapcount != mapcount2);
1229 }
1230
1231 int split_huge_page(struct page *page)
1232 {
1233         struct anon_vma *anon_vma;
1234         int ret = 1;
1235
1236         BUG_ON(!PageAnon(page));
1237         anon_vma = page_lock_anon_vma(page);
1238         if (!anon_vma)
1239                 goto out;
1240         ret = 0;
1241         if (!PageCompound(page))
1242                 goto out_unlock;
1243
1244         BUG_ON(!PageSwapBacked(page));
1245         __split_huge_page(page, anon_vma);
1246
1247         BUG_ON(PageCompound(page));
1248 out_unlock:
1249         page_unlock_anon_vma(anon_vma);
1250 out:
1251         return ret;
1252 }
1253
1254 int hugepage_madvise(unsigned long *vm_flags)
1255 {
1256         /*
1257          * Be somewhat over-protective like KSM for now!
1258          */
1259         if (*vm_flags & (VM_HUGEPAGE | VM_SHARED  | VM_MAYSHARE   |
1260                          VM_PFNMAP   | VM_IO      | VM_DONTEXPAND |
1261                          VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
1262                          VM_MIXEDMAP | VM_SAO))
1263                 return -EINVAL;
1264
1265         *vm_flags |= VM_HUGEPAGE;
1266
1267         return 0;
1268 }
1269
1270 static int __init khugepaged_slab_init(void)
1271 {
1272         mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1273                                           sizeof(struct mm_slot),
1274                                           __alignof__(struct mm_slot), 0, NULL);
1275         if (!mm_slot_cache)
1276                 return -ENOMEM;
1277
1278         return 0;
1279 }
1280
1281 static void __init khugepaged_slab_free(void)
1282 {
1283         kmem_cache_destroy(mm_slot_cache);
1284         mm_slot_cache = NULL;
1285 }
1286
1287 static inline struct mm_slot *alloc_mm_slot(void)
1288 {
1289         if (!mm_slot_cache)     /* initialization failed */
1290                 return NULL;
1291         return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1292 }
1293
1294 static inline void free_mm_slot(struct mm_slot *mm_slot)
1295 {
1296         kmem_cache_free(mm_slot_cache, mm_slot);
1297 }
1298
1299 static int __init mm_slots_hash_init(void)
1300 {
1301         mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1302                                 GFP_KERNEL);
1303         if (!mm_slots_hash)
1304                 return -ENOMEM;
1305         return 0;
1306 }
1307
1308 #if 0
1309 static void __init mm_slots_hash_free(void)
1310 {
1311         kfree(mm_slots_hash);
1312         mm_slots_hash = NULL;
1313 }
1314 #endif
1315
1316 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1317 {
1318         struct mm_slot *mm_slot;
1319         struct hlist_head *bucket;
1320         struct hlist_node *node;
1321
1322         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1323                                 % MM_SLOTS_HASH_HEADS];
1324         hlist_for_each_entry(mm_slot, node, bucket, hash) {
1325                 if (mm == mm_slot->mm)
1326                         return mm_slot;
1327         }
1328         return NULL;
1329 }
1330
1331 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1332                                     struct mm_slot *mm_slot)
1333 {
1334         struct hlist_head *bucket;
1335
1336         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1337                                 % MM_SLOTS_HASH_HEADS];
1338         mm_slot->mm = mm;
1339         hlist_add_head(&mm_slot->hash, bucket);
1340 }
1341
1342 static inline int khugepaged_test_exit(struct mm_struct *mm)
1343 {
1344         return atomic_read(&mm->mm_users) == 0;
1345 }
1346
1347 int __khugepaged_enter(struct mm_struct *mm)
1348 {
1349         struct mm_slot *mm_slot;
1350         int wakeup;
1351
1352         mm_slot = alloc_mm_slot();
1353         if (!mm_slot)
1354                 return -ENOMEM;
1355
1356         /* __khugepaged_exit() must not run from under us */
1357         VM_BUG_ON(khugepaged_test_exit(mm));
1358         if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1359                 free_mm_slot(mm_slot);
1360                 return 0;
1361         }
1362
1363         spin_lock(&khugepaged_mm_lock);
1364         insert_to_mm_slots_hash(mm, mm_slot);
1365         /*
1366          * Insert just behind the scanning cursor, to let the area settle
1367          * down a little.
1368          */
1369         wakeup = list_empty(&khugepaged_scan.mm_head);
1370         list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1371         spin_unlock(&khugepaged_mm_lock);
1372
1373         atomic_inc(&mm->mm_count);
1374         if (wakeup)
1375                 wake_up_interruptible(&khugepaged_wait);
1376
1377         return 0;
1378 }
1379
1380 int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
1381 {
1382         unsigned long hstart, hend;
1383         if (!vma->anon_vma)
1384                 /*
1385                  * Not yet faulted in so we will register later in the
1386                  * page fault if needed.
1387                  */
1388                 return 0;
1389         if (vma->vm_file || vma->vm_ops)
1390                 /* khugepaged not yet working on file or special mappings */
1391                 return 0;
1392         VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
1393         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1394         hend = vma->vm_end & HPAGE_PMD_MASK;
1395         if (hstart < hend)
1396                 return khugepaged_enter(vma);
1397         return 0;
1398 }
1399
1400 void __khugepaged_exit(struct mm_struct *mm)
1401 {
1402         struct mm_slot *mm_slot;
1403         int free = 0;
1404
1405         spin_lock(&khugepaged_mm_lock);
1406         mm_slot = get_mm_slot(mm);
1407         if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1408                 hlist_del(&mm_slot->hash);
1409                 list_del(&mm_slot->mm_node);
1410                 free = 1;
1411         }
1412
1413         if (free) {
1414                 spin_unlock(&khugepaged_mm_lock);
1415                 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1416                 free_mm_slot(mm_slot);
1417                 mmdrop(mm);
1418         } else if (mm_slot) {
1419                 spin_unlock(&khugepaged_mm_lock);
1420                 /*
1421                  * This is required to serialize against
1422                  * khugepaged_test_exit() (which is guaranteed to run
1423                  * under mmap sem read mode). Stop here (after we
1424                  * return all pagetables will be destroyed) until
1425                  * khugepaged has finished working on the pagetables
1426                  * under the mmap_sem.
1427                  */
1428                 down_write(&mm->mmap_sem);
1429                 up_write(&mm->mmap_sem);
1430         } else
1431                 spin_unlock(&khugepaged_mm_lock);
1432 }
1433
1434 static void release_pte_page(struct page *page)
1435 {
1436         /* 0 stands for page_is_file_cache(page) == false */
1437         dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1438         unlock_page(page);
1439         putback_lru_page(page);
1440 }
1441
1442 static void release_pte_pages(pte_t *pte, pte_t *_pte)
1443 {
1444         while (--_pte >= pte) {
1445                 pte_t pteval = *_pte;
1446                 if (!pte_none(pteval))
1447                         release_pte_page(pte_page(pteval));
1448         }
1449 }
1450
1451 static void release_all_pte_pages(pte_t *pte)
1452 {
1453         release_pte_pages(pte, pte + HPAGE_PMD_NR);
1454 }
1455
1456 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1457                                         unsigned long address,
1458                                         pte_t *pte)
1459 {
1460         struct page *page;
1461         pte_t *_pte;
1462         int referenced = 0, isolated = 0, none = 0;
1463         for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1464              _pte++, address += PAGE_SIZE) {
1465                 pte_t pteval = *_pte;
1466                 if (pte_none(pteval)) {
1467                         if (++none <= khugepaged_max_ptes_none)
1468                                 continue;
1469                         else {
1470                                 release_pte_pages(pte, _pte);
1471                                 goto out;
1472                         }
1473                 }
1474                 if (!pte_present(pteval) || !pte_write(pteval)) {
1475                         release_pte_pages(pte, _pte);
1476                         goto out;
1477                 }
1478                 page = vm_normal_page(vma, address, pteval);
1479                 if (unlikely(!page)) {
1480                         release_pte_pages(pte, _pte);
1481                         goto out;
1482                 }
1483                 VM_BUG_ON(PageCompound(page));
1484                 BUG_ON(!PageAnon(page));
1485                 VM_BUG_ON(!PageSwapBacked(page));
1486
1487                 /* cannot use mapcount: can't collapse if there's a gup pin */
1488                 if (page_count(page) != 1) {
1489                         release_pte_pages(pte, _pte);
1490                         goto out;
1491                 }
1492                 /*
1493                  * We can do it before isolate_lru_page because the
1494                  * page can't be freed from under us. NOTE: PG_lock
1495                  * is needed to serialize against split_huge_page
1496                  * when invoked from the VM.
1497                  */
1498                 if (!trylock_page(page)) {
1499                         release_pte_pages(pte, _pte);
1500                         goto out;
1501                 }
1502                 /*
1503                  * Isolate the page to avoid collapsing an hugepage
1504                  * currently in use by the VM.
1505                  */
1506                 if (isolate_lru_page(page)) {
1507                         unlock_page(page);
1508                         release_pte_pages(pte, _pte);
1509                         goto out;
1510                 }
1511                 /* 0 stands for page_is_file_cache(page) == false */
1512                 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1513                 VM_BUG_ON(!PageLocked(page));
1514                 VM_BUG_ON(PageLRU(page));
1515
1516                 /* If there is no mapped pte young don't collapse the page */
1517                 if (pte_young(pteval))
1518                         referenced = 1;
1519         }
1520         if (unlikely(!referenced))
1521                 release_all_pte_pages(pte);
1522         else
1523                 isolated = 1;
1524 out:
1525         return isolated;
1526 }
1527
1528 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1529                                       struct vm_area_struct *vma,
1530                                       unsigned long address,
1531                                       spinlock_t *ptl)
1532 {
1533         pte_t *_pte;
1534         for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1535                 pte_t pteval = *_pte;
1536                 struct page *src_page;
1537
1538                 if (pte_none(pteval)) {
1539                         clear_user_highpage(page, address);
1540                         add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1541                 } else {
1542                         src_page = pte_page(pteval);
1543                         copy_user_highpage(page, src_page, address, vma);
1544                         VM_BUG_ON(page_mapcount(src_page) != 1);
1545                         VM_BUG_ON(page_count(src_page) != 2);
1546                         release_pte_page(src_page);
1547                         /*
1548                          * ptl mostly unnecessary, but preempt has to
1549                          * be disabled to update the per-cpu stats
1550                          * inside page_remove_rmap().
1551                          */
1552                         spin_lock(ptl);
1553                         /*
1554                          * paravirt calls inside pte_clear here are
1555                          * superfluous.
1556                          */
1557                         pte_clear(vma->vm_mm, address, _pte);
1558                         page_remove_rmap(src_page);
1559                         spin_unlock(ptl);
1560                         free_page_and_swap_cache(src_page);
1561                 }
1562
1563                 address += PAGE_SIZE;
1564                 page++;
1565         }
1566 }
1567
1568 static void collapse_huge_page(struct mm_struct *mm,
1569                                unsigned long address,
1570                                struct page **hpage)
1571 {
1572         struct vm_area_struct *vma;
1573         pgd_t *pgd;
1574         pud_t *pud;
1575         pmd_t *pmd, _pmd;
1576         pte_t *pte;
1577         pgtable_t pgtable;
1578         struct page *new_page;
1579         spinlock_t *ptl;
1580         int isolated;
1581         unsigned long hstart, hend;
1582
1583         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1584         VM_BUG_ON(!*hpage);
1585
1586         /*
1587          * Prevent all access to pagetables with the exception of
1588          * gup_fast later hanlded by the ptep_clear_flush and the VM
1589          * handled by the anon_vma lock + PG_lock.
1590          */
1591         down_write(&mm->mmap_sem);
1592         if (unlikely(khugepaged_test_exit(mm)))
1593                 goto out;
1594
1595         vma = find_vma(mm, address);
1596         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1597         hend = vma->vm_end & HPAGE_PMD_MASK;
1598         if (address < hstart || address + HPAGE_PMD_SIZE > hend)
1599                 goto out;
1600
1601         if (!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always())
1602                 goto out;
1603
1604         /* VM_PFNMAP vmas may have vm_ops null but vm_file set */
1605         if (!vma->anon_vma || vma->vm_ops || vma->vm_file)
1606                 goto out;
1607         VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
1608
1609         pgd = pgd_offset(mm, address);
1610         if (!pgd_present(*pgd))
1611                 goto out;
1612
1613         pud = pud_offset(pgd, address);
1614         if (!pud_present(*pud))
1615                 goto out;
1616
1617         pmd = pmd_offset(pud, address);
1618         /* pmd can't go away or become huge under us */
1619         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
1620                 goto out;
1621
1622         new_page = *hpage;
1623         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL)))
1624                 goto out;
1625
1626         anon_vma_lock(vma->anon_vma);
1627
1628         pte = pte_offset_map(pmd, address);
1629         ptl = pte_lockptr(mm, pmd);
1630
1631         spin_lock(&mm->page_table_lock); /* probably unnecessary */
1632         /*
1633          * After this gup_fast can't run anymore. This also removes
1634          * any huge TLB entry from the CPU so we won't allow
1635          * huge and small TLB entries for the same virtual address
1636          * to avoid the risk of CPU bugs in that area.
1637          */
1638         _pmd = pmdp_clear_flush_notify(vma, address, pmd);
1639         spin_unlock(&mm->page_table_lock);
1640
1641         spin_lock(ptl);
1642         isolated = __collapse_huge_page_isolate(vma, address, pte);
1643         spin_unlock(ptl);
1644         pte_unmap(pte);
1645
1646         if (unlikely(!isolated)) {
1647                 spin_lock(&mm->page_table_lock);
1648                 BUG_ON(!pmd_none(*pmd));
1649                 set_pmd_at(mm, address, pmd, _pmd);
1650                 spin_unlock(&mm->page_table_lock);
1651                 anon_vma_unlock(vma->anon_vma);
1652                 mem_cgroup_uncharge_page(new_page);
1653                 goto out;
1654         }
1655
1656         /*
1657          * All pages are isolated and locked so anon_vma rmap
1658          * can't run anymore.
1659          */
1660         anon_vma_unlock(vma->anon_vma);
1661
1662         __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
1663         __SetPageUptodate(new_page);
1664         pgtable = pmd_pgtable(_pmd);
1665         VM_BUG_ON(page_count(pgtable) != 1);
1666         VM_BUG_ON(page_mapcount(pgtable) != 0);
1667
1668         _pmd = mk_pmd(new_page, vma->vm_page_prot);
1669         _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1670         _pmd = pmd_mkhuge(_pmd);
1671
1672         /*
1673          * spin_lock() below is not the equivalent of smp_wmb(), so
1674          * this is needed to avoid the copy_huge_page writes to become
1675          * visible after the set_pmd_at() write.
1676          */
1677         smp_wmb();
1678
1679         spin_lock(&mm->page_table_lock);
1680         BUG_ON(!pmd_none(*pmd));
1681         page_add_new_anon_rmap(new_page, vma, address);
1682         set_pmd_at(mm, address, pmd, _pmd);
1683         update_mmu_cache(vma, address, entry);
1684         prepare_pmd_huge_pte(pgtable, mm);
1685         mm->nr_ptes--;
1686         spin_unlock(&mm->page_table_lock);
1687
1688         *hpage = NULL;
1689         khugepaged_pages_collapsed++;
1690 out:
1691         up_write(&mm->mmap_sem);
1692 }
1693
1694 static int khugepaged_scan_pmd(struct mm_struct *mm,
1695                                struct vm_area_struct *vma,
1696                                unsigned long address,
1697                                struct page **hpage)
1698 {
1699         pgd_t *pgd;
1700         pud_t *pud;
1701         pmd_t *pmd;
1702         pte_t *pte, *_pte;
1703         int ret = 0, referenced = 0, none = 0;
1704         struct page *page;
1705         unsigned long _address;
1706         spinlock_t *ptl;
1707
1708         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1709
1710         pgd = pgd_offset(mm, address);
1711         if (!pgd_present(*pgd))
1712                 goto out;
1713
1714         pud = pud_offset(pgd, address);
1715         if (!pud_present(*pud))
1716                 goto out;
1717
1718         pmd = pmd_offset(pud, address);
1719         if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
1720                 goto out;
1721
1722         pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1723         for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1724              _pte++, _address += PAGE_SIZE) {
1725                 pte_t pteval = *_pte;
1726                 if (pte_none(pteval)) {
1727                         if (++none <= khugepaged_max_ptes_none)
1728                                 continue;
1729                         else
1730                                 goto out_unmap;
1731                 }
1732                 if (!pte_present(pteval) || !pte_write(pteval))
1733                         goto out_unmap;
1734                 page = vm_normal_page(vma, _address, pteval);
1735                 if (unlikely(!page))
1736                         goto out_unmap;
1737                 VM_BUG_ON(PageCompound(page));
1738                 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
1739                         goto out_unmap;
1740                 /* cannot use mapcount: can't collapse if there's a gup pin */
1741                 if (page_count(page) != 1)
1742                         goto out_unmap;
1743                 if (pte_young(pteval))
1744                         referenced = 1;
1745         }
1746         if (referenced)
1747                 ret = 1;
1748 out_unmap:
1749         pte_unmap_unlock(pte, ptl);
1750         if (ret) {
1751                 up_read(&mm->mmap_sem);
1752                 collapse_huge_page(mm, address, hpage);
1753         }
1754 out:
1755         return ret;
1756 }
1757
1758 static void collect_mm_slot(struct mm_slot *mm_slot)
1759 {
1760         struct mm_struct *mm = mm_slot->mm;
1761
1762         VM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock));
1763
1764         if (khugepaged_test_exit(mm)) {
1765                 /* free mm_slot */
1766                 hlist_del(&mm_slot->hash);
1767                 list_del(&mm_slot->mm_node);
1768
1769                 /*
1770                  * Not strictly needed because the mm exited already.
1771                  *
1772                  * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1773                  */
1774
1775                 /* khugepaged_mm_lock actually not necessary for the below */
1776                 free_mm_slot(mm_slot);
1777                 mmdrop(mm);
1778         }
1779 }
1780
1781 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
1782                                             struct page **hpage)
1783 {
1784         struct mm_slot *mm_slot;
1785         struct mm_struct *mm;
1786         struct vm_area_struct *vma;
1787         int progress = 0;
1788
1789         VM_BUG_ON(!pages);
1790         VM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock));
1791
1792         if (khugepaged_scan.mm_slot)
1793                 mm_slot = khugepaged_scan.mm_slot;
1794         else {
1795                 mm_slot = list_entry(khugepaged_scan.mm_head.next,
1796                                      struct mm_slot, mm_node);
1797                 khugepaged_scan.address = 0;
1798                 khugepaged_scan.mm_slot = mm_slot;
1799         }
1800         spin_unlock(&khugepaged_mm_lock);
1801
1802         mm = mm_slot->mm;
1803         down_read(&mm->mmap_sem);
1804         if (unlikely(khugepaged_test_exit(mm)))
1805                 vma = NULL;
1806         else
1807                 vma = find_vma(mm, khugepaged_scan.address);
1808
1809         progress++;
1810         for (; vma; vma = vma->vm_next) {
1811                 unsigned long hstart, hend;
1812
1813                 cond_resched();
1814                 if (unlikely(khugepaged_test_exit(mm))) {
1815                         progress++;
1816                         break;
1817                 }
1818
1819                 if (!(vma->vm_flags & VM_HUGEPAGE) &&
1820                     !khugepaged_always()) {
1821                         progress++;
1822                         continue;
1823                 }
1824
1825                 /* VM_PFNMAP vmas may have vm_ops null but vm_file set */
1826                 if (!vma->anon_vma || vma->vm_ops || vma->vm_file) {
1827                         khugepaged_scan.address = vma->vm_end;
1828                         progress++;
1829                         continue;
1830                 }
1831                 VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
1832
1833                 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1834                 hend = vma->vm_end & HPAGE_PMD_MASK;
1835                 if (hstart >= hend) {
1836                         progress++;
1837                         continue;
1838                 }
1839                 if (khugepaged_scan.address < hstart)
1840                         khugepaged_scan.address = hstart;
1841                 if (khugepaged_scan.address > hend) {
1842                         khugepaged_scan.address = hend + HPAGE_PMD_SIZE;
1843                         progress++;
1844                         continue;
1845                 }
1846                 BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
1847
1848                 while (khugepaged_scan.address < hend) {
1849                         int ret;
1850                         cond_resched();
1851                         if (unlikely(khugepaged_test_exit(mm)))
1852                                 goto breakouterloop;
1853
1854                         VM_BUG_ON(khugepaged_scan.address < hstart ||
1855                                   khugepaged_scan.address + HPAGE_PMD_SIZE >
1856                                   hend);
1857                         ret = khugepaged_scan_pmd(mm, vma,
1858                                                   khugepaged_scan.address,
1859                                                   hpage);
1860                         /* move to next address */
1861                         khugepaged_scan.address += HPAGE_PMD_SIZE;
1862                         progress += HPAGE_PMD_NR;
1863                         if (ret)
1864                                 /* we released mmap_sem so break loop */
1865                                 goto breakouterloop_mmap_sem;
1866                         if (progress >= pages)
1867                                 goto breakouterloop;
1868                 }
1869         }
1870 breakouterloop:
1871         up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
1872 breakouterloop_mmap_sem:
1873
1874         spin_lock(&khugepaged_mm_lock);
1875         BUG_ON(khugepaged_scan.mm_slot != mm_slot);
1876         /*
1877          * Release the current mm_slot if this mm is about to die, or
1878          * if we scanned all vmas of this mm.
1879          */
1880         if (khugepaged_test_exit(mm) || !vma) {
1881                 /*
1882                  * Make sure that if mm_users is reaching zero while
1883                  * khugepaged runs here, khugepaged_exit will find
1884                  * mm_slot not pointing to the exiting mm.
1885                  */
1886                 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
1887                         khugepaged_scan.mm_slot = list_entry(
1888                                 mm_slot->mm_node.next,
1889                                 struct mm_slot, mm_node);
1890                         khugepaged_scan.address = 0;
1891                 } else {
1892                         khugepaged_scan.mm_slot = NULL;
1893                         khugepaged_full_scans++;
1894                 }
1895
1896                 collect_mm_slot(mm_slot);
1897         }
1898
1899         return progress;
1900 }
1901
1902 static int khugepaged_has_work(void)
1903 {
1904         return !list_empty(&khugepaged_scan.mm_head) &&
1905                 khugepaged_enabled();
1906 }
1907
1908 static int khugepaged_wait_event(void)
1909 {
1910         return !list_empty(&khugepaged_scan.mm_head) ||
1911                 !khugepaged_enabled();
1912 }
1913
1914 static void khugepaged_do_scan(struct page **hpage)
1915 {
1916         unsigned int progress = 0, pass_through_head = 0;
1917         unsigned int pages = khugepaged_pages_to_scan;
1918
1919         barrier(); /* write khugepaged_pages_to_scan to local stack */
1920
1921         while (progress < pages) {
1922                 cond_resched();
1923
1924                 if (!*hpage) {
1925                         *hpage = alloc_hugepage(khugepaged_defrag());
1926                         if (unlikely(!*hpage))
1927                                 break;
1928                 }
1929
1930                 spin_lock(&khugepaged_mm_lock);
1931                 if (!khugepaged_scan.mm_slot)
1932                         pass_through_head++;
1933                 if (khugepaged_has_work() &&
1934                     pass_through_head < 2)
1935                         progress += khugepaged_scan_mm_slot(pages - progress,
1936                                                             hpage);
1937                 else
1938                         progress = pages;
1939                 spin_unlock(&khugepaged_mm_lock);
1940         }
1941 }
1942
1943 static struct page *khugepaged_alloc_hugepage(void)
1944 {
1945         struct page *hpage;
1946
1947         do {
1948                 hpage = alloc_hugepage(khugepaged_defrag());
1949                 if (!hpage) {
1950                         DEFINE_WAIT(wait);
1951                         add_wait_queue(&khugepaged_wait, &wait);
1952                         schedule_timeout_interruptible(
1953                                 msecs_to_jiffies(
1954                                         khugepaged_alloc_sleep_millisecs));
1955                         remove_wait_queue(&khugepaged_wait, &wait);
1956                 }
1957         } while (unlikely(!hpage) &&
1958                  likely(khugepaged_enabled()));
1959         return hpage;
1960 }
1961
1962 static void khugepaged_loop(void)
1963 {
1964         struct page *hpage;
1965
1966         while (likely(khugepaged_enabled())) {
1967                 hpage = khugepaged_alloc_hugepage();
1968                 if (unlikely(!hpage))
1969                         break;
1970
1971                 khugepaged_do_scan(&hpage);
1972                 if (hpage)
1973                         put_page(hpage);
1974                 if (khugepaged_has_work()) {
1975                         DEFINE_WAIT(wait);
1976                         if (!khugepaged_scan_sleep_millisecs)
1977                                 continue;
1978                         add_wait_queue(&khugepaged_wait, &wait);
1979                         schedule_timeout_interruptible(
1980                                 msecs_to_jiffies(
1981                                         khugepaged_scan_sleep_millisecs));
1982                         remove_wait_queue(&khugepaged_wait, &wait);
1983                 } else if (khugepaged_enabled())
1984                         wait_event_interruptible(khugepaged_wait,
1985                                                  khugepaged_wait_event());
1986         }
1987 }
1988
1989 static int khugepaged(void *none)
1990 {
1991         struct mm_slot *mm_slot;
1992
1993         set_user_nice(current, 19);
1994
1995         /* serialize with start_khugepaged() */
1996         mutex_lock(&khugepaged_mutex);
1997
1998         for (;;) {
1999                 mutex_unlock(&khugepaged_mutex);
2000                 BUG_ON(khugepaged_thread != current);
2001                 khugepaged_loop();
2002                 BUG_ON(khugepaged_thread != current);
2003
2004                 mutex_lock(&khugepaged_mutex);
2005                 if (!khugepaged_enabled())
2006                         break;
2007         }
2008
2009         spin_lock(&khugepaged_mm_lock);
2010         mm_slot = khugepaged_scan.mm_slot;
2011         khugepaged_scan.mm_slot = NULL;
2012         if (mm_slot)
2013                 collect_mm_slot(mm_slot);
2014         spin_unlock(&khugepaged_mm_lock);
2015
2016         khugepaged_thread = NULL;
2017         mutex_unlock(&khugepaged_mutex);
2018
2019         return 0;
2020 }
2021
2022 void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2023 {
2024         struct page *page;
2025
2026         spin_lock(&mm->page_table_lock);
2027         if (unlikely(!pmd_trans_huge(*pmd))) {
2028                 spin_unlock(&mm->page_table_lock);
2029                 return;
2030         }
2031         page = pmd_page(*pmd);
2032         VM_BUG_ON(!page_count(page));
2033         get_page(page);
2034         spin_unlock(&mm->page_table_lock);
2035
2036         split_huge_page(page);
2037
2038         put_page(page);
2039         BUG_ON(pmd_trans_huge(*pmd));
2040 }