• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (C) 2009  Red Hat, Inc.
3  *
4  *  This work is licensed under the terms of the GNU GPL, version 2. See
5  *  the COPYING file in the top-level directory.
6  */
7 
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
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>
17 #include <linux/shrinker.h>
18 #include <linux/mm_inline.h>
19 #include <linux/dax.h>
20 #include <linux/kthread.h>
21 #include <linux/khugepaged.h>
22 #include <linux/freezer.h>
23 #include <linux/mman.h>
24 #include <linux/pagemap.h>
25 #include <linux/migrate.h>
26 #include <linux/hashtable.h>
27 #include <linux/userfaultfd_k.h>
28 #include <linux/page_idle.h>
29 
30 #include <asm/tlb.h>
31 #include <asm/pgalloc.h>
32 #include "internal.h"
33 
34 /*
35  * By default transparent hugepage support is disabled in order that avoid
36  * to risk increase the memory footprint of applications without a guaranteed
37  * benefit. When transparent hugepage support is enabled, is for all mappings,
38  * and khugepaged scans all mappings.
39  * Defrag is invoked by khugepaged hugepage allocations and by page faults
40  * for all hugepage allocations.
41  */
42 unsigned long transparent_hugepage_flags __read_mostly =
43 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS
44 	(1<<TRANSPARENT_HUGEPAGE_FLAG)|
45 #endif
46 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE
47 	(1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|
48 #endif
49 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_FLAG)|
50 	(1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|
51 	(1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
52 
53 /* default scan 8*512 pte (or vmas) every 30 second */
54 static unsigned int khugepaged_pages_to_scan __read_mostly = HPAGE_PMD_NR*8;
55 static unsigned int khugepaged_pages_collapsed;
56 static unsigned int khugepaged_full_scans;
57 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
58 /* during fragmentation poll the hugepage allocator once every minute */
59 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
60 static struct task_struct *khugepaged_thread __read_mostly;
61 static DEFINE_MUTEX(khugepaged_mutex);
62 static DEFINE_SPINLOCK(khugepaged_mm_lock);
63 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
64 /*
65  * default collapse hugepages if there is at least one pte mapped like
66  * it would have happened if the vma was large enough during page
67  * fault.
68  */
69 static unsigned int khugepaged_max_ptes_none __read_mostly = HPAGE_PMD_NR-1;
70 
71 static int khugepaged(void *none);
72 static int khugepaged_slab_init(void);
73 static void khugepaged_slab_exit(void);
74 
75 #define MM_SLOTS_HASH_BITS 10
76 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
77 
78 static struct kmem_cache *mm_slot_cache __read_mostly;
79 
80 /**
81  * struct mm_slot - hash lookup from mm to mm_slot
82  * @hash: hash collision list
83  * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
84  * @mm: the mm that this information is valid for
85  */
86 struct mm_slot {
87 	struct hlist_node hash;
88 	struct list_head mm_node;
89 	struct mm_struct *mm;
90 };
91 
92 /**
93  * struct khugepaged_scan - cursor for scanning
94  * @mm_head: the head of the mm list to scan
95  * @mm_slot: the current mm_slot we are scanning
96  * @address: the next address inside that to be scanned
97  *
98  * There is only the one khugepaged_scan instance of this cursor structure.
99  */
100 struct khugepaged_scan {
101 	struct list_head mm_head;
102 	struct mm_slot *mm_slot;
103 	unsigned long address;
104 };
105 static struct khugepaged_scan khugepaged_scan = {
106 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
107 };
108 
109 
set_recommended_min_free_kbytes(void)110 static void set_recommended_min_free_kbytes(void)
111 {
112 	struct zone *zone;
113 	int nr_zones = 0;
114 	unsigned long recommended_min;
115 
116 	for_each_populated_zone(zone)
117 		nr_zones++;
118 
119 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
120 	recommended_min = pageblock_nr_pages * nr_zones * 2;
121 
122 	/*
123 	 * Make sure that on average at least two pageblocks are almost free
124 	 * of another type, one for a migratetype to fall back to and a
125 	 * second to avoid subsequent fallbacks of other types There are 3
126 	 * MIGRATE_TYPES we care about.
127 	 */
128 	recommended_min += pageblock_nr_pages * nr_zones *
129 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
130 
131 	/* don't ever allow to reserve more than 5% of the lowmem */
132 	recommended_min = min(recommended_min,
133 			      (unsigned long) nr_free_buffer_pages() / 20);
134 	recommended_min <<= (PAGE_SHIFT-10);
135 
136 	if (recommended_min > min_free_kbytes) {
137 		if (user_min_free_kbytes >= 0)
138 			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
139 				min_free_kbytes, recommended_min);
140 
141 		min_free_kbytes = recommended_min;
142 	}
143 	setup_per_zone_wmarks();
144 }
145 
start_stop_khugepaged(void)146 static int start_stop_khugepaged(void)
147 {
148 	int err = 0;
149 	if (khugepaged_enabled()) {
150 		if (!khugepaged_thread)
151 			khugepaged_thread = kthread_run(khugepaged, NULL,
152 							"khugepaged");
153 		if (IS_ERR(khugepaged_thread)) {
154 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
155 			err = PTR_ERR(khugepaged_thread);
156 			khugepaged_thread = NULL;
157 			goto fail;
158 		}
159 
160 		if (!list_empty(&khugepaged_scan.mm_head))
161 			wake_up_interruptible(&khugepaged_wait);
162 
163 		set_recommended_min_free_kbytes();
164 	} else if (khugepaged_thread) {
165 		kthread_stop(khugepaged_thread);
166 		khugepaged_thread = NULL;
167 	}
168 fail:
169 	return err;
170 }
171 
172 static atomic_t huge_zero_refcount;
173 struct page *huge_zero_page __read_mostly;
174 
get_huge_zero_page(void)175 struct page *get_huge_zero_page(void)
176 {
177 	struct page *zero_page;
178 retry:
179 	if (likely(atomic_inc_not_zero(&huge_zero_refcount)))
180 		return READ_ONCE(huge_zero_page);
181 
182 	zero_page = alloc_pages((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE,
183 			HPAGE_PMD_ORDER);
184 	if (!zero_page) {
185 		count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED);
186 		return NULL;
187 	}
188 	count_vm_event(THP_ZERO_PAGE_ALLOC);
189 	preempt_disable();
190 	if (cmpxchg(&huge_zero_page, NULL, zero_page)) {
191 		preempt_enable();
192 		__free_pages(zero_page, compound_order(zero_page));
193 		goto retry;
194 	}
195 
196 	/* We take additional reference here. It will be put back by shrinker */
197 	atomic_set(&huge_zero_refcount, 2);
198 	preempt_enable();
199 	return READ_ONCE(huge_zero_page);
200 }
201 
put_huge_zero_page(void)202 static void put_huge_zero_page(void)
203 {
204 	/*
205 	 * Counter should never go to zero here. Only shrinker can put
206 	 * last reference.
207 	 */
208 	BUG_ON(atomic_dec_and_test(&huge_zero_refcount));
209 }
210 
shrink_huge_zero_page_count(struct shrinker * shrink,struct shrink_control * sc)211 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink,
212 					struct shrink_control *sc)
213 {
214 	/* we can free zero page only if last reference remains */
215 	return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0;
216 }
217 
shrink_huge_zero_page_scan(struct shrinker * shrink,struct shrink_control * sc)218 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink,
219 				       struct shrink_control *sc)
220 {
221 	if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) {
222 		struct page *zero_page = xchg(&huge_zero_page, NULL);
223 		BUG_ON(zero_page == NULL);
224 		__free_pages(zero_page, compound_order(zero_page));
225 		return HPAGE_PMD_NR;
226 	}
227 
228 	return 0;
229 }
230 
231 static struct shrinker huge_zero_page_shrinker = {
232 	.count_objects = shrink_huge_zero_page_count,
233 	.scan_objects = shrink_huge_zero_page_scan,
234 	.seeks = DEFAULT_SEEKS,
235 };
236 
237 #ifdef CONFIG_SYSFS
238 
double_flag_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf,enum transparent_hugepage_flag enabled,enum transparent_hugepage_flag req_madv)239 static ssize_t double_flag_show(struct kobject *kobj,
240 				struct kobj_attribute *attr, char *buf,
241 				enum transparent_hugepage_flag enabled,
242 				enum transparent_hugepage_flag req_madv)
243 {
244 	if (test_bit(enabled, &transparent_hugepage_flags)) {
245 		VM_BUG_ON(test_bit(req_madv, &transparent_hugepage_flags));
246 		return sprintf(buf, "[always] madvise never\n");
247 	} else if (test_bit(req_madv, &transparent_hugepage_flags))
248 		return sprintf(buf, "always [madvise] never\n");
249 	else
250 		return sprintf(buf, "always madvise [never]\n");
251 }
double_flag_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count,enum transparent_hugepage_flag enabled,enum transparent_hugepage_flag req_madv)252 static ssize_t double_flag_store(struct kobject *kobj,
253 				 struct kobj_attribute *attr,
254 				 const char *buf, size_t count,
255 				 enum transparent_hugepage_flag enabled,
256 				 enum transparent_hugepage_flag req_madv)
257 {
258 	if (!memcmp("always", buf,
259 		    min(sizeof("always")-1, count))) {
260 		set_bit(enabled, &transparent_hugepage_flags);
261 		clear_bit(req_madv, &transparent_hugepage_flags);
262 	} else if (!memcmp("madvise", buf,
263 			   min(sizeof("madvise")-1, count))) {
264 		clear_bit(enabled, &transparent_hugepage_flags);
265 		set_bit(req_madv, &transparent_hugepage_flags);
266 	} else if (!memcmp("never", buf,
267 			   min(sizeof("never")-1, count))) {
268 		clear_bit(enabled, &transparent_hugepage_flags);
269 		clear_bit(req_madv, &transparent_hugepage_flags);
270 	} else
271 		return -EINVAL;
272 
273 	return count;
274 }
275 
enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)276 static ssize_t enabled_show(struct kobject *kobj,
277 			    struct kobj_attribute *attr, char *buf)
278 {
279 	return double_flag_show(kobj, attr, buf,
280 				TRANSPARENT_HUGEPAGE_FLAG,
281 				TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
282 }
enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)283 static ssize_t enabled_store(struct kobject *kobj,
284 			     struct kobj_attribute *attr,
285 			     const char *buf, size_t count)
286 {
287 	ssize_t ret;
288 
289 	ret = double_flag_store(kobj, attr, buf, count,
290 				TRANSPARENT_HUGEPAGE_FLAG,
291 				TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG);
292 
293 	if (ret > 0) {
294 		int err;
295 
296 		mutex_lock(&khugepaged_mutex);
297 		err = start_stop_khugepaged();
298 		mutex_unlock(&khugepaged_mutex);
299 
300 		if (err)
301 			ret = err;
302 	}
303 
304 	return ret;
305 }
306 static struct kobj_attribute enabled_attr =
307 	__ATTR(enabled, 0644, enabled_show, enabled_store);
308 
single_flag_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf,enum transparent_hugepage_flag flag)309 static ssize_t single_flag_show(struct kobject *kobj,
310 				struct kobj_attribute *attr, char *buf,
311 				enum transparent_hugepage_flag flag)
312 {
313 	return sprintf(buf, "%d\n",
314 		       !!test_bit(flag, &transparent_hugepage_flags));
315 }
316 
single_flag_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count,enum transparent_hugepage_flag flag)317 static ssize_t single_flag_store(struct kobject *kobj,
318 				 struct kobj_attribute *attr,
319 				 const char *buf, size_t count,
320 				 enum transparent_hugepage_flag flag)
321 {
322 	unsigned long value;
323 	int ret;
324 
325 	ret = kstrtoul(buf, 10, &value);
326 	if (ret < 0)
327 		return ret;
328 	if (value > 1)
329 		return -EINVAL;
330 
331 	if (value)
332 		set_bit(flag, &transparent_hugepage_flags);
333 	else
334 		clear_bit(flag, &transparent_hugepage_flags);
335 
336 	return count;
337 }
338 
339 /*
340  * Currently defrag only disables __GFP_NOWAIT for allocation. A blind
341  * __GFP_REPEAT is too aggressive, it's never worth swapping tons of
342  * memory just to allocate one more hugepage.
343  */
defrag_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)344 static ssize_t defrag_show(struct kobject *kobj,
345 			   struct kobj_attribute *attr, char *buf)
346 {
347 	return double_flag_show(kobj, attr, buf,
348 				TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
349 				TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
350 }
defrag_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)351 static ssize_t defrag_store(struct kobject *kobj,
352 			    struct kobj_attribute *attr,
353 			    const char *buf, size_t count)
354 {
355 	return double_flag_store(kobj, attr, buf, count,
356 				 TRANSPARENT_HUGEPAGE_DEFRAG_FLAG,
357 				 TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG);
358 }
359 static struct kobj_attribute defrag_attr =
360 	__ATTR(defrag, 0644, defrag_show, defrag_store);
361 
use_zero_page_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)362 static ssize_t use_zero_page_show(struct kobject *kobj,
363 		struct kobj_attribute *attr, char *buf)
364 {
365 	return single_flag_show(kobj, attr, buf,
366 				TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
367 }
use_zero_page_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)368 static ssize_t use_zero_page_store(struct kobject *kobj,
369 		struct kobj_attribute *attr, const char *buf, size_t count)
370 {
371 	return single_flag_store(kobj, attr, buf, count,
372 				 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);
373 }
374 static struct kobj_attribute use_zero_page_attr =
375 	__ATTR(use_zero_page, 0644, use_zero_page_show, use_zero_page_store);
376 #ifdef CONFIG_DEBUG_VM
debug_cow_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)377 static ssize_t debug_cow_show(struct kobject *kobj,
378 				struct kobj_attribute *attr, char *buf)
379 {
380 	return single_flag_show(kobj, attr, buf,
381 				TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
382 }
debug_cow_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)383 static ssize_t debug_cow_store(struct kobject *kobj,
384 			       struct kobj_attribute *attr,
385 			       const char *buf, size_t count)
386 {
387 	return single_flag_store(kobj, attr, buf, count,
388 				 TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG);
389 }
390 static struct kobj_attribute debug_cow_attr =
391 	__ATTR(debug_cow, 0644, debug_cow_show, debug_cow_store);
392 #endif /* CONFIG_DEBUG_VM */
393 
394 static struct attribute *hugepage_attr[] = {
395 	&enabled_attr.attr,
396 	&defrag_attr.attr,
397 	&use_zero_page_attr.attr,
398 #ifdef CONFIG_DEBUG_VM
399 	&debug_cow_attr.attr,
400 #endif
401 	NULL,
402 };
403 
404 static struct attribute_group hugepage_attr_group = {
405 	.attrs = hugepage_attr,
406 };
407 
scan_sleep_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)408 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
409 					 struct kobj_attribute *attr,
410 					 char *buf)
411 {
412 	return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
413 }
414 
scan_sleep_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)415 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
416 					  struct kobj_attribute *attr,
417 					  const char *buf, size_t count)
418 {
419 	unsigned long msecs;
420 	int err;
421 
422 	err = kstrtoul(buf, 10, &msecs);
423 	if (err || msecs > UINT_MAX)
424 		return -EINVAL;
425 
426 	khugepaged_scan_sleep_millisecs = msecs;
427 	wake_up_interruptible(&khugepaged_wait);
428 
429 	return count;
430 }
431 static struct kobj_attribute scan_sleep_millisecs_attr =
432 	__ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
433 	       scan_sleep_millisecs_store);
434 
alloc_sleep_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)435 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
436 					  struct kobj_attribute *attr,
437 					  char *buf)
438 {
439 	return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
440 }
441 
alloc_sleep_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)442 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
443 					   struct kobj_attribute *attr,
444 					   const char *buf, size_t count)
445 {
446 	unsigned long msecs;
447 	int err;
448 
449 	err = kstrtoul(buf, 10, &msecs);
450 	if (err || msecs > UINT_MAX)
451 		return -EINVAL;
452 
453 	khugepaged_alloc_sleep_millisecs = msecs;
454 	wake_up_interruptible(&khugepaged_wait);
455 
456 	return count;
457 }
458 static struct kobj_attribute alloc_sleep_millisecs_attr =
459 	__ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
460 	       alloc_sleep_millisecs_store);
461 
pages_to_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)462 static ssize_t pages_to_scan_show(struct kobject *kobj,
463 				  struct kobj_attribute *attr,
464 				  char *buf)
465 {
466 	return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
467 }
pages_to_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)468 static ssize_t pages_to_scan_store(struct kobject *kobj,
469 				   struct kobj_attribute *attr,
470 				   const char *buf, size_t count)
471 {
472 	int err;
473 	unsigned long pages;
474 
475 	err = kstrtoul(buf, 10, &pages);
476 	if (err || !pages || pages > UINT_MAX)
477 		return -EINVAL;
478 
479 	khugepaged_pages_to_scan = pages;
480 
481 	return count;
482 }
483 static struct kobj_attribute pages_to_scan_attr =
484 	__ATTR(pages_to_scan, 0644, pages_to_scan_show,
485 	       pages_to_scan_store);
486 
pages_collapsed_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)487 static ssize_t pages_collapsed_show(struct kobject *kobj,
488 				    struct kobj_attribute *attr,
489 				    char *buf)
490 {
491 	return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
492 }
493 static struct kobj_attribute pages_collapsed_attr =
494 	__ATTR_RO(pages_collapsed);
495 
full_scans_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)496 static ssize_t full_scans_show(struct kobject *kobj,
497 			       struct kobj_attribute *attr,
498 			       char *buf)
499 {
500 	return sprintf(buf, "%u\n", khugepaged_full_scans);
501 }
502 static struct kobj_attribute full_scans_attr =
503 	__ATTR_RO(full_scans);
504 
khugepaged_defrag_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)505 static ssize_t khugepaged_defrag_show(struct kobject *kobj,
506 				      struct kobj_attribute *attr, char *buf)
507 {
508 	return single_flag_show(kobj, attr, buf,
509 				TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
510 }
khugepaged_defrag_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)511 static ssize_t khugepaged_defrag_store(struct kobject *kobj,
512 				       struct kobj_attribute *attr,
513 				       const char *buf, size_t count)
514 {
515 	return single_flag_store(kobj, attr, buf, count,
516 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
517 }
518 static struct kobj_attribute khugepaged_defrag_attr =
519 	__ATTR(defrag, 0644, khugepaged_defrag_show,
520 	       khugepaged_defrag_store);
521 
522 /*
523  * max_ptes_none controls if khugepaged should collapse hugepages over
524  * any unmapped ptes in turn potentially increasing the memory
525  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
526  * reduce the available free memory in the system as it
527  * runs. Increasing max_ptes_none will instead potentially reduce the
528  * free memory in the system during the khugepaged scan.
529  */
khugepaged_max_ptes_none_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)530 static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
531 					     struct kobj_attribute *attr,
532 					     char *buf)
533 {
534 	return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
535 }
khugepaged_max_ptes_none_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)536 static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
537 					      struct kobj_attribute *attr,
538 					      const char *buf, size_t count)
539 {
540 	int err;
541 	unsigned long max_ptes_none;
542 
543 	err = kstrtoul(buf, 10, &max_ptes_none);
544 	if (err || max_ptes_none > HPAGE_PMD_NR-1)
545 		return -EINVAL;
546 
547 	khugepaged_max_ptes_none = max_ptes_none;
548 
549 	return count;
550 }
551 static struct kobj_attribute khugepaged_max_ptes_none_attr =
552 	__ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
553 	       khugepaged_max_ptes_none_store);
554 
555 static struct attribute *khugepaged_attr[] = {
556 	&khugepaged_defrag_attr.attr,
557 	&khugepaged_max_ptes_none_attr.attr,
558 	&pages_to_scan_attr.attr,
559 	&pages_collapsed_attr.attr,
560 	&full_scans_attr.attr,
561 	&scan_sleep_millisecs_attr.attr,
562 	&alloc_sleep_millisecs_attr.attr,
563 	NULL,
564 };
565 
566 static struct attribute_group khugepaged_attr_group = {
567 	.attrs = khugepaged_attr,
568 	.name = "khugepaged",
569 };
570 
hugepage_init_sysfs(struct kobject ** hugepage_kobj)571 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj)
572 {
573 	int err;
574 
575 	*hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj);
576 	if (unlikely(!*hugepage_kobj)) {
577 		pr_err("failed to create transparent hugepage kobject\n");
578 		return -ENOMEM;
579 	}
580 
581 	err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group);
582 	if (err) {
583 		pr_err("failed to register transparent hugepage group\n");
584 		goto delete_obj;
585 	}
586 
587 	err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group);
588 	if (err) {
589 		pr_err("failed to register transparent hugepage group\n");
590 		goto remove_hp_group;
591 	}
592 
593 	return 0;
594 
595 remove_hp_group:
596 	sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group);
597 delete_obj:
598 	kobject_put(*hugepage_kobj);
599 	return err;
600 }
601 
hugepage_exit_sysfs(struct kobject * hugepage_kobj)602 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj)
603 {
604 	sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group);
605 	sysfs_remove_group(hugepage_kobj, &hugepage_attr_group);
606 	kobject_put(hugepage_kobj);
607 }
608 #else
hugepage_init_sysfs(struct kobject ** hugepage_kobj)609 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj)
610 {
611 	return 0;
612 }
613 
hugepage_exit_sysfs(struct kobject * hugepage_kobj)614 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj)
615 {
616 }
617 #endif /* CONFIG_SYSFS */
618 
hugepage_init(void)619 static int __init hugepage_init(void)
620 {
621 	int err;
622 	struct kobject *hugepage_kobj;
623 
624 	if (!has_transparent_hugepage()) {
625 		transparent_hugepage_flags = 0;
626 		return -EINVAL;
627 	}
628 
629 	err = hugepage_init_sysfs(&hugepage_kobj);
630 	if (err)
631 		goto err_sysfs;
632 
633 	err = khugepaged_slab_init();
634 	if (err)
635 		goto err_slab;
636 
637 	err = register_shrinker(&huge_zero_page_shrinker);
638 	if (err)
639 		goto err_hzp_shrinker;
640 
641 	/*
642 	 * By default disable transparent hugepages on smaller systems,
643 	 * where the extra memory used could hurt more than TLB overhead
644 	 * is likely to save.  The admin can still enable it through /sys.
645 	 */
646 	if (totalram_pages < (512 << (20 - PAGE_SHIFT))) {
647 		transparent_hugepage_flags = 0;
648 		return 0;
649 	}
650 
651 	err = start_stop_khugepaged();
652 	if (err)
653 		goto err_khugepaged;
654 
655 	return 0;
656 err_khugepaged:
657 	unregister_shrinker(&huge_zero_page_shrinker);
658 err_hzp_shrinker:
659 	khugepaged_slab_exit();
660 err_slab:
661 	hugepage_exit_sysfs(hugepage_kobj);
662 err_sysfs:
663 	return err;
664 }
665 subsys_initcall(hugepage_init);
666 
setup_transparent_hugepage(char * str)667 static int __init setup_transparent_hugepage(char *str)
668 {
669 	int ret = 0;
670 	if (!str)
671 		goto out;
672 	if (!strcmp(str, "always")) {
673 		set_bit(TRANSPARENT_HUGEPAGE_FLAG,
674 			&transparent_hugepage_flags);
675 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
676 			  &transparent_hugepage_flags);
677 		ret = 1;
678 	} else if (!strcmp(str, "madvise")) {
679 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
680 			  &transparent_hugepage_flags);
681 		set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
682 			&transparent_hugepage_flags);
683 		ret = 1;
684 	} else if (!strcmp(str, "never")) {
685 		clear_bit(TRANSPARENT_HUGEPAGE_FLAG,
686 			  &transparent_hugepage_flags);
687 		clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,
688 			  &transparent_hugepage_flags);
689 		ret = 1;
690 	}
691 out:
692 	if (!ret)
693 		pr_warn("transparent_hugepage= cannot parse, ignored\n");
694 	return ret;
695 }
696 __setup("transparent_hugepage=", setup_transparent_hugepage);
697 
maybe_pmd_mkwrite(pmd_t pmd,struct vm_area_struct * vma)698 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
699 {
700 	if (likely(vma->vm_flags & VM_WRITE))
701 		pmd = pmd_mkwrite(pmd);
702 	return pmd;
703 }
704 
mk_huge_pmd(struct page * page,pgprot_t prot)705 static inline pmd_t mk_huge_pmd(struct page *page, pgprot_t prot)
706 {
707 	pmd_t entry;
708 	entry = mk_pmd(page, prot);
709 	entry = pmd_mkhuge(entry);
710 	return entry;
711 }
712 
__do_huge_pmd_anonymous_page(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pmd_t * pmd,struct page * page,gfp_t gfp,unsigned int flags)713 static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
714 					struct vm_area_struct *vma,
715 					unsigned long address, pmd_t *pmd,
716 					struct page *page, gfp_t gfp,
717 					unsigned int flags)
718 {
719 	struct mem_cgroup *memcg;
720 	pgtable_t pgtable;
721 	spinlock_t *ptl;
722 	unsigned long haddr = address & HPAGE_PMD_MASK;
723 
724 	VM_BUG_ON_PAGE(!PageCompound(page), page);
725 
726 	if (mem_cgroup_try_charge(page, mm, gfp, &memcg)) {
727 		put_page(page);
728 		count_vm_event(THP_FAULT_FALLBACK);
729 		return VM_FAULT_FALLBACK;
730 	}
731 
732 	pgtable = pte_alloc_one(mm, haddr);
733 	if (unlikely(!pgtable)) {
734 		mem_cgroup_cancel_charge(page, memcg);
735 		put_page(page);
736 		return VM_FAULT_OOM;
737 	}
738 
739 	clear_huge_page(page, haddr, HPAGE_PMD_NR);
740 	/*
741 	 * The memory barrier inside __SetPageUptodate makes sure that
742 	 * clear_huge_page writes become visible before the set_pmd_at()
743 	 * write.
744 	 */
745 	__SetPageUptodate(page);
746 
747 	ptl = pmd_lock(mm, pmd);
748 	if (unlikely(!pmd_none(*pmd))) {
749 		spin_unlock(ptl);
750 		mem_cgroup_cancel_charge(page, memcg);
751 		put_page(page);
752 		pte_free(mm, pgtable);
753 	} else {
754 		pmd_t entry;
755 
756 		/* Deliver the page fault to userland */
757 		if (userfaultfd_missing(vma)) {
758 			int ret;
759 
760 			spin_unlock(ptl);
761 			mem_cgroup_cancel_charge(page, memcg);
762 			put_page(page);
763 			pte_free(mm, pgtable);
764 			ret = handle_userfault(vma, address, flags,
765 					       VM_UFFD_MISSING);
766 			VM_BUG_ON(ret & VM_FAULT_FALLBACK);
767 			return ret;
768 		}
769 
770 		entry = mk_huge_pmd(page, vma->vm_page_prot);
771 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
772 		page_add_new_anon_rmap(page, vma, haddr);
773 		mem_cgroup_commit_charge(page, memcg, false);
774 		lru_cache_add_active_or_unevictable(page, vma);
775 		pgtable_trans_huge_deposit(mm, pmd, pgtable);
776 		set_pmd_at(mm, haddr, pmd, entry);
777 		add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
778 		atomic_long_inc(&mm->nr_ptes);
779 		spin_unlock(ptl);
780 		count_vm_event(THP_FAULT_ALLOC);
781 	}
782 
783 	return 0;
784 }
785 
alloc_hugepage_gfpmask(int defrag,gfp_t extra_gfp)786 static inline gfp_t alloc_hugepage_gfpmask(int defrag, gfp_t extra_gfp)
787 {
788 	return (GFP_TRANSHUGE & ~(defrag ? 0 : __GFP_RECLAIM)) | extra_gfp;
789 }
790 
791 /* Caller must hold page table lock. */
set_huge_zero_page(pgtable_t pgtable,struct mm_struct * mm,struct vm_area_struct * vma,unsigned long haddr,pmd_t * pmd,struct page * zero_page)792 static bool set_huge_zero_page(pgtable_t pgtable, struct mm_struct *mm,
793 		struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd,
794 		struct page *zero_page)
795 {
796 	pmd_t entry;
797 	if (!pmd_none(*pmd))
798 		return false;
799 	entry = mk_pmd(zero_page, vma->vm_page_prot);
800 	entry = pmd_mkhuge(entry);
801 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
802 	set_pmd_at(mm, haddr, pmd, entry);
803 	atomic_long_inc(&mm->nr_ptes);
804 	return true;
805 }
806 
do_huge_pmd_anonymous_page(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pmd_t * pmd,unsigned int flags)807 int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
808 			       unsigned long address, pmd_t *pmd,
809 			       unsigned int flags)
810 {
811 	gfp_t gfp;
812 	struct page *page;
813 	unsigned long haddr = address & HPAGE_PMD_MASK;
814 
815 	if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
816 		return VM_FAULT_FALLBACK;
817 	if (unlikely(anon_vma_prepare(vma)))
818 		return VM_FAULT_OOM;
819 	if (unlikely(khugepaged_enter(vma, vma->vm_flags)))
820 		return VM_FAULT_OOM;
821 	if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm) &&
822 			transparent_hugepage_use_zero_page()) {
823 		spinlock_t *ptl;
824 		pgtable_t pgtable;
825 		struct page *zero_page;
826 		int ret;
827 		pgtable = pte_alloc_one(mm, haddr);
828 		if (unlikely(!pgtable))
829 			return VM_FAULT_OOM;
830 		zero_page = get_huge_zero_page();
831 		if (unlikely(!zero_page)) {
832 			pte_free(mm, pgtable);
833 			count_vm_event(THP_FAULT_FALLBACK);
834 			return VM_FAULT_FALLBACK;
835 		}
836 		ptl = pmd_lock(mm, pmd);
837 		ret = 0;
838 		if (pmd_none(*pmd)) {
839 			if (userfaultfd_missing(vma)) {
840 				spin_unlock(ptl);
841 				pte_free(mm, pgtable);
842 				put_huge_zero_page();
843 				ret = handle_userfault(vma, address, flags,
844 						       VM_UFFD_MISSING);
845 				VM_BUG_ON(ret & VM_FAULT_FALLBACK);
846 			} else {
847 				set_huge_zero_page(pgtable, mm, vma,
848 						   haddr, pmd,
849 						   zero_page);
850 				spin_unlock(ptl);
851 			}
852 		} else {
853 			spin_unlock(ptl);
854 			pte_free(mm, pgtable);
855 			put_huge_zero_page();
856 		}
857 		return ret;
858 	}
859 	gfp = alloc_hugepage_gfpmask(transparent_hugepage_defrag(vma), 0);
860 	page = alloc_hugepage_vma(gfp, vma, haddr, HPAGE_PMD_ORDER);
861 	if (unlikely(!page)) {
862 		count_vm_event(THP_FAULT_FALLBACK);
863 		return VM_FAULT_FALLBACK;
864 	}
865 	return __do_huge_pmd_anonymous_page(mm, vma, address, pmd, page, gfp,
866 					    flags);
867 }
868 
insert_pfn_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t * pmd,unsigned long pfn,pgprot_t prot,bool write)869 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
870 		pmd_t *pmd, unsigned long pfn, pgprot_t prot, bool write)
871 {
872 	struct mm_struct *mm = vma->vm_mm;
873 	pmd_t entry;
874 	spinlock_t *ptl;
875 
876 	ptl = pmd_lock(mm, pmd);
877 	if (pmd_none(*pmd)) {
878 		entry = pmd_mkhuge(pfn_pmd(pfn, prot));
879 		if (write) {
880 			entry = pmd_mkyoung(pmd_mkdirty(entry));
881 			entry = maybe_pmd_mkwrite(entry, vma);
882 		}
883 		set_pmd_at(mm, addr, pmd, entry);
884 		update_mmu_cache_pmd(vma, addr, pmd);
885 	}
886 	spin_unlock(ptl);
887 }
888 
vmf_insert_pfn_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t * pmd,unsigned long pfn,bool write)889 int vmf_insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr,
890 			pmd_t *pmd, unsigned long pfn, bool write)
891 {
892 	pgprot_t pgprot = vma->vm_page_prot;
893 	/*
894 	 * If we had pmd_special, we could avoid all these restrictions,
895 	 * but we need to be consistent with PTEs and architectures that
896 	 * can't support a 'special' bit.
897 	 */
898 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
899 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
900 						(VM_PFNMAP|VM_MIXEDMAP));
901 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
902 	BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
903 
904 	if (addr < vma->vm_start || addr >= vma->vm_end)
905 		return VM_FAULT_SIGBUS;
906 	if (track_pfn_insert(vma, &pgprot, pfn))
907 		return VM_FAULT_SIGBUS;
908 	insert_pfn_pmd(vma, addr, pmd, pfn, pgprot, write);
909 	return VM_FAULT_NOPAGE;
910 }
911 
copy_huge_pmd(struct mm_struct * dst_mm,struct mm_struct * src_mm,pmd_t * dst_pmd,pmd_t * src_pmd,unsigned long addr,struct vm_area_struct * vma)912 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,
913 		  pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
914 		  struct vm_area_struct *vma)
915 {
916 	spinlock_t *dst_ptl, *src_ptl;
917 	struct page *src_page;
918 	pmd_t pmd;
919 	pgtable_t pgtable;
920 	int ret;
921 
922 	ret = -ENOMEM;
923 	pgtable = pte_alloc_one(dst_mm, addr);
924 	if (unlikely(!pgtable))
925 		goto out;
926 
927 	dst_ptl = pmd_lock(dst_mm, dst_pmd);
928 	src_ptl = pmd_lockptr(src_mm, src_pmd);
929 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
930 
931 	ret = -EAGAIN;
932 	pmd = *src_pmd;
933 	if (unlikely(!pmd_trans_huge(pmd))) {
934 		pte_free(dst_mm, pgtable);
935 		goto out_unlock;
936 	}
937 	/*
938 	 * When page table lock is held, the huge zero pmd should not be
939 	 * under splitting since we don't split the page itself, only pmd to
940 	 * a page table.
941 	 */
942 	if (is_huge_zero_pmd(pmd)) {
943 		struct page *zero_page;
944 		/*
945 		 * get_huge_zero_page() will never allocate a new page here,
946 		 * since we already have a zero page to copy. It just takes a
947 		 * reference.
948 		 */
949 		zero_page = get_huge_zero_page();
950 		set_huge_zero_page(pgtable, dst_mm, vma, addr, dst_pmd,
951 				zero_page);
952 		ret = 0;
953 		goto out_unlock;
954 	}
955 
956 	if (unlikely(pmd_trans_splitting(pmd))) {
957 		/* split huge page running from under us */
958 		spin_unlock(src_ptl);
959 		spin_unlock(dst_ptl);
960 		pte_free(dst_mm, pgtable);
961 
962 		wait_split_huge_page(vma->anon_vma, src_pmd); /* src_vma */
963 		goto out;
964 	}
965 	src_page = pmd_page(pmd);
966 	VM_BUG_ON_PAGE(!PageHead(src_page), src_page);
967 	get_page(src_page);
968 	page_dup_rmap(src_page);
969 	add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR);
970 
971 	pmdp_set_wrprotect(src_mm, addr, src_pmd);
972 	pmd = pmd_mkold(pmd_wrprotect(pmd));
973 	pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable);
974 	set_pmd_at(dst_mm, addr, dst_pmd, pmd);
975 	atomic_long_inc(&dst_mm->nr_ptes);
976 
977 	ret = 0;
978 out_unlock:
979 	spin_unlock(src_ptl);
980 	spin_unlock(dst_ptl);
981 out:
982 	return ret;
983 }
984 
huge_pmd_set_accessed(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pmd_t * pmd,pmd_t orig_pmd,int dirty)985 void huge_pmd_set_accessed(struct mm_struct *mm,
986 			   struct vm_area_struct *vma,
987 			   unsigned long address,
988 			   pmd_t *pmd, pmd_t orig_pmd,
989 			   int dirty)
990 {
991 	spinlock_t *ptl;
992 	pmd_t entry;
993 	unsigned long haddr;
994 
995 	ptl = pmd_lock(mm, pmd);
996 	if (unlikely(!pmd_same(*pmd, orig_pmd)))
997 		goto unlock;
998 
999 	entry = pmd_mkyoung(orig_pmd);
1000 	haddr = address & HPAGE_PMD_MASK;
1001 	if (pmdp_set_access_flags(vma, haddr, pmd, entry, dirty))
1002 		update_mmu_cache_pmd(vma, address, pmd);
1003 
1004 unlock:
1005 	spin_unlock(ptl);
1006 }
1007 
1008 /*
1009  * Save CONFIG_DEBUG_PAGEALLOC from faulting falsely on tail pages
1010  * during copy_user_huge_page()'s copy_page_rep(): in the case when
1011  * the source page gets split and a tail freed before copy completes.
1012  * Called under pmd_lock of checked pmd, so safe from splitting itself.
1013  */
get_user_huge_page(struct page * page)1014 static void get_user_huge_page(struct page *page)
1015 {
1016 	if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC)) {
1017 		struct page *endpage = page + HPAGE_PMD_NR;
1018 
1019 		atomic_add(HPAGE_PMD_NR, &page->_count);
1020 		while (++page < endpage)
1021 			get_huge_page_tail(page);
1022 	} else {
1023 		get_page(page);
1024 	}
1025 }
1026 
put_user_huge_page(struct page * page)1027 static void put_user_huge_page(struct page *page)
1028 {
1029 	if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC)) {
1030 		struct page *endpage = page + HPAGE_PMD_NR;
1031 
1032 		while (page < endpage)
1033 			put_page(page++);
1034 	} else {
1035 		put_page(page);
1036 	}
1037 }
1038 
do_huge_pmd_wp_page_fallback(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pmd_t * pmd,pmd_t orig_pmd,struct page * page,unsigned long haddr)1039 static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm,
1040 					struct vm_area_struct *vma,
1041 					unsigned long address,
1042 					pmd_t *pmd, pmd_t orig_pmd,
1043 					struct page *page,
1044 					unsigned long haddr)
1045 {
1046 	struct mem_cgroup *memcg;
1047 	spinlock_t *ptl;
1048 	pgtable_t pgtable;
1049 	pmd_t _pmd;
1050 	int ret = 0, i;
1051 	struct page **pages;
1052 	unsigned long mmun_start;	/* For mmu_notifiers */
1053 	unsigned long mmun_end;		/* For mmu_notifiers */
1054 
1055 	pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR,
1056 			GFP_KERNEL);
1057 	if (unlikely(!pages)) {
1058 		ret |= VM_FAULT_OOM;
1059 		goto out;
1060 	}
1061 
1062 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1063 		pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE |
1064 					       __GFP_OTHER_NODE,
1065 					       vma, address, page_to_nid(page));
1066 		if (unlikely(!pages[i] ||
1067 			     mem_cgroup_try_charge(pages[i], mm, GFP_KERNEL,
1068 						   &memcg))) {
1069 			if (pages[i])
1070 				put_page(pages[i]);
1071 			while (--i >= 0) {
1072 				memcg = (void *)page_private(pages[i]);
1073 				set_page_private(pages[i], 0);
1074 				mem_cgroup_cancel_charge(pages[i], memcg);
1075 				put_page(pages[i]);
1076 			}
1077 			kfree(pages);
1078 			ret |= VM_FAULT_OOM;
1079 			goto out;
1080 		}
1081 		set_page_private(pages[i], (unsigned long)memcg);
1082 	}
1083 
1084 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1085 		copy_user_highpage(pages[i], page + i,
1086 				   haddr + PAGE_SIZE * i, vma);
1087 		__SetPageUptodate(pages[i]);
1088 		cond_resched();
1089 	}
1090 
1091 	mmun_start = haddr;
1092 	mmun_end   = haddr + HPAGE_PMD_SIZE;
1093 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1094 
1095 	ptl = pmd_lock(mm, pmd);
1096 	if (unlikely(!pmd_same(*pmd, orig_pmd)))
1097 		goto out_free_pages;
1098 	VM_BUG_ON_PAGE(!PageHead(page), page);
1099 
1100 	pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1101 	/* leave pmd empty until pte is filled */
1102 
1103 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1104 	pmd_populate(mm, &_pmd, pgtable);
1105 
1106 	for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1107 		pte_t *pte, entry;
1108 		entry = mk_pte(pages[i], vma->vm_page_prot);
1109 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1110 		memcg = (void *)page_private(pages[i]);
1111 		set_page_private(pages[i], 0);
1112 		page_add_new_anon_rmap(pages[i], vma, haddr);
1113 		mem_cgroup_commit_charge(pages[i], memcg, false);
1114 		lru_cache_add_active_or_unevictable(pages[i], vma);
1115 		pte = pte_offset_map(&_pmd, haddr);
1116 		VM_BUG_ON(!pte_none(*pte));
1117 		set_pte_at(mm, haddr, pte, entry);
1118 		pte_unmap(pte);
1119 	}
1120 	kfree(pages);
1121 
1122 	smp_wmb(); /* make pte visible before pmd */
1123 	pmd_populate(mm, pmd, pgtable);
1124 	page_remove_rmap(page);
1125 	spin_unlock(ptl);
1126 
1127 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1128 
1129 	ret |= VM_FAULT_WRITE;
1130 	put_page(page);
1131 
1132 out:
1133 	return ret;
1134 
1135 out_free_pages:
1136 	spin_unlock(ptl);
1137 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1138 	for (i = 0; i < HPAGE_PMD_NR; i++) {
1139 		memcg = (void *)page_private(pages[i]);
1140 		set_page_private(pages[i], 0);
1141 		mem_cgroup_cancel_charge(pages[i], memcg);
1142 		put_page(pages[i]);
1143 	}
1144 	kfree(pages);
1145 	goto out;
1146 }
1147 
do_huge_pmd_wp_page(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pmd_t * pmd,pmd_t orig_pmd)1148 int do_huge_pmd_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
1149 			unsigned long address, pmd_t *pmd, pmd_t orig_pmd)
1150 {
1151 	spinlock_t *ptl;
1152 	int ret = 0;
1153 	struct page *page = NULL, *new_page;
1154 	struct mem_cgroup *memcg;
1155 	unsigned long haddr;
1156 	unsigned long mmun_start;	/* For mmu_notifiers */
1157 	unsigned long mmun_end;		/* For mmu_notifiers */
1158 	gfp_t huge_gfp;			/* for allocation and charge */
1159 
1160 	ptl = pmd_lockptr(mm, pmd);
1161 	VM_BUG_ON_VMA(!vma->anon_vma, vma);
1162 	haddr = address & HPAGE_PMD_MASK;
1163 	if (is_huge_zero_pmd(orig_pmd))
1164 		goto alloc;
1165 	spin_lock(ptl);
1166 	if (unlikely(!pmd_same(*pmd, orig_pmd)))
1167 		goto out_unlock;
1168 
1169 	page = pmd_page(orig_pmd);
1170 	VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
1171 	if (page_mapcount(page) == 1) {
1172 		pmd_t entry;
1173 		entry = pmd_mkyoung(orig_pmd);
1174 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1175 		if (pmdp_set_access_flags(vma, haddr, pmd, entry,  1))
1176 			update_mmu_cache_pmd(vma, address, pmd);
1177 		ret |= VM_FAULT_WRITE;
1178 		goto out_unlock;
1179 	}
1180 	get_user_huge_page(page);
1181 	spin_unlock(ptl);
1182 alloc:
1183 	if (transparent_hugepage_enabled(vma) &&
1184 	    !transparent_hugepage_debug_cow()) {
1185 		huge_gfp = alloc_hugepage_gfpmask(transparent_hugepage_defrag(vma), 0);
1186 		new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
1187 	} else
1188 		new_page = NULL;
1189 
1190 	if (unlikely(!new_page)) {
1191 		if (!page) {
1192 			split_huge_page_pmd(vma, address, pmd);
1193 			ret |= VM_FAULT_FALLBACK;
1194 		} else {
1195 			ret = do_huge_pmd_wp_page_fallback(mm, vma, address,
1196 					pmd, orig_pmd, page, haddr);
1197 			if (ret & VM_FAULT_OOM) {
1198 				split_huge_page(page);
1199 				ret |= VM_FAULT_FALLBACK;
1200 			}
1201 			put_user_huge_page(page);
1202 		}
1203 		count_vm_event(THP_FAULT_FALLBACK);
1204 		goto out;
1205 	}
1206 
1207 	if (unlikely(mem_cgroup_try_charge(new_page, mm, huge_gfp, &memcg))) {
1208 		put_page(new_page);
1209 		if (page) {
1210 			split_huge_page(page);
1211 			put_user_huge_page(page);
1212 		} else
1213 			split_huge_page_pmd(vma, address, pmd);
1214 		ret |= VM_FAULT_FALLBACK;
1215 		count_vm_event(THP_FAULT_FALLBACK);
1216 		goto out;
1217 	}
1218 
1219 	count_vm_event(THP_FAULT_ALLOC);
1220 
1221 	if (!page)
1222 		clear_huge_page(new_page, haddr, HPAGE_PMD_NR);
1223 	else
1224 		copy_user_huge_page(new_page, page, haddr, vma, HPAGE_PMD_NR);
1225 	__SetPageUptodate(new_page);
1226 
1227 	mmun_start = haddr;
1228 	mmun_end   = haddr + HPAGE_PMD_SIZE;
1229 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1230 
1231 	spin_lock(ptl);
1232 	if (page)
1233 		put_user_huge_page(page);
1234 	if (unlikely(!pmd_same(*pmd, orig_pmd))) {
1235 		spin_unlock(ptl);
1236 		mem_cgroup_cancel_charge(new_page, memcg);
1237 		put_page(new_page);
1238 		goto out_mn;
1239 	} else {
1240 		pmd_t entry;
1241 		entry = mk_huge_pmd(new_page, vma->vm_page_prot);
1242 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1243 		pmdp_huge_clear_flush_notify(vma, haddr, pmd);
1244 		page_add_new_anon_rmap(new_page, vma, haddr);
1245 		mem_cgroup_commit_charge(new_page, memcg, false);
1246 		lru_cache_add_active_or_unevictable(new_page, vma);
1247 		set_pmd_at(mm, haddr, pmd, entry);
1248 		update_mmu_cache_pmd(vma, address, pmd);
1249 		if (!page) {
1250 			add_mm_counter(mm, MM_ANONPAGES, HPAGE_PMD_NR);
1251 			put_huge_zero_page();
1252 		} else {
1253 			VM_BUG_ON_PAGE(!PageHead(page), page);
1254 			page_remove_rmap(page);
1255 			put_page(page);
1256 		}
1257 		ret |= VM_FAULT_WRITE;
1258 	}
1259 	spin_unlock(ptl);
1260 out_mn:
1261 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1262 out:
1263 	return ret;
1264 out_unlock:
1265 	spin_unlock(ptl);
1266 	return ret;
1267 }
1268 
1269 /*
1270  * FOLL_FORCE or a forced COW break can write even to unwritable pmd's,
1271  * but only after we've gone through a COW cycle and they are dirty.
1272  */
can_follow_write_pmd(pmd_t pmd,unsigned int flags)1273 static inline bool can_follow_write_pmd(pmd_t pmd, unsigned int flags)
1274 {
1275 	return pmd_write(pmd) || ((flags & FOLL_COW) && pmd_dirty(pmd));
1276 }
1277 
follow_trans_huge_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t * pmd,unsigned int flags)1278 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1279 				   unsigned long addr,
1280 				   pmd_t *pmd,
1281 				   unsigned int flags)
1282 {
1283 	struct mm_struct *mm = vma->vm_mm;
1284 	struct page *page = NULL;
1285 
1286 	assert_spin_locked(pmd_lockptr(mm, pmd));
1287 
1288 	if (flags & FOLL_WRITE && !can_follow_write_pmd(*pmd, flags))
1289 		goto out;
1290 
1291 	/* Avoid dumping huge zero page */
1292 	if ((flags & FOLL_DUMP) && is_huge_zero_pmd(*pmd))
1293 		return ERR_PTR(-EFAULT);
1294 
1295 	/* Full NUMA hinting faults to serialise migration in fault paths */
1296 	if ((flags & FOLL_NUMA) && pmd_protnone(*pmd))
1297 		goto out;
1298 
1299 	page = pmd_page(*pmd);
1300 	VM_BUG_ON_PAGE(!PageHead(page), page);
1301 	if (flags & FOLL_TOUCH) {
1302 		pmd_t _pmd;
1303 		_pmd = pmd_mkyoung(*pmd);
1304 		if (flags & FOLL_WRITE)
1305 			_pmd = pmd_mkdirty(_pmd);
1306 		if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK,
1307 					  pmd, _pmd, flags & FOLL_WRITE))
1308 			update_mmu_cache_pmd(vma, addr, pmd);
1309 	}
1310 	if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
1311 		if (page->mapping && trylock_page(page)) {
1312 			lru_add_drain();
1313 			if (page->mapping)
1314 				mlock_vma_page(page);
1315 			unlock_page(page);
1316 		}
1317 	}
1318 	page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
1319 	VM_BUG_ON_PAGE(!PageCompound(page), page);
1320 	if (flags & FOLL_GET)
1321 		get_page_foll(page);
1322 
1323 out:
1324 	return page;
1325 }
1326 
1327 /* NUMA hinting page fault entry point for trans huge pmds */
do_huge_pmd_numa_page(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pmd_t pmd,pmd_t * pmdp)1328 int do_huge_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
1329 				unsigned long addr, pmd_t pmd, pmd_t *pmdp)
1330 {
1331 	spinlock_t *ptl;
1332 	struct anon_vma *anon_vma = NULL;
1333 	struct page *page;
1334 	unsigned long haddr = addr & HPAGE_PMD_MASK;
1335 	int page_nid = -1, this_nid = numa_node_id();
1336 	int target_nid, last_cpupid = -1;
1337 	bool page_locked;
1338 	bool migrated = false;
1339 	bool was_writable;
1340 	int flags = 0;
1341 
1342 	ptl = pmd_lock(mm, pmdp);
1343 	if (unlikely(!pmd_same(pmd, *pmdp)))
1344 		goto out_unlock;
1345 
1346 	/*
1347 	 * If there are potential migrations, wait for completion and retry
1348 	 * without disrupting NUMA hinting information. Do not relock and
1349 	 * check_same as the page may no longer be mapped.
1350 	 */
1351 	if (unlikely(pmd_trans_migrating(*pmdp))) {
1352 		page = pmd_page(*pmdp);
1353 		if (!get_page_unless_zero(page))
1354 			goto out_unlock;
1355 		spin_unlock(ptl);
1356 		wait_on_page_locked(page);
1357 		put_page(page);
1358 		goto out;
1359 	}
1360 
1361 	page = pmd_page(pmd);
1362 	BUG_ON(is_huge_zero_page(page));
1363 	page_nid = page_to_nid(page);
1364 	last_cpupid = page_cpupid_last(page);
1365 	count_vm_numa_event(NUMA_HINT_FAULTS);
1366 	if (page_nid == this_nid) {
1367 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
1368 		flags |= TNF_FAULT_LOCAL;
1369 	}
1370 
1371 	/* See similar comment in do_numa_page for explanation */
1372 	if (!(vma->vm_flags & VM_WRITE))
1373 		flags |= TNF_NO_GROUP;
1374 
1375 	/*
1376 	 * Acquire the page lock to serialise THP migrations but avoid dropping
1377 	 * page_table_lock if at all possible
1378 	 */
1379 	page_locked = trylock_page(page);
1380 	target_nid = mpol_misplaced(page, vma, haddr);
1381 	if (target_nid == -1) {
1382 		/* If the page was locked, there are no parallel migrations */
1383 		if (page_locked)
1384 			goto clear_pmdnuma;
1385 	}
1386 
1387 	/* Migration could have started since the pmd_trans_migrating check */
1388 	if (!page_locked) {
1389 		page_nid = -1;
1390 		if (!get_page_unless_zero(page))
1391 			goto out_unlock;
1392 		spin_unlock(ptl);
1393 		wait_on_page_locked(page);
1394 		put_page(page);
1395 		goto out;
1396 	}
1397 
1398 	/*
1399 	 * Page is misplaced. Page lock serialises migrations. Acquire anon_vma
1400 	 * to serialises splits
1401 	 */
1402 	get_page(page);
1403 	spin_unlock(ptl);
1404 	anon_vma = page_lock_anon_vma_read(page);
1405 
1406 	/* Confirm the PMD did not change while page_table_lock was released */
1407 	spin_lock(ptl);
1408 	if (unlikely(!pmd_same(pmd, *pmdp))) {
1409 		unlock_page(page);
1410 		put_page(page);
1411 		page_nid = -1;
1412 		goto out_unlock;
1413 	}
1414 
1415 	/* Bail if we fail to protect against THP splits for any reason */
1416 	if (unlikely(!anon_vma)) {
1417 		put_page(page);
1418 		page_nid = -1;
1419 		goto clear_pmdnuma;
1420 	}
1421 
1422 	/*
1423 	 * Migrate the THP to the requested node, returns with page unlocked
1424 	 * and access rights restored.
1425 	 */
1426 	spin_unlock(ptl);
1427 	migrated = migrate_misplaced_transhuge_page(mm, vma,
1428 				pmdp, pmd, addr, page, target_nid);
1429 	if (migrated) {
1430 		flags |= TNF_MIGRATED;
1431 		page_nid = target_nid;
1432 	} else
1433 		flags |= TNF_MIGRATE_FAIL;
1434 
1435 	goto out;
1436 clear_pmdnuma:
1437 	BUG_ON(!PageLocked(page));
1438 	was_writable = pmd_write(pmd);
1439 	pmd = pmd_modify(pmd, vma->vm_page_prot);
1440 	pmd = pmd_mkyoung(pmd);
1441 	if (was_writable)
1442 		pmd = pmd_mkwrite(pmd);
1443 	set_pmd_at(mm, haddr, pmdp, pmd);
1444 	update_mmu_cache_pmd(vma, addr, pmdp);
1445 	unlock_page(page);
1446 out_unlock:
1447 	spin_unlock(ptl);
1448 
1449 out:
1450 	if (anon_vma)
1451 		page_unlock_anon_vma_read(anon_vma);
1452 
1453 	if (page_nid != -1)
1454 		task_numa_fault(last_cpupid, page_nid, HPAGE_PMD_NR, flags);
1455 
1456 	return 0;
1457 }
1458 
zap_huge_pmd(struct mmu_gather * tlb,struct vm_area_struct * vma,pmd_t * pmd,unsigned long addr)1459 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
1460 		 pmd_t *pmd, unsigned long addr)
1461 {
1462 	pmd_t orig_pmd;
1463 	spinlock_t *ptl;
1464 
1465 	if (__pmd_trans_huge_lock(pmd, vma, &ptl) != 1)
1466 		return 0;
1467 	/*
1468 	 * For architectures like ppc64 we look at deposited pgtable
1469 	 * when calling pmdp_huge_get_and_clear. So do the
1470 	 * pgtable_trans_huge_withdraw after finishing pmdp related
1471 	 * operations.
1472 	 */
1473 	orig_pmd = pmdp_huge_get_and_clear_full(tlb->mm, addr, pmd,
1474 			tlb->fullmm);
1475 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
1476 	if (vma_is_dax(vma)) {
1477 		spin_unlock(ptl);
1478 		if (is_huge_zero_pmd(orig_pmd))
1479 			put_huge_zero_page();
1480 	} else if (is_huge_zero_pmd(orig_pmd)) {
1481 		pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1482 		atomic_long_dec(&tlb->mm->nr_ptes);
1483 		spin_unlock(ptl);
1484 		put_huge_zero_page();
1485 	} else {
1486 		struct page *page = pmd_page(orig_pmd);
1487 		page_remove_rmap(page);
1488 		VM_BUG_ON_PAGE(page_mapcount(page) < 0, page);
1489 		add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR);
1490 		VM_BUG_ON_PAGE(!PageHead(page), page);
1491 		pte_free(tlb->mm, pgtable_trans_huge_withdraw(tlb->mm, pmd));
1492 		atomic_long_dec(&tlb->mm->nr_ptes);
1493 		spin_unlock(ptl);
1494 		tlb_remove_page(tlb, page);
1495 	}
1496 	return 1;
1497 }
1498 
move_huge_pmd(struct vm_area_struct * vma,struct vm_area_struct * new_vma,unsigned long old_addr,unsigned long new_addr,unsigned long old_end,pmd_t * old_pmd,pmd_t * new_pmd)1499 int move_huge_pmd(struct vm_area_struct *vma, struct vm_area_struct *new_vma,
1500 		  unsigned long old_addr,
1501 		  unsigned long new_addr, unsigned long old_end,
1502 		  pmd_t *old_pmd, pmd_t *new_pmd)
1503 {
1504 	spinlock_t *old_ptl, *new_ptl;
1505 	int ret = 0;
1506 	pmd_t pmd;
1507 	bool force_flush = false;
1508 	struct mm_struct *mm = vma->vm_mm;
1509 
1510 	if ((old_addr & ~HPAGE_PMD_MASK) ||
1511 	    (new_addr & ~HPAGE_PMD_MASK) ||
1512 	    old_end - old_addr < HPAGE_PMD_SIZE ||
1513 	    (new_vma->vm_flags & VM_NOHUGEPAGE))
1514 		goto out;
1515 
1516 	/*
1517 	 * The destination pmd shouldn't be established, free_pgtables()
1518 	 * should have release it.
1519 	 */
1520 	if (WARN_ON(!pmd_none(*new_pmd))) {
1521 		VM_BUG_ON(pmd_trans_huge(*new_pmd));
1522 		goto out;
1523 	}
1524 
1525 	/*
1526 	 * We don't have to worry about the ordering of src and dst
1527 	 * ptlocks because exclusive mmap_sem prevents deadlock.
1528 	 */
1529 	ret = __pmd_trans_huge_lock(old_pmd, vma, &old_ptl);
1530 	if (ret == 1) {
1531 		new_ptl = pmd_lockptr(mm, new_pmd);
1532 		if (new_ptl != old_ptl)
1533 			spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1534 		pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd);
1535 		if (pmd_present(pmd))
1536 			force_flush = true;
1537 		VM_BUG_ON(!pmd_none(*new_pmd));
1538 
1539 		if (pmd_move_must_withdraw(new_ptl, old_ptl)) {
1540 			pgtable_t pgtable;
1541 			pgtable = pgtable_trans_huge_withdraw(mm, old_pmd);
1542 			pgtable_trans_huge_deposit(mm, new_pmd, pgtable);
1543 		}
1544 		set_pmd_at(mm, new_addr, new_pmd, pmd_mksoft_dirty(pmd));
1545 		if (force_flush)
1546 			flush_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
1547 		if (new_ptl != old_ptl)
1548 			spin_unlock(new_ptl);
1549 		spin_unlock(old_ptl);
1550 	}
1551 out:
1552 	return ret;
1553 }
1554 
1555 /*
1556  * Returns
1557  *  - 0 if PMD could not be locked
1558  *  - 1 if PMD was locked but protections unchange and TLB flush unnecessary
1559  *  - HPAGE_PMD_NR is protections changed and TLB flush necessary
1560  */
change_huge_pmd(struct vm_area_struct * vma,pmd_t * pmd,unsigned long addr,pgprot_t newprot,int prot_numa)1561 int change_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,
1562 		unsigned long addr, pgprot_t newprot, int prot_numa)
1563 {
1564 	struct mm_struct *mm = vma->vm_mm;
1565 	spinlock_t *ptl;
1566 	pmd_t entry;
1567 	bool preserve_write;
1568 
1569 	int ret = 0;
1570 
1571 	if (__pmd_trans_huge_lock(pmd, vma, &ptl) != 1)
1572 		return 0;
1573 
1574 	preserve_write = prot_numa && pmd_write(*pmd);
1575 	ret = 1;
1576 
1577 	/*
1578 	 * Avoid trapping faults against the zero page. The read-only
1579 	 * data is likely to be read-cached on the local CPU and
1580 	 * local/remote hits to the zero page are not interesting.
1581 	 */
1582 	if (prot_numa && is_huge_zero_pmd(*pmd))
1583 		goto unlock;
1584 
1585 	if (prot_numa && pmd_protnone(*pmd))
1586 		goto unlock;
1587 
1588 	/*
1589 	 * In case prot_numa, we are under down_read(mmap_sem). It's critical
1590 	 * to not clear pmd intermittently to avoid race with MADV_DONTNEED
1591 	 * which is also under down_read(mmap_sem):
1592 	 *
1593 	 *	CPU0:				CPU1:
1594 	 *				change_huge_pmd(prot_numa=1)
1595 	 *				 pmdp_huge_get_and_clear_notify()
1596 	 * madvise_dontneed()
1597 	 *  zap_pmd_range()
1598 	 *   pmd_trans_huge(*pmd) == 0 (without ptl)
1599 	 *   // skip the pmd
1600 	 *				 set_pmd_at();
1601 	 *				 // pmd is re-established
1602 	 *
1603 	 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it
1604 	 * which may break userspace.
1605 	 *
1606 	 * pmdp_invalidate() is required to make sure we don't miss
1607 	 * dirty/young flags set by hardware.
1608 	 */
1609 	entry = *pmd;
1610 	pmdp_invalidate(vma, addr, pmd);
1611 
1612 	/*
1613 	 * Recover dirty/young flags.  It relies on pmdp_invalidate to not
1614 	 * corrupt them.
1615 	 */
1616 	if (pmd_dirty(*pmd))
1617 		entry = pmd_mkdirty(entry);
1618 	if (pmd_young(*pmd))
1619 		entry = pmd_mkyoung(entry);
1620 
1621 	entry = pmd_modify(entry, newprot);
1622 	if (preserve_write)
1623 		entry = pmd_mkwrite(entry);
1624 	ret = HPAGE_PMD_NR;
1625 	set_pmd_at(mm, addr, pmd, entry);
1626 	BUG_ON(!preserve_write && pmd_write(entry));
1627 unlock:
1628 	spin_unlock(ptl);
1629 	return ret;
1630 }
1631 
1632 /*
1633  * Returns 1 if a given pmd maps a stable (not under splitting) thp.
1634  * Returns -1 if it maps a thp under splitting. Returns 0 otherwise.
1635  *
1636  * Note that if it returns 1, this routine returns without unlocking page
1637  * table locks. So callers must unlock them.
1638  */
__pmd_trans_huge_lock(pmd_t * pmd,struct vm_area_struct * vma,spinlock_t ** ptl)1639 int __pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma,
1640 		spinlock_t **ptl)
1641 {
1642 	*ptl = pmd_lock(vma->vm_mm, pmd);
1643 	if (likely(pmd_trans_huge(*pmd))) {
1644 		if (unlikely(pmd_trans_splitting(*pmd))) {
1645 			spin_unlock(*ptl);
1646 			wait_split_huge_page(vma->anon_vma, pmd);
1647 			return -1;
1648 		} else {
1649 			/* Thp mapped by 'pmd' is stable, so we can
1650 			 * handle it as it is. */
1651 			return 1;
1652 		}
1653 	}
1654 	spin_unlock(*ptl);
1655 	return 0;
1656 }
1657 
1658 /*
1659  * This function returns whether a given @page is mapped onto the @address
1660  * in the virtual space of @mm.
1661  *
1662  * When it's true, this function returns *pmd with holding the page table lock
1663  * and passing it back to the caller via @ptl.
1664  * If it's false, returns NULL without holding the page table lock.
1665  */
page_check_address_pmd(struct page * page,struct mm_struct * mm,unsigned long address,enum page_check_address_pmd_flag flag,spinlock_t ** ptl)1666 pmd_t *page_check_address_pmd(struct page *page,
1667 			      struct mm_struct *mm,
1668 			      unsigned long address,
1669 			      enum page_check_address_pmd_flag flag,
1670 			      spinlock_t **ptl)
1671 {
1672 	pgd_t *pgd;
1673 	pud_t *pud;
1674 	pmd_t *pmd;
1675 
1676 	if (address & ~HPAGE_PMD_MASK)
1677 		return NULL;
1678 
1679 	pgd = pgd_offset(mm, address);
1680 	if (!pgd_present(*pgd))
1681 		return NULL;
1682 	pud = pud_offset(pgd, address);
1683 	if (!pud_present(*pud))
1684 		return NULL;
1685 	pmd = pmd_offset(pud, address);
1686 
1687 	*ptl = pmd_lock(mm, pmd);
1688 	if (!pmd_present(*pmd))
1689 		goto unlock;
1690 	if (pmd_page(*pmd) != page)
1691 		goto unlock;
1692 	/*
1693 	 * split_vma() may create temporary aliased mappings. There is
1694 	 * no risk as long as all huge pmd are found and have their
1695 	 * splitting bit set before __split_huge_page_refcount
1696 	 * runs. Finding the same huge pmd more than once during the
1697 	 * same rmap walk is not a problem.
1698 	 */
1699 	if (flag == PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG &&
1700 	    pmd_trans_splitting(*pmd))
1701 		goto unlock;
1702 	if (pmd_trans_huge(*pmd)) {
1703 		VM_BUG_ON(flag == PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG &&
1704 			  !pmd_trans_splitting(*pmd));
1705 		return pmd;
1706 	}
1707 unlock:
1708 	spin_unlock(*ptl);
1709 	return NULL;
1710 }
1711 
__split_huge_page_splitting(struct page * page,struct vm_area_struct * vma,unsigned long address)1712 static int __split_huge_page_splitting(struct page *page,
1713 				       struct vm_area_struct *vma,
1714 				       unsigned long address)
1715 {
1716 	struct mm_struct *mm = vma->vm_mm;
1717 	spinlock_t *ptl;
1718 	pmd_t *pmd;
1719 	int ret = 0;
1720 	/* For mmu_notifiers */
1721 	const unsigned long mmun_start = address;
1722 	const unsigned long mmun_end   = address + HPAGE_PMD_SIZE;
1723 
1724 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1725 	pmd = page_check_address_pmd(page, mm, address,
1726 			PAGE_CHECK_ADDRESS_PMD_NOTSPLITTING_FLAG, &ptl);
1727 	if (pmd) {
1728 		/*
1729 		 * We can't temporarily set the pmd to null in order
1730 		 * to split it, the pmd must remain marked huge at all
1731 		 * times or the VM won't take the pmd_trans_huge paths
1732 		 * and it won't wait on the anon_vma->root->rwsem to
1733 		 * serialize against split_huge_page*.
1734 		 */
1735 		pmdp_splitting_flush(vma, address, pmd);
1736 
1737 		ret = 1;
1738 		spin_unlock(ptl);
1739 	}
1740 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1741 
1742 	return ret;
1743 }
1744 
__split_huge_page_refcount(struct page * page,struct list_head * list)1745 static void __split_huge_page_refcount(struct page *page,
1746 				       struct list_head *list)
1747 {
1748 	int i;
1749 	struct zone *zone = page_zone(page);
1750 	struct lruvec *lruvec;
1751 	int tail_count = 0;
1752 
1753 	/* prevent PageLRU to go away from under us, and freeze lru stats */
1754 	spin_lock_irq(&zone->lru_lock);
1755 	lruvec = mem_cgroup_page_lruvec(page, zone);
1756 
1757 	compound_lock(page);
1758 	/* complete memcg works before add pages to LRU */
1759 	mem_cgroup_split_huge_fixup(page);
1760 
1761 	for (i = HPAGE_PMD_NR - 1; i >= 1; i--) {
1762 		struct page *page_tail = page + i;
1763 
1764 		/* tail_page->_mapcount cannot change */
1765 		BUG_ON(page_mapcount(page_tail) < 0);
1766 		tail_count += page_mapcount(page_tail);
1767 		/* check for overflow */
1768 		BUG_ON(tail_count < 0);
1769 		BUG_ON(atomic_read(&page_tail->_count) != 0);
1770 		/*
1771 		 * tail_page->_count is zero and not changing from
1772 		 * under us. But get_page_unless_zero() may be running
1773 		 * from under us on the tail_page. If we used
1774 		 * atomic_set() below instead of atomic_add(), we
1775 		 * would then run atomic_set() concurrently with
1776 		 * get_page_unless_zero(), and atomic_set() is
1777 		 * implemented in C not using locked ops. spin_unlock
1778 		 * on x86 sometime uses locked ops because of PPro
1779 		 * errata 66, 92, so unless somebody can guarantee
1780 		 * atomic_set() here would be safe on all archs (and
1781 		 * not only on x86), it's safer to use atomic_add().
1782 		 */
1783 		atomic_add(page_mapcount(page) + page_mapcount(page_tail) + 1,
1784 			   &page_tail->_count);
1785 
1786 		/* after clearing PageTail the gup refcount can be released */
1787 		smp_mb__after_atomic();
1788 
1789 		page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1790 		page_tail->flags |= (page->flags &
1791 				     ((1L << PG_referenced) |
1792 				      (1L << PG_swapbacked) |
1793 				      (1L << PG_mlocked) |
1794 				      (1L << PG_uptodate) |
1795 				      (1L << PG_active) |
1796 				      (1L << PG_unevictable)));
1797 		page_tail->flags |= (1L << PG_dirty);
1798 
1799 		clear_compound_head(page_tail);
1800 
1801 		if (page_is_young(page))
1802 			set_page_young(page_tail);
1803 		if (page_is_idle(page))
1804 			set_page_idle(page_tail);
1805 
1806 		/*
1807 		 * __split_huge_page_splitting() already set the
1808 		 * splitting bit in all pmd that could map this
1809 		 * hugepage, that will ensure no CPU can alter the
1810 		 * mapcount on the head page. The mapcount is only
1811 		 * accounted in the head page and it has to be
1812 		 * transferred to all tail pages in the below code. So
1813 		 * for this code to be safe, the split the mapcount
1814 		 * can't change. But that doesn't mean userland can't
1815 		 * keep changing and reading the page contents while
1816 		 * we transfer the mapcount, so the pmd splitting
1817 		 * status is achieved setting a reserved bit in the
1818 		 * pmd, not by clearing the present bit.
1819 		*/
1820 		page_tail->_mapcount = page->_mapcount;
1821 
1822 		BUG_ON(page_tail->mapping);
1823 		page_tail->mapping = page->mapping;
1824 
1825 		page_tail->index = page->index + i;
1826 		page_cpupid_xchg_last(page_tail, page_cpupid_last(page));
1827 
1828 		BUG_ON(!PageAnon(page_tail));
1829 		BUG_ON(!PageUptodate(page_tail));
1830 		BUG_ON(!PageDirty(page_tail));
1831 		BUG_ON(!PageSwapBacked(page_tail));
1832 
1833 		lru_add_page_tail(page, page_tail, lruvec, list);
1834 	}
1835 	atomic_sub(tail_count, &page->_count);
1836 	BUG_ON(atomic_read(&page->_count) <= 0);
1837 
1838 	__mod_zone_page_state(zone, NR_ANON_TRANSPARENT_HUGEPAGES, -1);
1839 
1840 	ClearPageCompound(page);
1841 	compound_unlock(page);
1842 	spin_unlock_irq(&zone->lru_lock);
1843 
1844 	for (i = 1; i < HPAGE_PMD_NR; i++) {
1845 		struct page *page_tail = page + i;
1846 		BUG_ON(page_count(page_tail) <= 0);
1847 		/*
1848 		 * Tail pages may be freed if there wasn't any mapping
1849 		 * like if add_to_swap() is running on a lru page that
1850 		 * had its mapping zapped. And freeing these pages
1851 		 * requires taking the lru_lock so we do the put_page
1852 		 * of the tail pages after the split is complete.
1853 		 */
1854 		put_page(page_tail);
1855 	}
1856 
1857 	/*
1858 	 * Only the head page (now become a regular page) is required
1859 	 * to be pinned by the caller.
1860 	 */
1861 	BUG_ON(page_count(page) <= 0);
1862 }
1863 
__split_huge_page_map(struct page * page,struct vm_area_struct * vma,unsigned long address)1864 static int __split_huge_page_map(struct page *page,
1865 				 struct vm_area_struct *vma,
1866 				 unsigned long address)
1867 {
1868 	struct mm_struct *mm = vma->vm_mm;
1869 	spinlock_t *ptl;
1870 	pmd_t *pmd, _pmd;
1871 	int ret = 0, i;
1872 	pgtable_t pgtable;
1873 	unsigned long haddr;
1874 
1875 	pmd = page_check_address_pmd(page, mm, address,
1876 			PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG, &ptl);
1877 	if (pmd) {
1878 		pgtable = pgtable_trans_huge_withdraw(mm, pmd);
1879 		pmd_populate(mm, &_pmd, pgtable);
1880 		if (pmd_write(*pmd))
1881 			BUG_ON(page_mapcount(page) != 1);
1882 
1883 		haddr = address;
1884 		for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
1885 			pte_t *pte, entry;
1886 			BUG_ON(PageCompound(page+i));
1887 			/*
1888 			 * Note that NUMA hinting access restrictions are not
1889 			 * transferred to avoid any possibility of altering
1890 			 * permissions across VMAs.
1891 			 */
1892 			entry = mk_pte(page + i, vma->vm_page_prot);
1893 			entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1894 			if (!pmd_write(*pmd))
1895 				entry = pte_wrprotect(entry);
1896 			if (!pmd_young(*pmd))
1897 				entry = pte_mkold(entry);
1898 			pte = pte_offset_map(&_pmd, haddr);
1899 			BUG_ON(!pte_none(*pte));
1900 			set_pte_at(mm, haddr, pte, entry);
1901 			pte_unmap(pte);
1902 		}
1903 
1904 		smp_wmb(); /* make pte visible before pmd */
1905 		/*
1906 		 * Up to this point the pmd is present and huge and
1907 		 * userland has the whole access to the hugepage
1908 		 * during the split (which happens in place). If we
1909 		 * overwrite the pmd with the not-huge version
1910 		 * pointing to the pte here (which of course we could
1911 		 * if all CPUs were bug free), userland could trigger
1912 		 * a small page size TLB miss on the small sized TLB
1913 		 * while the hugepage TLB entry is still established
1914 		 * in the huge TLB. Some CPU doesn't like that. See
1915 		 * http://support.amd.com/us/Processor_TechDocs/41322.pdf,
1916 		 * Erratum 383 on page 93. Intel should be safe but is
1917 		 * also warns that it's only safe if the permission
1918 		 * and cache attributes of the two entries loaded in
1919 		 * the two TLB is identical (which should be the case
1920 		 * here). But it is generally safer to never allow
1921 		 * small and huge TLB entries for the same virtual
1922 		 * address to be loaded simultaneously. So instead of
1923 		 * doing "pmd_populate(); flush_pmd_tlb_range();" we first
1924 		 * mark the current pmd notpresent (atomically because
1925 		 * here the pmd_trans_huge and pmd_trans_splitting
1926 		 * must remain set at all times on the pmd until the
1927 		 * split is complete for this pmd), then we flush the
1928 		 * SMP TLB and finally we write the non-huge version
1929 		 * of the pmd entry with pmd_populate.
1930 		 */
1931 		pmdp_invalidate(vma, address, pmd);
1932 		pmd_populate(mm, pmd, pgtable);
1933 		ret = 1;
1934 		spin_unlock(ptl);
1935 	}
1936 
1937 	return ret;
1938 }
1939 
1940 /* must be called with anon_vma->root->rwsem held */
__split_huge_page(struct page * page,struct anon_vma * anon_vma,struct list_head * list)1941 static void __split_huge_page(struct page *page,
1942 			      struct anon_vma *anon_vma,
1943 			      struct list_head *list)
1944 {
1945 	int mapcount, mapcount2;
1946 	pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
1947 	struct anon_vma_chain *avc;
1948 
1949 	BUG_ON(!PageHead(page));
1950 	BUG_ON(PageTail(page));
1951 
1952 	mapcount = 0;
1953 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1954 		struct vm_area_struct *vma = avc->vma;
1955 		unsigned long addr = vma_address(page, vma);
1956 		BUG_ON(is_vma_temporary_stack(vma));
1957 		mapcount += __split_huge_page_splitting(page, vma, addr);
1958 	}
1959 	/*
1960 	 * It is critical that new vmas are added to the tail of the
1961 	 * anon_vma list. This guarantes that if copy_huge_pmd() runs
1962 	 * and establishes a child pmd before
1963 	 * __split_huge_page_splitting() freezes the parent pmd (so if
1964 	 * we fail to prevent copy_huge_pmd() from running until the
1965 	 * whole __split_huge_page() is complete), we will still see
1966 	 * the newly established pmd of the child later during the
1967 	 * walk, to be able to set it as pmd_trans_splitting too.
1968 	 */
1969 	if (mapcount != page_mapcount(page)) {
1970 		pr_err("mapcount %d page_mapcount %d\n",
1971 			mapcount, page_mapcount(page));
1972 		BUG();
1973 	}
1974 
1975 	__split_huge_page_refcount(page, list);
1976 
1977 	mapcount2 = 0;
1978 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
1979 		struct vm_area_struct *vma = avc->vma;
1980 		unsigned long addr = vma_address(page, vma);
1981 		BUG_ON(is_vma_temporary_stack(vma));
1982 		mapcount2 += __split_huge_page_map(page, vma, addr);
1983 	}
1984 	if (mapcount != mapcount2) {
1985 		pr_err("mapcount %d mapcount2 %d page_mapcount %d\n",
1986 			mapcount, mapcount2, page_mapcount(page));
1987 		BUG();
1988 	}
1989 }
1990 
1991 /*
1992  * Split a hugepage into normal pages. This doesn't change the position of head
1993  * page. If @list is null, tail pages will be added to LRU list, otherwise, to
1994  * @list. Both head page and tail pages will inherit mapping, flags, and so on
1995  * from the hugepage.
1996  * Return 0 if the hugepage is split successfully otherwise return 1.
1997  */
split_huge_page_to_list(struct page * page,struct list_head * list)1998 int split_huge_page_to_list(struct page *page, struct list_head *list)
1999 {
2000 	struct anon_vma *anon_vma;
2001 	int ret = 1;
2002 
2003 	BUG_ON(is_huge_zero_page(page));
2004 	BUG_ON(!PageAnon(page));
2005 
2006 	/*
2007 	 * The caller does not necessarily hold an mmap_sem that would prevent
2008 	 * the anon_vma disappearing so we first we take a reference to it
2009 	 * and then lock the anon_vma for write. This is similar to
2010 	 * page_lock_anon_vma_read except the write lock is taken to serialise
2011 	 * against parallel split or collapse operations.
2012 	 */
2013 	anon_vma = page_get_anon_vma(page);
2014 	if (!anon_vma)
2015 		goto out;
2016 	anon_vma_lock_write(anon_vma);
2017 
2018 	ret = 0;
2019 	if (!PageCompound(page))
2020 		goto out_unlock;
2021 
2022 	BUG_ON(!PageSwapBacked(page));
2023 	__split_huge_page(page, anon_vma, list);
2024 	count_vm_event(THP_SPLIT);
2025 
2026 	BUG_ON(PageCompound(page));
2027 out_unlock:
2028 	anon_vma_unlock_write(anon_vma);
2029 	put_anon_vma(anon_vma);
2030 out:
2031 	return ret;
2032 }
2033 
2034 #define VM_NO_THP (VM_SPECIAL | VM_HUGETLB | VM_SHARED | VM_MAYSHARE)
2035 
hugepage_madvise(struct vm_area_struct * vma,unsigned long * vm_flags,int advice)2036 int hugepage_madvise(struct vm_area_struct *vma,
2037 		     unsigned long *vm_flags, int advice)
2038 {
2039 	switch (advice) {
2040 	case MADV_HUGEPAGE:
2041 #ifdef CONFIG_S390
2042 		/*
2043 		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
2044 		 * can't handle this properly after s390_enable_sie, so we simply
2045 		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
2046 		 */
2047 		if (mm_has_pgste(vma->vm_mm))
2048 			return 0;
2049 #endif
2050 		/*
2051 		 * Be somewhat over-protective like KSM for now!
2052 		 */
2053 		if (*vm_flags & VM_NO_THP)
2054 			return -EINVAL;
2055 		*vm_flags &= ~VM_NOHUGEPAGE;
2056 		*vm_flags |= VM_HUGEPAGE;
2057 		/*
2058 		 * If the vma become good for khugepaged to scan,
2059 		 * register it here without waiting a page fault that
2060 		 * may not happen any time soon.
2061 		 */
2062 		if (unlikely(khugepaged_enter_vma_merge(vma, *vm_flags)))
2063 			return -ENOMEM;
2064 		break;
2065 	case MADV_NOHUGEPAGE:
2066 		/*
2067 		 * Be somewhat over-protective like KSM for now!
2068 		 */
2069 		if (*vm_flags & VM_NO_THP)
2070 			return -EINVAL;
2071 		*vm_flags &= ~VM_HUGEPAGE;
2072 		*vm_flags |= VM_NOHUGEPAGE;
2073 		/*
2074 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
2075 		 * this vma even if we leave the mm registered in khugepaged if
2076 		 * it got registered before VM_NOHUGEPAGE was set.
2077 		 */
2078 		break;
2079 	}
2080 
2081 	return 0;
2082 }
2083 
khugepaged_slab_init(void)2084 static int __init khugepaged_slab_init(void)
2085 {
2086 	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
2087 					  sizeof(struct mm_slot),
2088 					  __alignof__(struct mm_slot), 0, NULL);
2089 	if (!mm_slot_cache)
2090 		return -ENOMEM;
2091 
2092 	return 0;
2093 }
2094 
khugepaged_slab_exit(void)2095 static void __init khugepaged_slab_exit(void)
2096 {
2097 	kmem_cache_destroy(mm_slot_cache);
2098 }
2099 
alloc_mm_slot(void)2100 static inline struct mm_slot *alloc_mm_slot(void)
2101 {
2102 	if (!mm_slot_cache)	/* initialization failed */
2103 		return NULL;
2104 	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
2105 }
2106 
free_mm_slot(struct mm_slot * mm_slot)2107 static inline void free_mm_slot(struct mm_slot *mm_slot)
2108 {
2109 	kmem_cache_free(mm_slot_cache, mm_slot);
2110 }
2111 
get_mm_slot(struct mm_struct * mm)2112 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
2113 {
2114 	struct mm_slot *mm_slot;
2115 
2116 	hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
2117 		if (mm == mm_slot->mm)
2118 			return mm_slot;
2119 
2120 	return NULL;
2121 }
2122 
insert_to_mm_slots_hash(struct mm_struct * mm,struct mm_slot * mm_slot)2123 static void insert_to_mm_slots_hash(struct mm_struct *mm,
2124 				    struct mm_slot *mm_slot)
2125 {
2126 	mm_slot->mm = mm;
2127 	hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
2128 }
2129 
khugepaged_test_exit(struct mm_struct * mm)2130 static inline int khugepaged_test_exit(struct mm_struct *mm)
2131 {
2132 	return atomic_read(&mm->mm_users) == 0 || !mmget_still_valid(mm);
2133 }
2134 
__khugepaged_enter(struct mm_struct * mm)2135 int __khugepaged_enter(struct mm_struct *mm)
2136 {
2137 	struct mm_slot *mm_slot;
2138 	int wakeup;
2139 
2140 	mm_slot = alloc_mm_slot();
2141 	if (!mm_slot)
2142 		return -ENOMEM;
2143 
2144 	/* __khugepaged_exit() must not run from under us */
2145 	VM_BUG_ON_MM(atomic_read(&mm->mm_users) == 0, mm);
2146 	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
2147 		free_mm_slot(mm_slot);
2148 		return 0;
2149 	}
2150 
2151 	spin_lock(&khugepaged_mm_lock);
2152 	insert_to_mm_slots_hash(mm, mm_slot);
2153 	/*
2154 	 * Insert just behind the scanning cursor, to let the area settle
2155 	 * down a little.
2156 	 */
2157 	wakeup = list_empty(&khugepaged_scan.mm_head);
2158 	list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
2159 	spin_unlock(&khugepaged_mm_lock);
2160 
2161 	atomic_inc(&mm->mm_count);
2162 	if (wakeup)
2163 		wake_up_interruptible(&khugepaged_wait);
2164 
2165 	return 0;
2166 }
2167 
khugepaged_enter_vma_merge(struct vm_area_struct * vma,unsigned long vm_flags)2168 int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
2169 			       unsigned long vm_flags)
2170 {
2171 	unsigned long hstart, hend;
2172 	if (!vma->anon_vma)
2173 		/*
2174 		 * Not yet faulted in so we will register later in the
2175 		 * page fault if needed.
2176 		 */
2177 		return 0;
2178 	if (vma->vm_ops || (vm_flags & VM_NO_THP))
2179 		/* khugepaged not yet working on file or special mappings */
2180 		return 0;
2181 	hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2182 	hend = vma->vm_end & HPAGE_PMD_MASK;
2183 	if (hstart < hend)
2184 		return khugepaged_enter(vma, vm_flags);
2185 	return 0;
2186 }
2187 
__khugepaged_exit(struct mm_struct * mm)2188 void __khugepaged_exit(struct mm_struct *mm)
2189 {
2190 	struct mm_slot *mm_slot;
2191 	int free = 0;
2192 
2193 	spin_lock(&khugepaged_mm_lock);
2194 	mm_slot = get_mm_slot(mm);
2195 	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
2196 		hash_del(&mm_slot->hash);
2197 		list_del(&mm_slot->mm_node);
2198 		free = 1;
2199 	}
2200 	spin_unlock(&khugepaged_mm_lock);
2201 
2202 	if (free) {
2203 		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2204 		free_mm_slot(mm_slot);
2205 		mmdrop(mm);
2206 	} else if (mm_slot) {
2207 		/*
2208 		 * This is required to serialize against
2209 		 * khugepaged_test_exit() (which is guaranteed to run
2210 		 * under mmap sem read mode). Stop here (after we
2211 		 * return all pagetables will be destroyed) until
2212 		 * khugepaged has finished working on the pagetables
2213 		 * under the mmap_sem.
2214 		 */
2215 		down_write(&mm->mmap_sem);
2216 		up_write(&mm->mmap_sem);
2217 	}
2218 }
2219 
release_pte_page(struct page * page)2220 static void release_pte_page(struct page *page)
2221 {
2222 	/* 0 stands for page_is_file_cache(page) == false */
2223 	dec_zone_page_state(page, NR_ISOLATED_ANON + 0);
2224 	unlock_page(page);
2225 	putback_lru_page(page);
2226 }
2227 
release_pte_pages(pte_t * pte,pte_t * _pte)2228 static void release_pte_pages(pte_t *pte, pte_t *_pte)
2229 {
2230 	while (--_pte >= pte) {
2231 		pte_t pteval = *_pte;
2232 		if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
2233 			release_pte_page(pte_page(pteval));
2234 	}
2235 }
2236 
__collapse_huge_page_isolate(struct vm_area_struct * vma,unsigned long address,pte_t * pte)2237 static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
2238 					unsigned long address,
2239 					pte_t *pte)
2240 {
2241 	struct page *page;
2242 	pte_t *_pte;
2243 	int none_or_zero = 0;
2244 	bool referenced = false, writable = false;
2245 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
2246 	     _pte++, address += PAGE_SIZE) {
2247 		pte_t pteval = *_pte;
2248 		if (pte_none(pteval) || (pte_present(pteval) &&
2249 				is_zero_pfn(pte_pfn(pteval)))) {
2250 			if (!userfaultfd_armed(vma) &&
2251 			    ++none_or_zero <= khugepaged_max_ptes_none)
2252 				continue;
2253 			else
2254 				goto out;
2255 		}
2256 		if (!pte_present(pteval))
2257 			goto out;
2258 		page = vm_normal_page(vma, address, pteval);
2259 		if (unlikely(!page))
2260 			goto out;
2261 
2262 		VM_BUG_ON_PAGE(PageCompound(page), page);
2263 		VM_BUG_ON_PAGE(!PageAnon(page), page);
2264 		VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
2265 
2266 		/*
2267 		 * We can do it before isolate_lru_page because the
2268 		 * page can't be freed from under us. NOTE: PG_lock
2269 		 * is needed to serialize against split_huge_page
2270 		 * when invoked from the VM.
2271 		 */
2272 		if (!trylock_page(page))
2273 			goto out;
2274 
2275 		/*
2276 		 * cannot use mapcount: can't collapse if there's a gup pin.
2277 		 * The page must only be referenced by the scanned process
2278 		 * and page swap cache.
2279 		 */
2280 		if (page_count(page) != 1 + !!PageSwapCache(page)) {
2281 			unlock_page(page);
2282 			goto out;
2283 		}
2284 		if (pte_write(pteval)) {
2285 			writable = true;
2286 		} else {
2287 			if (PageSwapCache(page) && !reuse_swap_page(page)) {
2288 				unlock_page(page);
2289 				goto out;
2290 			}
2291 			/*
2292 			 * Page is not in the swap cache. It can be collapsed
2293 			 * into a THP.
2294 			 */
2295 		}
2296 
2297 		/*
2298 		 * Isolate the page to avoid collapsing an hugepage
2299 		 * currently in use by the VM.
2300 		 */
2301 		if (isolate_lru_page(page)) {
2302 			unlock_page(page);
2303 			goto out;
2304 		}
2305 		/* 0 stands for page_is_file_cache(page) == false */
2306 		inc_zone_page_state(page, NR_ISOLATED_ANON + 0);
2307 		VM_BUG_ON_PAGE(!PageLocked(page), page);
2308 		VM_BUG_ON_PAGE(PageLRU(page), page);
2309 
2310 		/* If there is no mapped pte young don't collapse the page */
2311 		if (pte_young(pteval) ||
2312 		    page_is_young(page) || PageReferenced(page) ||
2313 		    mmu_notifier_test_young(vma->vm_mm, address))
2314 			referenced = true;
2315 	}
2316 	if (likely(referenced && writable))
2317 		return 1;
2318 out:
2319 	release_pte_pages(pte, _pte);
2320 	return 0;
2321 }
2322 
__collapse_huge_page_copy(pte_t * pte,struct page * page,struct vm_area_struct * vma,unsigned long address,spinlock_t * ptl)2323 static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
2324 				      struct vm_area_struct *vma,
2325 				      unsigned long address,
2326 				      spinlock_t *ptl)
2327 {
2328 	pte_t *_pte;
2329 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR; _pte++) {
2330 		pte_t pteval = *_pte;
2331 		struct page *src_page;
2332 
2333 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
2334 			clear_user_highpage(page, address);
2335 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
2336 			if (is_zero_pfn(pte_pfn(pteval))) {
2337 				/*
2338 				 * ptl mostly unnecessary.
2339 				 */
2340 				spin_lock(ptl);
2341 				/*
2342 				 * paravirt calls inside pte_clear here are
2343 				 * superfluous.
2344 				 */
2345 				pte_clear(vma->vm_mm, address, _pte);
2346 				spin_unlock(ptl);
2347 			}
2348 		} else {
2349 			src_page = pte_page(pteval);
2350 			copy_user_highpage(page, src_page, address, vma);
2351 			VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
2352 			release_pte_page(src_page);
2353 			/*
2354 			 * ptl mostly unnecessary, but preempt has to
2355 			 * be disabled to update the per-cpu stats
2356 			 * inside page_remove_rmap().
2357 			 */
2358 			spin_lock(ptl);
2359 			/*
2360 			 * paravirt calls inside pte_clear here are
2361 			 * superfluous.
2362 			 */
2363 			pte_clear(vma->vm_mm, address, _pte);
2364 			page_remove_rmap(src_page);
2365 			spin_unlock(ptl);
2366 			free_page_and_swap_cache(src_page);
2367 		}
2368 
2369 		address += PAGE_SIZE;
2370 		page++;
2371 	}
2372 }
2373 
khugepaged_alloc_sleep(void)2374 static void khugepaged_alloc_sleep(void)
2375 {
2376 	DEFINE_WAIT(wait);
2377 
2378 	add_wait_queue(&khugepaged_wait, &wait);
2379 	freezable_schedule_timeout_interruptible(
2380 		msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
2381 	remove_wait_queue(&khugepaged_wait, &wait);
2382 }
2383 
2384 static int khugepaged_node_load[MAX_NUMNODES];
2385 
khugepaged_scan_abort(int nid)2386 static bool khugepaged_scan_abort(int nid)
2387 {
2388 	int i;
2389 
2390 	/*
2391 	 * If zone_reclaim_mode is disabled, then no extra effort is made to
2392 	 * allocate memory locally.
2393 	 */
2394 	if (!zone_reclaim_mode)
2395 		return false;
2396 
2397 	/* If there is a count for this node already, it must be acceptable */
2398 	if (khugepaged_node_load[nid])
2399 		return false;
2400 
2401 	for (i = 0; i < MAX_NUMNODES; i++) {
2402 		if (!khugepaged_node_load[i])
2403 			continue;
2404 		if (node_distance(nid, i) > RECLAIM_DISTANCE)
2405 			return true;
2406 	}
2407 	return false;
2408 }
2409 
2410 #ifdef CONFIG_NUMA
khugepaged_find_target_node(void)2411 static int khugepaged_find_target_node(void)
2412 {
2413 	static int last_khugepaged_target_node = NUMA_NO_NODE;
2414 	int nid, target_node = 0, max_value = 0;
2415 
2416 	/* find first node with max normal pages hit */
2417 	for (nid = 0; nid < MAX_NUMNODES; nid++)
2418 		if (khugepaged_node_load[nid] > max_value) {
2419 			max_value = khugepaged_node_load[nid];
2420 			target_node = nid;
2421 		}
2422 
2423 	/* do some balance if several nodes have the same hit record */
2424 	if (target_node <= last_khugepaged_target_node)
2425 		for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
2426 				nid++)
2427 			if (max_value == khugepaged_node_load[nid]) {
2428 				target_node = nid;
2429 				break;
2430 			}
2431 
2432 	last_khugepaged_target_node = target_node;
2433 	return target_node;
2434 }
2435 
khugepaged_prealloc_page(struct page ** hpage,bool * wait)2436 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2437 {
2438 	if (IS_ERR(*hpage)) {
2439 		if (!*wait)
2440 			return false;
2441 
2442 		*wait = false;
2443 		*hpage = NULL;
2444 		khugepaged_alloc_sleep();
2445 	} else if (*hpage) {
2446 		put_page(*hpage);
2447 		*hpage = NULL;
2448 	}
2449 
2450 	return true;
2451 }
2452 
2453 static struct page *
khugepaged_alloc_page(struct page ** hpage,gfp_t gfp,struct mm_struct * mm,unsigned long address,int node)2454 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
2455 		       unsigned long address, int node)
2456 {
2457 	VM_BUG_ON_PAGE(*hpage, *hpage);
2458 
2459 	/*
2460 	 * Before allocating the hugepage, release the mmap_sem read lock.
2461 	 * The allocation can take potentially a long time if it involves
2462 	 * sync compaction, and we do not need to hold the mmap_sem during
2463 	 * that. We will recheck the vma after taking it again in write mode.
2464 	 */
2465 	up_read(&mm->mmap_sem);
2466 
2467 	*hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
2468 	if (unlikely(!*hpage)) {
2469 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2470 		*hpage = ERR_PTR(-ENOMEM);
2471 		return NULL;
2472 	}
2473 
2474 	count_vm_event(THP_COLLAPSE_ALLOC);
2475 	return *hpage;
2476 }
2477 #else
khugepaged_find_target_node(void)2478 static int khugepaged_find_target_node(void)
2479 {
2480 	return 0;
2481 }
2482 
alloc_hugepage(int defrag)2483 static inline struct page *alloc_hugepage(int defrag)
2484 {
2485 	return alloc_pages(alloc_hugepage_gfpmask(defrag, 0),
2486 			   HPAGE_PMD_ORDER);
2487 }
2488 
khugepaged_alloc_hugepage(bool * wait)2489 static struct page *khugepaged_alloc_hugepage(bool *wait)
2490 {
2491 	struct page *hpage;
2492 
2493 	do {
2494 		hpage = alloc_hugepage(khugepaged_defrag());
2495 		if (!hpage) {
2496 			count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
2497 			if (!*wait)
2498 				return NULL;
2499 
2500 			*wait = false;
2501 			khugepaged_alloc_sleep();
2502 		} else
2503 			count_vm_event(THP_COLLAPSE_ALLOC);
2504 	} while (unlikely(!hpage) && likely(khugepaged_enabled()));
2505 
2506 	return hpage;
2507 }
2508 
khugepaged_prealloc_page(struct page ** hpage,bool * wait)2509 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
2510 {
2511 	if (!*hpage)
2512 		*hpage = khugepaged_alloc_hugepage(wait);
2513 
2514 	if (unlikely(!*hpage))
2515 		return false;
2516 
2517 	return true;
2518 }
2519 
2520 static struct page *
khugepaged_alloc_page(struct page ** hpage,gfp_t gfp,struct mm_struct * mm,unsigned long address,int node)2521 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, struct mm_struct *mm,
2522 		       unsigned long address, int node)
2523 {
2524 	up_read(&mm->mmap_sem);
2525 	VM_BUG_ON(!*hpage);
2526 
2527 	return  *hpage;
2528 }
2529 #endif
2530 
hugepage_vma_check(struct vm_area_struct * vma)2531 static bool hugepage_vma_check(struct vm_area_struct *vma)
2532 {
2533 	if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
2534 	    (vma->vm_flags & VM_NOHUGEPAGE))
2535 		return false;
2536 
2537 	if (!vma->anon_vma || vma->vm_ops)
2538 		return false;
2539 	if (is_vma_temporary_stack(vma))
2540 		return false;
2541 	return !(vma->vm_flags & VM_NO_THP);
2542 }
2543 
collapse_huge_page(struct mm_struct * mm,unsigned long address,struct page ** hpage,struct vm_area_struct * vma,int node)2544 static void collapse_huge_page(struct mm_struct *mm,
2545 				   unsigned long address,
2546 				   struct page **hpage,
2547 				   struct vm_area_struct *vma,
2548 				   int node)
2549 {
2550 	pmd_t *pmd, _pmd;
2551 	pte_t *pte;
2552 	pgtable_t pgtable;
2553 	struct page *new_page;
2554 	spinlock_t *pmd_ptl, *pte_ptl;
2555 	int isolated;
2556 	unsigned long hstart, hend;
2557 	struct mem_cgroup *memcg;
2558 	unsigned long mmun_start;	/* For mmu_notifiers */
2559 	unsigned long mmun_end;		/* For mmu_notifiers */
2560 	gfp_t gfp;
2561 
2562 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2563 
2564 	/* Only allocate from the target node */
2565 	gfp = alloc_hugepage_gfpmask(khugepaged_defrag(), __GFP_OTHER_NODE) |
2566 		__GFP_THISNODE;
2567 
2568 	/* release the mmap_sem read lock. */
2569 	new_page = khugepaged_alloc_page(hpage, gfp, mm, address, node);
2570 	if (!new_page)
2571 		return;
2572 
2573 	if (unlikely(mem_cgroup_try_charge(new_page, mm,
2574 					   gfp, &memcg)))
2575 		return;
2576 
2577 	/*
2578 	 * Prevent all access to pagetables with the exception of
2579 	 * gup_fast later hanlded by the ptep_clear_flush and the VM
2580 	 * handled by the anon_vma lock + PG_lock.
2581 	 */
2582 	down_write(&mm->mmap_sem);
2583 	if (unlikely(khugepaged_test_exit(mm)))
2584 		goto out;
2585 
2586 	vma = find_vma(mm, address);
2587 	if (!vma)
2588 		goto out;
2589 	hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2590 	hend = vma->vm_end & HPAGE_PMD_MASK;
2591 	if (address < hstart || address + HPAGE_PMD_SIZE > hend)
2592 		goto out;
2593 	if (!hugepage_vma_check(vma))
2594 		goto out;
2595 	pmd = mm_find_pmd(mm, address);
2596 	if (!pmd)
2597 		goto out;
2598 
2599 	anon_vma_lock_write(vma->anon_vma);
2600 
2601 	pte = pte_offset_map(pmd, address);
2602 	pte_ptl = pte_lockptr(mm, pmd);
2603 
2604 	mmun_start = address;
2605 	mmun_end   = address + HPAGE_PMD_SIZE;
2606 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2607 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
2608 	/*
2609 	 * After this gup_fast can't run anymore. This also removes
2610 	 * any huge TLB entry from the CPU so we won't allow
2611 	 * huge and small TLB entries for the same virtual address
2612 	 * to avoid the risk of CPU bugs in that area.
2613 	 */
2614 	_pmd = pmdp_collapse_flush(vma, address, pmd);
2615 	spin_unlock(pmd_ptl);
2616 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2617 
2618 	spin_lock(pte_ptl);
2619 	isolated = __collapse_huge_page_isolate(vma, address, pte);
2620 	spin_unlock(pte_ptl);
2621 
2622 	if (unlikely(!isolated)) {
2623 		pte_unmap(pte);
2624 		spin_lock(pmd_ptl);
2625 		BUG_ON(!pmd_none(*pmd));
2626 		/*
2627 		 * We can only use set_pmd_at when establishing
2628 		 * hugepmds and never for establishing regular pmds that
2629 		 * points to regular pagetables. Use pmd_populate for that
2630 		 */
2631 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
2632 		spin_unlock(pmd_ptl);
2633 		anon_vma_unlock_write(vma->anon_vma);
2634 		goto out;
2635 	}
2636 
2637 	/*
2638 	 * All pages are isolated and locked so anon_vma rmap
2639 	 * can't run anymore.
2640 	 */
2641 	anon_vma_unlock_write(vma->anon_vma);
2642 
2643 	__collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
2644 	pte_unmap(pte);
2645 	__SetPageUptodate(new_page);
2646 	pgtable = pmd_pgtable(_pmd);
2647 
2648 	_pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
2649 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
2650 
2651 	/*
2652 	 * spin_lock() below is not the equivalent of smp_wmb(), so
2653 	 * this is needed to avoid the copy_huge_page writes to become
2654 	 * visible after the set_pmd_at() write.
2655 	 */
2656 	smp_wmb();
2657 
2658 	spin_lock(pmd_ptl);
2659 	BUG_ON(!pmd_none(*pmd));
2660 	page_add_new_anon_rmap(new_page, vma, address);
2661 	mem_cgroup_commit_charge(new_page, memcg, false);
2662 	lru_cache_add_active_or_unevictable(new_page, vma);
2663 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
2664 	set_pmd_at(mm, address, pmd, _pmd);
2665 	update_mmu_cache_pmd(vma, address, pmd);
2666 	spin_unlock(pmd_ptl);
2667 
2668 	*hpage = NULL;
2669 
2670 	khugepaged_pages_collapsed++;
2671 out_up_write:
2672 	up_write(&mm->mmap_sem);
2673 	return;
2674 
2675 out:
2676 	mem_cgroup_cancel_charge(new_page, memcg);
2677 	goto out_up_write;
2678 }
2679 
khugepaged_scan_pmd(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,struct page ** hpage)2680 static int khugepaged_scan_pmd(struct mm_struct *mm,
2681 			       struct vm_area_struct *vma,
2682 			       unsigned long address,
2683 			       struct page **hpage)
2684 {
2685 	pmd_t *pmd;
2686 	pte_t *pte, *_pte;
2687 	int ret = 0, none_or_zero = 0;
2688 	struct page *page;
2689 	unsigned long _address;
2690 	spinlock_t *ptl;
2691 	int node = NUMA_NO_NODE;
2692 	bool writable = false, referenced = false;
2693 
2694 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
2695 
2696 	pmd = mm_find_pmd(mm, address);
2697 	if (!pmd)
2698 		goto out;
2699 
2700 	memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
2701 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
2702 	for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
2703 	     _pte++, _address += PAGE_SIZE) {
2704 		pte_t pteval = *_pte;
2705 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
2706 			if (!userfaultfd_armed(vma) &&
2707 			    ++none_or_zero <= khugepaged_max_ptes_none)
2708 				continue;
2709 			else
2710 				goto out_unmap;
2711 		}
2712 		if (!pte_present(pteval))
2713 			goto out_unmap;
2714 		if (pte_write(pteval))
2715 			writable = true;
2716 
2717 		page = vm_normal_page(vma, _address, pteval);
2718 		if (unlikely(!page))
2719 			goto out_unmap;
2720 		/*
2721 		 * Record which node the original page is from and save this
2722 		 * information to khugepaged_node_load[].
2723 		 * Khupaged will allocate hugepage from the node has the max
2724 		 * hit record.
2725 		 */
2726 		node = page_to_nid(page);
2727 		if (khugepaged_scan_abort(node))
2728 			goto out_unmap;
2729 		khugepaged_node_load[node]++;
2730 		VM_BUG_ON_PAGE(PageCompound(page), page);
2731 		if (!PageLRU(page) || PageLocked(page) || !PageAnon(page))
2732 			goto out_unmap;
2733 		/*
2734 		 * cannot use mapcount: can't collapse if there's a gup pin.
2735 		 * The page must only be referenced by the scanned process
2736 		 * and page swap cache.
2737 		 */
2738 		if (page_count(page) != 1 + !!PageSwapCache(page))
2739 			goto out_unmap;
2740 		if (pte_young(pteval) ||
2741 		    page_is_young(page) || PageReferenced(page) ||
2742 		    mmu_notifier_test_young(vma->vm_mm, address))
2743 			referenced = true;
2744 	}
2745 	if (referenced && writable)
2746 		ret = 1;
2747 out_unmap:
2748 	pte_unmap_unlock(pte, ptl);
2749 	if (ret) {
2750 		node = khugepaged_find_target_node();
2751 		/* collapse_huge_page will return with the mmap_sem released */
2752 		collapse_huge_page(mm, address, hpage, vma, node);
2753 	}
2754 out:
2755 	return ret;
2756 }
2757 
collect_mm_slot(struct mm_slot * mm_slot)2758 static void collect_mm_slot(struct mm_slot *mm_slot)
2759 {
2760 	struct mm_struct *mm = mm_slot->mm;
2761 
2762 	VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2763 
2764 	if (khugepaged_test_exit(mm)) {
2765 		/* free mm_slot */
2766 		hash_del(&mm_slot->hash);
2767 		list_del(&mm_slot->mm_node);
2768 
2769 		/*
2770 		 * Not strictly needed because the mm exited already.
2771 		 *
2772 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
2773 		 */
2774 
2775 		/* khugepaged_mm_lock actually not necessary for the below */
2776 		free_mm_slot(mm_slot);
2777 		mmdrop(mm);
2778 	}
2779 }
2780 
khugepaged_scan_mm_slot(unsigned int pages,struct page ** hpage)2781 static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
2782 					    struct page **hpage)
2783 	__releases(&khugepaged_mm_lock)
2784 	__acquires(&khugepaged_mm_lock)
2785 {
2786 	struct mm_slot *mm_slot;
2787 	struct mm_struct *mm;
2788 	struct vm_area_struct *vma;
2789 	int progress = 0;
2790 
2791 	VM_BUG_ON(!pages);
2792 	VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
2793 
2794 	if (khugepaged_scan.mm_slot)
2795 		mm_slot = khugepaged_scan.mm_slot;
2796 	else {
2797 		mm_slot = list_entry(khugepaged_scan.mm_head.next,
2798 				     struct mm_slot, mm_node);
2799 		khugepaged_scan.address = 0;
2800 		khugepaged_scan.mm_slot = mm_slot;
2801 	}
2802 	spin_unlock(&khugepaged_mm_lock);
2803 
2804 	mm = mm_slot->mm;
2805 	down_read(&mm->mmap_sem);
2806 	if (unlikely(khugepaged_test_exit(mm)))
2807 		vma = NULL;
2808 	else
2809 		vma = find_vma(mm, khugepaged_scan.address);
2810 
2811 	progress++;
2812 	for (; vma; vma = vma->vm_next) {
2813 		unsigned long hstart, hend;
2814 
2815 		cond_resched();
2816 		if (unlikely(khugepaged_test_exit(mm))) {
2817 			progress++;
2818 			break;
2819 		}
2820 		if (!hugepage_vma_check(vma)) {
2821 skip:
2822 			progress++;
2823 			continue;
2824 		}
2825 		hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2826 		hend = vma->vm_end & HPAGE_PMD_MASK;
2827 		if (hstart >= hend)
2828 			goto skip;
2829 		if (khugepaged_scan.address > hend)
2830 			goto skip;
2831 		if (khugepaged_scan.address < hstart)
2832 			khugepaged_scan.address = hstart;
2833 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2834 
2835 		while (khugepaged_scan.address < hend) {
2836 			int ret;
2837 			cond_resched();
2838 			if (unlikely(khugepaged_test_exit(mm)))
2839 				goto breakouterloop;
2840 
2841 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2842 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2843 				  hend);
2844 			ret = khugepaged_scan_pmd(mm, vma,
2845 						  khugepaged_scan.address,
2846 						  hpage);
2847 			/* move to next address */
2848 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2849 			progress += HPAGE_PMD_NR;
2850 			if (ret)
2851 				/* we released mmap_sem so break loop */
2852 				goto breakouterloop_mmap_sem;
2853 			if (progress >= pages)
2854 				goto breakouterloop;
2855 		}
2856 	}
2857 breakouterloop:
2858 	up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
2859 breakouterloop_mmap_sem:
2860 
2861 	spin_lock(&khugepaged_mm_lock);
2862 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2863 	/*
2864 	 * Release the current mm_slot if this mm is about to die, or
2865 	 * if we scanned all vmas of this mm.
2866 	 */
2867 	if (khugepaged_test_exit(mm) || !vma) {
2868 		/*
2869 		 * Make sure that if mm_users is reaching zero while
2870 		 * khugepaged runs here, khugepaged_exit will find
2871 		 * mm_slot not pointing to the exiting mm.
2872 		 */
2873 		if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2874 			khugepaged_scan.mm_slot = list_entry(
2875 				mm_slot->mm_node.next,
2876 				struct mm_slot, mm_node);
2877 			khugepaged_scan.address = 0;
2878 		} else {
2879 			khugepaged_scan.mm_slot = NULL;
2880 			khugepaged_full_scans++;
2881 		}
2882 
2883 		collect_mm_slot(mm_slot);
2884 	}
2885 
2886 	return progress;
2887 }
2888 
khugepaged_has_work(void)2889 static int khugepaged_has_work(void)
2890 {
2891 	return !list_empty(&khugepaged_scan.mm_head) &&
2892 		khugepaged_enabled();
2893 }
2894 
khugepaged_wait_event(void)2895 static int khugepaged_wait_event(void)
2896 {
2897 	return !list_empty(&khugepaged_scan.mm_head) ||
2898 		kthread_should_stop();
2899 }
2900 
khugepaged_do_scan(void)2901 static void khugepaged_do_scan(void)
2902 {
2903 	struct page *hpage = NULL;
2904 	unsigned int progress = 0, pass_through_head = 0;
2905 	unsigned int pages = khugepaged_pages_to_scan;
2906 	bool wait = true;
2907 
2908 	barrier(); /* write khugepaged_pages_to_scan to local stack */
2909 
2910 	while (progress < pages) {
2911 		if (!khugepaged_prealloc_page(&hpage, &wait))
2912 			break;
2913 
2914 		cond_resched();
2915 
2916 		if (unlikely(kthread_should_stop() || try_to_freeze()))
2917 			break;
2918 
2919 		spin_lock(&khugepaged_mm_lock);
2920 		if (!khugepaged_scan.mm_slot)
2921 			pass_through_head++;
2922 		if (khugepaged_has_work() &&
2923 		    pass_through_head < 2)
2924 			progress += khugepaged_scan_mm_slot(pages - progress,
2925 							    &hpage);
2926 		else
2927 			progress = pages;
2928 		spin_unlock(&khugepaged_mm_lock);
2929 	}
2930 
2931 	if (!IS_ERR_OR_NULL(hpage))
2932 		put_page(hpage);
2933 }
2934 
khugepaged_wait_work(void)2935 static void khugepaged_wait_work(void)
2936 {
2937 	if (khugepaged_has_work()) {
2938 		if (!khugepaged_scan_sleep_millisecs)
2939 			return;
2940 
2941 		wait_event_freezable_timeout(khugepaged_wait,
2942 					     kthread_should_stop(),
2943 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs));
2944 		return;
2945 	}
2946 
2947 	if (khugepaged_enabled())
2948 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2949 }
2950 
khugepaged(void * none)2951 static int khugepaged(void *none)
2952 {
2953 	struct mm_slot *mm_slot;
2954 
2955 	set_freezable();
2956 	set_user_nice(current, MAX_NICE);
2957 
2958 	while (!kthread_should_stop()) {
2959 		khugepaged_do_scan();
2960 		khugepaged_wait_work();
2961 	}
2962 
2963 	spin_lock(&khugepaged_mm_lock);
2964 	mm_slot = khugepaged_scan.mm_slot;
2965 	khugepaged_scan.mm_slot = NULL;
2966 	if (mm_slot)
2967 		collect_mm_slot(mm_slot);
2968 	spin_unlock(&khugepaged_mm_lock);
2969 	return 0;
2970 }
2971 
__split_huge_zero_page_pmd(struct vm_area_struct * vma,unsigned long haddr,pmd_t * pmd)2972 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
2973 		unsigned long haddr, pmd_t *pmd)
2974 {
2975 	struct mm_struct *mm = vma->vm_mm;
2976 	pgtable_t pgtable;
2977 	pmd_t _pmd;
2978 	int i;
2979 
2980 	pmdp_huge_clear_flush_notify(vma, haddr, pmd);
2981 	/* leave pmd empty until pte is filled */
2982 
2983 	pgtable = pgtable_trans_huge_withdraw(mm, pmd);
2984 	pmd_populate(mm, &_pmd, pgtable);
2985 
2986 	for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
2987 		pte_t *pte, entry;
2988 		entry = pfn_pte(my_zero_pfn(haddr), vma->vm_page_prot);
2989 		entry = pte_mkspecial(entry);
2990 		pte = pte_offset_map(&_pmd, haddr);
2991 		VM_BUG_ON(!pte_none(*pte));
2992 		set_pte_at(mm, haddr, pte, entry);
2993 		pte_unmap(pte);
2994 	}
2995 	smp_wmb(); /* make pte visible before pmd */
2996 	pmd_populate(mm, pmd, pgtable);
2997 	put_huge_zero_page();
2998 }
2999 
__split_huge_page_pmd(struct vm_area_struct * vma,unsigned long address,pmd_t * pmd)3000 void __split_huge_page_pmd(struct vm_area_struct *vma, unsigned long address,
3001 		pmd_t *pmd)
3002 {
3003 	spinlock_t *ptl;
3004 	struct page *page = NULL;
3005 	struct mm_struct *mm = vma->vm_mm;
3006 	unsigned long haddr = address & HPAGE_PMD_MASK;
3007 	unsigned long mmun_start;	/* For mmu_notifiers */
3008 	unsigned long mmun_end;		/* For mmu_notifiers */
3009 
3010 	BUG_ON(vma->vm_start > haddr || vma->vm_end < haddr + HPAGE_PMD_SIZE);
3011 
3012 	mmun_start = haddr;
3013 	mmun_end   = haddr + HPAGE_PMD_SIZE;
3014 again:
3015 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
3016 	ptl = pmd_lock(mm, pmd);
3017 	if (unlikely(!pmd_trans_huge(*pmd)))
3018 		goto unlock;
3019 	if (vma_is_dax(vma)) {
3020 		pmd_t _pmd = pmdp_huge_clear_flush_notify(vma, haddr, pmd);
3021 		if (is_huge_zero_pmd(_pmd))
3022 			put_huge_zero_page();
3023 	} else if (is_huge_zero_pmd(*pmd)) {
3024 		__split_huge_zero_page_pmd(vma, haddr, pmd);
3025 	} else {
3026 		page = pmd_page(*pmd);
3027 		VM_BUG_ON_PAGE(!page_count(page), page);
3028 		get_page(page);
3029 	}
3030  unlock:
3031 	spin_unlock(ptl);
3032 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
3033 
3034 	if (!page)
3035 		return;
3036 
3037 	split_huge_page(page);
3038 	put_page(page);
3039 
3040 	/*
3041 	 * We don't always have down_write of mmap_sem here: a racing
3042 	 * do_huge_pmd_wp_page() might have copied-on-write to another
3043 	 * huge page before our split_huge_page() got the anon_vma lock.
3044 	 */
3045 	if (unlikely(pmd_trans_huge(*pmd)))
3046 		goto again;
3047 }
3048 
split_huge_page_pmd_mm(struct mm_struct * mm,unsigned long address,pmd_t * pmd)3049 void split_huge_page_pmd_mm(struct mm_struct *mm, unsigned long address,
3050 		pmd_t *pmd)
3051 {
3052 	struct vm_area_struct *vma;
3053 
3054 	vma = find_vma(mm, address);
3055 	BUG_ON(vma == NULL);
3056 	split_huge_page_pmd(vma, address, pmd);
3057 }
3058 
split_huge_page_address(struct mm_struct * mm,unsigned long address)3059 static void split_huge_page_address(struct mm_struct *mm,
3060 				    unsigned long address)
3061 {
3062 	pgd_t *pgd;
3063 	pud_t *pud;
3064 	pmd_t *pmd;
3065 
3066 	VM_BUG_ON(!(address & ~HPAGE_PMD_MASK));
3067 
3068 	pgd = pgd_offset(mm, address);
3069 	if (!pgd_present(*pgd))
3070 		return;
3071 
3072 	pud = pud_offset(pgd, address);
3073 	if (!pud_present(*pud))
3074 		return;
3075 
3076 	pmd = pmd_offset(pud, address);
3077 	if (!pmd_present(*pmd))
3078 		return;
3079 	/*
3080 	 * Caller holds the mmap_sem write mode, so a huge pmd cannot
3081 	 * materialize from under us.
3082 	 */
3083 	split_huge_page_pmd_mm(mm, address, pmd);
3084 }
3085 
vma_adjust_trans_huge(struct vm_area_struct * vma,unsigned long start,unsigned long end,long adjust_next)3086 void vma_adjust_trans_huge(struct vm_area_struct *vma,
3087 			     unsigned long start,
3088 			     unsigned long end,
3089 			     long adjust_next)
3090 {
3091 	/*
3092 	 * If the new start address isn't hpage aligned and it could
3093 	 * previously contain an hugepage: check if we need to split
3094 	 * an huge pmd.
3095 	 */
3096 	if (start & ~HPAGE_PMD_MASK &&
3097 	    (start & HPAGE_PMD_MASK) >= vma->vm_start &&
3098 	    (start & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
3099 		split_huge_page_address(vma->vm_mm, start);
3100 
3101 	/*
3102 	 * If the new end address isn't hpage aligned and it could
3103 	 * previously contain an hugepage: check if we need to split
3104 	 * an huge pmd.
3105 	 */
3106 	if (end & ~HPAGE_PMD_MASK &&
3107 	    (end & HPAGE_PMD_MASK) >= vma->vm_start &&
3108 	    (end & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= vma->vm_end)
3109 		split_huge_page_address(vma->vm_mm, end);
3110 
3111 	/*
3112 	 * If we're also updating the vma->vm_next->vm_start, if the new
3113 	 * vm_next->vm_start isn't page aligned and it could previously
3114 	 * contain an hugepage: check if we need to split an huge pmd.
3115 	 */
3116 	if (adjust_next > 0) {
3117 		struct vm_area_struct *next = vma->vm_next;
3118 		unsigned long nstart = next->vm_start;
3119 		nstart += adjust_next << PAGE_SHIFT;
3120 		if (nstart & ~HPAGE_PMD_MASK &&
3121 		    (nstart & HPAGE_PMD_MASK) >= next->vm_start &&
3122 		    (nstart & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE <= next->vm_end)
3123 			split_huge_page_address(next->vm_mm, nstart);
3124 	}
3125 }
3126