]> rtime.felk.cvut.cz Git - can-eth-gw-linux.git/blob - mm/huge_memory.c
thp: cleanup: introduce mk_huge_pmd()
[can-eth-gw-linux.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 static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
788                                         struct vm_area_struct *vma,
789                                         unsigned long address,
790                                         pmd_t *pmd, pmd_t orig_pmd,
791                                         struct page *page,
792                                         unsigned long haddr)
793 {
794         pgtable_t pgtable;
795         pmd_t _pmd;
796         int ret = 0, i;
797         struct page **pages;
798         unsigned long mmun_start;       /* For mmu_notifiers */
799         unsigned long mmun_end;         /* For mmu_notifiers */
800
801         pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
802                         GFP_KERNEL);
803         if (unlikely(!pages)) {
804                 ret |= VM_FAULT_OOM;
805                 goto out;
806         }
807
808         for (i = 0; i < HPAGE_PMD_NR; i++) {
809                 pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
810                                                __GFP_OTHER_NODE,
811                                                vma, address, page_to_nid(page));
812                 if (unlikely(!pages[i] ||
813                              mem_cgroup_newpage_charge(pages[i], mm,
814                                                        GFP_KERNEL))) {
815                         if (pages[i])
816                                 put_page(pages[i]);
817                         mem_cgroup_uncharge_start();
818                         while (--i >= 0) {
819                                 mem_cgroup_uncharge_page(pages[i]);
820                                 put_page(pages[i]);
821                         }
822                         mem_cgroup_uncharge_end();
823                         kfree(pages);
824                         ret |= VM_FAULT_OOM;
825                         goto out;
826                 }
827         }
828
829         for (i = 0; i < HPAGE_PMD_NR; i++) {
830                 copy_user_highpage(pages[i], page + i,
831                                    haddr + PAGE_SIZE * i, vma);
832                 __SetPageUptodate(pages[i]);
833                 cond_resched();
834         }
835
836         mmun_start = haddr;
837         mmun_end   = haddr + HPAGE_PMD_SIZE;
838         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
839
840         spin_lock(&mm->page_table_lock);
841         if (unlikely(!pmd_same(*pmd, orig_pmd)))
842                 goto out_free_pages;
843         VM_BUG_ON(!PageHead(page));
844
845         pmdp_clear_flush(vma, haddr, pmd);
846         /* leave pmd empty until pte is filled */
847
848         pgtable = pgtable_trans_huge_withdraw(mm);
849         pmd_populate(mm, &_pmd, pgtable);
850
851         for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
852                 pte_t *pte, entry;
853                 entry = mk_pte(pages[i], vma->vm_page_prot);
854                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
855                 page_add_new_anon_rmap(pages[i], vma, haddr);
856                 pte = pte_offset_map(&_pmd, haddr);
857                 VM_BUG_ON(!pte_none(*pte));
858                 set_pte_at(mm, haddr, pte, entry);
859                 pte_unmap(pte);
860         }
861         kfree(pages);
862
863         smp_wmb(); /* make pte visible before pmd */
864         pmd_populate(mm, pmd, pgtable);
865         page_remove_rmap(page);
866         spin_unlock(&mm->page_table_lock);
867
868         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
869
870         ret |= VM_FAULT_WRITE;
871         put_page(page);
872
873 out:
874         return ret;
875
876 out_free_pages:
877         spin_unlock(&mm->page_table_lock);
878         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
879         mem_cgroup_uncharge_start();
880         for (i = 0; i < HPAGE_PMD_NR; i++) {
881                 mem_cgroup_uncharge_page(pages[i]);
882                 put_page(pages[i]);
883         }
884         mem_cgroup_uncharge_end();
885         kfree(pages);
886         goto out;
887 }
888
889 int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
890                         unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
891 {
892         int ret = 0;
893         struct page *page, *new_page;
894         unsigned long haddr;
895         unsigned long mmun_start;       /* For mmu_notifiers */
896         unsigned long mmun_end;         /* For mmu_notifiers */
897
898         VM_BUG_ON(!vma->anon_vma);
899         spin_lock(&mm->page_table_lock);
900         if (unlikely(!pmd_same(*pmd, orig_pmd)))
901                 goto out_unlock;
902
903         page = pmd_page(orig_pmd);
904         VM_BUG_ON(!PageCompound(page) || !PageHead(page));
905         haddr = address & HPAGE_PMD_MASK;
906         if (page_mapcount(page) == 1) {
907                 pmd_t entry;
908                 entry = pmd_mkyoung(orig_pmd);
909                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
910                 if (pmdp_set_access_flags(vma, haddr, pmd, entry,  1))
911                         update_mmu_cache_pmd(vma, address, pmd);
912                 ret |= VM_FAULT_WRITE;
913                 goto out_unlock;
914         }
915         get_page(page);
916         spin_unlock(&mm->page_table_lock);
917
918         if (transparent_hugepage_enabled(vma) &&
919             !transparent_hugepage_debug_cow())
920                 new_page = alloc_hugepage_vma(transparent_hugepage_defrag(vma),
921                                               vma, haddr, numa_node_id(), 0);
922         else
923                 new_page = NULL;
924
925         if (unlikely(!new_page)) {
926                 count_vm_event(THP_FAULT_FALLBACK);
927                 ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
928                                                    pmd, orig_pmd, page, haddr);
929                 if (ret & VM_FAULT_OOM)
930                         split_huge_page(page);
931                 put_page(page);
932                 goto out;
933         }
934         count_vm_event(THP_FAULT_ALLOC);
935
936         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
937                 put_page(new_page);
938                 split_huge_page(page);
939                 put_page(page);
940                 ret |= VM_FAULT_OOM;
941                 goto out;
942         }
943
944         copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
945         __SetPageUptodate(new_page);
946
947         mmun_start = haddr;
948         mmun_end   = haddr + HPAGE_PMD_SIZE;
949         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
950
951         spin_lock(&mm->page_table_lock);
952         put_page(page);
953         if (unlikely(!pmd_same(*pmd, orig_pmd))) {
954                 spin_unlock(&mm->page_table_lock);
955                 mem_cgroup_uncharge_page(new_page);
956                 put_page(new_page);
957                 goto out_mn;
958         } else {
959                 pmd_t entry;
960                 VM_BUG_ON(!PageHead(page));
961                 entry = mk_huge_pmd(new_page, vma);
962                 pmdp_clear_flush(vma, haddr, pmd);
963                 page_add_new_anon_rmap(new_page, vma, haddr);
964                 set_pmd_at(mm, haddr, pmd, entry);
965                 update_mmu_cache_pmd(vma, address, pmd);
966                 page_remove_rmap(page);
967                 put_page(page);
968                 ret |= VM_FAULT_WRITE;
969         }
970         spin_unlock(&mm->page_table_lock);
971 out_mn:
972         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
973 out:
974         return ret;
975 out_unlock:
976         spin_unlock(&mm->page_table_lock);
977         return ret;
978 }
979
980 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
981                                    unsigned long addr,
982                                    pmd_t *pmd,
983                                    unsigned int flags)
984 {
985         struct mm_struct *mm = vma->vm_mm;
986         struct page *page = NULL;
987
988         assert_spin_locked(&mm->page_table_lock);
989
990         if (flags & FOLL_WRITE && !pmd_write(*pmd))
991                 goto out;
992
993         page = pmd_page(*pmd);
994         VM_BUG_ON(!PageHead(page));
995         if (flags & FOLL_TOUCH) {
996                 pmd_t _pmd;
997                 /*
998                  * We should set the dirty bit only for FOLL_WRITE but
999                  * for now the dirty bit in the pmd is meaningless.
1000                  * And if the dirty bit will become meaningful and
1001                  * we'll only set it with FOLL_WRITE, an atomic
1002                  * set_bit will be required on the pmd to set the
1003                  * young bit, instead of the current set_pmd_at.
1004                  */
1005                 _pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
1006                 set_pmd_at(mm, addr & HPAGE_PMD_MASK, pmd, _pmd);
1007         }
1008         if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
1009                 if (page->mapping && trylock_page(page)) {
1010                         lru_add_drain();
1011                         if (page->mapping)
1012                                 mlock_vma_page(page);
1013                         unlock_page(page);
1014                 }
1015         }
1016         page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1017         VM_BUG_ON(!PageCompound(page));
1018         if (flags & FOLL_GET)
1019                 get_page_foll(page);
1020
1021 out:
1022         return page;
1023 }
1024
1025 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1026                  pmd_t *pmd, unsigned long addr)
1027 {
1028         int ret = 0;
1029
1030         if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1031                 struct page *page;
1032                 pgtable_t pgtable;
1033                 pmd_t orig_pmd;
1034                 pgtable = pgtable_trans_huge_withdraw(tlb->mm);
1035                 orig_pmd = pmdp_get_and_clear(tlb->mm, addr, pmd);
1036                 page = pmd_page(orig_pmd);
1037                 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1038                 page_remove_rmap(page);
1039                 VM_BUG_ON(page_mapcount(page) < 0);
1040                 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1041                 VM_BUG_ON(!PageHead(page));
1042                 tlb->mm->nr_ptes--;
1043                 spin_unlock(&tlb->mm->page_table_lock);
1044                 tlb_remove_page(tlb, page);
1045                 pte_free(tlb->mm, pgtable);
1046                 ret = 1;
1047         }
1048         return ret;
1049 }
1050
1051 int mincore_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1052                 unsigned long addr, unsigned long end,
1053                 unsigned char *vec)
1054 {
1055         int ret = 0;
1056
1057         if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1058                 /*
1059                  * All logical pages in the range are present
1060                  * if backed by a huge page.
1061                  */
1062                 spin_unlock(&vma->vm_mm->page_table_lock);
1063                 memset(vec, 1, (end - addr) >> PAGE_SHIFT);
1064                 ret = 1;
1065         }
1066
1067         return ret;
1068 }
1069
1070 int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1071                   unsigned long old_addr,
1072                   unsigned long new_addr, unsigned long old_end,
1073                   pmd_t *old_pmd, pmd_t *new_pmd)
1074 {
1075         int ret = 0;
1076         pmd_t pmd;
1077
1078         struct mm_struct *mm = vma->vm_mm;
1079
1080         if ((old_addr & ~HPAGE_PMD_MASK) ||
1081             (new_addr & ~HPAGE_PMD_MASK) ||
1082             old_end - old_addr < HPAGE_PMD_SIZE ||
1083             (new_vma->vm_flags & VM_NOHUGEPAGE))
1084                 goto out;
1085
1086         /*
1087          * The destination pmd shouldn't be established, free_pgtables()
1088          * should have release it.
1089          */
1090         if (WARN_ON(!pmd_none(*new_pmd))) {
1091                 VM_BUG_ON(pmd_trans_huge(*new_pmd));
1092                 goto out;
1093         }
1094
1095         ret = __pmd_trans_huge_lock(old_pmd, vma);
1096         if (ret == 1) {
1097                 pmd = pmdp_get_and_clear(mm, old_addr, old_pmd);
1098                 VM_BUG_ON(!pmd_none(*new_pmd));
1099                 set_pmd_at(mm, new_addr, new_pmd, pmd);
1100                 spin_unlock(&mm->page_table_lock);
1101         }
1102 out:
1103         return ret;
1104 }
1105
1106 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1107                 unsigned long addr, pgprot_t newprot)
1108 {
1109         struct mm_struct *mm = vma->vm_mm;
1110         int ret = 0;
1111
1112         if (__pmd_trans_huge_lock(pmd, vma) == 1) {
1113                 pmd_t entry;
1114                 entry = pmdp_get_and_clear(mm, addr, pmd);
1115                 entry = pmd_modify(entry, newprot);
1116                 set_pmd_at(mm, addr, pmd, entry);
1117                 spin_unlock(&vma->vm_mm->page_table_lock);
1118                 ret = 1;
1119         }
1120
1121         return ret;
1122 }
1123
1124 /*
1125  * Returns 1 if a given pmd maps a stable (not under splitting) thp.
1126  * Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
1127  *
1128  * Note that if it returns 1, this routine returns without unlocking page
1129  * table locks. So callers must unlock them.
1130  */
1131 int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
1132 {
1133         spin_lock(&vma->vm_mm->page_table_lock);
1134         if (likely(pmd_trans_huge(*pmd))) {
1135                 if (unlikely(pmd_trans_splitting(*pmd))) {
1136                         spin_unlock(&vma->vm_mm->page_table_lock);
1137                         wait_split_huge_page(vma->anon_vma, pmd);
1138                         return -1;
1139                 } else {
1140                         /* Thp mapped by 'pmd' is stable, so we can
1141                          * handle it as it is. */
1142                         return 1;
1143                 }
1144         }
1145         spin_unlock(&vma->vm_mm->page_table_lock);
1146         return 0;
1147 }
1148
1149 pmd_t *page_check_address_pmd(struct page *page,
1150                               struct mm_struct *mm,
1151                               unsigned long address,
1152                               enum page_check_address_pmd_flag flag)
1153 {
1154         pmd_t *pmd, *ret = NULL;
1155
1156         if (address & ~HPAGE_PMD_MASK)
1157                 goto out;
1158
1159         pmd = mm_find_pmd(mm, address);
1160         if (!pmd)
1161                 goto out;
1162         if (pmd_none(*pmd))
1163                 goto out;
1164         if (pmd_page(*pmd) != page)
1165                 goto out;
1166         /*
1167          * split_vma() may create temporary aliased mappings. There is
1168          * no risk as long as all huge pmd are found and have their
1169          * splitting bit set before __split_huge_page_refcount
1170          * runs. Finding the same huge pmd more than once during the
1171          * same rmap walk is not a problem.
1172          */
1173         if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1174             pmd_trans_splitting(*pmd))
1175                 goto out;
1176         if (pmd_trans_huge(*pmd)) {
1177                 VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1178                           !pmd_trans_splitting(*pmd));
1179                 ret = pmd;
1180         }
1181 out:
1182         return ret;
1183 }
1184
1185 static int __split_huge_page_splitting(struct page *page,
1186                                        struct vm_area_struct *vma,
1187                                        unsigned long address)
1188 {
1189         struct mm_struct *mm = vma->vm_mm;
1190         pmd_t *pmd;
1191         int ret = 0;
1192         /* For mmu_notifiers */
1193         const unsigned long mmun_start = address;
1194         const unsigned long mmun_end   = address + HPAGE_PMD_SIZE;
1195
1196         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1197         spin_lock(&mm->page_table_lock);
1198         pmd = page_check_address_pmd(page, mm, address,
1199                                      PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG);
1200         if (pmd) {
1201                 /*
1202                  * We can't temporarily set the pmd to null in order
1203                  * to split it, the pmd must remain marked huge at all
1204                  * times or the VM won't take the pmd_trans_huge paths
1205                  * and it won't wait on the anon_vma->root->mutex to
1206                  * serialize against split_huge_page*.
1207                  */
1208                 pmdp_splitting_flush(vma, address, pmd);
1209                 ret = 1;
1210         }
1211         spin_unlock(&mm->page_table_lock);
1212         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1213
1214         return ret;
1215 }
1216
1217 static void __split_huge_page_refcount(struct page *page)
1218 {
1219         int i;
1220         struct zone *zone = page_zone(page);
1221         struct lruvec *lruvec;
1222         int tail_count = 0;
1223
1224         /* prevent PageLRU to go away from under us, and freeze lru stats */
1225         spin_lock_irq(&zone->lru_lock);
1226         lruvec = mem_cgroup_page_lruvec(page, zone);
1227
1228         compound_lock(page);
1229         /* complete memcg works before add pages to LRU */
1230         mem_cgroup_split_huge_fixup(page);
1231
1232         for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
1233                 struct page *page_tail = page + i;
1234
1235                 /* tail_page->_mapcount cannot change */
1236                 BUG_ON(page_mapcount(page_tail) < 0);
1237                 tail_count += page_mapcount(page_tail);
1238                 /* check for overflow */
1239                 BUG_ON(tail_count < 0);
1240                 BUG_ON(atomic_read(&page_tail->_count) != 0);
1241                 /*
1242                  * tail_page->_count is zero and not changing from
1243                  * under us. But get_page_unless_zero() may be running
1244                  * from under us on the tail_page. If we used
1245                  * atomic_set() below instead of atomic_add(), we
1246                  * would then run atomic_set() concurrently with
1247                  * get_page_unless_zero(), and atomic_set() is
1248                  * implemented in C not using locked ops. spin_unlock
1249                  * on x86 sometime uses locked ops because of PPro
1250                  * errata 66, 92, so unless somebody can guarantee
1251                  * atomic_set() here would be safe on all archs (and
1252                  * not only on x86), it's safer to use atomic_add().
1253                  */
1254                 atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1255                            &page_tail->_count);
1256
1257                 /* after clearing PageTail the gup refcount can be released */
1258                 smp_mb();
1259
1260                 /*
1261                  * retain hwpoison flag of the poisoned tail page:
1262                  *   fix for the unsuitable process killed on Guest Machine(KVM)
1263                  *   by the memory-failure.
1264                  */
1265                 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP | __PG_HWPOISON;
1266                 page_tail->flags |= (page->flags &
1267                                      ((1L << PG_referenced) |
1268                                       (1L << PG_swapbacked) |
1269                                       (1L << PG_mlocked) |
1270                                       (1L << PG_uptodate)));
1271                 page_tail->flags |= (1L << PG_dirty);
1272
1273                 /* clear PageTail before overwriting first_page */
1274                 smp_wmb();
1275
1276                 /*
1277                  * __split_huge_page_splitting() already set the
1278                  * splitting bit in all pmd that could map this
1279                  * hugepage, that will ensure no CPU can alter the
1280                  * mapcount on the head page. The mapcount is only
1281                  * accounted in the head page and it has to be
1282                  * transferred to all tail pages in the below code. So
1283                  * for this code to be safe, the split the mapcount
1284                  * can't change. But that doesn't mean userland can't
1285                  * keep changing and reading the page contents while
1286                  * we transfer the mapcount, so the pmd splitting
1287                  * status is achieved setting a reserved bit in the
1288                  * pmd, not by clearing the present bit.
1289                 */
1290                 page_tail->_mapcount = page->_mapcount;
1291
1292                 BUG_ON(page_tail->mapping);
1293                 page_tail->mapping = page->mapping;
1294
1295                 page_tail->index = page->index + i;
1296
1297                 BUG_ON(!PageAnon(page_tail));
1298                 BUG_ON(!PageUptodate(page_tail));
1299                 BUG_ON(!PageDirty(page_tail));
1300                 BUG_ON(!PageSwapBacked(page_tail));
1301
1302                 lru_add_page_tail(page, page_tail, lruvec);
1303         }
1304         atomic_sub(tail_count, &page->_count);
1305         BUG_ON(atomic_read(&page->_count) <= 0);
1306
1307         __mod_zone_page_state(zone, NR_ANON_TRANSPARENT_HUGEPAGES, -1);
1308         __mod_zone_page_state(zone, NR_ANON_PAGES, HPAGE_PMD_NR);
1309
1310         ClearPageCompound(page);
1311         compound_unlock(page);
1312         spin_unlock_irq(&zone->lru_lock);
1313
1314         for (i = 1; i < HPAGE_PMD_NR; i++) {
1315                 struct page *page_tail = page + i;
1316                 BUG_ON(page_count(page_tail) <= 0);
1317                 /*
1318                  * Tail pages may be freed if there wasn't any mapping
1319                  * like if add_to_swap() is running on a lru page that
1320                  * had its mapping zapped. And freeing these pages
1321                  * requires taking the lru_lock so we do the put_page
1322                  * of the tail pages after the split is complete.
1323                  */
1324                 put_page(page_tail);
1325         }
1326
1327         /*
1328          * Only the head page (now become a regular page) is required
1329          * to be pinned by the caller.
1330          */
1331         BUG_ON(page_count(page) <= 0);
1332 }
1333
1334 static int __split_huge_page_map(struct page *page,
1335                                  struct vm_area_struct *vma,
1336                                  unsigned long address)
1337 {
1338         struct mm_struct *mm = vma->vm_mm;
1339         pmd_t *pmd, _pmd;
1340         int ret = 0, i;
1341         pgtable_t pgtable;
1342         unsigned long haddr;
1343
1344         spin_lock(&mm->page_table_lock);
1345         pmd = page_check_address_pmd(page, mm, address,
1346                                      PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG);
1347         if (pmd) {
1348                 pgtable = pgtable_trans_huge_withdraw(mm);
1349                 pmd_populate(mm, &_pmd, pgtable);
1350
1351                 haddr = address;
1352                 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1353                         pte_t *pte, entry;
1354                         BUG_ON(PageCompound(page+i));
1355                         entry = mk_pte(page + i, vma->vm_page_prot);
1356                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1357                         if (!pmd_write(*pmd))
1358                                 entry = pte_wrprotect(entry);
1359                         else
1360                                 BUG_ON(page_mapcount(page) != 1);
1361                         if (!pmd_young(*pmd))
1362                                 entry = pte_mkold(entry);
1363                         pte = pte_offset_map(&_pmd, haddr);
1364                         BUG_ON(!pte_none(*pte));
1365                         set_pte_at(mm, haddr, pte, entry);
1366                         pte_unmap(pte);
1367                 }
1368
1369                 smp_wmb(); /* make pte visible before pmd */
1370                 /*
1371                  * Up to this point the pmd is present and huge and
1372                  * userland has the whole access to the hugepage
1373                  * during the split (which happens in place). If we
1374                  * overwrite the pmd with the not-huge version
1375                  * pointing to the pte here (which of course we could
1376                  * if all CPUs were bug free), userland could trigger
1377                  * a small page size TLB miss on the small sized TLB
1378                  * while the hugepage TLB entry is still established
1379                  * in the huge TLB. Some CPU doesn't like that. See
1380                  * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1381                  * Erratum 383 on page 93. Intel should be safe but is
1382                  * also warns that it's only safe if the permission
1383                  * and cache attributes of the two entries loaded in
1384                  * the two TLB is identical (which should be the case
1385                  * here). But it is generally safer to never allow
1386                  * small and huge TLB entries for the same virtual
1387                  * address to be loaded simultaneously. So instead of
1388                  * doing "pmd_populate(); flush_tlb_range();" we first
1389                  * mark the current pmd notpresent (atomically because
1390                  * here the pmd_trans_huge and pmd_trans_splitting
1391                  * must remain set at all times on the pmd until the
1392                  * split is complete for this pmd), then we flush the
1393                  * SMP TLB and finally we write the non-huge version
1394                  * of the pmd entry with pmd_populate.
1395                  */
1396                 pmdp_invalidate(vma, address, pmd);
1397                 pmd_populate(mm, pmd, pgtable);
1398                 ret = 1;
1399         }
1400         spin_unlock(&mm->page_table_lock);
1401
1402         return ret;
1403 }
1404
1405 /* must be called with anon_vma->root->mutex hold */
1406 static void __split_huge_page(struct page *page,
1407                               struct anon_vma *anon_vma)
1408 {
1409         int mapcount, mapcount2;
1410         pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
1411         struct anon_vma_chain *avc;
1412
1413         BUG_ON(!PageHead(page));
1414         BUG_ON(PageTail(page));
1415
1416         mapcount = 0;
1417         anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1418                 struct vm_area_struct *vma = avc->vma;
1419                 unsigned long addr = vma_address(page, vma);
1420                 BUG_ON(is_vma_temporary_stack(vma));
1421                 mapcount += __split_huge_page_splitting(page, vma, addr);
1422         }
1423         /*
1424          * It is critical that new vmas are added to the tail of the
1425          * anon_vma list. This guarantes that if copy_huge_pmd() runs
1426          * and establishes a child pmd before
1427          * __split_huge_page_splitting() freezes the parent pmd (so if
1428          * we fail to prevent copy_huge_pmd() from running until the
1429          * whole __split_huge_page() is complete), we will still see
1430          * the newly established pmd of the child later during the
1431          * walk, to be able to set it as pmd_trans_splitting too.
1432          */
1433         if (mapcount != page_mapcount(page))
1434                 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1435                        mapcount, page_mapcount(page));
1436         BUG_ON(mapcount != page_mapcount(page));
1437
1438         __split_huge_page_refcount(page);
1439
1440         mapcount2 = 0;
1441         anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1442                 struct vm_area_struct *vma = avc->vma;
1443                 unsigned long addr = vma_address(page, vma);
1444                 BUG_ON(is_vma_temporary_stack(vma));
1445                 mapcount2 += __split_huge_page_map(page, vma, addr);
1446         }
1447         if (mapcount != mapcount2)
1448                 printk(KERN_ERR "mapcount %d mapcount2 %d page_mapcount %d\n",
1449                        mapcount, mapcount2, page_mapcount(page));
1450         BUG_ON(mapcount != mapcount2);
1451 }
1452
1453 int split_huge_page(struct page *page)
1454 {
1455         struct anon_vma *anon_vma;
1456         int ret = 1;
1457
1458         BUG_ON(!PageAnon(page));
1459         anon_vma = page_lock_anon_vma(page);
1460         if (!anon_vma)
1461                 goto out;
1462         ret = 0;
1463         if (!PageCompound(page))
1464                 goto out_unlock;
1465
1466         BUG_ON(!PageSwapBacked(page));
1467         __split_huge_page(page, anon_vma);
1468         count_vm_event(THP_SPLIT);
1469
1470         BUG_ON(PageCompound(page));
1471 out_unlock:
1472         page_unlock_anon_vma(anon_vma);
1473 out:
1474         return ret;
1475 }
1476
1477 #define VM_NO_THP (VM_SPECIAL|VM_MIXEDMAP|VM_HUGETLB|VM_SHARED|VM_MAYSHARE)
1478
1479 int hugepage_madvise(struct vm_area_struct *vma,
1480                      unsigned long *vm_flags, int advice)
1481 {
1482         struct mm_struct *mm = vma->vm_mm;
1483
1484         switch (advice) {
1485         case MADV_HUGEPAGE:
1486                 /*
1487                  * Be somewhat over-protective like KSM for now!
1488                  */
1489                 if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP))
1490                         return -EINVAL;
1491                 if (mm->def_flags & VM_NOHUGEPAGE)
1492                         return -EINVAL;
1493                 *vm_flags &= ~VM_NOHUGEPAGE;
1494                 *vm_flags |= VM_HUGEPAGE;
1495                 /*
1496                  * If the vma become good for khugepaged to scan,
1497                  * register it here without waiting a page fault that
1498                  * may not happen any time soon.
1499                  */
1500                 if (unlikely(khugepaged_enter_vma_merge(vma)))
1501                         return -ENOMEM;
1502                 break;
1503         case MADV_NOHUGEPAGE:
1504                 /*
1505                  * Be somewhat over-protective like KSM for now!
1506                  */
1507                 if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP))
1508                         return -EINVAL;
1509                 *vm_flags &= ~VM_HUGEPAGE;
1510                 *vm_flags |= VM_NOHUGEPAGE;
1511                 /*
1512                  * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1513                  * this vma even if we leave the mm registered in khugepaged if
1514                  * it got registered before VM_NOHUGEPAGE was set.
1515                  */
1516                 break;
1517         }
1518
1519         return 0;
1520 }
1521
1522 static int __init khugepaged_slab_init(void)
1523 {
1524         mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1525                                           sizeof(struct mm_slot),
1526                                           __alignof__(struct mm_slot), 0, NULL);
1527         if (!mm_slot_cache)
1528                 return -ENOMEM;
1529
1530         return 0;
1531 }
1532
1533 static void __init khugepaged_slab_free(void)
1534 {
1535         kmem_cache_destroy(mm_slot_cache);
1536         mm_slot_cache = NULL;
1537 }
1538
1539 static inline struct mm_slot *alloc_mm_slot(void)
1540 {
1541         if (!mm_slot_cache)     /* initialization failed */
1542                 return NULL;
1543         return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1544 }
1545
1546 static inline void free_mm_slot(struct mm_slot *mm_slot)
1547 {
1548         kmem_cache_free(mm_slot_cache, mm_slot);
1549 }
1550
1551 static int __init mm_slots_hash_init(void)
1552 {
1553         mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
1554                                 GFP_KERNEL);
1555         if (!mm_slots_hash)
1556                 return -ENOMEM;
1557         return 0;
1558 }
1559
1560 #if 0
1561 static void __init mm_slots_hash_free(void)
1562 {
1563         kfree(mm_slots_hash);
1564         mm_slots_hash = NULL;
1565 }
1566 #endif
1567
1568 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1569 {
1570         struct mm_slot *mm_slot;
1571         struct hlist_head *bucket;
1572         struct hlist_node *node;
1573
1574         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1575                                 % MM_SLOTS_HASH_HEADS];
1576         hlist_for_each_entry(mm_slot, node, bucket, hash) {
1577                 if (mm == mm_slot->mm)
1578                         return mm_slot;
1579         }
1580         return NULL;
1581 }
1582
1583 static void insert_to_mm_slots_hash(struct mm_struct *mm,
1584                                     struct mm_slot *mm_slot)
1585 {
1586         struct hlist_head *bucket;
1587
1588         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
1589                                 % MM_SLOTS_HASH_HEADS];
1590         mm_slot->mm = mm;
1591         hlist_add_head(&mm_slot->hash, bucket);
1592 }
1593
1594 static inline int khugepaged_test_exit(struct mm_struct *mm)
1595 {
1596         return atomic_read(&mm->mm_users) == 0;
1597 }
1598
1599 int __khugepaged_enter(struct mm_struct *mm)
1600 {
1601         struct mm_slot *mm_slot;
1602         int wakeup;
1603
1604         mm_slot = alloc_mm_slot();
1605         if (!mm_slot)
1606                 return -ENOMEM;
1607
1608         /* __khugepaged_exit() must not run from under us */
1609         VM_BUG_ON(khugepaged_test_exit(mm));
1610         if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1611                 free_mm_slot(mm_slot);
1612                 return 0;
1613         }
1614
1615         spin_lock(&khugepaged_mm_lock);
1616         insert_to_mm_slots_hash(mm, mm_slot);
1617         /*
1618          * Insert just behind the scanning cursor, to let the area settle
1619          * down a little.
1620          */
1621         wakeup = list_empty(&khugepaged_scan.mm_head);
1622         list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1623         spin_unlock(&khugepaged_mm_lock);
1624
1625         atomic_inc(&mm->mm_count);
1626         if (wakeup)
1627                 wake_up_interruptible(&khugepaged_wait);
1628
1629         return 0;
1630 }
1631
1632 int khugepaged_enter_vma_merge(struct vm_area_struct *vma)
1633 {
1634         unsigned long hstart, hend;
1635         if (!vma->anon_vma)
1636                 /*
1637                  * Not yet faulted in so we will register later in the
1638                  * page fault if needed.
1639                  */
1640                 return 0;
1641         if (vma->vm_ops)
1642                 /* khugepaged not yet working on file or special mappings */
1643                 return 0;
1644         VM_BUG_ON(vma->vm_flags & VM_NO_THP);
1645         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1646         hend = vma->vm_end & HPAGE_PMD_MASK;
1647         if (hstart < hend)
1648                 return khugepaged_enter(vma);
1649         return 0;
1650 }
1651
1652 void __khugepaged_exit(struct mm_struct *mm)
1653 {
1654         struct mm_slot *mm_slot;
1655         int free = 0;
1656
1657         spin_lock(&khugepaged_mm_lock);
1658         mm_slot = get_mm_slot(mm);
1659         if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
1660                 hlist_del(&mm_slot->hash);
1661                 list_del(&mm_slot->mm_node);
1662                 free = 1;
1663         }
1664         spin_unlock(&khugepaged_mm_lock);
1665
1666         if (free) {
1667                 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1668                 free_mm_slot(mm_slot);
1669                 mmdrop(mm);
1670         } else if (mm_slot) {
1671                 /*
1672                  * This is required to serialize against
1673                  * khugepaged_test_exit() (which is guaranteed to run
1674                  * under mmap sem read mode). Stop here (after we
1675                  * return all pagetables will be destroyed) until
1676                  * khugepaged has finished working on the pagetables
1677                  * under the mmap_sem.
1678                  */
1679                 down_write(&mm->mmap_sem);
1680                 up_write(&mm->mmap_sem);
1681         }
1682 }
1683
1684 static void release_pte_page(struct page *page)
1685 {
1686         /* 0 stands for page_is_file_cache(page) == false */
1687         dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
1688         unlock_page(page);
1689         putback_lru_page(page);
1690 }
1691
1692 static void release_pte_pages(pte_t *pte, pte_t *_pte)
1693 {
1694         while (--_pte >= pte) {
1695                 pte_t pteval = *_pte;
1696                 if (!pte_none(pteval))
1697                         release_pte_page(pte_page(pteval));
1698         }
1699 }
1700
1701 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
1702                                         unsigned long address,
1703                                         pte_t *pte)
1704 {
1705         struct page *page;
1706         pte_t *_pte;
1707         int referenced = 0, none = 0;
1708         for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
1709              _pte++, address += PAGE_SIZE) {
1710                 pte_t pteval = *_pte;
1711                 if (pte_none(pteval)) {
1712                         if (++none <= khugepaged_max_ptes_none)
1713                                 continue;
1714                         else
1715                                 goto out;
1716                 }
1717                 if (!pte_present(pteval) || !pte_write(pteval))
1718                         goto out;
1719                 page = vm_normal_page(vma, address, pteval);
1720                 if (unlikely(!page))
1721                         goto out;
1722
1723                 VM_BUG_ON(PageCompound(page));
1724                 BUG_ON(!PageAnon(page));
1725                 VM_BUG_ON(!PageSwapBacked(page));
1726
1727                 /* cannot use mapcount: can't collapse if there's a gup pin */
1728                 if (page_count(page) != 1)
1729                         goto out;
1730                 /*
1731                  * We can do it before isolate_lru_page because the
1732                  * page can't be freed from under us. NOTE: PG_lock
1733                  * is needed to serialize against split_huge_page
1734                  * when invoked from the VM.
1735                  */
1736                 if (!trylock_page(page))
1737                         goto out;
1738                 /*
1739                  * Isolate the page to avoid collapsing an hugepage
1740                  * currently in use by the VM.
1741                  */
1742                 if (isolate_lru_page(page)) {
1743                         unlock_page(page);
1744                         goto out;
1745                 }
1746                 /* 0 stands for page_is_file_cache(page) == false */
1747                 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
1748                 VM_BUG_ON(!PageLocked(page));
1749                 VM_BUG_ON(PageLRU(page));
1750
1751                 /* If there is no mapped pte young don't collapse the page */
1752                 if (pte_young(pteval) || PageReferenced(page) ||
1753                     mmu_notifier_test_young(vma->vm_mm, address))
1754                         referenced = 1;
1755         }
1756         if (likely(referenced))
1757                 return 1;
1758 out:
1759         release_pte_pages(pte, _pte);
1760         return 0;
1761 }
1762
1763 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
1764                                       struct vm_area_struct *vma,
1765                                       unsigned long address,
1766                                       spinlock_t *ptl)
1767 {
1768         pte_t *_pte;
1769         for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
1770                 pte_t pteval = *_pte;
1771                 struct page *src_page;
1772
1773                 if (pte_none(pteval)) {
1774                         clear_user_highpage(page, address);
1775                         add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
1776                 } else {
1777                         src_page = pte_page(pteval);
1778                         copy_user_highpage(page, src_page, address, vma);
1779                         VM_BUG_ON(page_mapcount(src_page) != 1);
1780                         release_pte_page(src_page);
1781                         /*
1782                          * ptl mostly unnecessary, but preempt has to
1783                          * be disabled to update the per-cpu stats
1784                          * inside page_remove_rmap().
1785                          */
1786                         spin_lock(ptl);
1787                         /*
1788                          * paravirt calls inside pte_clear here are
1789                          * superfluous.
1790                          */
1791                         pte_clear(vma->vm_mm, address, _pte);
1792                         page_remove_rmap(src_page);
1793                         spin_unlock(ptl);
1794                         free_page_and_swap_cache(src_page);
1795                 }
1796
1797                 address += PAGE_SIZE;
1798                 page++;
1799         }
1800 }
1801
1802 static void khugepaged_alloc_sleep(void)
1803 {
1804         wait_event_freezable_timeout(khugepaged_wait, false,
1805                         msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
1806 }
1807
1808 #ifdef CONFIG_NUMA
1809 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
1810 {
1811         if (IS_ERR(*hpage)) {
1812                 if (!*wait)
1813                         return false;
1814
1815                 *wait = false;
1816                 *hpage = NULL;
1817                 khugepaged_alloc_sleep();
1818         } else if (*hpage) {
1819                 put_page(*hpage);
1820                 *hpage = NULL;
1821         }
1822
1823         return true;
1824 }
1825
1826 static struct page
1827 *khugepaged_alloc_page(struct page **hpage, struct mm_struct *mm,
1828                        struct vm_area_struct *vma, unsigned long address,
1829                        int node)
1830 {
1831         VM_BUG_ON(*hpage);
1832         /*
1833          * Allocate the page while the vma is still valid and under
1834          * the mmap_sem read mode so there is no memory allocation
1835          * later when we take the mmap_sem in write mode. This is more
1836          * friendly behavior (OTOH it may actually hide bugs) to
1837          * filesystems in userland with daemons allocating memory in
1838          * the userland I/O paths.  Allocating memory with the
1839          * mmap_sem in read mode is good idea also to allow greater
1840          * scalability.
1841          */
1842         *hpage  = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
1843                                       node, __GFP_OTHER_NODE);
1844
1845         /*
1846          * After allocating the hugepage, release the mmap_sem read lock in
1847          * preparation for taking it in write mode.
1848          */
1849         up_read(&mm->mmap_sem);
1850         if (unlikely(!*hpage)) {
1851                 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1852                 *hpage = ERR_PTR(-ENOMEM);
1853                 return NULL;
1854         }
1855
1856         count_vm_event(THP_COLLAPSE_ALLOC);
1857         return *hpage;
1858 }
1859 #else
1860 static struct page *khugepaged_alloc_hugepage(bool *wait)
1861 {
1862         struct page *hpage;
1863
1864         do {
1865                 hpage = alloc_hugepage(khugepaged_defrag());
1866                 if (!hpage) {
1867                         count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1868                         if (!*wait)
1869                                 return NULL;
1870
1871                         *wait = false;
1872                         khugepaged_alloc_sleep();
1873                 } else
1874                         count_vm_event(THP_COLLAPSE_ALLOC);
1875         } while (unlikely(!hpage) && likely(khugepaged_enabled()));
1876
1877         return hpage;
1878 }
1879
1880 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
1881 {
1882         if (!*hpage)
1883                 *hpage = khugepaged_alloc_hugepage(wait);
1884
1885         if (unlikely(!*hpage))
1886                 return false;
1887
1888         return true;
1889 }
1890
1891 static struct page
1892 *khugepaged_alloc_page(struct page **hpage, struct mm_struct *mm,
1893                        struct vm_area_struct *vma, unsigned long address,
1894                        int node)
1895 {
1896         up_read(&mm->mmap_sem);
1897         VM_BUG_ON(!*hpage);
1898         return  *hpage;
1899 }
1900 #endif
1901
1902 static bool hugepage_vma_check(struct vm_area_struct *vma)
1903 {
1904         if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
1905             (vma->vm_flags & VM_NOHUGEPAGE))
1906                 return false;
1907
1908         if (!vma->anon_vma || vma->vm_ops)
1909                 return false;
1910         if (is_vma_temporary_stack(vma))
1911                 return false;
1912         VM_BUG_ON(vma->vm_flags & VM_NO_THP);
1913         return true;
1914 }
1915
1916 static void collapse_huge_page(struct mm_struct *mm,
1917                                    unsigned long address,
1918                                    struct page **hpage,
1919                                    struct vm_area_struct *vma,
1920                                    int node)
1921 {
1922         pmd_t *pmd, _pmd;
1923         pte_t *pte;
1924         pgtable_t pgtable;
1925         struct page *new_page;
1926         spinlock_t *ptl;
1927         int isolated;
1928         unsigned long hstart, hend;
1929         unsigned long mmun_start;       /* For mmu_notifiers */
1930         unsigned long mmun_end;         /* For mmu_notifiers */
1931
1932         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1933
1934         /* release the mmap_sem read lock. */
1935         new_page = khugepaged_alloc_page(hpage, mm, vma, address, node);
1936         if (!new_page)
1937                 return;
1938
1939         if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL)))
1940                 return;
1941
1942         /*
1943          * Prevent all access to pagetables with the exception of
1944          * gup_fast later hanlded by the ptep_clear_flush and the VM
1945          * handled by the anon_vma lock + PG_lock.
1946          */
1947         down_write(&mm->mmap_sem);
1948         if (unlikely(khugepaged_test_exit(mm)))
1949                 goto out;
1950
1951         vma = find_vma(mm, address);
1952         hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1953         hend = vma->vm_end & HPAGE_PMD_MASK;
1954         if (address < hstart || address + HPAGE_PMD_SIZE > hend)
1955                 goto out;
1956         if (!hugepage_vma_check(vma))
1957                 goto out;
1958         pmd = mm_find_pmd(mm, address);
1959         if (!pmd)
1960                 goto out;
1961         if (pmd_trans_huge(*pmd))
1962                 goto out;
1963
1964         anon_vma_lock(vma->anon_vma);
1965
1966         pte = pte_offset_map(pmd, address);
1967         ptl = pte_lockptr(mm, pmd);
1968
1969         mmun_start = address;
1970         mmun_end   = address + HPAGE_PMD_SIZE;
1971         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1972         spin_lock(&mm->page_table_lock); /* probably unnecessary */
1973         /*
1974          * After this gup_fast can't run anymore. This also removes
1975          * any huge TLB entry from the CPU so we won't allow
1976          * huge and small TLB entries for the same virtual address
1977          * to avoid the risk of CPU bugs in that area.
1978          */
1979         _pmd = pmdp_clear_flush(vma, address, pmd);
1980         spin_unlock(&mm->page_table_lock);
1981         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1982
1983         spin_lock(ptl);
1984         isolated = __collapse_huge_page_isolate(vma, address, pte);
1985         spin_unlock(ptl);
1986
1987         if (unlikely(!isolated)) {
1988                 pte_unmap(pte);
1989                 spin_lock(&mm->page_table_lock);
1990                 BUG_ON(!pmd_none(*pmd));
1991                 set_pmd_at(mm, address, pmd, _pmd);
1992                 spin_unlock(&mm->page_table_lock);
1993                 anon_vma_unlock(vma->anon_vma);
1994                 goto out;
1995         }
1996
1997         /*
1998          * All pages are isolated and locked so anon_vma rmap
1999          * can't run anymore.
2000          */
2001         anon_vma_unlock(vma->anon_vma);
2002
2003         __collapse_huge_page_copy(pte, new_page, vma, address, ptl);
2004         pte_unmap(pte);
2005         __SetPageUptodate(new_page);
2006         pgtable = pmd_pgtable(_pmd);
2007
2008         _pmd = mk_huge_pmd(new_page, vma);
2009
2010         /*
2011          * spin_lock() below is not the equivalent of smp_wmb(), so
2012          * this is needed to avoid the copy_huge_page writes to become
2013          * visible after the set_pmd_at() write.
2014          */
2015         smp_wmb();
2016
2017         spin_lock(&mm->page_table_lock);
2018         BUG_ON(!pmd_none(*pmd));
2019         page_add_new_anon_rmap(new_page, vma, address);
2020         set_pmd_at(mm, address, pmd, _pmd);
2021         update_mmu_cache_pmd(vma, address, pmd);
2022         pgtable_trans_huge_deposit(mm, pgtable);
2023         spin_unlock(&mm->page_table_lock);
2024
2025         *hpage = NULL;
2026
2027         khugepaged_pages_collapsed++;
2028 out_up_write:
2029         up_write(&mm->mmap_sem);
2030         return;
2031
2032 out:
2033         mem_cgroup_uncharge_page(new_page);
2034         goto out_up_write;
2035 }
2036
2037 static int khugepaged_scan_pmd(struct mm_struct *mm,
2038                                struct vm_area_struct *vma,
2039                                unsigned long address,
2040                                struct page **hpage)
2041 {
2042         pmd_t *pmd;
2043         pte_t *pte, *_pte;
2044         int ret = 0, referenced = 0, none = 0;
2045         struct page *page;
2046         unsigned long _address;
2047         spinlock_t *ptl;
2048         int node = -1;
2049
2050         VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2051
2052         pmd = mm_find_pmd(mm, address);
2053         if (!pmd)
2054                 goto out;
2055         if (pmd_trans_huge(*pmd))
2056                 goto out;
2057
2058         pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2059         for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2060              _pte++, _address += PAGE_SIZE) {
2061                 pte_t pteval = *_pte;
2062                 if (pte_none(pteval)) {
2063                         if (++none <= khugepaged_max_ptes_none)
2064                                 continue;
2065                         else
2066                                 goto out_unmap;
2067                 }
2068                 if (!pte_present(pteval) || !pte_write(pteval))
2069                         goto out_unmap;
2070                 page = vm_normal_page(vma, _address, pteval);
2071                 if (unlikely(!page))
2072                         goto out_unmap;
2073                 /*
2074                  * Chose the node of the first page. This could
2075                  * be more sophisticated and look at more pages,
2076                  * but isn't for now.
2077                  */
2078                 if (node == -1)
2079                         node = page_to_nid(page);
2080                 VM_BUG_ON(PageCompound(page));
2081                 if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2082                         goto out_unmap;
2083                 /* cannot use mapcount: can't collapse if there's a gup pin */
2084                 if (page_count(page) != 1)
2085                         goto out_unmap;
2086                 if (pte_young(pteval) || PageReferenced(page) ||
2087                     mmu_notifier_test_young(vma->vm_mm, address))
2088                         referenced = 1;
2089         }
2090         if (referenced)
2091                 ret = 1;
2092 out_unmap:
2093         pte_unmap_unlock(pte, ptl);
2094         if (ret)
2095                 /* collapse_huge_page will return with the mmap_sem released */
2096                 collapse_huge_page(mm, address, hpage, vma, node);
2097 out:
2098         return ret;
2099 }
2100
2101 static void collect_mm_slot(struct mm_slot *mm_slot)
2102 {
2103         struct mm_struct *mm = mm_slot->mm;
2104
2105         VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2106
2107         if (khugepaged_test_exit(mm)) {
2108                 /* free mm_slot */
2109                 hlist_del(&mm_slot->hash);
2110                 list_del(&mm_slot->mm_node);
2111
2112                 /*
2113                  * Not strictly needed because the mm exited already.
2114                  *
2115                  * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2116                  */
2117
2118                 /* khugepaged_mm_lock actually not necessary for the below */
2119                 free_mm_slot(mm_slot);
2120                 mmdrop(mm);
2121         }
2122 }
2123
2124 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2125                                             struct page **hpage)
2126         __releases(&khugepaged_mm_lock)
2127         __acquires(&khugepaged_mm_lock)
2128 {
2129         struct mm_slot *mm_slot;
2130         struct mm_struct *mm;
2131         struct vm_area_struct *vma;
2132         int progress = 0;
2133
2134         VM_BUG_ON(!pages);
2135         VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2136
2137         if (khugepaged_scan.mm_slot)
2138                 mm_slot = khugepaged_scan.mm_slot;
2139         else {
2140                 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2141                                      struct mm_slot, mm_node);
2142                 khugepaged_scan.address = 0;
2143                 khugepaged_scan.mm_slot = mm_slot;
2144         }
2145         spin_unlock(&khugepaged_mm_lock);
2146
2147         mm = mm_slot->mm;
2148         down_read(&mm->mmap_sem);
2149         if (unlikely(khugepaged_test_exit(mm)))
2150                 vma = NULL;
2151         else
2152                 vma = find_vma(mm, khugepaged_scan.address);
2153
2154         progress++;
2155         for (; vma; vma = vma->vm_next) {
2156                 unsigned long hstart, hend;
2157
2158                 cond_resched();
2159                 if (unlikely(khugepaged_test_exit(mm))) {
2160                         progress++;
2161                         break;
2162                 }
2163                 if (!hugepage_vma_check(vma)) {
2164 skip:
2165                         progress++;
2166                         continue;
2167                 }
2168                 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2169                 hend = vma->vm_end & HPAGE_PMD_MASK;
2170                 if (hstart >= hend)
2171                         goto skip;
2172                 if (khugepaged_scan.address > hend)
2173                         goto skip;
2174                 if (khugepaged_scan.address < hstart)
2175                         khugepaged_scan.address = hstart;
2176                 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2177
2178                 while (khugepaged_scan.address < hend) {
2179                         int ret;
2180                         cond_resched();
2181                         if (unlikely(khugepaged_test_exit(mm)))
2182                                 goto breakouterloop;
2183
2184                         VM_BUG_ON(khugepaged_scan.address < hstart ||
2185                                   khugepaged_scan.address + HPAGE_PMD_SIZE >
2186                                   hend);
2187                         ret = khugepaged_scan_pmd(mm, vma,
2188                                                   khugepaged_scan.address,
2189                                                   hpage);
2190                         /* move to next address */
2191                         khugepaged_scan.address += HPAGE_PMD_SIZE;
2192                         progress += HPAGE_PMD_NR;
2193                         if (ret)
2194                                 /* we released mmap_sem so break loop */
2195                                 goto breakouterloop_mmap_sem;
2196                         if (progress >= pages)
2197                                 goto breakouterloop;
2198                 }
2199         }
2200 breakouterloop:
2201         up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2202 breakouterloop_mmap_sem:
2203
2204         spin_lock(&khugepaged_mm_lock);
2205         VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2206         /*
2207          * Release the current mm_slot if this mm is about to die, or
2208          * if we scanned all vmas of this mm.
2209          */
2210         if (khugepaged_test_exit(mm) || !vma) {
2211                 /*
2212                  * Make sure that if mm_users is reaching zero while
2213                  * khugepaged runs here, khugepaged_exit will find
2214                  * mm_slot not pointing to the exiting mm.
2215                  */
2216                 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2217                         khugepaged_scan.mm_slot = list_entry(
2218                                 mm_slot->mm_node.next,
2219                                 struct mm_slot, mm_node);
2220                         khugepaged_scan.address = 0;
2221                 } else {
2222                         khugepaged_scan.mm_slot = NULL;
2223                         khugepaged_full_scans++;
2224                 }
2225
2226                 collect_mm_slot(mm_slot);
2227         }
2228
2229         return progress;
2230 }
2231
2232 static int khugepaged_has_work(void)
2233 {
2234         return !list_empty(&khugepaged_scan.mm_head) &&
2235                 khugepaged_enabled();
2236 }
2237
2238 static int khugepaged_wait_event(void)
2239 {
2240         return !list_empty(&khugepaged_scan.mm_head) ||
2241                 kthread_should_stop();
2242 }
2243
2244 static void khugepaged_do_scan(void)
2245 {
2246         struct page *hpage = NULL;
2247         unsigned int progress = 0, pass_through_head = 0;
2248         unsigned int pages = khugepaged_pages_to_scan;
2249         bool wait = true;
2250
2251         barrier(); /* write khugepaged_pages_to_scan to local stack */
2252
2253         while (progress < pages) {
2254                 if (!khugepaged_prealloc_page(&hpage, &wait))
2255                         break;
2256
2257                 cond_resched();
2258
2259                 if (unlikely(kthread_should_stop() || freezing(current)))
2260                         break;
2261
2262                 spin_lock(&khugepaged_mm_lock);
2263                 if (!khugepaged_scan.mm_slot)
2264                         pass_through_head++;
2265                 if (khugepaged_has_work() &&
2266                     pass_through_head < 2)
2267                         progress += khugepaged_scan_mm_slot(pages - progress,
2268                                                             &hpage);
2269                 else
2270                         progress = pages;
2271                 spin_unlock(&khugepaged_mm_lock);
2272         }
2273
2274         if (!IS_ERR_OR_NULL(hpage))
2275                 put_page(hpage);
2276 }
2277
2278 static void khugepaged_wait_work(void)
2279 {
2280         try_to_freeze();
2281
2282         if (khugepaged_has_work()) {
2283                 if (!khugepaged_scan_sleep_millisecs)
2284                         return;
2285
2286                 wait_event_freezable_timeout(khugepaged_wait,
2287                                              kthread_should_stop(),
2288                         msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2289                 return;
2290         }
2291
2292         if (khugepaged_enabled())
2293                 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2294 }
2295
2296 static int khugepaged(void *none)
2297 {
2298         struct mm_slot *mm_slot;
2299
2300         set_freezable();
2301         set_user_nice(current, 19);
2302
2303         while (!kthread_should_stop()) {
2304                 khugepaged_do_scan();
2305                 khugepaged_wait_work();
2306         }
2307
2308         spin_lock(&khugepaged_mm_lock);
2309         mm_slot = khugepaged_scan.mm_slot;
2310         khugepaged_scan.mm_slot = NULL;
2311         if (mm_slot)
2312                 collect_mm_slot(mm_slot);
2313         spin_unlock(&khugepaged_mm_lock);
2314         return 0;
2315 }
2316
2317 void __split_huge_page_pmd(struct mm_struct *mm, pmd_t *pmd)
2318 {
2319         struct page *page;
2320
2321         spin_lock(&mm->page_table_lock);
2322         if (unlikely(!pmd_trans_huge(*pmd))) {
2323                 spin_unlock(&mm->page_table_lock);
2324                 return;
2325         }
2326         page = pmd_page(*pmd);
2327         VM_BUG_ON(!page_count(page));
2328         get_page(page);
2329         spin_unlock(&mm->page_table_lock);
2330
2331         split_huge_page(page);
2332
2333         put_page(page);
2334         BUG_ON(pmd_trans_huge(*pmd));
2335 }
2336
2337 static void split_huge_page_address(struct mm_struct *mm,
2338                                     unsigned long address)
2339 {
2340         pmd_t *pmd;
2341
2342         VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
2343
2344         pmd = mm_find_pmd(mm, address);
2345         if (!pmd)
2346                 return;
2347         /*
2348          * Caller holds the mmap_sem write mode, so a huge pmd cannot
2349          * materialize from under us.
2350          */
2351         split_huge_page_pmd(mm, pmd);
2352 }
2353
2354 void __vma_adjust_trans_huge(struct vm_area_struct *vma,
2355                              unsigned long start,
2356                              unsigned long end,
2357                              long adjust_next)
2358 {
2359         /*
2360          * If the new start address isn't hpage aligned and it could
2361          * previously contain an hugepage: check if we need to split
2362          * an huge pmd.
2363          */
2364         if (start & ~HPAGE_PMD_MASK &&
2365             (start & HPAGE_PMD_MASK) >= vma->vm_start &&
2366             (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2367                 split_huge_page_address(vma->vm_mm, start);
2368
2369         /*
2370          * If the new end address isn't hpage aligned and it could
2371          * previously contain an hugepage: check if we need to split
2372          * an huge pmd.
2373          */
2374         if (end & ~HPAGE_PMD_MASK &&
2375             (end & HPAGE_PMD_MASK) >= vma->vm_start &&
2376             (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
2377                 split_huge_page_address(vma->vm_mm, end);
2378
2379         /*
2380          * If we're also updating the vma->vm_next->vm_start, if the new
2381          * vm_next->vm_start isn't page aligned and it could previously
2382          * contain an hugepage: check if we need to split an huge pmd.
2383          */
2384         if (adjust_next > 0) {
2385                 struct vm_area_struct *next = vma->vm_next;
2386                 unsigned long nstart = next->vm_start;
2387                 nstart += adjust_next << PAGE_SHIFT;
2388                 if (nstart & ~HPAGE_PMD_MASK &&
2389                     (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
2390                     (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
2391                         split_huge_page_address(next->vm_mm, nstart);
2392         }
2393 }