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