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