]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - mm/huge_memory.c
mm/page_ref: use page_ref helper instead of direct modification of _count
[mirror_ubuntu-artful-kernel.git] / mm / huge_memory.c
CommitLineData
71e3aac0
AA
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
ae3a8c1c
AM
8#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9
71e3aac0
AA
10#include <linux/mm.h>
11#include <linux/sched.h>
12#include <linux/highmem.h>
13#include <linux/hugetlb.h>
14#include <linux/mmu_notifier.h>
15#include <linux/rmap.h>
16#include <linux/swap.h>
97ae1749 17#include <linux/shrinker.h>
ba76149f 18#include <linux/mm_inline.h>
e9b61f19 19#include <linux/swapops.h>
4897c765 20#include <linux/dax.h>
ba76149f
AA
21#include <linux/kthread.h>
22#include <linux/khugepaged.h>
878aee7d 23#include <linux/freezer.h>
f25748e3 24#include <linux/pfn_t.h>
a664b2d8 25#include <linux/mman.h>
3565fce3 26#include <linux/memremap.h>
325adeb5 27#include <linux/pagemap.h>
49071d43 28#include <linux/debugfs.h>
4daae3b4 29#include <linux/migrate.h>
43b5fbbd 30#include <linux/hashtable.h>
6b251fc9 31#include <linux/userfaultfd_k.h>
33c3fc71 32#include <linux/page_idle.h>
97ae1749 33
71e3aac0
AA
34#include <asm/tlb.h>
35#include <asm/pgalloc.h>
36#include "internal.h"
37
7d2eba05
EA
38enum scan_result {
39 SCAN_FAIL,
40 SCAN_SUCCEED,
41 SCAN_PMD_NULL,
42 SCAN_EXCEED_NONE_PTE,
43 SCAN_PTE_NON_PRESENT,
44 SCAN_PAGE_RO,
45 SCAN_NO_REFERENCED_PAGE,
46 SCAN_PAGE_NULL,
47 SCAN_SCAN_ABORT,
48 SCAN_PAGE_COUNT,
49 SCAN_PAGE_LRU,
50 SCAN_PAGE_LOCK,
51 SCAN_PAGE_ANON,
b1caa957 52 SCAN_PAGE_COMPOUND,
7d2eba05
EA
53 SCAN_ANY_PROCESS,
54 SCAN_VMA_NULL,
55 SCAN_VMA_CHECK,
56 SCAN_ADDRESS_RANGE,
57 SCAN_SWAP_CACHE_PAGE,
58 SCAN_DEL_PAGE_LRU,
59 SCAN_ALLOC_HUGE_PAGE_FAIL,
60 SCAN_CGROUP_CHARGE_FAIL
61};
62
63#define CREATE_TRACE_POINTS
64#include <trace/events/huge_memory.h>
65
ba76149f 66/*
8bfa3f9a
JW
67 * By default transparent hugepage support is disabled in order that avoid
68 * to risk increase the memory footprint of applications without a guaranteed
69 * benefit. When transparent hugepage support is enabled, is for all mappings,
70 * and khugepaged scans all mappings.
71 * Defrag is invoked by khugepaged hugepage allocations and by page faults
72 * for all hugepage allocations.
ba76149f 73 */
71e3aac0 74unsigned long transparent_hugepage_flags __read_mostly =
13ece886 75#ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
ba76149f 76 (1<<TRANSPARENT_HUGEPAGE_FLAG)|
13ece886
AA
77#endif
78#ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
79 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
80#endif
444eb2a4 81 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|
79da5407
KS
82 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
83 (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
ba76149f
AA
84
85/* default scan 8*512 pte (or vmas) every 30 second */
ff20c2e0 86static unsigned int khugepaged_pages_to_scan __read_mostly;
ba76149f
AA
87static unsigned int khugepaged_pages_collapsed;
88static unsigned int khugepaged_full_scans;
89static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
90/* during fragmentation poll the hugepage allocator once every minute */
91static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
92static struct task_struct *khugepaged_thread __read_mostly;
93static DEFINE_MUTEX(khugepaged_mutex);
94static DEFINE_SPINLOCK(khugepaged_mm_lock);
95static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
96/*
97 * default collapse hugepages if there is at least one pte mapped like
98 * it would have happened if the vma was large enough during page
99 * fault.
100 */
ff20c2e0 101static unsigned int khugepaged_max_ptes_none __read_mostly;
ba76149f
AA
102
103static int khugepaged(void *none);
ba76149f 104static int khugepaged_slab_init(void);
65ebb64f 105static void khugepaged_slab_exit(void);
ba76149f 106
43b5fbbd
SL
107#define MM_SLOTS_HASH_BITS 10
108static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
109
ba76149f
AA
110static struct kmem_cache *mm_slot_cache __read_mostly;
111
112/**
113 * struct mm_slot - hash lookup from mm to mm_slot
114 * @hash: hash collision list
115 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
116 * @mm: the mm that this information is valid for
117 */
118struct mm_slot {
119 struct hlist_node hash;
120 struct list_head mm_node;
121 struct mm_struct *mm;
122};
123
124/**
125 * struct khugepaged_scan - cursor for scanning
126 * @mm_head: the head of the mm list to scan
127 * @mm_slot: the current mm_slot we are scanning
128 * @address: the next address inside that to be scanned
129 *
130 * There is only the one khugepaged_scan instance of this cursor structure.
131 */
132struct khugepaged_scan {
133 struct list_head mm_head;
134 struct mm_slot *mm_slot;
135 unsigned long address;
2f1da642
HS
136};
137static struct khugepaged_scan khugepaged_scan = {
ba76149f
AA
138 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
139};
140
9a982250 141static struct shrinker deferred_split_shrinker;
f000565a 142
2c0b80d4 143static void set_recommended_min_free_kbytes(void)
f000565a
AA
144{
145 struct zone *zone;
146 int nr_zones = 0;
147 unsigned long recommended_min;
f000565a 148
f000565a
AA
149 for_each_populated_zone(zone)
150 nr_zones++;
151
974a786e 152 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
f000565a
AA
153 recommended_min = pageblock_nr_pages * nr_zones * 2;
154
155 /*
156 * Make sure that on average at least two pageblocks are almost free
157 * of another type, one for a migratetype to fall back to and a
158 * second to avoid subsequent fallbacks of other types There are 3
159 * MIGRATE_TYPES we care about.
160 */
161 recommended_min += pageblock_nr_pages * nr_zones *
162 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
163
164 /* don't ever allow to reserve more than 5% of the lowmem */
165 recommended_min = min(recommended_min,
166 (unsigned long) nr_free_buffer_pages() / 20);
167 recommended_min <<= (PAGE_SHIFT-10);
168
42aa83cb
HP
169 if (recommended_min > min_free_kbytes) {
170 if (user_min_free_kbytes >= 0)
756a025f 171 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
42aa83cb
HP
172 min_free_kbytes, recommended_min);
173
f000565a 174 min_free_kbytes = recommended_min;
42aa83cb 175 }
f000565a 176 setup_per_zone_wmarks();
f000565a 177}
f000565a 178
79553da2 179static int start_stop_khugepaged(void)
ba76149f
AA
180{
181 int err = 0;
182 if (khugepaged_enabled()) {
ba76149f
AA
183 if (!khugepaged_thread)
184 khugepaged_thread = kthread_run(khugepaged, NULL,
185 "khugepaged");
18e8e5c7 186 if (IS_ERR(khugepaged_thread)) {
ae3a8c1c 187 pr_err("khugepaged: kthread_run(khugepaged) failed\n");
ba76149f
AA
188 err = PTR_ERR(khugepaged_thread);
189 khugepaged_thread = NULL;
79553da2 190 goto fail;
ba76149f 191 }
911891af
XG
192
193 if (!list_empty(&khugepaged_scan.mm_head))
ba76149f 194 wake_up_interruptible(&khugepaged_wait);
f000565a
AA
195
196 set_recommended_min_free_kbytes();
911891af 197 } else if (khugepaged_thread) {
911891af
XG
198 kthread_stop(khugepaged_thread);
199 khugepaged_thread = NULL;
200 }
79553da2 201fail:
ba76149f
AA
202 return err;
203}
71e3aac0 204
97ae1749 205static atomic_t huge_zero_refcount;
56873f43 206struct page *huge_zero_page __read_mostly;
4a6c1297 207
fc437044 208struct page *get_huge_zero_page(void)
97ae1749
KS
209{
210 struct page *zero_page;
211retry:
212 if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
4db0c3c2 213 return READ_ONCE(huge_zero_page);
97ae1749
KS
214
215 zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
4a6c1297 216 HPAGE_PMD_ORDER);
d8a8e1f0
KS
217 if (!zero_page) {
218 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
5918d10a 219 return NULL;
d8a8e1f0
KS
220 }
221 count_vm_event(THP_ZERO_PAGE_ALLOC);
97ae1749 222 preempt_disable();
5918d10a 223 if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
97ae1749 224 preempt_enable();
5ddacbe9 225 __free_pages(zero_page, compound_order(zero_page));
97ae1749
KS
226 goto retry;
227 }
228
229 /* We take additional reference here. It will be put back by shrinker */
230 atomic_set(&huge_zero_refcount, 2);
231 preempt_enable();
4db0c3c2 232 return READ_ONCE(huge_zero_page);
4a6c1297
KS
233}
234
aa88b68c 235void put_huge_zero_page(void)
4a6c1297 236{
97ae1749
KS
237 /*
238 * Counter should never go to zero here. Only shrinker can put
239 * last reference.
240 */
241 BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
4a6c1297
KS
242}
243
48896466
GC
244static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
245 struct shrink_control *sc)
4a6c1297 246{
48896466
GC
247 /* we can free zero page only if last reference remains */
248 return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
249}
97ae1749 250
48896466
GC
251static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
252 struct shrink_control *sc)
253{
97ae1749 254 if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
5918d10a
KS
255 struct page *zero_page = xchg(&huge_zero_page, NULL);
256 BUG_ON(zero_page == NULL);
5ddacbe9 257 __free_pages(zero_page, compound_order(zero_page));
48896466 258 return HPAGE_PMD_NR;
97ae1749
KS
259 }
260
261 return 0;
4a6c1297
KS
262}
263
97ae1749 264static struct shrinker huge_zero_page_shrinker = {
48896466
GC
265 .count_objects = shrink_huge_zero_page_count,
266 .scan_objects = shrink_huge_zero_page_scan,
97ae1749
KS
267 .seeks = DEFAULT_SEEKS,
268};
269
71e3aac0 270#ifdef CONFIG_SYSFS
ba76149f 271
444eb2a4 272static ssize_t triple_flag_store(struct kobject *kobj,
71e3aac0
AA
273 struct kobj_attribute *attr,
274 const char *buf, size_t count,
275 enum transparent_hugepage_flag enabled,
444eb2a4 276 enum transparent_hugepage_flag deferred,
71e3aac0
AA
277 enum transparent_hugepage_flag req_madv)
278{
444eb2a4
MG
279 if (!memcmp("defer", buf,
280 min(sizeof("defer")-1, count))) {
281 if (enabled == deferred)
282 return -EINVAL;
283 clear_bit(enabled, &transparent_hugepage_flags);
284 clear_bit(req_madv, &transparent_hugepage_flags);
285 set_bit(deferred, &transparent_hugepage_flags);
286 } else if (!memcmp("always", buf,
71e3aac0 287 min(sizeof("always")-1, count))) {
444eb2a4 288 clear_bit(deferred, &transparent_hugepage_flags);
71e3aac0 289 clear_bit(req_madv, &transparent_hugepage_flags);
444eb2a4 290 set_bit(enabled, &transparent_hugepage_flags);
71e3aac0
AA
291 } else if (!memcmp("madvise", buf,
292 min(sizeof("madvise")-1, count))) {
293 clear_bit(enabled, &transparent_hugepage_flags);
444eb2a4 294 clear_bit(deferred, &transparent_hugepage_flags);
71e3aac0
AA
295 set_bit(req_madv, &transparent_hugepage_flags);
296 } else if (!memcmp("never", buf,
297 min(sizeof("never")-1, count))) {
298 clear_bit(enabled, &transparent_hugepage_flags);
299 clear_bit(req_madv, &transparent_hugepage_flags);
444eb2a4 300 clear_bit(deferred, &transparent_hugepage_flags);
71e3aac0
AA
301 } else
302 return -EINVAL;
303
304 return count;
305}
306
307static ssize_t enabled_show(struct kobject *kobj,
308 struct kobj_attribute *attr, char *buf)
309{
444eb2a4
MG
310 if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags))
311 return sprintf(buf, "[always] madvise never\n");
312 else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags))
313 return sprintf(buf, "always [madvise] never\n");
314 else
315 return sprintf(buf, "always madvise [never]\n");
71e3aac0 316}
444eb2a4 317
71e3aac0
AA
318static ssize_t enabled_store(struct kobject *kobj,
319 struct kobj_attribute *attr,
320 const char *buf, size_t count)
321{
ba76149f
AA
322 ssize_t ret;
323
444eb2a4
MG
324 ret = triple_flag_store(kobj, attr, buf, count,
325 TRANSPARENT_HUGEPAGE_FLAG,
ba76149f
AA
326 TRANSPARENT_HUGEPAGE_FLAG,
327 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
328
329 if (ret > 0) {
911891af
XG
330 int err;
331
332 mutex_lock(&khugepaged_mutex);
79553da2 333 err = start_stop_khugepaged();
911891af
XG
334 mutex_unlock(&khugepaged_mutex);
335
ba76149f
AA
336 if (err)
337 ret = err;
338 }
339
340 return ret;
71e3aac0
AA
341}
342static struct kobj_attribute enabled_attr =
343 __ATTR(enabled, 0644, enabled_show, enabled_store);
344
345static ssize_t single_flag_show(struct kobject *kobj,
346 struct kobj_attribute *attr, char *buf,
347 enum transparent_hugepage_flag flag)
348{
e27e6151
BH
349 return sprintf(buf, "%d\n",
350 !!test_bit(flag, &transparent_hugepage_flags));
71e3aac0 351}
e27e6151 352
71e3aac0
AA
353static ssize_t single_flag_store(struct kobject *kobj,
354 struct kobj_attribute *attr,
355 const char *buf, size_t count,
356 enum transparent_hugepage_flag flag)
357{
e27e6151
BH
358 unsigned long value;
359 int ret;
360
361 ret = kstrtoul(buf, 10, &value);
362 if (ret < 0)
363 return ret;
364 if (value > 1)
365 return -EINVAL;
366
367 if (value)
71e3aac0 368 set_bit(flag, &transparent_hugepage_flags);
e27e6151 369 else
71e3aac0 370 clear_bit(flag, &transparent_hugepage_flags);
71e3aac0
AA
371
372 return count;
373}
374
375/*
376 * Currently defrag only disables __GFP_NOWAIT for allocation. A blind
377 * __GFP_REPEAT is too aggressive, it's never worth swapping tons of
378 * memory just to allocate one more hugepage.
379 */
380static ssize_t defrag_show(struct kobject *kobj,
381 struct kobj_attribute *attr, char *buf)
382{
444eb2a4
MG
383 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
384 return sprintf(buf, "[always] defer madvise never\n");
385 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
386 return sprintf(buf, "always [defer] madvise never\n");
387 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags))
388 return sprintf(buf, "always defer [madvise] never\n");
389 else
390 return sprintf(buf, "always defer madvise [never]\n");
391
71e3aac0
AA
392}
393static ssize_t defrag_store(struct kobject *kobj,
394 struct kobj_attribute *attr,
395 const char *buf, size_t count)
396{
444eb2a4
MG
397 return triple_flag_store(kobj, attr, buf, count,
398 TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,
399 TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,
71e3aac0
AA
400 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
401}
402static struct kobj_attribute defrag_attr =
403 __ATTR(defrag, 0644, defrag_show, defrag_store);
404
79da5407
KS
405static ssize_t use_zero_page_show(struct kobject *kobj,
406 struct kobj_attribute *attr, char *buf)
407{
408 return single_flag_show(kobj, attr, buf,
409 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
410}
411static ssize_t use_zero_page_store(struct kobject *kobj,
412 struct kobj_attribute *attr, const char *buf, size_t count)
413{
414 return single_flag_store(kobj, attr, buf, count,
415 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
416}
417static struct kobj_attribute use_zero_page_attr =
418 __ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
71e3aac0
AA
419#ifdef CONFIG_DEBUG_VM
420static ssize_t debug_cow_show(struct kobject *kobj,
421 struct kobj_attribute *attr, char *buf)
422{
423 return single_flag_show(kobj, attr, buf,
424 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
425}
426static ssize_t debug_cow_store(struct kobject *kobj,
427 struct kobj_attribute *attr,
428 const char *buf, size_t count)
429{
430 return single_flag_store(kobj, attr, buf, count,
431 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
432}
433static struct kobj_attribute debug_cow_attr =
434 __ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
435#endif /* CONFIG_DEBUG_VM */
436
437static struct attribute *hugepage_attr[] = {
438 &enabled_attr.attr,
439 &defrag_attr.attr,
79da5407 440 &use_zero_page_attr.attr,
71e3aac0
AA
441#ifdef CONFIG_DEBUG_VM
442 &debug_cow_attr.attr,
443#endif
444 NULL,
445};
446
447static struct attribute_group hugepage_attr_group = {
448 .attrs = hugepage_attr,
ba76149f
AA
449};
450
451static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
452 struct kobj_attribute *attr,
453 char *buf)
454{
455 return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
456}
457
458static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
459 struct kobj_attribute *attr,
460 const char *buf, size_t count)
461{
462 unsigned long msecs;
463 int err;
464
3dbb95f7 465 err = kstrtoul(buf, 10, &msecs);
ba76149f
AA
466 if (err || msecs > UINT_MAX)
467 return -EINVAL;
468
469 khugepaged_scan_sleep_millisecs = msecs;
470 wake_up_interruptible(&khugepaged_wait);
471
472 return count;
473}
474static struct kobj_attribute scan_sleep_millisecs_attr =
475 __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
476 scan_sleep_millisecs_store);
477
478static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
479 struct kobj_attribute *attr,
480 char *buf)
481{
482 return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
483}
484
485static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
486 struct kobj_attribute *attr,
487 const char *buf, size_t count)
488{
489 unsigned long msecs;
490 int err;
491
3dbb95f7 492 err = kstrtoul(buf, 10, &msecs);
ba76149f
AA
493 if (err || msecs > UINT_MAX)
494 return -EINVAL;
495
496 khugepaged_alloc_sleep_millisecs = msecs;
497 wake_up_interruptible(&khugepaged_wait);
498
499 return count;
500}
501static struct kobj_attribute alloc_sleep_millisecs_attr =
502 __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
503 alloc_sleep_millisecs_store);
504
505static ssize_t pages_to_scan_show(struct kobject *kobj,
506 struct kobj_attribute *attr,
507 char *buf)
508{
509 return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
510}
511static ssize_t pages_to_scan_store(struct kobject *kobj,
512 struct kobj_attribute *attr,
513 const char *buf, size_t count)
514{
515 int err;
516 unsigned long pages;
517
3dbb95f7 518 err = kstrtoul(buf, 10, &pages);
ba76149f
AA
519 if (err || !pages || pages > UINT_MAX)
520 return -EINVAL;
521
522 khugepaged_pages_to_scan = pages;
523
524 return count;
525}
526static struct kobj_attribute pages_to_scan_attr =
527 __ATTR(pages_to_scan, 0644, pages_to_scan_show,
528 pages_to_scan_store);
529
530static ssize_t pages_collapsed_show(struct kobject *kobj,
531 struct kobj_attribute *attr,
532 char *buf)
533{
534 return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
535}
536static struct kobj_attribute pages_collapsed_attr =
537 __ATTR_RO(pages_collapsed);
538
539static ssize_t full_scans_show(struct kobject *kobj,
540 struct kobj_attribute *attr,
541 char *buf)
542{
543 return sprintf(buf, "%u\n", khugepaged_full_scans);
544}
545static struct kobj_attribute full_scans_attr =
546 __ATTR_RO(full_scans);
547
548static ssize_t khugepaged_defrag_show(struct kobject *kobj,
549 struct kobj_attribute *attr, char *buf)
550{
551 return single_flag_show(kobj, attr, buf,
552 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
553}
554static ssize_t khugepaged_defrag_store(struct kobject *kobj,
555 struct kobj_attribute *attr,
556 const char *buf, size_t count)
557{
558 return single_flag_store(kobj, attr, buf, count,
559 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
560}
561static struct kobj_attribute khugepaged_defrag_attr =
562 __ATTR(defrag, 0644, khugepaged_defrag_show,
563 khugepaged_defrag_store);
564
565/*
566 * max_ptes_none controls if khugepaged should collapse hugepages over
567 * any unmapped ptes in turn potentially increasing the memory
568 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
569 * reduce the available free memory in the system as it
570 * runs. Increasing max_ptes_none will instead potentially reduce the
571 * free memory in the system during the khugepaged scan.
572 */
573static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
574 struct kobj_attribute *attr,
575 char *buf)
576{
577 return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
578}
579static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
580 struct kobj_attribute *attr,
581 const char *buf, size_t count)
582{
583 int err;
584 unsigned long max_ptes_none;
585
3dbb95f7 586 err = kstrtoul(buf, 10, &max_ptes_none);
ba76149f
AA
587 if (err || max_ptes_none > HPAGE_PMD_NR-1)
588 return -EINVAL;
589
590 khugepaged_max_ptes_none = max_ptes_none;
591
592 return count;
593}
594static struct kobj_attribute khugepaged_max_ptes_none_attr =
595 __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
596 khugepaged_max_ptes_none_store);
597
598static struct attribute *khugepaged_attr[] = {
599 &khugepaged_defrag_attr.attr,
600 &khugepaged_max_ptes_none_attr.attr,
601 &pages_to_scan_attr.attr,
602 &pages_collapsed_attr.attr,
603 &full_scans_attr.attr,
604 &scan_sleep_millisecs_attr.attr,
605 &alloc_sleep_millisecs_attr.attr,
606 NULL,
607};
608
609static struct attribute_group khugepaged_attr_group = {
610 .attrs = khugepaged_attr,
611 .name = "khugepaged",
71e3aac0 612};
71e3aac0 613
569e5590 614static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
71e3aac0 615{
71e3aac0
AA
616 int err;
617
569e5590
SL
618 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
619 if (unlikely(!*hugepage_kobj)) {
ae3a8c1c 620 pr_err("failed to create transparent hugepage kobject\n");
569e5590 621 return -ENOMEM;
ba76149f
AA
622 }
623
569e5590 624 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
ba76149f 625 if (err) {
ae3a8c1c 626 pr_err("failed to register transparent hugepage group\n");
569e5590 627 goto delete_obj;
ba76149f
AA
628 }
629
569e5590 630 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
ba76149f 631 if (err) {
ae3a8c1c 632 pr_err("failed to register transparent hugepage group\n");
569e5590 633 goto remove_hp_group;
ba76149f 634 }
569e5590
SL
635
636 return 0;
637
638remove_hp_group:
639 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
640delete_obj:
641 kobject_put(*hugepage_kobj);
642 return err;
643}
644
645static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
646{
647 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
648 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
649 kobject_put(hugepage_kobj);
650}
651#else
652static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
653{
654 return 0;
655}
656
657static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
658{
659}
660#endif /* CONFIG_SYSFS */
661
662static int __init hugepage_init(void)
663{
664 int err;
665 struct kobject *hugepage_kobj;
666
667 if (!has_transparent_hugepage()) {
668 transparent_hugepage_flags = 0;
669 return -EINVAL;
670 }
671
ff20c2e0
KS
672 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
673 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
674 /*
675 * hugepages can't be allocated by the buddy allocator
676 */
677 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER >= MAX_ORDER);
678 /*
679 * we use page->mapping and page->index in second tail page
680 * as list_head: assuming THP order >= 2
681 */
682 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER < 2);
683
569e5590
SL
684 err = hugepage_init_sysfs(&hugepage_kobj);
685 if (err)
65ebb64f 686 goto err_sysfs;
ba76149f
AA
687
688 err = khugepaged_slab_init();
689 if (err)
65ebb64f 690 goto err_slab;
ba76149f 691
65ebb64f
KS
692 err = register_shrinker(&huge_zero_page_shrinker);
693 if (err)
694 goto err_hzp_shrinker;
9a982250
KS
695 err = register_shrinker(&deferred_split_shrinker);
696 if (err)
697 goto err_split_shrinker;
97ae1749 698
97562cd2
RR
699 /*
700 * By default disable transparent hugepages on smaller systems,
701 * where the extra memory used could hurt more than TLB overhead
702 * is likely to save. The admin can still enable it through /sys.
703 */
79553da2 704 if (totalram_pages < (512 << (20 - PAGE_SHIFT))) {
97562cd2 705 transparent_hugepage_flags = 0;
79553da2
KS
706 return 0;
707 }
97562cd2 708
79553da2 709 err = start_stop_khugepaged();
65ebb64f
KS
710 if (err)
711 goto err_khugepaged;
ba76149f 712
569e5590 713 return 0;
65ebb64f 714err_khugepaged:
9a982250
KS
715 unregister_shrinker(&deferred_split_shrinker);
716err_split_shrinker:
65ebb64f
KS
717 unregister_shrinker(&huge_zero_page_shrinker);
718err_hzp_shrinker:
719 khugepaged_slab_exit();
720err_slab:
569e5590 721 hugepage_exit_sysfs(hugepage_kobj);
65ebb64f 722err_sysfs:
ba76149f 723 return err;
71e3aac0 724}
a64fb3cd 725subsys_initcall(hugepage_init);
71e3aac0
AA
726
727static int __init setup_transparent_hugepage(char *str)
728{
729 int ret = 0;
730 if (!str)
731 goto out;
732 if (!strcmp(str, "always")) {
733 set_bit(TRANSPARENT_HUGEPAGE_FLAG,
734 &transparent_hugepage_flags);
735 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
736 &transparent_hugepage_flags);
737 ret = 1;
738 } else if (!strcmp(str, "madvise")) {
739 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
740 &transparent_hugepage_flags);
741 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
742 &transparent_hugepage_flags);
743 ret = 1;
744 } else if (!strcmp(str, "never")) {
745 clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
746 &transparent_hugepage_flags);
747 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
748 &transparent_hugepage_flags);
749 ret = 1;
750 }
751out:
752 if (!ret)
ae3a8c1c 753 pr_warn("transparent_hugepage= cannot parse, ignored\n");
71e3aac0
AA
754 return ret;
755}
756__setup("transparent_hugepage=", setup_transparent_hugepage);
757
b32967ff 758pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
71e3aac0
AA
759{
760 if (likely(vma->vm_flags & VM_WRITE))
761 pmd = pmd_mkwrite(pmd);
762 return pmd;
763}
764
3122359a 765static inline pmd_t mk_huge_pmd(struct page *page, pgprot_t prot)
b3092b3b
BL
766{
767 pmd_t entry;
3122359a 768 entry = mk_pmd(page, prot);
b3092b3b
BL
769 entry = pmd_mkhuge(entry);
770 return entry;
771}
772
9a982250
KS
773static inline struct list_head *page_deferred_list(struct page *page)
774{
775 /*
776 * ->lru in the tail pages is occupied by compound_head.
777 * Let's use ->mapping + ->index in the second tail page as list_head.
778 */
779 return (struct list_head *)&page[2].mapping;
780}
781
782void prep_transhuge_page(struct page *page)
783{
784 /*
785 * we use page->mapping and page->indexlru in second tail page
786 * as list_head: assuming THP order >= 2
787 */
9a982250
KS
788
789 INIT_LIST_HEAD(page_deferred_list(page));
790 set_compound_page_dtor(page, TRANSHUGE_PAGE_DTOR);
791}
792
71e3aac0
AA
793static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
794 struct vm_area_struct *vma,
230c92a8 795 unsigned long address, pmd_t *pmd,
6b251fc9
AA
796 struct page *page, gfp_t gfp,
797 unsigned int flags)
71e3aac0 798{
00501b53 799 struct mem_cgroup *memcg;
71e3aac0 800 pgtable_t pgtable;
c4088ebd 801 spinlock_t *ptl;
230c92a8 802 unsigned long haddr = address & HPAGE_PMD_MASK;
71e3aac0 803
309381fe 804 VM_BUG_ON_PAGE(!PageCompound(page), page);
00501b53 805
f627c2f5 806 if (mem_cgroup_try_charge(page, mm, gfp, &memcg, true)) {
6b251fc9
AA
807 put_page(page);
808 count_vm_event(THP_FAULT_FALLBACK);
809 return VM_FAULT_FALLBACK;
810 }
00501b53 811
71e3aac0 812 pgtable = pte_alloc_one(mm, haddr);
00501b53 813 if (unlikely(!pgtable)) {
f627c2f5 814 mem_cgroup_cancel_charge(page, memcg, true);
6b251fc9 815 put_page(page);
71e3aac0 816 return VM_FAULT_OOM;
00501b53 817 }
71e3aac0
AA
818
819 clear_huge_page(page, haddr, HPAGE_PMD_NR);
52f37629
MK
820 /*
821 * The memory barrier inside __SetPageUptodate makes sure that
822 * clear_huge_page writes become visible before the set_pmd_at()
823 * write.
824 */
71e3aac0
AA
825 __SetPageUptodate(page);
826
c4088ebd 827 ptl = pmd_lock(mm, pmd);
71e3aac0 828 if (unlikely(!pmd_none(*pmd))) {
c4088ebd 829 spin_unlock(ptl);
f627c2f5 830 mem_cgroup_cancel_charge(page, memcg, true);
71e3aac0
AA
831 put_page(page);
832 pte_free(mm, pgtable);
833 } else {
834 pmd_t entry;
6b251fc9
AA
835
836 /* Deliver the page fault to userland */
837 if (userfaultfd_missing(vma)) {
838 int ret;
839
840 spin_unlock(ptl);
f627c2f5 841 mem_cgroup_cancel_charge(page, memcg, true);
6b251fc9
AA
842 put_page(page);
843 pte_free(mm, pgtable);
230c92a8 844 ret = handle_userfault(vma, address, flags,
6b251fc9
AA
845 VM_UFFD_MISSING);
846 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
847 return ret;
848 }
849
3122359a
KS
850 entry = mk_huge_pmd(page, vma->vm_page_prot);
851 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
d281ee61 852 page_add_new_anon_rmap(page, vma, haddr, true);
f627c2f5 853 mem_cgroup_commit_charge(page, memcg, false, true);
00501b53 854 lru_cache_add_active_or_unevictable(page, vma);
6b0b50b0 855 pgtable_trans_huge_deposit(mm, pmd, pgtable);
71e3aac0 856 set_pmd_at(mm, haddr, pmd, entry);
71e3aac0 857 add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
e1f56c89 858 atomic_long_inc(&mm->nr_ptes);
c4088ebd 859 spin_unlock(ptl);
6b251fc9 860 count_vm_event(THP_FAULT_ALLOC);
71e3aac0
AA
861 }
862
aa2e878e 863 return 0;
71e3aac0
AA
864}
865
444eb2a4
MG
866/*
867 * If THP is set to always then directly reclaim/compact as necessary
868 * If set to defer then do no reclaim and defer to khugepaged
869 * If set to madvise and the VMA is flagged then directly reclaim/compact
870 */
871static inline gfp_t alloc_hugepage_direct_gfpmask(struct vm_area_struct *vma)
872{
873 gfp_t reclaim_flags = 0;
874
875 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags) &&
876 (vma->vm_flags & VM_HUGEPAGE))
877 reclaim_flags = __GFP_DIRECT_RECLAIM;
878 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags))
879 reclaim_flags = __GFP_KSWAPD_RECLAIM;
880 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags))
881 reclaim_flags = __GFP_DIRECT_RECLAIM;
882
883 return GFP_TRANSHUGE | reclaim_flags;
884}
885
886/* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
887static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
0bbbc0b3 888{
444eb2a4 889 return GFP_TRANSHUGE | (khugepaged_defrag() ? __GFP_DIRECT_RECLAIM : 0);
0bbbc0b3
AA
890}
891
c4088ebd 892/* Caller must hold page table lock. */
d295e341 893static bool set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
97ae1749 894 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
5918d10a 895 struct page *zero_page)
fc9fe822
KS
896{
897 pmd_t entry;
7c414164
AM
898 if (!pmd_none(*pmd))
899 return false;
5918d10a 900 entry = mk_pmd(zero_page, vma->vm_page_prot);
fc9fe822 901 entry = pmd_mkhuge(entry);
12c9d70b
MW
902 if (pgtable)
903 pgtable_trans_huge_deposit(mm, pmd, pgtable);
fc9fe822 904 set_pmd_at(mm, haddr, pmd, entry);
e1f56c89 905 atomic_long_inc(&mm->nr_ptes);
7c414164 906 return true;
fc9fe822
KS
907}
908
71e3aac0
AA
909int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
910 unsigned long address, pmd_t *pmd,
911 unsigned int flags)
912{
077fcf11 913 gfp_t gfp;
71e3aac0
AA
914 struct page *page;
915 unsigned long haddr = address & HPAGE_PMD_MASK;
71e3aac0 916
128ec037 917 if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
c0292554 918 return VM_FAULT_FALLBACK;
128ec037
KS
919 if (unlikely(anon_vma_prepare(vma)))
920 return VM_FAULT_OOM;
6d50e60c 921 if (unlikely(khugepaged_enter(vma, vma->vm_flags)))
128ec037 922 return VM_FAULT_OOM;
593befa6 923 if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm) &&
128ec037 924 transparent_hugepage_use_zero_page()) {
c4088ebd 925 spinlock_t *ptl;
128ec037
KS
926 pgtable_t pgtable;
927 struct page *zero_page;
928 bool set;
6b251fc9 929 int ret;
128ec037
KS
930 pgtable = pte_alloc_one(mm, haddr);
931 if (unlikely(!pgtable))
ba76149f 932 return VM_FAULT_OOM;
128ec037
KS
933 zero_page = get_huge_zero_page();
934 if (unlikely(!zero_page)) {
935 pte_free(mm, pgtable);
81ab4201 936 count_vm_event(THP_FAULT_FALLBACK);
c0292554 937 return VM_FAULT_FALLBACK;
b9bbfbe3 938 }
c4088ebd 939 ptl = pmd_lock(mm, pmd);
6b251fc9
AA
940 ret = 0;
941 set = false;
942 if (pmd_none(*pmd)) {
943 if (userfaultfd_missing(vma)) {
944 spin_unlock(ptl);
230c92a8 945 ret = handle_userfault(vma, address, flags,
6b251fc9
AA
946 VM_UFFD_MISSING);
947 VM_BUG_ON(ret & VM_FAULT_FALLBACK);
948 } else {
949 set_huge_zero_page(pgtable, mm, vma,
950 haddr, pmd,
951 zero_page);
952 spin_unlock(ptl);
953 set = true;
954 }
955 } else
956 spin_unlock(ptl);
128ec037
KS
957 if (!set) {
958 pte_free(mm, pgtable);
959 put_huge_zero_page();
edad9d2c 960 }
6b251fc9 961 return ret;
71e3aac0 962 }
444eb2a4 963 gfp = alloc_hugepage_direct_gfpmask(vma);
077fcf11 964 page = alloc_hugepage_vma(gfp, vma, haddr, HPAGE_PMD_ORDER);
128ec037
KS
965 if (unlikely(!page)) {
966 count_vm_event(THP_FAULT_FALLBACK);
c0292554 967 return VM_FAULT_FALLBACK;
128ec037 968 }
9a982250 969 prep_transhuge_page(page);
230c92a8
AA
970 return __do_huge_pmd_anonymous_page(mm, vma, address, pmd, page, gfp,
971 flags);
71e3aac0
AA
972}
973
ae18d6dc 974static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
f25748e3 975 pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write)
5cad465d
MW
976{
977 struct mm_struct *mm = vma->vm_mm;
978 pmd_t entry;
979 spinlock_t *ptl;
980
981 ptl = pmd_lock(mm, pmd);
f25748e3
DW
982 entry = pmd_mkhuge(pfn_t_pmd(pfn, prot));
983 if (pfn_t_devmap(pfn))
984 entry = pmd_mkdevmap(entry);
01871e59
RZ
985 if (write) {
986 entry = pmd_mkyoung(pmd_mkdirty(entry));
987 entry = maybe_pmd_mkwrite(entry, vma);
5cad465d 988 }
01871e59
RZ
989 set_pmd_at(mm, addr, pmd, entry);
990 update_mmu_cache_pmd(vma, addr, pmd);
5cad465d 991 spin_unlock(ptl);
5cad465d
MW
992}
993
994int vmf_insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
f25748e3 995 pmd_t *pmd, pfn_t pfn, bool write)
5cad465d
MW
996{
997 pgprot_t pgprot = vma->vm_page_prot;
998 /*
999 * If we had pmd_special, we could avoid all these restrictions,
1000 * but we need to be consistent with PTEs and architectures that
1001 * can't support a 'special' bit.
1002 */
1003 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1004 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1005 (VM_PFNMAP|VM_MIXEDMAP));
1006 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
f25748e3 1007 BUG_ON(!pfn_t_devmap(pfn));
5cad465d
MW
1008
1009 if (addr < vma->vm_start || addr >= vma->vm_end)
1010 return VM_FAULT_SIGBUS;
1011 if (track_pfn_insert(vma, &pgprot, pfn))
1012 return VM_FAULT_SIGBUS;
ae18d6dc
MW
1013 insert_pfn_pmd(vma, addr, pmd, pfn, pgprot, write);
1014 return VM_FAULT_NOPAGE;
5cad465d
MW
1015}
1016
3565fce3
DW
1017static void touch_pmd(struct vm_area_struct *vma, unsigned long addr,
1018 pmd_t *pmd)
1019{
1020 pmd_t _pmd;
1021
1022 /*
1023 * We should set the dirty bit only for FOLL_WRITE but for now
1024 * the dirty bit in the pmd is meaningless. And if the dirty
1025 * bit will become meaningful and we'll only set it with
1026 * FOLL_WRITE, an atomic set_bit will be required on the pmd to
1027 * set the young bit, instead of the current set_pmd_at.
1028 */
1029 _pmd = pmd_mkyoung(pmd_mkdirty(*pmd));
1030 if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1031 pmd, _pmd, 1))
1032 update_mmu_cache_pmd(vma, addr, pmd);
1033}
1034
1035struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr,
1036 pmd_t *pmd, int flags)
1037{
1038 unsigned long pfn = pmd_pfn(*pmd);
1039 struct mm_struct *mm = vma->vm_mm;
1040 struct dev_pagemap *pgmap;
1041 struct page *page;
1042
1043 assert_spin_locked(pmd_lockptr(mm, pmd));
1044
1045 if (flags & FOLL_WRITE && !pmd_write(*pmd))
1046 return NULL;
1047
1048 if (pmd_present(*pmd) && pmd_devmap(*pmd))
1049 /* pass */;
1050 else
1051 return NULL;
1052
1053 if (flags & FOLL_TOUCH)
1054 touch_pmd(vma, addr, pmd);
1055
1056 /*
1057 * device mapped pages can only be returned if the
1058 * caller will manage the page reference count.
1059 */
1060 if (!(flags & FOLL_GET))
1061 return ERR_PTR(-EEXIST);
1062
1063 pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT;
1064 pgmap = get_dev_pagemap(pfn, NULL);
1065 if (!pgmap)
1066 return ERR_PTR(-EFAULT);
1067 page = pfn_to_page(pfn);
1068 get_page(page);
1069 put_dev_pagemap(pgmap);
1070
1071 return page;
1072}
1073
71e3aac0
AA
1074int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1075 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1076 struct vm_area_struct *vma)
1077{
c4088ebd 1078 spinlock_t *dst_ptl, *src_ptl;
71e3aac0
AA
1079 struct page *src_page;
1080 pmd_t pmd;
12c9d70b 1081 pgtable_t pgtable = NULL;
71e3aac0
AA
1082 int ret;
1083
12c9d70b
MW
1084 if (!vma_is_dax(vma)) {
1085 ret = -ENOMEM;
1086 pgtable = pte_alloc_one(dst_mm, addr);
1087 if (unlikely(!pgtable))
1088 goto out;
1089 }
71e3aac0 1090
c4088ebd
KS
1091 dst_ptl = pmd_lock(dst_mm, dst_pmd);
1092 src_ptl = pmd_lockptr(src_mm, src_pmd);
1093 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
71e3aac0
AA
1094
1095 ret = -EAGAIN;
1096 pmd = *src_pmd;
5c7fb56e 1097 if (unlikely(!pmd_trans_huge(pmd) && !pmd_devmap(pmd))) {
71e3aac0
AA
1098 pte_free(dst_mm, pgtable);
1099 goto out_unlock;
1100 }
fc9fe822 1101 /*
c4088ebd 1102 * When page table lock is held, the huge zero pmd should not be
fc9fe822
KS
1103 * under splitting since we don't split the page itself, only pmd to
1104 * a page table.
1105 */
1106 if (is_huge_zero_pmd(pmd)) {
5918d10a 1107 struct page *zero_page;
97ae1749
KS
1108 /*
1109 * get_huge_zero_page() will never allocate a new page here,
1110 * since we already have a zero page to copy. It just takes a
1111 * reference.
1112 */
5918d10a 1113 zero_page = get_huge_zero_page();
6b251fc9 1114 set_huge_zero_page(pgtable, dst_mm, vma, addr, dst_pmd,
5918d10a 1115 zero_page);
fc9fe822
KS
1116 ret = 0;
1117 goto out_unlock;
1118 }
de466bd6 1119
12c9d70b 1120 if (!vma_is_dax(vma)) {
5c7fb56e
DW
1121 /* thp accounting separate from pmd_devmap accounting */
1122 src_page = pmd_page(pmd);
1123 VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
1124 get_page(src_page);
1125 page_dup_rmap(src_page, true);
1126 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
1127 atomic_long_inc(&dst_mm->nr_ptes);
1128 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
1129 }
71e3aac0
AA
1130
1131 pmdp_set_wrprotect(src_mm, addr, src_pmd);
1132 pmd = pmd_mkold(pmd_wrprotect(pmd));
1133 set_pmd_at(dst_mm, addr, dst_pmd, pmd);
71e3aac0
AA
1134
1135 ret = 0;
1136out_unlock:
c4088ebd
KS
1137 spin_unlock(src_ptl);
1138 spin_unlock(dst_ptl);
71e3aac0
AA
1139out:
1140 return ret;
1141}
1142
a1dd450b
WD
1143void huge_pmd_set_accessed(struct mm_struct *mm,
1144 struct vm_area_struct *vma,
1145 unsigned long address,
1146 pmd_t *pmd, pmd_t orig_pmd,
1147 int dirty)
1148{
c4088ebd 1149 spinlock_t *ptl;
a1dd450b
WD
1150 pmd_t entry;
1151 unsigned long haddr;
1152
c4088ebd 1153 ptl = pmd_lock(mm, pmd);
a1dd450b
WD
1154 if (unlikely(!pmd_same(*pmd, orig_pmd)))
1155 goto unlock;
1156
1157 entry = pmd_mkyoung(orig_pmd);
1158 haddr = address & HPAGE_PMD_MASK;
1159 if (pmdp_set_access_flags(vma, haddr, pmd, entry, dirty))
1160 update_mmu_cache_pmd(vma, address, pmd);
1161
1162unlock:
c4088ebd 1163 spin_unlock(ptl);
a1dd450b
WD
1164}
1165
71e3aac0
AA
1166static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
1167 struct vm_area_struct *vma,
1168 unsigned long address,
1169 pmd_t *pmd, pmd_t orig_pmd,
1170 struct page *page,
1171 unsigned long haddr)
1172{
00501b53 1173 struct mem_cgroup *memcg;
c4088ebd 1174 spinlock_t *ptl;
71e3aac0
AA
1175 pgtable_t pgtable;
1176 pmd_t _pmd;
1177 int ret = 0, i;
1178 struct page **pages;
2ec74c3e
SG
1179 unsigned long mmun_start; /* For mmu_notifiers */
1180 unsigned long mmun_end; /* For mmu_notifiers */
71e3aac0
AA
1181
1182 pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
1183 GFP_KERNEL);
1184 if (unlikely(!pages)) {
1185 ret |= VM_FAULT_OOM;
1186 goto out;
1187 }
1188
1189 for (i = 0; i < HPAGE_PMD_NR; i++) {
cc5d462f
AK
1190 pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
1191 __GFP_OTHER_NODE,
19ee151e 1192 vma, address, page_to_nid(page));
b9bbfbe3 1193 if (unlikely(!pages[i] ||
00501b53 1194 mem_cgroup_try_charge(pages[i], mm, GFP_KERNEL,
f627c2f5 1195 &memcg, false))) {
b9bbfbe3 1196 if (pages[i])
71e3aac0 1197 put_page(pages[i]);
b9bbfbe3 1198 while (--i >= 0) {
00501b53
JW
1199 memcg = (void *)page_private(pages[i]);
1200 set_page_private(pages[i], 0);
f627c2f5
KS
1201 mem_cgroup_cancel_charge(pages[i], memcg,
1202 false);
b9bbfbe3
AA
1203 put_page(pages[i]);
1204 }
71e3aac0
AA
1205 kfree(pages);
1206 ret |= VM_FAULT_OOM;
1207 goto out;
1208 }
00501b53 1209 set_page_private(pages[i], (unsigned long)memcg);
71e3aac0
AA
1210 }
1211
1212 for (i = 0; i < HPAGE_PMD_NR; i++) {
1213 copy_user_highpage(pages[i], page + i,
0089e485 1214 haddr + PAGE_SIZE * i, vma);
71e3aac0
AA
1215 __SetPageUptodate(pages[i]);
1216 cond_resched();
1217 }
1218
2ec74c3e
SG
1219 mmun_start = haddr;
1220 mmun_end = haddr + HPAGE_PMD_SIZE;
1221 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1222
c4088ebd 1223 ptl = pmd_lock(mm, pmd);
71e3aac0
AA
1224 if (unlikely(!pmd_same(*pmd, orig_pmd)))
1225 goto out_free_pages;
309381fe 1226 VM_BUG_ON_PAGE(!PageHead(page), page);
71e3aac0 1227
8809aa2d 1228 pmdp_huge_clear_flush_notify(vma, haddr, pmd);
71e3aac0
AA
1229 /* leave pmd empty until pte is filled */
1230
6b0b50b0 1231 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
71e3aac0
AA
1232 pmd_populate(mm, &_pmd, pgtable);
1233
1234 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1235 pte_t *pte, entry;
1236 entry = mk_pte(pages[i], vma->vm_page_prot);
1237 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
00501b53
JW
1238 memcg = (void *)page_private(pages[i]);
1239 set_page_private(pages[i], 0);
d281ee61 1240 page_add_new_anon_rmap(pages[i], vma, haddr, false);
f627c2f5 1241 mem_cgroup_commit_charge(pages[i], memcg, false, false);
00501b53 1242 lru_cache_add_active_or_unevictable(pages[i], vma);
71e3aac0
AA
1243 pte = pte_offset_map(&_pmd, haddr);
1244 VM_BUG_ON(!pte_none(*pte));
1245 set_pte_at(mm, haddr, pte, entry);
1246 pte_unmap(pte);
1247 }
1248 kfree(pages);
1249
71e3aac0
AA
1250 smp_wmb(); /* make pte visible before pmd */
1251 pmd_populate(mm, pmd, pgtable);
d281ee61 1252 page_remove_rmap(page, true);
c4088ebd 1253 spin_unlock(ptl);
71e3aac0 1254
2ec74c3e
SG
1255 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1256
71e3aac0
AA
1257 ret |= VM_FAULT_WRITE;
1258 put_page(page);
1259
1260out:
1261 return ret;
1262
1263out_free_pages:
c4088ebd 1264 spin_unlock(ptl);
2ec74c3e 1265 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
b9bbfbe3 1266 for (i = 0; i < HPAGE_PMD_NR; i++) {
00501b53
JW
1267 memcg = (void *)page_private(pages[i]);
1268 set_page_private(pages[i], 0);
f627c2f5 1269 mem_cgroup_cancel_charge(pages[i], memcg, false);
71e3aac0 1270 put_page(pages[i]);
b9bbfbe3 1271 }
71e3aac0
AA
1272 kfree(pages);
1273 goto out;
1274}
1275
1276int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
1277 unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
1278{
c4088ebd 1279 spinlock_t *ptl;
71e3aac0 1280 int ret = 0;
93b4796d 1281 struct page *page = NULL, *new_page;
00501b53 1282 struct mem_cgroup *memcg;
71e3aac0 1283 unsigned long haddr;
2ec74c3e
SG
1284 unsigned long mmun_start; /* For mmu_notifiers */
1285 unsigned long mmun_end; /* For mmu_notifiers */
3b363692 1286 gfp_t huge_gfp; /* for allocation and charge */
71e3aac0 1287
c4088ebd 1288 ptl = pmd_lockptr(mm, pmd);
81d1b09c 1289 VM_BUG_ON_VMA(!vma->anon_vma, vma);
93b4796d
KS
1290 haddr = address & HPAGE_PMD_MASK;
1291 if (is_huge_zero_pmd(orig_pmd))
1292 goto alloc;
c4088ebd 1293 spin_lock(ptl);
71e3aac0
AA
1294 if (unlikely(!pmd_same(*pmd, orig_pmd)))
1295 goto out_unlock;
1296
1297 page = pmd_page(orig_pmd);
309381fe 1298 VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
1f25fe20
KS
1299 /*
1300 * We can only reuse the page if nobody else maps the huge page or it's
6d0a07ed 1301 * part.
1f25fe20 1302 */
6d0a07ed 1303 if (page_trans_huge_mapcount(page, NULL) == 1) {
71e3aac0
AA
1304 pmd_t entry;
1305 entry = pmd_mkyoung(orig_pmd);
1306 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1307 if (pmdp_set_access_flags(vma, haddr, pmd, entry, 1))
b113da65 1308 update_mmu_cache_pmd(vma, address, pmd);
71e3aac0
AA
1309 ret |= VM_FAULT_WRITE;
1310 goto out_unlock;
1311 }
ddc58f27 1312 get_page(page);
c4088ebd 1313 spin_unlock(ptl);
93b4796d 1314alloc:
71e3aac0 1315 if (transparent_hugepage_enabled(vma) &&
077fcf11 1316 !transparent_hugepage_debug_cow()) {
444eb2a4 1317 huge_gfp = alloc_hugepage_direct_gfpmask(vma);
3b363692 1318 new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
077fcf11 1319 } else
71e3aac0
AA
1320 new_page = NULL;
1321
9a982250
KS
1322 if (likely(new_page)) {
1323 prep_transhuge_page(new_page);
1324 } else {
eecc1e42 1325 if (!page) {
78ddc534 1326 split_huge_pmd(vma, pmd, address);
e9b71ca9 1327 ret |= VM_FAULT_FALLBACK;
93b4796d
KS
1328 } else {
1329 ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
1330 pmd, orig_pmd, page, haddr);
9845cbbd 1331 if (ret & VM_FAULT_OOM) {
78ddc534 1332 split_huge_pmd(vma, pmd, address);
9845cbbd
KS
1333 ret |= VM_FAULT_FALLBACK;
1334 }
ddc58f27 1335 put_page(page);
93b4796d 1336 }
17766dde 1337 count_vm_event(THP_FAULT_FALLBACK);
71e3aac0
AA
1338 goto out;
1339 }
1340
f627c2f5
KS
1341 if (unlikely(mem_cgroup_try_charge(new_page, mm, huge_gfp, &memcg,
1342 true))) {
b9bbfbe3 1343 put_page(new_page);
93b4796d 1344 if (page) {
78ddc534 1345 split_huge_pmd(vma, pmd, address);
ddc58f27 1346 put_page(page);
9845cbbd 1347 } else
78ddc534 1348 split_huge_pmd(vma, pmd, address);
9845cbbd 1349 ret |= VM_FAULT_FALLBACK;
17766dde 1350 count_vm_event(THP_FAULT_FALLBACK);
b9bbfbe3
AA
1351 goto out;
1352 }
1353
17766dde
DR
1354 count_vm_event(THP_FAULT_ALLOC);
1355
eecc1e42 1356 if (!page)
93b4796d
KS
1357 clear_huge_page(new_page, haddr, HPAGE_PMD_NR);
1358 else
1359 copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
71e3aac0
AA
1360 __SetPageUptodate(new_page);
1361
2ec74c3e
SG
1362 mmun_start = haddr;
1363 mmun_end = haddr + HPAGE_PMD_SIZE;
1364 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1365
c4088ebd 1366 spin_lock(ptl);
93b4796d 1367 if (page)
ddc58f27 1368 put_page(page);
b9bbfbe3 1369 if (unlikely(!pmd_same(*pmd, orig_pmd))) {
c4088ebd 1370 spin_unlock(ptl);
f627c2f5 1371 mem_cgroup_cancel_charge(new_page, memcg, true);
71e3aac0 1372 put_page(new_page);
2ec74c3e 1373 goto out_mn;
b9bbfbe3 1374 } else {
71e3aac0 1375 pmd_t entry;
3122359a
KS
1376 entry = mk_huge_pmd(new_page, vma->vm_page_prot);
1377 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
8809aa2d 1378 pmdp_huge_clear_flush_notify(vma, haddr, pmd);
d281ee61 1379 page_add_new_anon_rmap(new_page, vma, haddr, true);
f627c2f5 1380 mem_cgroup_commit_charge(new_page, memcg, false, true);
00501b53 1381 lru_cache_add_active_or_unevictable(new_page, vma);
71e3aac0 1382 set_pmd_at(mm, haddr, pmd, entry);
b113da65 1383 update_mmu_cache_pmd(vma, address, pmd);
eecc1e42 1384 if (!page) {
93b4796d 1385 add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
97ae1749
KS
1386 put_huge_zero_page();
1387 } else {
309381fe 1388 VM_BUG_ON_PAGE(!PageHead(page), page);
d281ee61 1389 page_remove_rmap(page, true);
93b4796d
KS
1390 put_page(page);
1391 }
71e3aac0
AA
1392 ret |= VM_FAULT_WRITE;
1393 }
c4088ebd 1394 spin_unlock(ptl);
2ec74c3e
SG
1395out_mn:
1396 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
71e3aac0
AA
1397out:
1398 return ret;
2ec74c3e 1399out_unlock:
c4088ebd 1400 spin_unlock(ptl);
2ec74c3e 1401 return ret;
71e3aac0
AA
1402}
1403
b676b293 1404struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
71e3aac0
AA
1405 unsigned long addr,
1406 pmd_t *pmd,
1407 unsigned int flags)
1408{
b676b293 1409 struct mm_struct *mm = vma->vm_mm;
71e3aac0
AA
1410 struct page *page = NULL;
1411
c4088ebd 1412 assert_spin_locked(pmd_lockptr(mm, pmd));
71e3aac0
AA
1413
1414 if (flags & FOLL_WRITE && !pmd_write(*pmd))
1415 goto out;
1416
85facf25
KS
1417 /* Avoid dumping huge zero page */
1418 if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1419 return ERR_PTR(-EFAULT);
1420
2b4847e7 1421 /* Full NUMA hinting faults to serialise migration in fault paths */
8a0516ed 1422 if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
2b4847e7
MG
1423 goto out;
1424
71e3aac0 1425 page = pmd_page(*pmd);
309381fe 1426 VM_BUG_ON_PAGE(!PageHead(page), page);
3565fce3
DW
1427 if (flags & FOLL_TOUCH)
1428 touch_pmd(vma, addr, pmd);
de60f5f1 1429 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
e90309c9
KS
1430 /*
1431 * We don't mlock() pte-mapped THPs. This way we can avoid
1432 * leaking mlocked pages into non-VM_LOCKED VMAs.
1433 *
1434 * In most cases the pmd is the only mapping of the page as we
1435 * break COW for the mlock() -- see gup_flags |= FOLL_WRITE for
1436 * writable private mappings in populate_vma_page_range().
1437 *
1438 * The only scenario when we have the page shared here is if we
1439 * mlocking read-only mapping shared over fork(). We skip
1440 * mlocking such pages.
1441 */
1442 if (compound_mapcount(page) == 1 && !PageDoubleMap(page) &&
1443 page->mapping && trylock_page(page)) {
b676b293
DR
1444 lru_add_drain();
1445 if (page->mapping)
1446 mlock_vma_page(page);
1447 unlock_page(page);
1448 }
1449 }
71e3aac0 1450 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
309381fe 1451 VM_BUG_ON_PAGE(!PageCompound(page), page);
71e3aac0 1452 if (flags & FOLL_GET)
ddc58f27 1453 get_page(page);
71e3aac0
AA
1454
1455out:
1456 return page;
1457}
1458
d10e63f2 1459/* NUMA hinting page fault entry point for trans huge pmds */
4daae3b4
MG
1460int do_huge_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
1461 unsigned long addr, pmd_t pmd, pmd_t *pmdp)
d10e63f2 1462{
c4088ebd 1463 spinlock_t *ptl;
b8916634 1464 struct anon_vma *anon_vma = NULL;
b32967ff 1465 struct page *page;
d10e63f2 1466 unsigned long haddr = addr & HPAGE_PMD_MASK;
8191acbd 1467 int page_nid = -1, this_nid = numa_node_id();
90572890 1468 int target_nid, last_cpupid = -1;
8191acbd
MG
1469 bool page_locked;
1470 bool migrated = false;
b191f9b1 1471 bool was_writable;
6688cc05 1472 int flags = 0;
d10e63f2 1473
c0e7cad9
MG
1474 /* A PROT_NONE fault should not end up here */
1475 BUG_ON(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)));
1476
c4088ebd 1477 ptl = pmd_lock(mm, pmdp);
d10e63f2
MG
1478 if (unlikely(!pmd_same(pmd, *pmdp)))
1479 goto out_unlock;
1480
de466bd6
MG
1481 /*
1482 * If there are potential migrations, wait for completion and retry
1483 * without disrupting NUMA hinting information. Do not relock and
1484 * check_same as the page may no longer be mapped.
1485 */
1486 if (unlikely(pmd_trans_migrating(*pmdp))) {
5d833062 1487 page = pmd_page(*pmdp);
de466bd6 1488 spin_unlock(ptl);
5d833062 1489 wait_on_page_locked(page);
de466bd6
MG
1490 goto out;
1491 }
1492
d10e63f2 1493 page = pmd_page(pmd);
a1a46184 1494 BUG_ON(is_huge_zero_page(page));
8191acbd 1495 page_nid = page_to_nid(page);
90572890 1496 last_cpupid = page_cpupid_last(page);
03c5a6e1 1497 count_vm_numa_event(NUMA_HINT_FAULTS);
04bb2f94 1498 if (page_nid == this_nid) {
03c5a6e1 1499 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
04bb2f94
RR
1500 flags |= TNF_FAULT_LOCAL;
1501 }
4daae3b4 1502
bea66fbd
MG
1503 /* See similar comment in do_numa_page for explanation */
1504 if (!(vma->vm_flags & VM_WRITE))
6688cc05
PZ
1505 flags |= TNF_NO_GROUP;
1506
ff9042b1
MG
1507 /*
1508 * Acquire the page lock to serialise THP migrations but avoid dropping
1509 * page_table_lock if at all possible
1510 */
b8916634
MG
1511 page_locked = trylock_page(page);
1512 target_nid = mpol_misplaced(page, vma, haddr);
1513 if (target_nid == -1) {
1514 /* If the page was locked, there are no parallel migrations */
a54a407f 1515 if (page_locked)
b8916634 1516 goto clear_pmdnuma;
2b4847e7 1517 }
4daae3b4 1518
de466bd6 1519 /* Migration could have started since the pmd_trans_migrating check */
2b4847e7 1520 if (!page_locked) {
c4088ebd 1521 spin_unlock(ptl);
b8916634 1522 wait_on_page_locked(page);
a54a407f 1523 page_nid = -1;
b8916634
MG
1524 goto out;
1525 }
1526
2b4847e7
MG
1527 /*
1528 * Page is misplaced. Page lock serialises migrations. Acquire anon_vma
1529 * to serialises splits
1530 */
b8916634 1531 get_page(page);
c4088ebd 1532 spin_unlock(ptl);
b8916634 1533 anon_vma = page_lock_anon_vma_read(page);
4daae3b4 1534
c69307d5 1535 /* Confirm the PMD did not change while page_table_lock was released */
c4088ebd 1536 spin_lock(ptl);
b32967ff
MG
1537 if (unlikely(!pmd_same(pmd, *pmdp))) {
1538 unlock_page(page);
1539 put_page(page);
a54a407f 1540 page_nid = -1;
4daae3b4 1541 goto out_unlock;
b32967ff 1542 }
ff9042b1 1543
c3a489ca
MG
1544 /* Bail if we fail to protect against THP splits for any reason */
1545 if (unlikely(!anon_vma)) {
1546 put_page(page);
1547 page_nid = -1;
1548 goto clear_pmdnuma;
1549 }
1550
a54a407f
MG
1551 /*
1552 * Migrate the THP to the requested node, returns with page unlocked
8a0516ed 1553 * and access rights restored.
a54a407f 1554 */
c4088ebd 1555 spin_unlock(ptl);
b32967ff 1556 migrated = migrate_misplaced_transhuge_page(mm, vma,
340ef390 1557 pmdp, pmd, addr, page, target_nid);
6688cc05
PZ
1558 if (migrated) {
1559 flags |= TNF_MIGRATED;
8191acbd 1560 page_nid = target_nid;
074c2381
MG
1561 } else
1562 flags |= TNF_MIGRATE_FAIL;
b32967ff 1563
8191acbd 1564 goto out;
b32967ff 1565clear_pmdnuma:
a54a407f 1566 BUG_ON(!PageLocked(page));
b191f9b1 1567 was_writable = pmd_write(pmd);
4d942466 1568 pmd = pmd_modify(pmd, vma->vm_page_prot);
b7b04004 1569 pmd = pmd_mkyoung(pmd);
b191f9b1
MG
1570 if (was_writable)
1571 pmd = pmd_mkwrite(pmd);
d10e63f2 1572 set_pmd_at(mm, haddr, pmdp, pmd);
d10e63f2 1573 update_mmu_cache_pmd(vma, addr, pmdp);
a54a407f 1574 unlock_page(page);
d10e63f2 1575out_unlock:
c4088ebd 1576 spin_unlock(ptl);
b8916634
MG
1577
1578out:
1579 if (anon_vma)
1580 page_unlock_anon_vma_read(anon_vma);
1581
8191acbd 1582 if (page_nid != -1)
6688cc05 1583 task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR, flags);
8191acbd 1584
d10e63f2
MG
1585 return 0;
1586}
1587
b8d3c4c3
MK
1588int madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1589 pmd_t *pmd, unsigned long addr, unsigned long next)
1590
1591{
1592 spinlock_t *ptl;
1593 pmd_t orig_pmd;
1594 struct page *page;
1595 struct mm_struct *mm = tlb->mm;
1596 int ret = 0;
1597
b6ec57f4
KS
1598 ptl = pmd_trans_huge_lock(pmd, vma);
1599 if (!ptl)
25eedabe 1600 goto out_unlocked;
b8d3c4c3
MK
1601
1602 orig_pmd = *pmd;
1603 if (is_huge_zero_pmd(orig_pmd)) {
1604 ret = 1;
1605 goto out;
1606 }
1607
1608 page = pmd_page(orig_pmd);
1609 /*
1610 * If other processes are mapping this page, we couldn't discard
1611 * the page unless they all do MADV_FREE so let's skip the page.
1612 */
1613 if (page_mapcount(page) != 1)
1614 goto out;
1615
1616 if (!trylock_page(page))
1617 goto out;
1618
1619 /*
1620 * If user want to discard part-pages of THP, split it so MADV_FREE
1621 * will deactivate only them.
1622 */
1623 if (next - addr != HPAGE_PMD_SIZE) {
1624 get_page(page);
1625 spin_unlock(ptl);
1626 if (split_huge_page(page)) {
1627 put_page(page);
1628 unlock_page(page);
1629 goto out_unlocked;
1630 }
1631 put_page(page);
1632 unlock_page(page);
1633 ret = 1;
1634 goto out_unlocked;
1635 }
1636
1637 if (PageDirty(page))
1638 ClearPageDirty(page);
1639 unlock_page(page);
1640
1641 if (PageActive(page))
1642 deactivate_page(page);
1643
1644 if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) {
1645 orig_pmd = pmdp_huge_get_and_clear_full(tlb->mm, addr, pmd,
1646 tlb->fullmm);
1647 orig_pmd = pmd_mkold(orig_pmd);
1648 orig_pmd = pmd_mkclean(orig_pmd);
1649
1650 set_pmd_at(mm, addr, pmd, orig_pmd);
1651 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1652 }
1653 ret = 1;
1654out:
1655 spin_unlock(ptl);
1656out_unlocked:
1657 return ret;
1658}
1659
71e3aac0 1660int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
f21760b1 1661 pmd_t *pmd, unsigned long addr)
71e3aac0 1662{
da146769 1663 pmd_t orig_pmd;
bf929152 1664 spinlock_t *ptl;
71e3aac0 1665
b6ec57f4
KS
1666 ptl = __pmd_trans_huge_lock(pmd, vma);
1667 if (!ptl)
da146769
KS
1668 return 0;
1669 /*
1670 * For architectures like ppc64 we look at deposited pgtable
1671 * when calling pmdp_huge_get_and_clear. So do the
1672 * pgtable_trans_huge_withdraw after finishing pmdp related
1673 * operations.
1674 */
1675 orig_pmd = pmdp_huge_get_and_clear_full(tlb->mm, addr, pmd,
1676 tlb->fullmm);
1677 tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1678 if (vma_is_dax(vma)) {
1679 spin_unlock(ptl);
1680 if (is_huge_zero_pmd(orig_pmd))
aa88b68c 1681 tlb_remove_page(tlb, pmd_page(orig_pmd));
da146769
KS
1682 } else if (is_huge_zero_pmd(orig_pmd)) {
1683 pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1684 atomic_long_dec(&tlb->mm->nr_ptes);
1685 spin_unlock(ptl);
aa88b68c 1686 tlb_remove_page(tlb, pmd_page(orig_pmd));
da146769
KS
1687 } else {
1688 struct page *page = pmd_page(orig_pmd);
d281ee61 1689 page_remove_rmap(page, true);
da146769
KS
1690 VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1691 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1692 VM_BUG_ON_PAGE(!PageHead(page), page);
1693 pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1694 atomic_long_dec(&tlb->mm->nr_ptes);
1695 spin_unlock(ptl);
1696 tlb_remove_page(tlb, page);
025c5b24 1697 }
da146769 1698 return 1;
71e3aac0
AA
1699}
1700
4b471e88 1701bool move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
37a1c49a
AA
1702 unsigned long old_addr,
1703 unsigned long new_addr, unsigned long old_end,
1704 pmd_t *old_pmd, pmd_t *new_pmd)
1705{
bf929152 1706 spinlock_t *old_ptl, *new_ptl;
37a1c49a
AA
1707 pmd_t pmd;
1708
1709 struct mm_struct *mm = vma->vm_mm;
1710
1711 if ((old_addr & ~HPAGE_PMD_MASK) ||
1712 (new_addr & ~HPAGE_PMD_MASK) ||
1713 old_end - old_addr < HPAGE_PMD_SIZE ||
1714 (new_vma->vm_flags & VM_NOHUGEPAGE))
4b471e88 1715 return false;
37a1c49a
AA
1716
1717 /*
1718 * The destination pmd shouldn't be established, free_pgtables()
1719 * should have release it.
1720 */
1721 if (WARN_ON(!pmd_none(*new_pmd))) {
1722 VM_BUG_ON(pmd_trans_huge(*new_pmd));
4b471e88 1723 return false;
37a1c49a
AA
1724 }
1725
bf929152
KS
1726 /*
1727 * We don't have to worry about the ordering of src and dst
1728 * ptlocks because exclusive mmap_sem prevents deadlock.
1729 */
b6ec57f4
KS
1730 old_ptl = __pmd_trans_huge_lock(old_pmd, vma);
1731 if (old_ptl) {
bf929152
KS
1732 new_ptl = pmd_lockptr(mm, new_pmd);
1733 if (new_ptl != old_ptl)
1734 spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
8809aa2d 1735 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
025c5b24 1736 VM_BUG_ON(!pmd_none(*new_pmd));
3592806c 1737
69a8ec2d
KS
1738 if (pmd_move_must_withdraw(new_ptl, old_ptl) &&
1739 vma_is_anonymous(vma)) {
b3084f4d 1740 pgtable_t pgtable;
3592806c
KS
1741 pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1742 pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
3592806c 1743 }
b3084f4d
AK
1744 set_pmd_at(mm, new_addr, new_pmd, pmd_mksoft_dirty(pmd));
1745 if (new_ptl != old_ptl)
1746 spin_unlock(new_ptl);
bf929152 1747 spin_unlock(old_ptl);
4b471e88 1748 return true;
37a1c49a 1749 }
4b471e88 1750 return false;
37a1c49a
AA
1751}
1752
f123d74a
MG
1753/*
1754 * Returns
1755 * - 0 if PMD could not be locked
1756 * - 1 if PMD was locked but protections unchange and TLB flush unnecessary
1757 * - HPAGE_PMD_NR is protections changed and TLB flush necessary
1758 */
cd7548ab 1759int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
e944fd67 1760 unsigned long addr, pgprot_t newprot, int prot_numa)
cd7548ab
JW
1761{
1762 struct mm_struct *mm = vma->vm_mm;
bf929152 1763 spinlock_t *ptl;
cd7548ab
JW
1764 int ret = 0;
1765
b6ec57f4
KS
1766 ptl = __pmd_trans_huge_lock(pmd, vma);
1767 if (ptl) {
025c5b24 1768 pmd_t entry;
b191f9b1 1769 bool preserve_write = prot_numa && pmd_write(*pmd);
ba68bc01 1770 ret = 1;
e944fd67
MG
1771
1772 /*
1773 * Avoid trapping faults against the zero page. The read-only
1774 * data is likely to be read-cached on the local CPU and
1775 * local/remote hits to the zero page are not interesting.
1776 */
1777 if (prot_numa && is_huge_zero_pmd(*pmd)) {
1778 spin_unlock(ptl);
ba68bc01 1779 return ret;
e944fd67
MG
1780 }
1781
10c1045f 1782 if (!prot_numa || !pmd_protnone(*pmd)) {
8809aa2d 1783 entry = pmdp_huge_get_and_clear_notify(mm, addr, pmd);
10c1045f 1784 entry = pmd_modify(entry, newprot);
b191f9b1
MG
1785 if (preserve_write)
1786 entry = pmd_mkwrite(entry);
10c1045f
MG
1787 ret = HPAGE_PMD_NR;
1788 set_pmd_at(mm, addr, pmd, entry);
b191f9b1 1789 BUG_ON(!preserve_write && pmd_write(entry));
10c1045f 1790 }
bf929152 1791 spin_unlock(ptl);
025c5b24
NH
1792 }
1793
1794 return ret;
1795}
1796
1797/*
4b471e88 1798 * Returns true if a given pmd maps a thp, false otherwise.
025c5b24 1799 *
4b471e88
KS
1800 * Note that if it returns true, this routine returns without unlocking page
1801 * table lock. So callers must unlock it.
025c5b24 1802 */
b6ec57f4 1803spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma)
025c5b24 1804{
b6ec57f4
KS
1805 spinlock_t *ptl;
1806 ptl = pmd_lock(vma->vm_mm, pmd);
5c7fb56e 1807 if (likely(pmd_trans_huge(*pmd) || pmd_devmap(*pmd)))
b6ec57f4
KS
1808 return ptl;
1809 spin_unlock(ptl);
1810 return NULL;
cd7548ab
JW
1811}
1812
9050d7eb 1813#define VM_NO_THP (VM_SPECIAL | VM_HUGETLB | VM_SHARED | VM_MAYSHARE)
78f11a25 1814
60ab3244
AA
1815int hugepage_madvise(struct vm_area_struct *vma,
1816 unsigned long *vm_flags, int advice)
0af4e98b 1817{
a664b2d8
AA
1818 switch (advice) {
1819 case MADV_HUGEPAGE:
1e1836e8
AT
1820#ifdef CONFIG_S390
1821 /*
1822 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
1823 * can't handle this properly after s390_enable_sie, so we simply
1824 * ignore the madvise to prevent qemu from causing a SIGSEGV.
1825 */
1826 if (mm_has_pgste(vma->vm_mm))
1827 return 0;
1828#endif
a664b2d8
AA
1829 /*
1830 * Be somewhat over-protective like KSM for now!
1831 */
1a763615 1832 if (*vm_flags & VM_NO_THP)
a664b2d8
AA
1833 return -EINVAL;
1834 *vm_flags &= ~VM_NOHUGEPAGE;
1835 *vm_flags |= VM_HUGEPAGE;
60ab3244
AA
1836 /*
1837 * If the vma become good for khugepaged to scan,
1838 * register it here without waiting a page fault that
1839 * may not happen any time soon.
1840 */
6d50e60c 1841 if (unlikely(khugepaged_enter_vma_merge(vma, *vm_flags)))
60ab3244 1842 return -ENOMEM;
a664b2d8
AA
1843 break;
1844 case MADV_NOHUGEPAGE:
1845 /*
1846 * Be somewhat over-protective like KSM for now!
1847 */
1a763615 1848 if (*vm_flags & VM_NO_THP)
a664b2d8
AA
1849 return -EINVAL;
1850 *vm_flags &= ~VM_HUGEPAGE;
1851 *vm_flags |= VM_NOHUGEPAGE;
60ab3244
AA
1852 /*
1853 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
1854 * this vma even if we leave the mm registered in khugepaged if
1855 * it got registered before VM_NOHUGEPAGE was set.
1856 */
a664b2d8
AA
1857 break;
1858 }
0af4e98b
AA
1859
1860 return 0;
1861}
1862
ba76149f
AA
1863static int __init khugepaged_slab_init(void)
1864{
1865 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
1866 sizeof(struct mm_slot),
1867 __alignof__(struct mm_slot), 0, NULL);
1868 if (!mm_slot_cache)
1869 return -ENOMEM;
1870
1871 return 0;
1872}
1873
65ebb64f
KS
1874static void __init khugepaged_slab_exit(void)
1875{
1876 kmem_cache_destroy(mm_slot_cache);
1877}
1878
ba76149f
AA
1879static inline struct mm_slot *alloc_mm_slot(void)
1880{
1881 if (!mm_slot_cache) /* initialization failed */
1882 return NULL;
1883 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
1884}
1885
1886static inline void free_mm_slot(struct mm_slot *mm_slot)
1887{
1888 kmem_cache_free(mm_slot_cache, mm_slot);
1889}
1890
ba76149f
AA
1891static struct mm_slot *get_mm_slot(struct mm_struct *mm)
1892{
1893 struct mm_slot *mm_slot;
ba76149f 1894
b67bfe0d 1895 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
ba76149f
AA
1896 if (mm == mm_slot->mm)
1897 return mm_slot;
43b5fbbd 1898
ba76149f
AA
1899 return NULL;
1900}
1901
1902static void insert_to_mm_slots_hash(struct mm_struct *mm,
1903 struct mm_slot *mm_slot)
1904{
ba76149f 1905 mm_slot->mm = mm;
43b5fbbd 1906 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
ba76149f
AA
1907}
1908
1909static inline int khugepaged_test_exit(struct mm_struct *mm)
1910{
1911 return atomic_read(&mm->mm_users) == 0;
1912}
1913
1914int __khugepaged_enter(struct mm_struct *mm)
1915{
1916 struct mm_slot *mm_slot;
1917 int wakeup;
1918
1919 mm_slot = alloc_mm_slot();
1920 if (!mm_slot)
1921 return -ENOMEM;
1922
1923 /* __khugepaged_exit() must not run from under us */
96dad67f 1924 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
ba76149f
AA
1925 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
1926 free_mm_slot(mm_slot);
1927 return 0;
1928 }
1929
1930 spin_lock(&khugepaged_mm_lock);
1931 insert_to_mm_slots_hash(mm, mm_slot);
1932 /*
1933 * Insert just behind the scanning cursor, to let the area settle
1934 * down a little.
1935 */
1936 wakeup = list_empty(&khugepaged_scan.mm_head);
1937 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
1938 spin_unlock(&khugepaged_mm_lock);
1939
1940 atomic_inc(&mm->mm_count);
1941 if (wakeup)
1942 wake_up_interruptible(&khugepaged_wait);
1943
1944 return 0;
1945}
1946
6d50e60c
DR
1947int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
1948 unsigned long vm_flags)
ba76149f
AA
1949{
1950 unsigned long hstart, hend;
1951 if (!vma->anon_vma)
1952 /*
1953 * Not yet faulted in so we will register later in the
1954 * page fault if needed.
1955 */
1956 return 0;
3486b85a 1957 if (vma->vm_ops || (vm_flags & VM_NO_THP))
ba76149f
AA
1958 /* khugepaged not yet working on file or special mappings */
1959 return 0;
ba76149f
AA
1960 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1961 hend = vma->vm_end & HPAGE_PMD_MASK;
1962 if (hstart < hend)
6d50e60c 1963 return khugepaged_enter(vma, vm_flags);
ba76149f
AA
1964 return 0;
1965}
1966
1967void __khugepaged_exit(struct mm_struct *mm)
1968{
1969 struct mm_slot *mm_slot;
1970 int free = 0;
1971
1972 spin_lock(&khugepaged_mm_lock);
1973 mm_slot = get_mm_slot(mm);
1974 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
43b5fbbd 1975 hash_del(&mm_slot->hash);
ba76149f
AA
1976 list_del(&mm_slot->mm_node);
1977 free = 1;
1978 }
d788e80a 1979 spin_unlock(&khugepaged_mm_lock);
ba76149f
AA
1980
1981 if (free) {
ba76149f
AA
1982 clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1983 free_mm_slot(mm_slot);
1984 mmdrop(mm);
1985 } else if (mm_slot) {
ba76149f
AA
1986 /*
1987 * This is required to serialize against
1988 * khugepaged_test_exit() (which is guaranteed to run
1989 * under mmap sem read mode). Stop here (after we
1990 * return all pagetables will be destroyed) until
1991 * khugepaged has finished working on the pagetables
1992 * under the mmap_sem.
1993 */
1994 down_write(&mm->mmap_sem);
1995 up_write(&mm->mmap_sem);
d788e80a 1996 }
ba76149f
AA
1997}
1998
1999static void release_pte_page(struct page *page)
2000{
2001 /* 0 stands for page_is_file_cache(page) == false */
2002 dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
2003 unlock_page(page);
2004 putback_lru_page(page);
2005}
2006
2007static void release_pte_pages(pte_t *pte, pte_t *_pte)
2008{
2009 while (--_pte >= pte) {
2010 pte_t pteval = *_pte;
ca0984ca 2011 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
ba76149f
AA
2012 release_pte_page(pte_page(pteval));
2013 }
2014}
2015
ba76149f
AA
2016static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
2017 unsigned long address,
2018 pte_t *pte)
2019{
7d2eba05 2020 struct page *page = NULL;
ba76149f 2021 pte_t *_pte;
7d2eba05 2022 int none_or_zero = 0, result = 0;
10359213 2023 bool referenced = false, writable = false;
7d2eba05 2024
ba76149f
AA
2025 for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
2026 _pte++, address += PAGE_SIZE) {
2027 pte_t pteval = *_pte;
47aee4d8
MK
2028 if (pte_none(pteval) || (pte_present(pteval) &&
2029 is_zero_pfn(pte_pfn(pteval)))) {
c1294d05 2030 if (!userfaultfd_armed(vma) &&
7d2eba05 2031 ++none_or_zero <= khugepaged_max_ptes_none) {
ba76149f 2032 continue;
7d2eba05
EA
2033 } else {
2034 result = SCAN_EXCEED_NONE_PTE;
ba76149f 2035 goto out;
7d2eba05 2036 }
ba76149f 2037 }
7d2eba05
EA
2038 if (!pte_present(pteval)) {
2039 result = SCAN_PTE_NON_PRESENT;
ba76149f 2040 goto out;
7d2eba05 2041 }
ba76149f 2042 page = vm_normal_page(vma, address, pteval);
7d2eba05
EA
2043 if (unlikely(!page)) {
2044 result = SCAN_PAGE_NULL;
ba76149f 2045 goto out;
7d2eba05 2046 }
344aa35c 2047
309381fe
SL
2048 VM_BUG_ON_PAGE(PageCompound(page), page);
2049 VM_BUG_ON_PAGE(!PageAnon(page), page);
2050 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
ba76149f 2051
ba76149f
AA
2052 /*
2053 * We can do it before isolate_lru_page because the
2054 * page can't be freed from under us. NOTE: PG_lock
2055 * is needed to serialize against split_huge_page
2056 * when invoked from the VM.
2057 */
7d2eba05
EA
2058 if (!trylock_page(page)) {
2059 result = SCAN_PAGE_LOCK;
ba76149f 2060 goto out;
7d2eba05 2061 }
10359213
EA
2062
2063 /*
2064 * cannot use mapcount: can't collapse if there's a gup pin.
2065 * The page must only be referenced by the scanned process
2066 * and page swap cache.
2067 */
2068 if (page_count(page) != 1 + !!PageSwapCache(page)) {
2069 unlock_page(page);
7d2eba05 2070 result = SCAN_PAGE_COUNT;
10359213
EA
2071 goto out;
2072 }
2073 if (pte_write(pteval)) {
2074 writable = true;
2075 } else {
6d0a07ed
AA
2076 if (PageSwapCache(page) &&
2077 !reuse_swap_page(page, NULL)) {
10359213 2078 unlock_page(page);
7d2eba05 2079 result = SCAN_SWAP_CACHE_PAGE;
10359213
EA
2080 goto out;
2081 }
2082 /*
2083 * Page is not in the swap cache. It can be collapsed
2084 * into a THP.
2085 */
2086 }
2087
ba76149f
AA
2088 /*
2089 * Isolate the page to avoid collapsing an hugepage
2090 * currently in use by the VM.
2091 */
2092 if (isolate_lru_page(page)) {
2093 unlock_page(page);
7d2eba05 2094 result = SCAN_DEL_PAGE_LRU;
ba76149f
AA
2095 goto out;
2096 }
2097 /* 0 stands for page_is_file_cache(page) == false */
2098 inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
309381fe
SL
2099 VM_BUG_ON_PAGE(!PageLocked(page), page);
2100 VM_BUG_ON_PAGE(PageLRU(page), page);
ba76149f
AA
2101
2102 /* If there is no mapped pte young don't collapse the page */
33c3fc71
VD
2103 if (pte_young(pteval) ||
2104 page_is_young(page) || PageReferenced(page) ||
8ee53820 2105 mmu_notifier_test_young(vma->vm_mm, address))
10359213 2106 referenced = true;
ba76149f 2107 }
7d2eba05
EA
2108 if (likely(writable)) {
2109 if (likely(referenced)) {
2110 result = SCAN_SUCCEED;
16fd0fe4 2111 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
7d2eba05
EA
2112 referenced, writable, result);
2113 return 1;
2114 }
2115 } else {
2116 result = SCAN_PAGE_RO;
2117 }
2118
ba76149f 2119out:
344aa35c 2120 release_pte_pages(pte, _pte);
16fd0fe4 2121 trace_mm_collapse_huge_page_isolate(page, none_or_zero,
7d2eba05 2122 referenced, writable, result);
344aa35c 2123 return 0;
ba76149f
AA
2124}
2125
2126static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
2127 struct vm_area_struct *vma,
2128 unsigned long address,
2129 spinlock_t *ptl)
2130{
2131 pte_t *_pte;
2132 for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
2133 pte_t pteval = *_pte;
2134 struct page *src_page;
2135
ca0984ca 2136 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
ba76149f
AA
2137 clear_user_highpage(page, address);
2138 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
ca0984ca
EA
2139 if (is_zero_pfn(pte_pfn(pteval))) {
2140 /*
2141 * ptl mostly unnecessary.
2142 */
2143 spin_lock(ptl);
2144 /*
2145 * paravirt calls inside pte_clear here are
2146 * superfluous.
2147 */
2148 pte_clear(vma->vm_mm, address, _pte);
2149 spin_unlock(ptl);
2150 }
ba76149f
AA
2151 } else {
2152 src_page = pte_page(pteval);
2153 copy_user_highpage(page, src_page, address, vma);
309381fe 2154 VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
ba76149f
AA
2155 release_pte_page(src_page);
2156 /*
2157 * ptl mostly unnecessary, but preempt has to
2158 * be disabled to update the per-cpu stats
2159 * inside page_remove_rmap().
2160 */
2161 spin_lock(ptl);
2162 /*
2163 * paravirt calls inside pte_clear here are
2164 * superfluous.
2165 */
2166 pte_clear(vma->vm_mm, address, _pte);
d281ee61 2167 page_remove_rmap(src_page, false);
ba76149f
AA
2168 spin_unlock(ptl);
2169 free_page_and_swap_cache(src_page);
2170 }
2171
2172 address += PAGE_SIZE;
2173 page++;
2174 }
2175}
2176
26234f36 2177static void khugepaged_alloc_sleep(void)
ba76149f 2178{
bde43c6c
PM
2179 DEFINE_WAIT(wait);
2180
2181 add_wait_queue(&khugepaged_wait, &wait);
2182 freezable_schedule_timeout_interruptible(
2183 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
2184 remove_wait_queue(&khugepaged_wait, &wait);
26234f36 2185}
ba76149f 2186
9f1b868a
BL
2187static int khugepaged_node_load[MAX_NUMNODES];
2188
14a4e214
DR
2189static bool khugepaged_scan_abort(int nid)
2190{
2191 int i;
2192
2193 /*
2194 * If zone_reclaim_mode is disabled, then no extra effort is made to
2195 * allocate memory locally.
2196 */
2197 if (!zone_reclaim_mode)
2198 return false;
2199
2200 /* If there is a count for this node already, it must be acceptable */
2201 if (khugepaged_node_load[nid])
2202 return false;
2203
2204 for (i = 0; i < MAX_NUMNODES; i++) {
2205 if (!khugepaged_node_load[i])
2206 continue;
2207 if (node_distance(nid, i) > RECLAIM_DISTANCE)
2208 return true;
2209 }
2210 return false;
2211}
2212
26234f36 2213#ifdef CONFIG_NUMA
9f1b868a
BL
2214static int khugepaged_find_target_node(void)
2215{
2216 static int last_khugepaged_target_node = NUMA_NO_NODE;
2217 int nid, target_node = 0, max_value = 0;
2218
2219 /* find first node with max normal pages hit */
2220 for (nid = 0; nid < MAX_NUMNODES; nid++)
2221 if (khugepaged_node_load[nid] > max_value) {
2222 max_value = khugepaged_node_load[nid];
2223 target_node = nid;
2224 }
2225
2226 /* do some balance if several nodes have the same hit record */
2227 if (target_node <= last_khugepaged_target_node)
2228 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
2229 nid++)
2230 if (max_value == khugepaged_node_load[nid]) {
2231 target_node = nid;
2232 break;
2233 }
2234
2235 last_khugepaged_target_node = target_node;
2236 return target_node;
2237}
2238
26234f36
XG
2239static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2240{
2241 if (IS_ERR(*hpage)) {
2242 if (!*wait)
2243 return false;
2244
2245 *wait = false;
e3b4126c 2246 *hpage = NULL;
26234f36
XG
2247 khugepaged_alloc_sleep();
2248 } else if (*hpage) {
2249 put_page(*hpage);
2250 *hpage = NULL;
2251 }
2252
2253 return true;
2254}
2255
3b363692
MH
2256static struct page *
2257khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
d6669d68 2258 unsigned long address, int node)
26234f36 2259{
309381fe 2260 VM_BUG_ON_PAGE(*hpage, *hpage);
8b164568 2261
ce83d217 2262 /*
8b164568
VB
2263 * Before allocating the hugepage, release the mmap_sem read lock.
2264 * The allocation can take potentially a long time if it involves
2265 * sync compaction, and we do not need to hold the mmap_sem during
2266 * that. We will recheck the vma after taking it again in write mode.
ce83d217 2267 */
8b164568
VB
2268 up_read(&mm->mmap_sem);
2269
96db800f 2270 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
26234f36 2271 if (unlikely(!*hpage)) {
81ab4201 2272 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
ce83d217 2273 *hpage = ERR_PTR(-ENOMEM);
26234f36 2274 return NULL;
ce83d217 2275 }
26234f36 2276
9a982250 2277 prep_transhuge_page(*hpage);
65b3c07b 2278 count_vm_event(THP_COLLAPSE_ALLOC);
26234f36
XG
2279 return *hpage;
2280}
2281#else
9f1b868a
BL
2282static int khugepaged_find_target_node(void)
2283{
2284 return 0;
2285}
2286
444eb2a4 2287static inline struct page *alloc_khugepaged_hugepage(void)
10dc4155 2288{
9a982250
KS
2289 struct page *page;
2290
444eb2a4
MG
2291 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
2292 HPAGE_PMD_ORDER);
9a982250
KS
2293 if (page)
2294 prep_transhuge_page(page);
2295 return page;
10dc4155
BL
2296}
2297
26234f36
XG
2298static struct page *khugepaged_alloc_hugepage(bool *wait)
2299{
2300 struct page *hpage;
2301
2302 do {
444eb2a4 2303 hpage = alloc_khugepaged_hugepage();
26234f36
XG
2304 if (!hpage) {
2305 count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2306 if (!*wait)
2307 return NULL;
2308
2309 *wait = false;
2310 khugepaged_alloc_sleep();
2311 } else
2312 count_vm_event(THP_COLLAPSE_ALLOC);
2313 } while (unlikely(!hpage) && likely(khugepaged_enabled()));
2314
2315 return hpage;
2316}
2317
2318static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2319{
2320 if (!*hpage)
2321 *hpage = khugepaged_alloc_hugepage(wait);
2322
2323 if (unlikely(!*hpage))
2324 return false;
2325
2326 return true;
2327}
2328
3b363692
MH
2329static struct page *
2330khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
d6669d68 2331 unsigned long address, int node)
26234f36
XG
2332{
2333 up_read(&mm->mmap_sem);
2334 VM_BUG_ON(!*hpage);
3b363692 2335
26234f36
XG
2336 return *hpage;
2337}
692e0b35
AA
2338#endif
2339
fa475e51
BL
2340static bool hugepage_vma_check(struct vm_area_struct *vma)
2341{
2342 if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
2343 (vma->vm_flags & VM_NOHUGEPAGE))
2344 return false;
fa475e51
BL
2345 if (!vma->anon_vma || vma->vm_ops)
2346 return false;
2347 if (is_vma_temporary_stack(vma))
2348 return false;
3486b85a 2349 return !(vma->vm_flags & VM_NO_THP);
fa475e51
BL
2350}
2351
26234f36
XG
2352static void collapse_huge_page(struct mm_struct *mm,
2353 unsigned long address,
2354 struct page **hpage,
2355 struct vm_area_struct *vma,
2356 int node)
2357{
26234f36
XG
2358 pmd_t *pmd, _pmd;
2359 pte_t *pte;
2360 pgtable_t pgtable;
2361 struct page *new_page;
c4088ebd 2362 spinlock_t *pmd_ptl, *pte_ptl;
629d9d1c 2363 int isolated = 0, result = 0;
26234f36 2364 unsigned long hstart, hend;
00501b53 2365 struct mem_cgroup *memcg;
2ec74c3e
SG
2366 unsigned long mmun_start; /* For mmu_notifiers */
2367 unsigned long mmun_end; /* For mmu_notifiers */
3b363692 2368 gfp_t gfp;
26234f36
XG
2369
2370 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2371
3b363692 2372 /* Only allocate from the target node */
444eb2a4 2373 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_OTHER_NODE | __GFP_THISNODE;
3b363692 2374
26234f36 2375 /* release the mmap_sem read lock. */
d6669d68 2376 new_page = khugepaged_alloc_page(hpage, gfp, mm, address, node);
7d2eba05
EA
2377 if (!new_page) {
2378 result = SCAN_ALLOC_HUGE_PAGE_FAIL;
2379 goto out_nolock;
2380 }
26234f36 2381
f627c2f5 2382 if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
7d2eba05
EA
2383 result = SCAN_CGROUP_CHARGE_FAIL;
2384 goto out_nolock;
2385 }
ba76149f
AA
2386
2387 /*
2388 * Prevent all access to pagetables with the exception of
2389 * gup_fast later hanlded by the ptep_clear_flush and the VM
2390 * handled by the anon_vma lock + PG_lock.
2391 */
2392 down_write(&mm->mmap_sem);
7d2eba05
EA
2393 if (unlikely(khugepaged_test_exit(mm))) {
2394 result = SCAN_ANY_PROCESS;
ba76149f 2395 goto out;
7d2eba05 2396 }
ba76149f
AA
2397
2398 vma = find_vma(mm, address);
7d2eba05
EA
2399 if (!vma) {
2400 result = SCAN_VMA_NULL;
a8f531eb 2401 goto out;
7d2eba05 2402 }
ba76149f
AA
2403 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2404 hend = vma->vm_end & HPAGE_PMD_MASK;
7d2eba05
EA
2405 if (address < hstart || address + HPAGE_PMD_SIZE > hend) {
2406 result = SCAN_ADDRESS_RANGE;
ba76149f 2407 goto out;
7d2eba05
EA
2408 }
2409 if (!hugepage_vma_check(vma)) {
2410 result = SCAN_VMA_CHECK;
a7d6e4ec 2411 goto out;
7d2eba05 2412 }
6219049a 2413 pmd = mm_find_pmd(mm, address);
7d2eba05
EA
2414 if (!pmd) {
2415 result = SCAN_PMD_NULL;
ba76149f 2416 goto out;
7d2eba05 2417 }
ba76149f 2418
4fc3f1d6 2419 anon_vma_lock_write(vma->anon_vma);
ba76149f
AA
2420
2421 pte = pte_offset_map(pmd, address);
c4088ebd 2422 pte_ptl = pte_lockptr(mm, pmd);
ba76149f 2423
2ec74c3e
SG
2424 mmun_start = address;
2425 mmun_end = address + HPAGE_PMD_SIZE;
2426 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
c4088ebd 2427 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
ba76149f
AA
2428 /*
2429 * After this gup_fast can't run anymore. This also removes
2430 * any huge TLB entry from the CPU so we won't allow
2431 * huge and small TLB entries for the same virtual address
2432 * to avoid the risk of CPU bugs in that area.
2433 */
15a25b2e 2434 _pmd = pmdp_collapse_flush(vma, address, pmd);
c4088ebd 2435 spin_unlock(pmd_ptl);
2ec74c3e 2436 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
ba76149f 2437
c4088ebd 2438 spin_lock(pte_ptl);
ba76149f 2439 isolated = __collapse_huge_page_isolate(vma, address, pte);
c4088ebd 2440 spin_unlock(pte_ptl);
ba76149f
AA
2441
2442 if (unlikely(!isolated)) {
453c7192 2443 pte_unmap(pte);
c4088ebd 2444 spin_lock(pmd_ptl);
ba76149f 2445 BUG_ON(!pmd_none(*pmd));
7c342512
AK
2446 /*
2447 * We can only use set_pmd_at when establishing
2448 * hugepmds and never for establishing regular pmds that
2449 * points to regular pagetables. Use pmd_populate for that
2450 */
2451 pmd_populate(mm, pmd, pmd_pgtable(_pmd));
c4088ebd 2452 spin_unlock(pmd_ptl);
08b52706 2453 anon_vma_unlock_write(vma->anon_vma);
7d2eba05 2454 result = SCAN_FAIL;
ce83d217 2455 goto out;
ba76149f
AA
2456 }
2457
2458 /*
2459 * All pages are isolated and locked so anon_vma rmap
2460 * can't run anymore.
2461 */
08b52706 2462 anon_vma_unlock_write(vma->anon_vma);
ba76149f 2463
c4088ebd 2464 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
453c7192 2465 pte_unmap(pte);
ba76149f
AA
2466 __SetPageUptodate(new_page);
2467 pgtable = pmd_pgtable(_pmd);
ba76149f 2468
3122359a
KS
2469 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
2470 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
ba76149f
AA
2471
2472 /*
2473 * spin_lock() below is not the equivalent of smp_wmb(), so
2474 * this is needed to avoid the copy_huge_page writes to become
2475 * visible after the set_pmd_at() write.
2476 */
2477 smp_wmb();
2478
c4088ebd 2479 spin_lock(pmd_ptl);
ba76149f 2480 BUG_ON(!pmd_none(*pmd));
d281ee61 2481 page_add_new_anon_rmap(new_page, vma, address, true);
f627c2f5 2482 mem_cgroup_commit_charge(new_page, memcg, false, true);
00501b53 2483 lru_cache_add_active_or_unevictable(new_page, vma);
fce144b4 2484 pgtable_trans_huge_deposit(mm, pmd, pgtable);
ba76149f 2485 set_pmd_at(mm, address, pmd, _pmd);
b113da65 2486 update_mmu_cache_pmd(vma, address, pmd);
c4088ebd 2487 spin_unlock(pmd_ptl);
ba76149f
AA
2488
2489 *hpage = NULL;
420256ef 2490
ba76149f 2491 khugepaged_pages_collapsed++;
7d2eba05 2492 result = SCAN_SUCCEED;
ce83d217 2493out_up_write:
ba76149f 2494 up_write(&mm->mmap_sem);
7d2eba05 2495 trace_mm_collapse_huge_page(mm, isolated, result);
0bbbc0b3
AA
2496 return;
2497
7d2eba05
EA
2498out_nolock:
2499 trace_mm_collapse_huge_page(mm, isolated, result);
2500 return;
ce83d217 2501out:
f627c2f5 2502 mem_cgroup_cancel_charge(new_page, memcg, true);
ce83d217 2503 goto out_up_write;
ba76149f
AA
2504}
2505
2506static int khugepaged_scan_pmd(struct mm_struct *mm,
2507 struct vm_area_struct *vma,
2508 unsigned long address,
2509 struct page **hpage)
2510{
ba76149f
AA
2511 pmd_t *pmd;
2512 pte_t *pte, *_pte;
7d2eba05
EA
2513 int ret = 0, none_or_zero = 0, result = 0;
2514 struct page *page = NULL;
ba76149f
AA
2515 unsigned long _address;
2516 spinlock_t *ptl;
00ef2d2f 2517 int node = NUMA_NO_NODE;
10359213 2518 bool writable = false, referenced = false;
ba76149f
AA
2519
2520 VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2521
6219049a 2522 pmd = mm_find_pmd(mm, address);
7d2eba05
EA
2523 if (!pmd) {
2524 result = SCAN_PMD_NULL;
ba76149f 2525 goto out;
7d2eba05 2526 }
ba76149f 2527
9f1b868a 2528 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
ba76149f
AA
2529 pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2530 for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2531 _pte++, _address += PAGE_SIZE) {
2532 pte_t pteval = *_pte;
ca0984ca 2533 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
c1294d05 2534 if (!userfaultfd_armed(vma) &&
7d2eba05 2535 ++none_or_zero <= khugepaged_max_ptes_none) {
ba76149f 2536 continue;
7d2eba05
EA
2537 } else {
2538 result = SCAN_EXCEED_NONE_PTE;
ba76149f 2539 goto out_unmap;
7d2eba05 2540 }
ba76149f 2541 }
7d2eba05
EA
2542 if (!pte_present(pteval)) {
2543 result = SCAN_PTE_NON_PRESENT;
ba76149f 2544 goto out_unmap;
7d2eba05 2545 }
10359213
EA
2546 if (pte_write(pteval))
2547 writable = true;
2548
ba76149f 2549 page = vm_normal_page(vma, _address, pteval);
7d2eba05
EA
2550 if (unlikely(!page)) {
2551 result = SCAN_PAGE_NULL;
ba76149f 2552 goto out_unmap;
7d2eba05 2553 }
b1caa957
KS
2554
2555 /* TODO: teach khugepaged to collapse THP mapped with pte */
2556 if (PageCompound(page)) {
2557 result = SCAN_PAGE_COMPOUND;
2558 goto out_unmap;
2559 }
2560
5c4b4be3 2561 /*
9f1b868a
BL
2562 * Record which node the original page is from and save this
2563 * information to khugepaged_node_load[].
2564 * Khupaged will allocate hugepage from the node has the max
2565 * hit record.
5c4b4be3 2566 */
9f1b868a 2567 node = page_to_nid(page);
7d2eba05
EA
2568 if (khugepaged_scan_abort(node)) {
2569 result = SCAN_SCAN_ABORT;
14a4e214 2570 goto out_unmap;
7d2eba05 2571 }
9f1b868a 2572 khugepaged_node_load[node]++;
7d2eba05 2573 if (!PageLRU(page)) {
0fda2788 2574 result = SCAN_PAGE_LRU;
7d2eba05
EA
2575 goto out_unmap;
2576 }
2577 if (PageLocked(page)) {
2578 result = SCAN_PAGE_LOCK;
ba76149f 2579 goto out_unmap;
7d2eba05
EA
2580 }
2581 if (!PageAnon(page)) {
2582 result = SCAN_PAGE_ANON;
2583 goto out_unmap;
2584 }
2585
10359213
EA
2586 /*
2587 * cannot use mapcount: can't collapse if there's a gup pin.
2588 * The page must only be referenced by the scanned process
2589 * and page swap cache.
2590 */
7d2eba05
EA
2591 if (page_count(page) != 1 + !!PageSwapCache(page)) {
2592 result = SCAN_PAGE_COUNT;
ba76149f 2593 goto out_unmap;
7d2eba05 2594 }
33c3fc71
VD
2595 if (pte_young(pteval) ||
2596 page_is_young(page) || PageReferenced(page) ||
8ee53820 2597 mmu_notifier_test_young(vma->vm_mm, address))
10359213 2598 referenced = true;
ba76149f 2599 }
7d2eba05
EA
2600 if (writable) {
2601 if (referenced) {
2602 result = SCAN_SUCCEED;
2603 ret = 1;
2604 } else {
2605 result = SCAN_NO_REFERENCED_PAGE;
2606 }
2607 } else {
2608 result = SCAN_PAGE_RO;
2609 }
ba76149f
AA
2610out_unmap:
2611 pte_unmap_unlock(pte, ptl);
9f1b868a
BL
2612 if (ret) {
2613 node = khugepaged_find_target_node();
ce83d217 2614 /* collapse_huge_page will return with the mmap_sem released */
5c4b4be3 2615 collapse_huge_page(mm, address, hpage, vma, node);
9f1b868a 2616 }
ba76149f 2617out:
16fd0fe4 2618 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
7d2eba05 2619 none_or_zero, result);
ba76149f
AA
2620 return ret;
2621}
2622
2623static void collect_mm_slot(struct mm_slot *mm_slot)
2624{
2625 struct mm_struct *mm = mm_slot->mm;
2626
b9980cdc 2627 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
ba76149f
AA
2628
2629 if (khugepaged_test_exit(mm)) {
2630 /* free mm_slot */
43b5fbbd 2631 hash_del(&mm_slot->hash);
ba76149f
AA
2632 list_del(&mm_slot->mm_node);
2633
2634 /*
2635 * Not strictly needed because the mm exited already.
2636 *
2637 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2638 */
2639
2640 /* khugepaged_mm_lock actually not necessary for the below */
2641 free_mm_slot(mm_slot);
2642 mmdrop(mm);
2643 }
2644}
2645
2646static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2647 struct page **hpage)
2f1da642
HS
2648 __releases(&khugepaged_mm_lock)
2649 __acquires(&khugepaged_mm_lock)
ba76149f
AA
2650{
2651 struct mm_slot *mm_slot;
2652 struct mm_struct *mm;
2653 struct vm_area_struct *vma;
2654 int progress = 0;
2655
2656 VM_BUG_ON(!pages);
b9980cdc 2657 VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
ba76149f
AA
2658
2659 if (khugepaged_scan.mm_slot)
2660 mm_slot = khugepaged_scan.mm_slot;
2661 else {
2662 mm_slot = list_entry(khugepaged_scan.mm_head.next,
2663 struct mm_slot, mm_node);
2664 khugepaged_scan.address = 0;
2665 khugepaged_scan.mm_slot = mm_slot;
2666 }
2667 spin_unlock(&khugepaged_mm_lock);
2668
2669 mm = mm_slot->mm;
2670 down_read(&mm->mmap_sem);
2671 if (unlikely(khugepaged_test_exit(mm)))
2672 vma = NULL;
2673 else
2674 vma = find_vma(mm, khugepaged_scan.address);
2675
2676 progress++;
2677 for (; vma; vma = vma->vm_next) {
2678 unsigned long hstart, hend;
2679
2680 cond_resched();
2681 if (unlikely(khugepaged_test_exit(mm))) {
2682 progress++;
2683 break;
2684 }
fa475e51
BL
2685 if (!hugepage_vma_check(vma)) {
2686skip:
ba76149f
AA
2687 progress++;
2688 continue;
2689 }
ba76149f
AA
2690 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2691 hend = vma->vm_end & HPAGE_PMD_MASK;
a7d6e4ec
AA
2692 if (hstart >= hend)
2693 goto skip;
2694 if (khugepaged_scan.address > hend)
2695 goto skip;
ba76149f
AA
2696 if (khugepaged_scan.address < hstart)
2697 khugepaged_scan.address = hstart;
a7d6e4ec 2698 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
ba76149f
AA
2699
2700 while (khugepaged_scan.address < hend) {
2701 int ret;
2702 cond_resched();
2703 if (unlikely(khugepaged_test_exit(mm)))
2704 goto breakouterloop;
2705
2706 VM_BUG_ON(khugepaged_scan.address < hstart ||
2707 khugepaged_scan.address + HPAGE_PMD_SIZE >
2708 hend);
2709 ret = khugepaged_scan_pmd(mm, vma,
2710 khugepaged_scan.address,
2711 hpage);
2712 /* move to next address */
2713 khugepaged_scan.address += HPAGE_PMD_SIZE;
2714 progress += HPAGE_PMD_NR;
2715 if (ret)
2716 /* we released mmap_sem so break loop */
2717 goto breakouterloop_mmap_sem;
2718 if (progress >= pages)
2719 goto breakouterloop;
2720 }
2721 }
2722breakouterloop:
2723 up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2724breakouterloop_mmap_sem:
2725
2726 spin_lock(&khugepaged_mm_lock);
a7d6e4ec 2727 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
ba76149f
AA
2728 /*
2729 * Release the current mm_slot if this mm is about to die, or
2730 * if we scanned all vmas of this mm.
2731 */
2732 if (khugepaged_test_exit(mm) || !vma) {
2733 /*
2734 * Make sure that if mm_users is reaching zero while
2735 * khugepaged runs here, khugepaged_exit will find
2736 * mm_slot not pointing to the exiting mm.
2737 */
2738 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2739 khugepaged_scan.mm_slot = list_entry(
2740 mm_slot->mm_node.next,
2741 struct mm_slot, mm_node);
2742 khugepaged_scan.address = 0;
2743 } else {
2744 khugepaged_scan.mm_slot = NULL;
2745 khugepaged_full_scans++;
2746 }
2747
2748 collect_mm_slot(mm_slot);
2749 }
2750
2751 return progress;
2752}
2753
2754static int khugepaged_has_work(void)
2755{
2756 return !list_empty(&khugepaged_scan.mm_head) &&
2757 khugepaged_enabled();
2758}
2759
2760static int khugepaged_wait_event(void)
2761{
2762 return !list_empty(&khugepaged_scan.mm_head) ||
2017c0bf 2763 kthread_should_stop();
ba76149f
AA
2764}
2765
d516904b 2766static void khugepaged_do_scan(void)
ba76149f 2767{
d516904b 2768 struct page *hpage = NULL;
ba76149f
AA
2769 unsigned int progress = 0, pass_through_head = 0;
2770 unsigned int pages = khugepaged_pages_to_scan;
d516904b 2771 bool wait = true;
ba76149f
AA
2772
2773 barrier(); /* write khugepaged_pages_to_scan to local stack */
2774
2775 while (progress < pages) {
26234f36 2776 if (!khugepaged_prealloc_page(&hpage, &wait))
d516904b 2777 break;
26234f36 2778
420256ef 2779 cond_resched();
ba76149f 2780
cd092411 2781 if (unlikely(kthread_should_stop() || try_to_freeze()))
878aee7d
AA
2782 break;
2783
ba76149f
AA
2784 spin_lock(&khugepaged_mm_lock);
2785 if (!khugepaged_scan.mm_slot)
2786 pass_through_head++;
2787 if (khugepaged_has_work() &&
2788 pass_through_head < 2)
2789 progress += khugepaged_scan_mm_slot(pages - progress,
d516904b 2790 &hpage);
ba76149f
AA
2791 else
2792 progress = pages;
2793 spin_unlock(&khugepaged_mm_lock);
2794 }
ba76149f 2795
d516904b
XG
2796 if (!IS_ERR_OR_NULL(hpage))
2797 put_page(hpage);
0bbbc0b3
AA
2798}
2799
2017c0bf
XG
2800static void khugepaged_wait_work(void)
2801{
2017c0bf
XG
2802 if (khugepaged_has_work()) {
2803 if (!khugepaged_scan_sleep_millisecs)
2804 return;
2805
2806 wait_event_freezable_timeout(khugepaged_wait,
2807 kthread_should_stop(),
2808 msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2809 return;
2810 }
2811
2812 if (khugepaged_enabled())
2813 wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2814}
2815
ba76149f
AA
2816static int khugepaged(void *none)
2817{
2818 struct mm_slot *mm_slot;
2819
878aee7d 2820 set_freezable();
8698a745 2821 set_user_nice(current, MAX_NICE);
ba76149f 2822
b7231789
XG
2823 while (!kthread_should_stop()) {
2824 khugepaged_do_scan();
2825 khugepaged_wait_work();
2826 }
ba76149f
AA
2827
2828 spin_lock(&khugepaged_mm_lock);
2829 mm_slot = khugepaged_scan.mm_slot;
2830 khugepaged_scan.mm_slot = NULL;
2831 if (mm_slot)
2832 collect_mm_slot(mm_slot);
2833 spin_unlock(&khugepaged_mm_lock);
ba76149f
AA
2834 return 0;
2835}
2836
eef1b3ba
KS
2837static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2838 unsigned long haddr, pmd_t *pmd)
2839{
2840 struct mm_struct *mm = vma->vm_mm;
2841 pgtable_t pgtable;
2842 pmd_t _pmd;
2843 int i;
2844
2845 /* leave pmd empty until pte is filled */
2846 pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2847
2848 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2849 pmd_populate(mm, &_pmd, pgtable);
2850
2851 for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
2852 pte_t *pte, entry;
2853 entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
2854 entry = pte_mkspecial(entry);
2855 pte = pte_offset_map(&_pmd, haddr);
2856 VM_BUG_ON(!pte_none(*pte));
2857 set_pte_at(mm, haddr, pte, entry);
2858 pte_unmap(pte);
2859 }
2860 smp_wmb(); /* make pte visible before pmd */
2861 pmd_populate(mm, pmd, pgtable);
2862 put_huge_zero_page();
2863}
2864
2865static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
ba988280 2866 unsigned long haddr, bool freeze)
eef1b3ba
KS
2867{
2868 struct mm_struct *mm = vma->vm_mm;
2869 struct page *page;
2870 pgtable_t pgtable;
2871 pmd_t _pmd;
b8d3c4c3 2872 bool young, write, dirty;
2ac015e2 2873 unsigned long addr;
eef1b3ba
KS
2874 int i;
2875
2876 VM_BUG_ON(haddr & ~HPAGE_PMD_MASK);
2877 VM_BUG_ON_VMA(vma->vm_start > haddr, vma);
2878 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma);
5c7fb56e 2879 VM_BUG_ON(!pmd_trans_huge(*pmd) && !pmd_devmap(*pmd));
eef1b3ba
KS
2880
2881 count_vm_event(THP_SPLIT_PMD);
2882
2883 if (vma_is_dax(vma)) {
2884 pmd_t _pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2885 if (is_huge_zero_pmd(_pmd))
2886 put_huge_zero_page();
2887 return;
2888 } else if (is_huge_zero_pmd(*pmd)) {
2889 return __split_huge_zero_page_pmd(vma, haddr, pmd);
2890 }
2891
2892 page = pmd_page(*pmd);
2893 VM_BUG_ON_PAGE(!page_count(page), page);
fe896d18 2894 page_ref_add(page, HPAGE_PMD_NR - 1);
eef1b3ba
KS
2895 write = pmd_write(*pmd);
2896 young = pmd_young(*pmd);
b8d3c4c3 2897 dirty = pmd_dirty(*pmd);
eef1b3ba 2898
c777e2a8 2899 pmdp_huge_split_prepare(vma, haddr, pmd);
eef1b3ba
KS
2900 pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2901 pmd_populate(mm, &_pmd, pgtable);
2902
2ac015e2 2903 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) {
eef1b3ba
KS
2904 pte_t entry, *pte;
2905 /*
2906 * Note that NUMA hinting access restrictions are not
2907 * transferred to avoid any possibility of altering
2908 * permissions across VMAs.
2909 */
ba988280
KS
2910 if (freeze) {
2911 swp_entry_t swp_entry;
2912 swp_entry = make_migration_entry(page + i, write);
2913 entry = swp_entry_to_pte(swp_entry);
2914 } else {
2915 entry = mk_pte(page + i, vma->vm_page_prot);
b8d3c4c3 2916 entry = maybe_mkwrite(entry, vma);
ba988280
KS
2917 if (!write)
2918 entry = pte_wrprotect(entry);
2919 if (!young)
2920 entry = pte_mkold(entry);
2921 }
b8d3c4c3
MK
2922 if (dirty)
2923 SetPageDirty(page + i);
2ac015e2 2924 pte = pte_offset_map(&_pmd, addr);
eef1b3ba 2925 BUG_ON(!pte_none(*pte));
2ac015e2 2926 set_pte_at(mm, addr, pte, entry);
eef1b3ba
KS
2927 atomic_inc(&page[i]._mapcount);
2928 pte_unmap(pte);
2929 }
2930
2931 /*
2932 * Set PG_double_map before dropping compound_mapcount to avoid
2933 * false-negative page_mapped().
2934 */
2935 if (compound_mapcount(page) > 1 && !TestSetPageDoubleMap(page)) {
2936 for (i = 0; i < HPAGE_PMD_NR; i++)
2937 atomic_inc(&page[i]._mapcount);
2938 }
2939
2940 if (atomic_add_negative(-1, compound_mapcount_ptr(page))) {
2941 /* Last compound_mapcount is gone. */
2942 __dec_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
2943 if (TestClearPageDoubleMap(page)) {
2944 /* No need in mapcount reference anymore */
2945 for (i = 0; i < HPAGE_PMD_NR; i++)
2946 atomic_dec(&page[i]._mapcount);
2947 }
2948 }
2949
2950 smp_wmb(); /* make pte visible before pmd */
e9b61f19
KS
2951 /*
2952 * Up to this point the pmd is present and huge and userland has the
2953 * whole access to the hugepage during the split (which happens in
2954 * place). If we overwrite the pmd with the not-huge version pointing
2955 * to the pte here (which of course we could if all CPUs were bug
2956 * free), userland could trigger a small page size TLB miss on the
2957 * small sized TLB while the hugepage TLB entry is still established in
2958 * the huge TLB. Some CPU doesn't like that.
2959 * See http://support.amd.com/us/Processor_TechDocs/41322.pdf, Erratum
2960 * 383 on page 93. Intel should be safe but is also warns that it's
2961 * only safe if the permission and cache attributes of the two entries
2962 * loaded in the two TLB is identical (which should be the case here).
2963 * But it is generally safer to never allow small and huge TLB entries
2964 * for the same virtual address to be loaded simultaneously. So instead
2965 * of doing "pmd_populate(); flush_pmd_tlb_range();" we first mark the
2966 * current pmd notpresent (atomically because here the pmd_trans_huge
2967 * and pmd_trans_splitting must remain set at all times on the pmd
2968 * until the split is complete for this pmd), then we flush the SMP TLB
2969 * and finally we write the non-huge version of the pmd entry with
2970 * pmd_populate.
2971 */
2972 pmdp_invalidate(vma, haddr, pmd);
eef1b3ba 2973 pmd_populate(mm, pmd, pgtable);
e9b61f19
KS
2974
2975 if (freeze) {
2ac015e2 2976 for (i = 0; i < HPAGE_PMD_NR; i++) {
e9b61f19
KS
2977 page_remove_rmap(page + i, false);
2978 put_page(page + i);
2979 }
2980 }
eef1b3ba
KS
2981}
2982
2983void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
fec89c10 2984 unsigned long address, bool freeze)
eef1b3ba
KS
2985{
2986 spinlock_t *ptl;
2987 struct mm_struct *mm = vma->vm_mm;
2988 unsigned long haddr = address & HPAGE_PMD_MASK;
2989
2990 mmu_notifier_invalidate_range_start(mm, haddr, haddr + HPAGE_PMD_SIZE);
2991 ptl = pmd_lock(mm, pmd);
5c7fb56e 2992 if (pmd_trans_huge(*pmd)) {
5f737714 2993 struct page *page = pmd_page(*pmd);
5c7fb56e 2994 if (PageMlocked(page))
5f737714 2995 clear_page_mlock(page);
5c7fb56e 2996 } else if (!pmd_devmap(*pmd))
e90309c9 2997 goto out;
fec89c10 2998 __split_huge_pmd_locked(vma, pmd, haddr, freeze);
e90309c9 2999out:
eef1b3ba
KS
3000 spin_unlock(ptl);
3001 mmu_notifier_invalidate_range_end(mm, haddr, haddr + HPAGE_PMD_SIZE);
3002}
3003
fec89c10
KS
3004void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address,
3005 bool freeze, struct page *page)
94fcc585 3006{
f72e7dcd
HD
3007 pgd_t *pgd;
3008 pud_t *pud;
94fcc585
AA
3009 pmd_t *pmd;
3010
78ddc534 3011 pgd = pgd_offset(vma->vm_mm, address);
f72e7dcd
HD
3012 if (!pgd_present(*pgd))
3013 return;
3014
3015 pud = pud_offset(pgd, address);
3016 if (!pud_present(*pud))
3017 return;
3018
3019 pmd = pmd_offset(pud, address);
5c7fb56e 3020 if (!pmd_present(*pmd) || (!pmd_trans_huge(*pmd) && !pmd_devmap(*pmd)))
94fcc585 3021 return;
fec89c10
KS
3022
3023 /*
3024 * If caller asks to setup a migration entries, we need a page to check
3025 * pmd against. Otherwise we can end up replacing wrong page.
3026 */
3027 VM_BUG_ON(freeze && !page);
3028 if (page && page != pmd_page(*pmd))
3029 return;
3030
94fcc585
AA
3031 /*
3032 * Caller holds the mmap_sem write mode, so a huge pmd cannot
3033 * materialize from under us.
3034 */
fec89c10 3035 __split_huge_pmd(vma, pmd, address, freeze);
94fcc585
AA
3036}
3037
e1b9996b 3038void vma_adjust_trans_huge(struct vm_area_struct *vma,
94fcc585
AA
3039 unsigned long start,
3040 unsigned long end,
3041 long adjust_next)
3042{
3043 /*
3044 * If the new start address isn't hpage aligned and it could
3045 * previously contain an hugepage: check if we need to split
3046 * an huge pmd.
3047 */
3048 if (start & ~HPAGE_PMD_MASK &&
3049 (start & HPAGE_PMD_MASK) >= vma->vm_start &&
3050 (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
fec89c10 3051 split_huge_pmd_address(vma, start, false, NULL);
94fcc585
AA
3052
3053 /*
3054 * If the new end address isn't hpage aligned and it could
3055 * previously contain an hugepage: check if we need to split
3056 * an huge pmd.
3057 */
3058 if (end & ~HPAGE_PMD_MASK &&
3059 (end & HPAGE_PMD_MASK) >= vma->vm_start &&
3060 (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
fec89c10 3061 split_huge_pmd_address(vma, end, false, NULL);
94fcc585
AA
3062
3063 /*
3064 * If we're also updating the vma->vm_next->vm_start, if the new
3065 * vm_next->vm_start isn't page aligned and it could previously
3066 * contain an hugepage: check if we need to split an huge pmd.
3067 */
3068 if (adjust_next > 0) {
3069 struct vm_area_struct *next = vma->vm_next;
3070 unsigned long nstart = next->vm_start;
3071 nstart += adjust_next << PAGE_SHIFT;
3072 if (nstart & ~HPAGE_PMD_MASK &&
3073 (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
3074 (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
fec89c10 3075 split_huge_pmd_address(next, nstart, false, NULL);
94fcc585
AA
3076 }
3077}
e9b61f19 3078
fec89c10 3079static void freeze_page(struct page *page)
e9b61f19 3080{
fec89c10
KS
3081 enum ttu_flags ttu_flags = TTU_MIGRATION | TTU_IGNORE_MLOCK |
3082 TTU_IGNORE_ACCESS | TTU_RMAP_LOCKED;
3083 int i, ret;
e9b61f19
KS
3084
3085 VM_BUG_ON_PAGE(!PageHead(page), page);
3086
fec89c10
KS
3087 /* We only need TTU_SPLIT_HUGE_PMD once */
3088 ret = try_to_unmap(page, ttu_flags | TTU_SPLIT_HUGE_PMD);
3089 for (i = 1; !ret && i < HPAGE_PMD_NR; i++) {
3090 /* Cut short if the page is unmapped */
3091 if (page_count(page) == 1)
3092 return;
e9b61f19 3093
fec89c10 3094 ret = try_to_unmap(page + i, ttu_flags);
e9b61f19 3095 }
fec89c10 3096 VM_BUG_ON(ret);
e9b61f19
KS
3097}
3098
fec89c10 3099static void unfreeze_page(struct page *page)
e9b61f19 3100{
fec89c10 3101 int i;
e9b61f19 3102
fec89c10
KS
3103 for (i = 0; i < HPAGE_PMD_NR; i++)
3104 remove_migration_ptes(page + i, page + i, true);
e9b61f19
KS
3105}
3106
8df651c7 3107static void __split_huge_page_tail(struct page *head, int tail,
e9b61f19
KS
3108 struct lruvec *lruvec, struct list_head *list)
3109{
e9b61f19
KS
3110 struct page *page_tail = head + tail;
3111
8df651c7 3112 VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail);
fe896d18 3113 VM_BUG_ON_PAGE(page_ref_count(page_tail) != 0, page_tail);
e9b61f19
KS
3114
3115 /*
3116 * tail_page->_count is zero and not changing from under us. But
3117 * get_page_unless_zero() may be running from under us on the
8df651c7 3118 * tail_page. If we used atomic_set() below instead of atomic_inc(), we
e9b61f19
KS
3119 * would then run atomic_set() concurrently with
3120 * get_page_unless_zero(), and atomic_set() is implemented in C not
3121 * using locked ops. spin_unlock on x86 sometime uses locked ops
3122 * because of PPro errata 66, 92, so unless somebody can guarantee
3123 * atomic_set() here would be safe on all archs (and not only on x86),
8df651c7 3124 * it's safer to use atomic_inc().
e9b61f19 3125 */
fe896d18 3126 page_ref_inc(page_tail);
e9b61f19
KS
3127
3128 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
3129 page_tail->flags |= (head->flags &
3130 ((1L << PG_referenced) |
3131 (1L << PG_swapbacked) |
3132 (1L << PG_mlocked) |
3133 (1L << PG_uptodate) |
3134 (1L << PG_active) |
3135 (1L << PG_locked) |
b8d3c4c3
MK
3136 (1L << PG_unevictable) |
3137 (1L << PG_dirty)));
e9b61f19
KS
3138
3139 /*
3140 * After clearing PageTail the gup refcount can be released.
3141 * Page flags also must be visible before we make the page non-compound.
3142 */
3143 smp_wmb();
3144
3145 clear_compound_head(page_tail);
3146
3147 if (page_is_young(head))
3148 set_page_young(page_tail);
3149 if (page_is_idle(head))
3150 set_page_idle(page_tail);
3151
3152 /* ->mapping in first tail page is compound_mapcount */
9a982250 3153 VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING,
e9b61f19
KS
3154 page_tail);
3155 page_tail->mapping = head->mapping;
3156
3157 page_tail->index = head->index + tail;
3158 page_cpupid_xchg_last(page_tail, page_cpupid_last(head));
3159 lru_add_page_tail(head, page_tail, lruvec, list);
e9b61f19
KS
3160}
3161
3162static void __split_huge_page(struct page *page, struct list_head *list)
3163{
3164 struct page *head = compound_head(page);
3165 struct zone *zone = page_zone(head);
3166 struct lruvec *lruvec;
8df651c7 3167 int i;
e9b61f19
KS
3168
3169 /* prevent PageLRU to go away from under us, and freeze lru stats */
3170 spin_lock_irq(&zone->lru_lock);
3171 lruvec = mem_cgroup_page_lruvec(head, zone);
3172
3173 /* complete memcg works before add pages to LRU */
3174 mem_cgroup_split_huge_fixup(head);
3175
e9b61f19 3176 for (i = HPAGE_PMD_NR - 1; i >= 1; i--)
8df651c7 3177 __split_huge_page_tail(head, i, lruvec, list);
e9b61f19
KS
3178
3179 ClearPageCompound(head);
3180 spin_unlock_irq(&zone->lru_lock);
3181
fec89c10 3182 unfreeze_page(head);
e9b61f19
KS
3183
3184 for (i = 0; i < HPAGE_PMD_NR; i++) {
3185 struct page *subpage = head + i;
3186 if (subpage == page)
3187 continue;
3188 unlock_page(subpage);
3189
3190 /*
3191 * Subpages may be freed if there wasn't any mapping
3192 * like if add_to_swap() is running on a lru page that
3193 * had its mapping zapped. And freeing these pages
3194 * requires taking the lru_lock so we do the put_page
3195 * of the tail pages after the split is complete.
3196 */
3197 put_page(subpage);
3198 }
3199}
3200
b20ce5e0
KS
3201int total_mapcount(struct page *page)
3202{
3203 int i, ret;
3204
3205 VM_BUG_ON_PAGE(PageTail(page), page);
3206
3207 if (likely(!PageCompound(page)))
3208 return atomic_read(&page->_mapcount) + 1;
3209
3210 ret = compound_mapcount(page);
3211 if (PageHuge(page))
3212 return ret;
3213 for (i = 0; i < HPAGE_PMD_NR; i++)
3214 ret += atomic_read(&page[i]._mapcount) + 1;
3215 if (PageDoubleMap(page))
3216 ret -= HPAGE_PMD_NR;
3217 return ret;
3218}
3219
6d0a07ed
AA
3220/*
3221 * This calculates accurately how many mappings a transparent hugepage
3222 * has (unlike page_mapcount() which isn't fully accurate). This full
3223 * accuracy is primarily needed to know if copy-on-write faults can
3224 * reuse the page and change the mapping to read-write instead of
3225 * copying them. At the same time this returns the total_mapcount too.
3226 *
3227 * The function returns the highest mapcount any one of the subpages
3228 * has. If the return value is one, even if different processes are
3229 * mapping different subpages of the transparent hugepage, they can
3230 * all reuse it, because each process is reusing a different subpage.
3231 *
3232 * The total_mapcount is instead counting all virtual mappings of the
3233 * subpages. If the total_mapcount is equal to "one", it tells the
3234 * caller all mappings belong to the same "mm" and in turn the
3235 * anon_vma of the transparent hugepage can become the vma->anon_vma
3236 * local one as no other process may be mapping any of the subpages.
3237 *
3238 * It would be more accurate to replace page_mapcount() with
3239 * page_trans_huge_mapcount(), however we only use
3240 * page_trans_huge_mapcount() in the copy-on-write faults where we
3241 * need full accuracy to avoid breaking page pinning, because
3242 * page_trans_huge_mapcount() is slower than page_mapcount().
3243 */
3244int page_trans_huge_mapcount(struct page *page, int *total_mapcount)
3245{
3246 int i, ret, _total_mapcount, mapcount;
3247
3248 /* hugetlbfs shouldn't call it */
3249 VM_BUG_ON_PAGE(PageHuge(page), page);
3250
3251 if (likely(!PageTransCompound(page))) {
3252 mapcount = atomic_read(&page->_mapcount) + 1;
3253 if (total_mapcount)
3254 *total_mapcount = mapcount;
3255 return mapcount;
3256 }
3257
3258 page = compound_head(page);
3259
3260 _total_mapcount = ret = 0;
3261 for (i = 0; i < HPAGE_PMD_NR; i++) {
3262 mapcount = atomic_read(&page[i]._mapcount) + 1;
3263 ret = max(ret, mapcount);
3264 _total_mapcount += mapcount;
3265 }
3266 if (PageDoubleMap(page)) {
3267 ret -= 1;
3268 _total_mapcount -= HPAGE_PMD_NR;
3269 }
3270 mapcount = compound_mapcount(page);
3271 ret += mapcount;
3272 _total_mapcount += mapcount;
3273 if (total_mapcount)
3274 *total_mapcount = _total_mapcount;
3275 return ret;
3276}
3277
e9b61f19
KS
3278/*
3279 * This function splits huge page into normal pages. @page can point to any
3280 * subpage of huge page to split. Split doesn't change the position of @page.
3281 *
3282 * Only caller must hold pin on the @page, otherwise split fails with -EBUSY.
3283 * The huge page must be locked.
3284 *
3285 * If @list is null, tail pages will be added to LRU list, otherwise, to @list.
3286 *
3287 * Both head page and tail pages will inherit mapping, flags, and so on from
3288 * the hugepage.
3289 *
3290 * GUP pin and PG_locked transferred to @page. Rest subpages can be freed if
3291 * they are not mapped.
3292 *
3293 * Returns 0 if the hugepage is split successfully.
3294 * Returns -EBUSY if the page is pinned or if anon_vma disappeared from under
3295 * us.
3296 */
3297int split_huge_page_to_list(struct page *page, struct list_head *list)
3298{
3299 struct page *head = compound_head(page);
a3d0a918 3300 struct pglist_data *pgdata = NODE_DATA(page_to_nid(head));
e9b61f19
KS
3301 struct anon_vma *anon_vma;
3302 int count, mapcount, ret;
d9654322 3303 bool mlocked;
0b9b6fff 3304 unsigned long flags;
e9b61f19
KS
3305
3306 VM_BUG_ON_PAGE(is_huge_zero_page(page), page);
3307 VM_BUG_ON_PAGE(!PageAnon(page), page);
3308 VM_BUG_ON_PAGE(!PageLocked(page), page);
3309 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
3310 VM_BUG_ON_PAGE(!PageCompound(page), page);
3311
3312 /*
3313 * The caller does not necessarily hold an mmap_sem that would prevent
3314 * the anon_vma disappearing so we first we take a reference to it
3315 * and then lock the anon_vma for write. This is similar to
3316 * page_lock_anon_vma_read except the write lock is taken to serialise
3317 * against parallel split or collapse operations.
3318 */
3319 anon_vma = page_get_anon_vma(head);
3320 if (!anon_vma) {
3321 ret = -EBUSY;
3322 goto out;
3323 }
3324 anon_vma_lock_write(anon_vma);
3325
3326 /*
3327 * Racy check if we can split the page, before freeze_page() will
3328 * split PMDs
3329 */
3330 if (total_mapcount(head) != page_count(head) - 1) {
3331 ret = -EBUSY;
3332 goto out_unlock;
3333 }
3334
d9654322 3335 mlocked = PageMlocked(page);
fec89c10 3336 freeze_page(head);
e9b61f19
KS
3337 VM_BUG_ON_PAGE(compound_mapcount(head), head);
3338
d9654322
KS
3339 /* Make sure the page is not on per-CPU pagevec as it takes pin */
3340 if (mlocked)
3341 lru_add_drain();
3342
9a982250 3343 /* Prevent deferred_split_scan() touching ->_count */
a3d0a918 3344 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
e9b61f19
KS
3345 count = page_count(head);
3346 mapcount = total_mapcount(head);
bd56086f 3347 if (!mapcount && count == 1) {
9a982250 3348 if (!list_empty(page_deferred_list(head))) {
a3d0a918 3349 pgdata->split_queue_len--;
9a982250
KS
3350 list_del(page_deferred_list(head));
3351 }
a3d0a918 3352 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
e9b61f19
KS
3353 __split_huge_page(page, list);
3354 ret = 0;
bd56086f 3355 } else if (IS_ENABLED(CONFIG_DEBUG_VM) && mapcount) {
a3d0a918 3356 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
e9b61f19
KS
3357 pr_alert("total_mapcount: %u, page_count(): %u\n",
3358 mapcount, count);
3359 if (PageTail(page))
3360 dump_page(head, NULL);
bd56086f 3361 dump_page(page, "total_mapcount(head) > 0");
e9b61f19
KS
3362 BUG();
3363 } else {
a3d0a918 3364 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
fec89c10 3365 unfreeze_page(head);
e9b61f19
KS
3366 ret = -EBUSY;
3367 }
3368
3369out_unlock:
3370 anon_vma_unlock_write(anon_vma);
3371 put_anon_vma(anon_vma);
3372out:
3373 count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED);
3374 return ret;
3375}
9a982250
KS
3376
3377void free_transhuge_page(struct page *page)
3378{
a3d0a918 3379 struct pglist_data *pgdata = NODE_DATA(page_to_nid(page));
9a982250
KS
3380 unsigned long flags;
3381
a3d0a918 3382 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
9a982250 3383 if (!list_empty(page_deferred_list(page))) {
a3d0a918 3384 pgdata->split_queue_len--;
9a982250
KS
3385 list_del(page_deferred_list(page));
3386 }
a3d0a918 3387 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
9a982250
KS
3388 free_compound_page(page);
3389}
3390
3391void deferred_split_huge_page(struct page *page)
3392{
a3d0a918 3393 struct pglist_data *pgdata = NODE_DATA(page_to_nid(page));
9a982250
KS
3394 unsigned long flags;
3395
3396 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
3397
a3d0a918 3398 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
9a982250 3399 if (list_empty(page_deferred_list(page))) {
f9719a03 3400 count_vm_event(THP_DEFERRED_SPLIT_PAGE);
a3d0a918
KS
3401 list_add_tail(page_deferred_list(page), &pgdata->split_queue);
3402 pgdata->split_queue_len++;
9a982250 3403 }
a3d0a918 3404 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
9a982250
KS
3405}
3406
3407static unsigned long deferred_split_count(struct shrinker *shrink,
3408 struct shrink_control *sc)
3409{
a3d0a918 3410 struct pglist_data *pgdata = NODE_DATA(sc->nid);
cb8d68ec 3411 return ACCESS_ONCE(pgdata->split_queue_len);
9a982250
KS
3412}
3413
3414static unsigned long deferred_split_scan(struct shrinker *shrink,
3415 struct shrink_control *sc)
3416{
a3d0a918 3417 struct pglist_data *pgdata = NODE_DATA(sc->nid);
9a982250
KS
3418 unsigned long flags;
3419 LIST_HEAD(list), *pos, *next;
3420 struct page *page;
3421 int split = 0;
3422
a3d0a918 3423 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
9a982250 3424 /* Take pin on all head pages to avoid freeing them under us */
ae026204 3425 list_for_each_safe(pos, next, &pgdata->split_queue) {
9a982250
KS
3426 page = list_entry((void *)pos, struct page, mapping);
3427 page = compound_head(page);
e3ae1953
KS
3428 if (get_page_unless_zero(page)) {
3429 list_move(page_deferred_list(page), &list);
3430 } else {
3431 /* We lost race with put_compound_page() */
9a982250 3432 list_del_init(page_deferred_list(page));
a3d0a918 3433 pgdata->split_queue_len--;
9a982250 3434 }
e3ae1953
KS
3435 if (!--sc->nr_to_scan)
3436 break;
9a982250 3437 }
a3d0a918 3438 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
9a982250
KS
3439
3440 list_for_each_safe(pos, next, &list) {
3441 page = list_entry((void *)pos, struct page, mapping);
3442 lock_page(page);
3443 /* split_huge_page() removes page from list on success */
3444 if (!split_huge_page(page))
3445 split++;
3446 unlock_page(page);
3447 put_page(page);
3448 }
3449
a3d0a918
KS
3450 spin_lock_irqsave(&pgdata->split_queue_lock, flags);
3451 list_splice_tail(&list, &pgdata->split_queue);
3452 spin_unlock_irqrestore(&pgdata->split_queue_lock, flags);
9a982250 3453
cb8d68ec
KS
3454 /*
3455 * Stop shrinker if we didn't split any page, but the queue is empty.
3456 * This can happen if pages were freed under us.
3457 */
3458 if (!split && list_empty(&pgdata->split_queue))
3459 return SHRINK_STOP;
3460 return split;
9a982250
KS
3461}
3462
3463static struct shrinker deferred_split_shrinker = {
3464 .count_objects = deferred_split_count,
3465 .scan_objects = deferred_split_scan,
3466 .seeks = DEFAULT_SEEKS,
a3d0a918 3467 .flags = SHRINKER_NUMA_AWARE,
9a982250 3468};
49071d43
KS
3469
3470#ifdef CONFIG_DEBUG_FS
3471static int split_huge_pages_set(void *data, u64 val)
3472{
3473 struct zone *zone;
3474 struct page *page;
3475 unsigned long pfn, max_zone_pfn;
3476 unsigned long total = 0, split = 0;
3477
3478 if (val != 1)
3479 return -EINVAL;
3480
3481 for_each_populated_zone(zone) {
3482 max_zone_pfn = zone_end_pfn(zone);
3483 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) {
3484 if (!pfn_valid(pfn))
3485 continue;
3486
3487 page = pfn_to_page(pfn);
3488 if (!get_page_unless_zero(page))
3489 continue;
3490
3491 if (zone != page_zone(page))
3492 goto next;
3493
3494 if (!PageHead(page) || !PageAnon(page) ||
3495 PageHuge(page))
3496 goto next;
3497
3498 total++;
3499 lock_page(page);
3500 if (!split_huge_page(page))
3501 split++;
3502 unlock_page(page);
3503next:
3504 put_page(page);
3505 }
3506 }
3507
145bdaa1 3508 pr_info("%lu of %lu THP split\n", split, total);
49071d43
KS
3509
3510 return 0;
3511}
3512DEFINE_SIMPLE_ATTRIBUTE(split_huge_pages_fops, NULL, split_huge_pages_set,
3513 "%llu\n");
3514
3515static int __init split_huge_pages_debugfs(void)
3516{
3517 void *ret;
3518
145bdaa1 3519 ret = debugfs_create_file("split_huge_pages", 0200, NULL, NULL,
49071d43
KS
3520 &split_huge_pages_fops);
3521 if (!ret)
3522 pr_warn("Failed to create split_huge_pages in debugfs");
3523 return 0;
3524}
3525late_initcall(split_huge_pages_debugfs);
3526#endif