xref: /linux/mm/khugepaged.c (revision 9710a78ab2aed09690edf34a5c82f5107f448946)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2b46e756fSKirill A. Shutemov #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3b46e756fSKirill A. Shutemov 
4b46e756fSKirill A. Shutemov #include <linux/mm.h>
5b46e756fSKirill A. Shutemov #include <linux/sched.h>
66e84f315SIngo Molnar #include <linux/sched/mm.h>
7f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
8b46e756fSKirill A. Shutemov #include <linux/mmu_notifier.h>
9b46e756fSKirill A. Shutemov #include <linux/rmap.h>
10b46e756fSKirill A. Shutemov #include <linux/swap.h>
11b46e756fSKirill A. Shutemov #include <linux/mm_inline.h>
12b46e756fSKirill A. Shutemov #include <linux/kthread.h>
13b46e756fSKirill A. Shutemov #include <linux/khugepaged.h>
14b46e756fSKirill A. Shutemov #include <linux/freezer.h>
15b46e756fSKirill A. Shutemov #include <linux/mman.h>
16b46e756fSKirill A. Shutemov #include <linux/hashtable.h>
17b46e756fSKirill A. Shutemov #include <linux/userfaultfd_k.h>
18b46e756fSKirill A. Shutemov #include <linux/page_idle.h>
1980110bbfSPasha Tatashin #include <linux/page_table_check.h>
20b46e756fSKirill A. Shutemov #include <linux/swapops.h>
21f3f0e1d2SKirill A. Shutemov #include <linux/shmem_fs.h>
22b46e756fSKirill A. Shutemov 
23b46e756fSKirill A. Shutemov #include <asm/tlb.h>
24b46e756fSKirill A. Shutemov #include <asm/pgalloc.h>
25b46e756fSKirill A. Shutemov #include "internal.h"
26b46e756fSKirill A. Shutemov 
27b46e756fSKirill A. Shutemov enum scan_result {
28b46e756fSKirill A. Shutemov 	SCAN_FAIL,
29b46e756fSKirill A. Shutemov 	SCAN_SUCCEED,
30b46e756fSKirill A. Shutemov 	SCAN_PMD_NULL,
31b46e756fSKirill A. Shutemov 	SCAN_EXCEED_NONE_PTE,
3271a2c112SKirill A. Shutemov 	SCAN_EXCEED_SWAP_PTE,
3371a2c112SKirill A. Shutemov 	SCAN_EXCEED_SHARED_PTE,
34b46e756fSKirill A. Shutemov 	SCAN_PTE_NON_PRESENT,
35e1e267c7SPeter Xu 	SCAN_PTE_UFFD_WP,
36b46e756fSKirill A. Shutemov 	SCAN_PAGE_RO,
370db501f7SEbru Akagunduz 	SCAN_LACK_REFERENCED_PAGE,
38b46e756fSKirill A. Shutemov 	SCAN_PAGE_NULL,
39b46e756fSKirill A. Shutemov 	SCAN_SCAN_ABORT,
40b46e756fSKirill A. Shutemov 	SCAN_PAGE_COUNT,
41b46e756fSKirill A. Shutemov 	SCAN_PAGE_LRU,
42b46e756fSKirill A. Shutemov 	SCAN_PAGE_LOCK,
43b46e756fSKirill A. Shutemov 	SCAN_PAGE_ANON,
44b46e756fSKirill A. Shutemov 	SCAN_PAGE_COMPOUND,
45b46e756fSKirill A. Shutemov 	SCAN_ANY_PROCESS,
46b46e756fSKirill A. Shutemov 	SCAN_VMA_NULL,
47b46e756fSKirill A. Shutemov 	SCAN_VMA_CHECK,
48b46e756fSKirill A. Shutemov 	SCAN_ADDRESS_RANGE,
49b46e756fSKirill A. Shutemov 	SCAN_DEL_PAGE_LRU,
50b46e756fSKirill A. Shutemov 	SCAN_ALLOC_HUGE_PAGE_FAIL,
51b46e756fSKirill A. Shutemov 	SCAN_CGROUP_CHARGE_FAIL,
52f3f0e1d2SKirill A. Shutemov 	SCAN_TRUNCATED,
5399cb0dbdSSong Liu 	SCAN_PAGE_HAS_PRIVATE,
54b46e756fSKirill A. Shutemov };
55b46e756fSKirill A. Shutemov 
56b46e756fSKirill A. Shutemov #define CREATE_TRACE_POINTS
57b46e756fSKirill A. Shutemov #include <trace/events/huge_memory.h>
58b46e756fSKirill A. Shutemov 
594aab2be0SVijay Balakrishna static struct task_struct *khugepaged_thread __read_mostly;
604aab2be0SVijay Balakrishna static DEFINE_MUTEX(khugepaged_mutex);
614aab2be0SVijay Balakrishna 
62b46e756fSKirill A. Shutemov /* default scan 8*512 pte (or vmas) every 30 second */
63b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_to_scan __read_mostly;
64b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_collapsed;
65b46e756fSKirill A. Shutemov static unsigned int khugepaged_full_scans;
66b46e756fSKirill A. Shutemov static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
67b46e756fSKirill A. Shutemov /* during fragmentation poll the hugepage allocator once every minute */
68b46e756fSKirill A. Shutemov static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
69b46e756fSKirill A. Shutemov static unsigned long khugepaged_sleep_expire;
70b46e756fSKirill A. Shutemov static DEFINE_SPINLOCK(khugepaged_mm_lock);
71b46e756fSKirill A. Shutemov static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
72b46e756fSKirill A. Shutemov /*
73b46e756fSKirill A. Shutemov  * default collapse hugepages if there is at least one pte mapped like
74b46e756fSKirill A. Shutemov  * it would have happened if the vma was large enough during page
75b46e756fSKirill A. Shutemov  * fault.
76b46e756fSKirill A. Shutemov  */
77b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_none __read_mostly;
78b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_swap __read_mostly;
7971a2c112SKirill A. Shutemov static unsigned int khugepaged_max_ptes_shared __read_mostly;
80b46e756fSKirill A. Shutemov 
81b46e756fSKirill A. Shutemov #define MM_SLOTS_HASH_BITS 10
82b46e756fSKirill A. Shutemov static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
83b46e756fSKirill A. Shutemov 
84b46e756fSKirill A. Shutemov static struct kmem_cache *mm_slot_cache __read_mostly;
85b46e756fSKirill A. Shutemov 
8627e1f827SSong Liu #define MAX_PTE_MAPPED_THP 8
8727e1f827SSong Liu 
8834d6b470SZach O'Keefe struct collapse_control {
8934d6b470SZach O'Keefe 	/* Num pages scanned per node */
9034d6b470SZach O'Keefe 	u32 node_load[MAX_NUMNODES];
9134d6b470SZach O'Keefe 
9234d6b470SZach O'Keefe 	/* Last target selected in khugepaged_find_target_node() */
9334d6b470SZach O'Keefe 	int last_target_node;
9434d6b470SZach O'Keefe };
9534d6b470SZach O'Keefe 
96b46e756fSKirill A. Shutemov /**
97b46e756fSKirill A. Shutemov  * struct mm_slot - hash lookup from mm to mm_slot
98b46e756fSKirill A. Shutemov  * @hash: hash collision list
99b46e756fSKirill A. Shutemov  * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
100b46e756fSKirill A. Shutemov  * @mm: the mm that this information is valid for
101336e6b53SAlex Shi  * @nr_pte_mapped_thp: number of pte mapped THP
102336e6b53SAlex Shi  * @pte_mapped_thp: address array corresponding pte mapped THP
103b46e756fSKirill A. Shutemov  */
104b46e756fSKirill A. Shutemov struct mm_slot {
105b46e756fSKirill A. Shutemov 	struct hlist_node hash;
106b46e756fSKirill A. Shutemov 	struct list_head mm_node;
107b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
10827e1f827SSong Liu 
10927e1f827SSong Liu 	/* pte-mapped THP in this mm */
11027e1f827SSong Liu 	int nr_pte_mapped_thp;
11127e1f827SSong Liu 	unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
112b46e756fSKirill A. Shutemov };
113b46e756fSKirill A. Shutemov 
114b46e756fSKirill A. Shutemov /**
115b46e756fSKirill A. Shutemov  * struct khugepaged_scan - cursor for scanning
116b46e756fSKirill A. Shutemov  * @mm_head: the head of the mm list to scan
117b46e756fSKirill A. Shutemov  * @mm_slot: the current mm_slot we are scanning
118b46e756fSKirill A. Shutemov  * @address: the next address inside that to be scanned
119b46e756fSKirill A. Shutemov  *
120b46e756fSKirill A. Shutemov  * There is only the one khugepaged_scan instance of this cursor structure.
121b46e756fSKirill A. Shutemov  */
122b46e756fSKirill A. Shutemov struct khugepaged_scan {
123b46e756fSKirill A. Shutemov 	struct list_head mm_head;
124b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
125b46e756fSKirill A. Shutemov 	unsigned long address;
126b46e756fSKirill A. Shutemov };
127b46e756fSKirill A. Shutemov 
128b46e756fSKirill A. Shutemov static struct khugepaged_scan khugepaged_scan = {
129b46e756fSKirill A. Shutemov 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
130b46e756fSKirill A. Shutemov };
131b46e756fSKirill A. Shutemov 
132e1465d12SJérémy Lefaure #ifdef CONFIG_SYSFS
133b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
134b46e756fSKirill A. Shutemov 					 struct kobj_attribute *attr,
135b46e756fSKirill A. Shutemov 					 char *buf)
136b46e756fSKirill A. Shutemov {
137ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
138b46e756fSKirill A. Shutemov }
139b46e756fSKirill A. Shutemov 
140b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
141b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
142b46e756fSKirill A. Shutemov 					  const char *buf, size_t count)
143b46e756fSKirill A. Shutemov {
144dfefd226SAlexey Dobriyan 	unsigned int msecs;
145b46e756fSKirill A. Shutemov 	int err;
146b46e756fSKirill A. Shutemov 
147dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
148dfefd226SAlexey Dobriyan 	if (err)
149b46e756fSKirill A. Shutemov 		return -EINVAL;
150b46e756fSKirill A. Shutemov 
151b46e756fSKirill A. Shutemov 	khugepaged_scan_sleep_millisecs = msecs;
152b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
153b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
154b46e756fSKirill A. Shutemov 
155b46e756fSKirill A. Shutemov 	return count;
156b46e756fSKirill A. Shutemov }
157b46e756fSKirill A. Shutemov static struct kobj_attribute scan_sleep_millisecs_attr =
1586dcdc94dSMiaohe Lin 	__ATTR_RW(scan_sleep_millisecs);
159b46e756fSKirill A. Shutemov 
160b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
161b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
162b46e756fSKirill A. Shutemov 					  char *buf)
163b46e756fSKirill A. Shutemov {
164ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
165b46e756fSKirill A. Shutemov }
166b46e756fSKirill A. Shutemov 
167b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
168b46e756fSKirill A. Shutemov 					   struct kobj_attribute *attr,
169b46e756fSKirill A. Shutemov 					   const char *buf, size_t count)
170b46e756fSKirill A. Shutemov {
171dfefd226SAlexey Dobriyan 	unsigned int msecs;
172b46e756fSKirill A. Shutemov 	int err;
173b46e756fSKirill A. Shutemov 
174dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
175dfefd226SAlexey Dobriyan 	if (err)
176b46e756fSKirill A. Shutemov 		return -EINVAL;
177b46e756fSKirill A. Shutemov 
178b46e756fSKirill A. Shutemov 	khugepaged_alloc_sleep_millisecs = msecs;
179b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
180b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
181b46e756fSKirill A. Shutemov 
182b46e756fSKirill A. Shutemov 	return count;
183b46e756fSKirill A. Shutemov }
184b46e756fSKirill A. Shutemov static struct kobj_attribute alloc_sleep_millisecs_attr =
1856dcdc94dSMiaohe Lin 	__ATTR_RW(alloc_sleep_millisecs);
186b46e756fSKirill A. Shutemov 
187b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_show(struct kobject *kobj,
188b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
189b46e756fSKirill A. Shutemov 				  char *buf)
190b46e756fSKirill A. Shutemov {
191ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
192b46e756fSKirill A. Shutemov }
193b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_store(struct kobject *kobj,
194b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
195b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
196b46e756fSKirill A. Shutemov {
197dfefd226SAlexey Dobriyan 	unsigned int pages;
198b46e756fSKirill A. Shutemov 	int err;
199b46e756fSKirill A. Shutemov 
200dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &pages);
201dfefd226SAlexey Dobriyan 	if (err || !pages)
202b46e756fSKirill A. Shutemov 		return -EINVAL;
203b46e756fSKirill A. Shutemov 
204b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = pages;
205b46e756fSKirill A. Shutemov 
206b46e756fSKirill A. Shutemov 	return count;
207b46e756fSKirill A. Shutemov }
208b46e756fSKirill A. Shutemov static struct kobj_attribute pages_to_scan_attr =
2096dcdc94dSMiaohe Lin 	__ATTR_RW(pages_to_scan);
210b46e756fSKirill A. Shutemov 
211b46e756fSKirill A. Shutemov static ssize_t pages_collapsed_show(struct kobject *kobj,
212b46e756fSKirill A. Shutemov 				    struct kobj_attribute *attr,
213b46e756fSKirill A. Shutemov 				    char *buf)
214b46e756fSKirill A. Shutemov {
215ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
216b46e756fSKirill A. Shutemov }
217b46e756fSKirill A. Shutemov static struct kobj_attribute pages_collapsed_attr =
218b46e756fSKirill A. Shutemov 	__ATTR_RO(pages_collapsed);
219b46e756fSKirill A. Shutemov 
220b46e756fSKirill A. Shutemov static ssize_t full_scans_show(struct kobject *kobj,
221b46e756fSKirill A. Shutemov 			       struct kobj_attribute *attr,
222b46e756fSKirill A. Shutemov 			       char *buf)
223b46e756fSKirill A. Shutemov {
224ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
225b46e756fSKirill A. Shutemov }
226b46e756fSKirill A. Shutemov static struct kobj_attribute full_scans_attr =
227b46e756fSKirill A. Shutemov 	__ATTR_RO(full_scans);
228b46e756fSKirill A. Shutemov 
2296dcdc94dSMiaohe Lin static ssize_t defrag_show(struct kobject *kobj,
230b46e756fSKirill A. Shutemov 			   struct kobj_attribute *attr, char *buf)
231b46e756fSKirill A. Shutemov {
232b46e756fSKirill A. Shutemov 	return single_hugepage_flag_show(kobj, attr, buf,
233b46e756fSKirill A. Shutemov 					 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
234b46e756fSKirill A. Shutemov }
2356dcdc94dSMiaohe Lin static ssize_t defrag_store(struct kobject *kobj,
236b46e756fSKirill A. Shutemov 			    struct kobj_attribute *attr,
237b46e756fSKirill A. Shutemov 			    const char *buf, size_t count)
238b46e756fSKirill A. Shutemov {
239b46e756fSKirill A. Shutemov 	return single_hugepage_flag_store(kobj, attr, buf, count,
240b46e756fSKirill A. Shutemov 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
241b46e756fSKirill A. Shutemov }
242b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_defrag_attr =
2436dcdc94dSMiaohe Lin 	__ATTR_RW(defrag);
244b46e756fSKirill A. Shutemov 
245b46e756fSKirill A. Shutemov /*
246b46e756fSKirill A. Shutemov  * max_ptes_none controls if khugepaged should collapse hugepages over
247b46e756fSKirill A. Shutemov  * any unmapped ptes in turn potentially increasing the memory
248b46e756fSKirill A. Shutemov  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
249b46e756fSKirill A. Shutemov  * reduce the available free memory in the system as it
250b46e756fSKirill A. Shutemov  * runs. Increasing max_ptes_none will instead potentially reduce the
251b46e756fSKirill A. Shutemov  * free memory in the system during the khugepaged scan.
252b46e756fSKirill A. Shutemov  */
2536dcdc94dSMiaohe Lin static ssize_t max_ptes_none_show(struct kobject *kobj,
254b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
255b46e756fSKirill A. Shutemov 				  char *buf)
256b46e756fSKirill A. Shutemov {
257ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
258b46e756fSKirill A. Shutemov }
2596dcdc94dSMiaohe Lin static ssize_t max_ptes_none_store(struct kobject *kobj,
260b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
261b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
262b46e756fSKirill A. Shutemov {
263b46e756fSKirill A. Shutemov 	int err;
264b46e756fSKirill A. Shutemov 	unsigned long max_ptes_none;
265b46e756fSKirill A. Shutemov 
266b46e756fSKirill A. Shutemov 	err = kstrtoul(buf, 10, &max_ptes_none);
267b46e756fSKirill A. Shutemov 	if (err || max_ptes_none > HPAGE_PMD_NR - 1)
268b46e756fSKirill A. Shutemov 		return -EINVAL;
269b46e756fSKirill A. Shutemov 
270b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = max_ptes_none;
271b46e756fSKirill A. Shutemov 
272b46e756fSKirill A. Shutemov 	return count;
273b46e756fSKirill A. Shutemov }
274b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_none_attr =
2756dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_none);
276b46e756fSKirill A. Shutemov 
2776dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_show(struct kobject *kobj,
278b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
279b46e756fSKirill A. Shutemov 				  char *buf)
280b46e756fSKirill A. Shutemov {
281ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
282b46e756fSKirill A. Shutemov }
283b46e756fSKirill A. Shutemov 
2846dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_store(struct kobject *kobj,
285b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
286b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
287b46e756fSKirill A. Shutemov {
288b46e756fSKirill A. Shutemov 	int err;
289b46e756fSKirill A. Shutemov 	unsigned long max_ptes_swap;
290b46e756fSKirill A. Shutemov 
291b46e756fSKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_swap);
292b46e756fSKirill A. Shutemov 	if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
293b46e756fSKirill A. Shutemov 		return -EINVAL;
294b46e756fSKirill A. Shutemov 
295b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = max_ptes_swap;
296b46e756fSKirill A. Shutemov 
297b46e756fSKirill A. Shutemov 	return count;
298b46e756fSKirill A. Shutemov }
299b46e756fSKirill A. Shutemov 
300b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_swap_attr =
3016dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_swap);
302b46e756fSKirill A. Shutemov 
3036dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_show(struct kobject *kobj,
30471a2c112SKirill A. Shutemov 				    struct kobj_attribute *attr,
30571a2c112SKirill A. Shutemov 				    char *buf)
30671a2c112SKirill A. Shutemov {
307ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
30871a2c112SKirill A. Shutemov }
30971a2c112SKirill A. Shutemov 
3106dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_store(struct kobject *kobj,
31171a2c112SKirill A. Shutemov 				     struct kobj_attribute *attr,
31271a2c112SKirill A. Shutemov 				     const char *buf, size_t count)
31371a2c112SKirill A. Shutemov {
31471a2c112SKirill A. Shutemov 	int err;
31571a2c112SKirill A. Shutemov 	unsigned long max_ptes_shared;
31671a2c112SKirill A. Shutemov 
31771a2c112SKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_shared);
31871a2c112SKirill A. Shutemov 	if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
31971a2c112SKirill A. Shutemov 		return -EINVAL;
32071a2c112SKirill A. Shutemov 
32171a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = max_ptes_shared;
32271a2c112SKirill A. Shutemov 
32371a2c112SKirill A. Shutemov 	return count;
32471a2c112SKirill A. Shutemov }
32571a2c112SKirill A. Shutemov 
32671a2c112SKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_shared_attr =
3276dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_shared);
32871a2c112SKirill A. Shutemov 
329b46e756fSKirill A. Shutemov static struct attribute *khugepaged_attr[] = {
330b46e756fSKirill A. Shutemov 	&khugepaged_defrag_attr.attr,
331b46e756fSKirill A. Shutemov 	&khugepaged_max_ptes_none_attr.attr,
33271a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_swap_attr.attr,
33371a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_shared_attr.attr,
334b46e756fSKirill A. Shutemov 	&pages_to_scan_attr.attr,
335b46e756fSKirill A. Shutemov 	&pages_collapsed_attr.attr,
336b46e756fSKirill A. Shutemov 	&full_scans_attr.attr,
337b46e756fSKirill A. Shutemov 	&scan_sleep_millisecs_attr.attr,
338b46e756fSKirill A. Shutemov 	&alloc_sleep_millisecs_attr.attr,
339b46e756fSKirill A. Shutemov 	NULL,
340b46e756fSKirill A. Shutemov };
341b46e756fSKirill A. Shutemov 
342b46e756fSKirill A. Shutemov struct attribute_group khugepaged_attr_group = {
343b46e756fSKirill A. Shutemov 	.attrs = khugepaged_attr,
344b46e756fSKirill A. Shutemov 	.name = "khugepaged",
345b46e756fSKirill A. Shutemov };
346e1465d12SJérémy Lefaure #endif /* CONFIG_SYSFS */
347b46e756fSKirill A. Shutemov 
348b46e756fSKirill A. Shutemov int hugepage_madvise(struct vm_area_struct *vma,
349b46e756fSKirill A. Shutemov 		     unsigned long *vm_flags, int advice)
350b46e756fSKirill A. Shutemov {
351b46e756fSKirill A. Shutemov 	switch (advice) {
352b46e756fSKirill A. Shutemov 	case MADV_HUGEPAGE:
353b46e756fSKirill A. Shutemov #ifdef CONFIG_S390
354b46e756fSKirill A. Shutemov 		/*
355b46e756fSKirill A. Shutemov 		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
356b46e756fSKirill A. Shutemov 		 * can't handle this properly after s390_enable_sie, so we simply
357b46e756fSKirill A. Shutemov 		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
358b46e756fSKirill A. Shutemov 		 */
359b46e756fSKirill A. Shutemov 		if (mm_has_pgste(vma->vm_mm))
360b46e756fSKirill A. Shutemov 			return 0;
361b46e756fSKirill A. Shutemov #endif
362b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_NOHUGEPAGE;
363b46e756fSKirill A. Shutemov 		*vm_flags |= VM_HUGEPAGE;
364b46e756fSKirill A. Shutemov 		/*
365b46e756fSKirill A. Shutemov 		 * If the vma become good for khugepaged to scan,
366b46e756fSKirill A. Shutemov 		 * register it here without waiting a page fault that
367b46e756fSKirill A. Shutemov 		 * may not happen any time soon.
368b46e756fSKirill A. Shutemov 		 */
369c791576cSYang Shi 		khugepaged_enter_vma(vma, *vm_flags);
370b46e756fSKirill A. Shutemov 		break;
371b46e756fSKirill A. Shutemov 	case MADV_NOHUGEPAGE:
372b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_HUGEPAGE;
373b46e756fSKirill A. Shutemov 		*vm_flags |= VM_NOHUGEPAGE;
374b46e756fSKirill A. Shutemov 		/*
375b46e756fSKirill A. Shutemov 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
376b46e756fSKirill A. Shutemov 		 * this vma even if we leave the mm registered in khugepaged if
377b46e756fSKirill A. Shutemov 		 * it got registered before VM_NOHUGEPAGE was set.
378b46e756fSKirill A. Shutemov 		 */
379b46e756fSKirill A. Shutemov 		break;
380b46e756fSKirill A. Shutemov 	}
381b46e756fSKirill A. Shutemov 
382b46e756fSKirill A. Shutemov 	return 0;
383b46e756fSKirill A. Shutemov }
384b46e756fSKirill A. Shutemov 
385b46e756fSKirill A. Shutemov int __init khugepaged_init(void)
386b46e756fSKirill A. Shutemov {
387b46e756fSKirill A. Shutemov 	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
388b46e756fSKirill A. Shutemov 					  sizeof(struct mm_slot),
389b46e756fSKirill A. Shutemov 					  __alignof__(struct mm_slot), 0, NULL);
390b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)
391b46e756fSKirill A. Shutemov 		return -ENOMEM;
392b46e756fSKirill A. Shutemov 
393b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
394b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
395b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
39671a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
397b46e756fSKirill A. Shutemov 
398b46e756fSKirill A. Shutemov 	return 0;
399b46e756fSKirill A. Shutemov }
400b46e756fSKirill A. Shutemov 
401b46e756fSKirill A. Shutemov void __init khugepaged_destroy(void)
402b46e756fSKirill A. Shutemov {
403b46e756fSKirill A. Shutemov 	kmem_cache_destroy(mm_slot_cache);
404b46e756fSKirill A. Shutemov }
405b46e756fSKirill A. Shutemov 
406b46e756fSKirill A. Shutemov static inline struct mm_slot *alloc_mm_slot(void)
407b46e756fSKirill A. Shutemov {
408b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)	/* initialization failed */
409b46e756fSKirill A. Shutemov 		return NULL;
410b46e756fSKirill A. Shutemov 	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
411b46e756fSKirill A. Shutemov }
412b46e756fSKirill A. Shutemov 
413b46e756fSKirill A. Shutemov static inline void free_mm_slot(struct mm_slot *mm_slot)
414b46e756fSKirill A. Shutemov {
415b46e756fSKirill A. Shutemov 	kmem_cache_free(mm_slot_cache, mm_slot);
416b46e756fSKirill A. Shutemov }
417b46e756fSKirill A. Shutemov 
418b46e756fSKirill A. Shutemov static struct mm_slot *get_mm_slot(struct mm_struct *mm)
419b46e756fSKirill A. Shutemov {
420b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
421b46e756fSKirill A. Shutemov 
422b46e756fSKirill A. Shutemov 	hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
423b46e756fSKirill A. Shutemov 		if (mm == mm_slot->mm)
424b46e756fSKirill A. Shutemov 			return mm_slot;
425b46e756fSKirill A. Shutemov 
426b46e756fSKirill A. Shutemov 	return NULL;
427b46e756fSKirill A. Shutemov }
428b46e756fSKirill A. Shutemov 
429b46e756fSKirill A. Shutemov static void insert_to_mm_slots_hash(struct mm_struct *mm,
430b46e756fSKirill A. Shutemov 				    struct mm_slot *mm_slot)
431b46e756fSKirill A. Shutemov {
432b46e756fSKirill A. Shutemov 	mm_slot->mm = mm;
433b46e756fSKirill A. Shutemov 	hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
434b46e756fSKirill A. Shutemov }
435b46e756fSKirill A. Shutemov 
436b46e756fSKirill A. Shutemov static inline int khugepaged_test_exit(struct mm_struct *mm)
437b46e756fSKirill A. Shutemov {
4384d45e75aSJann Horn 	return atomic_read(&mm->mm_users) == 0;
439b46e756fSKirill A. Shutemov }
440b46e756fSKirill A. Shutemov 
441d2081b2bSYang Shi void __khugepaged_enter(struct mm_struct *mm)
442b46e756fSKirill A. Shutemov {
443b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
444b46e756fSKirill A. Shutemov 	int wakeup;
445b46e756fSKirill A. Shutemov 
446b46e756fSKirill A. Shutemov 	mm_slot = alloc_mm_slot();
447b46e756fSKirill A. Shutemov 	if (!mm_slot)
448d2081b2bSYang Shi 		return;
449b46e756fSKirill A. Shutemov 
450b46e756fSKirill A. Shutemov 	/* __khugepaged_exit() must not run from under us */
45128ff0a3cSMiaohe Lin 	VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
452b46e756fSKirill A. Shutemov 	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
453b46e756fSKirill A. Shutemov 		free_mm_slot(mm_slot);
454d2081b2bSYang Shi 		return;
455b46e756fSKirill A. Shutemov 	}
456b46e756fSKirill A. Shutemov 
457b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
458b46e756fSKirill A. Shutemov 	insert_to_mm_slots_hash(mm, mm_slot);
459b46e756fSKirill A. Shutemov 	/*
460b46e756fSKirill A. Shutemov 	 * Insert just behind the scanning cursor, to let the area settle
461b46e756fSKirill A. Shutemov 	 * down a little.
462b46e756fSKirill A. Shutemov 	 */
463b46e756fSKirill A. Shutemov 	wakeup = list_empty(&khugepaged_scan.mm_head);
464b46e756fSKirill A. Shutemov 	list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
465b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
466b46e756fSKirill A. Shutemov 
467f1f10076SVegard Nossum 	mmgrab(mm);
468b46e756fSKirill A. Shutemov 	if (wakeup)
469b46e756fSKirill A. Shutemov 		wake_up_interruptible(&khugepaged_wait);
470b46e756fSKirill A. Shutemov }
471b46e756fSKirill A. Shutemov 
472c791576cSYang Shi void khugepaged_enter_vma(struct vm_area_struct *vma,
473b46e756fSKirill A. Shutemov 			  unsigned long vm_flags)
474b46e756fSKirill A. Shutemov {
4752647d11bSYang Shi 	if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
4761064026bSYang Shi 	    hugepage_flags_enabled()) {
4777da4e2cbSYang Shi 		if (hugepage_vma_check(vma, vm_flags, false, false))
4782647d11bSYang Shi 			__khugepaged_enter(vma->vm_mm);
4792647d11bSYang Shi 	}
480b46e756fSKirill A. Shutemov }
481b46e756fSKirill A. Shutemov 
482b46e756fSKirill A. Shutemov void __khugepaged_exit(struct mm_struct *mm)
483b46e756fSKirill A. Shutemov {
484b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
485b46e756fSKirill A. Shutemov 	int free = 0;
486b46e756fSKirill A. Shutemov 
487b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
488b46e756fSKirill A. Shutemov 	mm_slot = get_mm_slot(mm);
489b46e756fSKirill A. Shutemov 	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
490b46e756fSKirill A. Shutemov 		hash_del(&mm_slot->hash);
491b46e756fSKirill A. Shutemov 		list_del(&mm_slot->mm_node);
492b46e756fSKirill A. Shutemov 		free = 1;
493b46e756fSKirill A. Shutemov 	}
494b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
495b46e756fSKirill A. Shutemov 
496b46e756fSKirill A. Shutemov 	if (free) {
497b46e756fSKirill A. Shutemov 		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
498b46e756fSKirill A. Shutemov 		free_mm_slot(mm_slot);
499b46e756fSKirill A. Shutemov 		mmdrop(mm);
500b46e756fSKirill A. Shutemov 	} else if (mm_slot) {
501b46e756fSKirill A. Shutemov 		/*
502b46e756fSKirill A. Shutemov 		 * This is required to serialize against
503b46e756fSKirill A. Shutemov 		 * khugepaged_test_exit() (which is guaranteed to run
504b46e756fSKirill A. Shutemov 		 * under mmap sem read mode). Stop here (after we
505b46e756fSKirill A. Shutemov 		 * return all pagetables will be destroyed) until
506b46e756fSKirill A. Shutemov 		 * khugepaged has finished working on the pagetables
507c1e8d7c6SMichel Lespinasse 		 * under the mmap_lock.
508b46e756fSKirill A. Shutemov 		 */
509d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
510d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
511b46e756fSKirill A. Shutemov 	}
512b46e756fSKirill A. Shutemov }
513b46e756fSKirill A. Shutemov 
514b46e756fSKirill A. Shutemov static void release_pte_page(struct page *page)
515b46e756fSKirill A. Shutemov {
5165503fbf2SKirill A. Shutemov 	mod_node_page_state(page_pgdat(page),
5175503fbf2SKirill A. Shutemov 			NR_ISOLATED_ANON + page_is_file_lru(page),
5185503fbf2SKirill A. Shutemov 			-compound_nr(page));
519b46e756fSKirill A. Shutemov 	unlock_page(page);
520b46e756fSKirill A. Shutemov 	putback_lru_page(page);
521b46e756fSKirill A. Shutemov }
522b46e756fSKirill A. Shutemov 
5235503fbf2SKirill A. Shutemov static void release_pte_pages(pte_t *pte, pte_t *_pte,
5245503fbf2SKirill A. Shutemov 		struct list_head *compound_pagelist)
525b46e756fSKirill A. Shutemov {
5265503fbf2SKirill A. Shutemov 	struct page *page, *tmp;
5275503fbf2SKirill A. Shutemov 
528b46e756fSKirill A. Shutemov 	while (--_pte >= pte) {
529b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
5305503fbf2SKirill A. Shutemov 
5315503fbf2SKirill A. Shutemov 		page = pte_page(pteval);
5325503fbf2SKirill A. Shutemov 		if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
5335503fbf2SKirill A. Shutemov 				!PageCompound(page))
5345503fbf2SKirill A. Shutemov 			release_pte_page(page);
5355503fbf2SKirill A. Shutemov 	}
5365503fbf2SKirill A. Shutemov 
5375503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
5385503fbf2SKirill A. Shutemov 		list_del(&page->lru);
5395503fbf2SKirill A. Shutemov 		release_pte_page(page);
540b46e756fSKirill A. Shutemov 	}
541b46e756fSKirill A. Shutemov }
542b46e756fSKirill A. Shutemov 
5439445689fSKirill A. Shutemov static bool is_refcount_suitable(struct page *page)
5449445689fSKirill A. Shutemov {
5459445689fSKirill A. Shutemov 	int expected_refcount;
5469445689fSKirill A. Shutemov 
5479445689fSKirill A. Shutemov 	expected_refcount = total_mapcount(page);
5489445689fSKirill A. Shutemov 	if (PageSwapCache(page))
5499445689fSKirill A. Shutemov 		expected_refcount += compound_nr(page);
5509445689fSKirill A. Shutemov 
5519445689fSKirill A. Shutemov 	return page_count(page) == expected_refcount;
5529445689fSKirill A. Shutemov }
5539445689fSKirill A. Shutemov 
554b46e756fSKirill A. Shutemov static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
555b46e756fSKirill A. Shutemov 					unsigned long address,
5565503fbf2SKirill A. Shutemov 					pte_t *pte,
5575503fbf2SKirill A. Shutemov 					struct list_head *compound_pagelist)
558b46e756fSKirill A. Shutemov {
559b46e756fSKirill A. Shutemov 	struct page *page = NULL;
560b46e756fSKirill A. Shutemov 	pte_t *_pte;
56171a2c112SKirill A. Shutemov 	int none_or_zero = 0, shared = 0, result = 0, referenced = 0;
5620db501f7SEbru Akagunduz 	bool writable = false;
563b46e756fSKirill A. Shutemov 
564b46e756fSKirill A. Shutemov 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
565b46e756fSKirill A. Shutemov 	     _pte++, address += PAGE_SIZE) {
566b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
567b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || (pte_present(pteval) &&
568b46e756fSKirill A. Shutemov 				is_zero_pfn(pte_pfn(pteval)))) {
569b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
570b46e756fSKirill A. Shutemov 			    ++none_or_zero <= khugepaged_max_ptes_none) {
571b46e756fSKirill A. Shutemov 				continue;
572b46e756fSKirill A. Shutemov 			} else {
573b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
574e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
575b46e756fSKirill A. Shutemov 				goto out;
576b46e756fSKirill A. Shutemov 			}
577b46e756fSKirill A. Shutemov 		}
578b46e756fSKirill A. Shutemov 		if (!pte_present(pteval)) {
579b46e756fSKirill A. Shutemov 			result = SCAN_PTE_NON_PRESENT;
580b46e756fSKirill A. Shutemov 			goto out;
581b46e756fSKirill A. Shutemov 		}
582b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, address, pteval);
5833218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
584b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
585b46e756fSKirill A. Shutemov 			goto out;
586b46e756fSKirill A. Shutemov 		}
587b46e756fSKirill A. Shutemov 
588b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageAnon(page), page);
589b46e756fSKirill A. Shutemov 
59071a2c112SKirill A. Shutemov 		if (page_mapcount(page) > 1 &&
59171a2c112SKirill A. Shutemov 				++shared > khugepaged_max_ptes_shared) {
59271a2c112SKirill A. Shutemov 			result = SCAN_EXCEED_SHARED_PTE;
593e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
59471a2c112SKirill A. Shutemov 			goto out;
59571a2c112SKirill A. Shutemov 		}
59671a2c112SKirill A. Shutemov 
5975503fbf2SKirill A. Shutemov 		if (PageCompound(page)) {
5985503fbf2SKirill A. Shutemov 			struct page *p;
5995503fbf2SKirill A. Shutemov 			page = compound_head(page);
6005503fbf2SKirill A. Shutemov 
6015503fbf2SKirill A. Shutemov 			/*
6025503fbf2SKirill A. Shutemov 			 * Check if we have dealt with the compound page
6035503fbf2SKirill A. Shutemov 			 * already
6045503fbf2SKirill A. Shutemov 			 */
6055503fbf2SKirill A. Shutemov 			list_for_each_entry(p, compound_pagelist, lru) {
6065503fbf2SKirill A. Shutemov 				if (page == p)
6075503fbf2SKirill A. Shutemov 					goto next;
6085503fbf2SKirill A. Shutemov 			}
6095503fbf2SKirill A. Shutemov 		}
6105503fbf2SKirill A. Shutemov 
611b46e756fSKirill A. Shutemov 		/*
612b46e756fSKirill A. Shutemov 		 * We can do it before isolate_lru_page because the
613b46e756fSKirill A. Shutemov 		 * page can't be freed from under us. NOTE: PG_lock
614b46e756fSKirill A. Shutemov 		 * is needed to serialize against split_huge_page
615b46e756fSKirill A. Shutemov 		 * when invoked from the VM.
616b46e756fSKirill A. Shutemov 		 */
617b46e756fSKirill A. Shutemov 		if (!trylock_page(page)) {
618b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
619b46e756fSKirill A. Shutemov 			goto out;
620b46e756fSKirill A. Shutemov 		}
621b46e756fSKirill A. Shutemov 
622b46e756fSKirill A. Shutemov 		/*
6239445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
6249445689fSKirill A. Shutemov 		 *
6259445689fSKirill A. Shutemov 		 * The page table that maps the page has been already unlinked
6269445689fSKirill A. Shutemov 		 * from the page table tree and this process cannot get
627f0953a1bSIngo Molnar 		 * an additional pin on the page.
6289445689fSKirill A. Shutemov 		 *
6299445689fSKirill A. Shutemov 		 * New pins can come later if the page is shared across fork,
6309445689fSKirill A. Shutemov 		 * but not from this process. The other process cannot write to
6319445689fSKirill A. Shutemov 		 * the page, only trigger CoW.
632b46e756fSKirill A. Shutemov 		 */
6339445689fSKirill A. Shutemov 		if (!is_refcount_suitable(page)) {
634b46e756fSKirill A. Shutemov 			unlock_page(page);
635b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
636b46e756fSKirill A. Shutemov 			goto out;
637b46e756fSKirill A. Shutemov 		}
638b46e756fSKirill A. Shutemov 
639b46e756fSKirill A. Shutemov 		/*
640b46e756fSKirill A. Shutemov 		 * Isolate the page to avoid collapsing an hugepage
641b46e756fSKirill A. Shutemov 		 * currently in use by the VM.
642b46e756fSKirill A. Shutemov 		 */
643b46e756fSKirill A. Shutemov 		if (isolate_lru_page(page)) {
644b46e756fSKirill A. Shutemov 			unlock_page(page);
645b46e756fSKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
646b46e756fSKirill A. Shutemov 			goto out;
647b46e756fSKirill A. Shutemov 		}
6485503fbf2SKirill A. Shutemov 		mod_node_page_state(page_pgdat(page),
6495503fbf2SKirill A. Shutemov 				NR_ISOLATED_ANON + page_is_file_lru(page),
6505503fbf2SKirill A. Shutemov 				compound_nr(page));
651b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
652b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageLRU(page), page);
653b46e756fSKirill A. Shutemov 
6545503fbf2SKirill A. Shutemov 		if (PageCompound(page))
6555503fbf2SKirill A. Shutemov 			list_add_tail(&page->lru, compound_pagelist);
6565503fbf2SKirill A. Shutemov next:
6570db501f7SEbru Akagunduz 		/* There should be enough young pte to collapse the page */
658b46e756fSKirill A. Shutemov 		if (pte_young(pteval) ||
659b46e756fSKirill A. Shutemov 		    page_is_young(page) || PageReferenced(page) ||
660b46e756fSKirill A. Shutemov 		    mmu_notifier_test_young(vma->vm_mm, address))
6610db501f7SEbru Akagunduz 			referenced++;
6625503fbf2SKirill A. Shutemov 
6635503fbf2SKirill A. Shutemov 		if (pte_write(pteval))
6645503fbf2SKirill A. Shutemov 			writable = true;
665b46e756fSKirill A. Shutemov 	}
66674e579bfSMiaohe Lin 
66774e579bfSMiaohe Lin 	if (unlikely(!writable)) {
66874e579bfSMiaohe Lin 		result = SCAN_PAGE_RO;
66974e579bfSMiaohe Lin 	} else if (unlikely(!referenced)) {
67074e579bfSMiaohe Lin 		result = SCAN_LACK_REFERENCED_PAGE;
67174e579bfSMiaohe Lin 	} else {
672b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
673b46e756fSKirill A. Shutemov 		trace_mm_collapse_huge_page_isolate(page, none_or_zero,
674b46e756fSKirill A. Shutemov 						    referenced, writable, result);
675b46e756fSKirill A. Shutemov 		return 1;
676b46e756fSKirill A. Shutemov 	}
677b46e756fSKirill A. Shutemov out:
6785503fbf2SKirill A. Shutemov 	release_pte_pages(pte, _pte, compound_pagelist);
679b46e756fSKirill A. Shutemov 	trace_mm_collapse_huge_page_isolate(page, none_or_zero,
680b46e756fSKirill A. Shutemov 					    referenced, writable, result);
681b46e756fSKirill A. Shutemov 	return 0;
682b46e756fSKirill A. Shutemov }
683b46e756fSKirill A. Shutemov 
684b46e756fSKirill A. Shutemov static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
685b46e756fSKirill A. Shutemov 				      struct vm_area_struct *vma,
686b46e756fSKirill A. Shutemov 				      unsigned long address,
6875503fbf2SKirill A. Shutemov 				      spinlock_t *ptl,
6885503fbf2SKirill A. Shutemov 				      struct list_head *compound_pagelist)
689b46e756fSKirill A. Shutemov {
6905503fbf2SKirill A. Shutemov 	struct page *src_page, *tmp;
691b46e756fSKirill A. Shutemov 	pte_t *_pte;
692338a16baSDavid Rientjes 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
693338a16baSDavid Rientjes 				_pte++, page++, address += PAGE_SIZE) {
694b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
695b46e756fSKirill A. Shutemov 
696b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
697b46e756fSKirill A. Shutemov 			clear_user_highpage(page, address);
698b46e756fSKirill A. Shutemov 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
699b46e756fSKirill A. Shutemov 			if (is_zero_pfn(pte_pfn(pteval))) {
700b46e756fSKirill A. Shutemov 				/*
701b46e756fSKirill A. Shutemov 				 * ptl mostly unnecessary.
702b46e756fSKirill A. Shutemov 				 */
703b46e756fSKirill A. Shutemov 				spin_lock(ptl);
70408d5b29eSPasha Tatashin 				ptep_clear(vma->vm_mm, address, _pte);
705b46e756fSKirill A. Shutemov 				spin_unlock(ptl);
706b46e756fSKirill A. Shutemov 			}
707b46e756fSKirill A. Shutemov 		} else {
708b46e756fSKirill A. Shutemov 			src_page = pte_page(pteval);
709b46e756fSKirill A. Shutemov 			copy_user_highpage(page, src_page, address, vma);
7105503fbf2SKirill A. Shutemov 			if (!PageCompound(src_page))
711b46e756fSKirill A. Shutemov 				release_pte_page(src_page);
712b46e756fSKirill A. Shutemov 			/*
713b46e756fSKirill A. Shutemov 			 * ptl mostly unnecessary, but preempt has to
714b46e756fSKirill A. Shutemov 			 * be disabled to update the per-cpu stats
715b46e756fSKirill A. Shutemov 			 * inside page_remove_rmap().
716b46e756fSKirill A. Shutemov 			 */
717b46e756fSKirill A. Shutemov 			spin_lock(ptl);
71808d5b29eSPasha Tatashin 			ptep_clear(vma->vm_mm, address, _pte);
719cea86fe2SHugh Dickins 			page_remove_rmap(src_page, vma, false);
720b46e756fSKirill A. Shutemov 			spin_unlock(ptl);
721b46e756fSKirill A. Shutemov 			free_page_and_swap_cache(src_page);
722b46e756fSKirill A. Shutemov 		}
723b46e756fSKirill A. Shutemov 	}
7245503fbf2SKirill A. Shutemov 
7255503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
7265503fbf2SKirill A. Shutemov 		list_del(&src_page->lru);
7271baec203SMiaohe Lin 		mod_node_page_state(page_pgdat(src_page),
7281baec203SMiaohe Lin 				    NR_ISOLATED_ANON + page_is_file_lru(src_page),
7291baec203SMiaohe Lin 				    -compound_nr(src_page));
7301baec203SMiaohe Lin 		unlock_page(src_page);
7311baec203SMiaohe Lin 		free_swap_cache(src_page);
7321baec203SMiaohe Lin 		putback_lru_page(src_page);
7335503fbf2SKirill A. Shutemov 	}
734b46e756fSKirill A. Shutemov }
735b46e756fSKirill A. Shutemov 
736b46e756fSKirill A. Shutemov static void khugepaged_alloc_sleep(void)
737b46e756fSKirill A. Shutemov {
738b46e756fSKirill A. Shutemov 	DEFINE_WAIT(wait);
739b46e756fSKirill A. Shutemov 
740b46e756fSKirill A. Shutemov 	add_wait_queue(&khugepaged_wait, &wait);
741b46e756fSKirill A. Shutemov 	freezable_schedule_timeout_interruptible(
742b46e756fSKirill A. Shutemov 		msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
743b46e756fSKirill A. Shutemov 	remove_wait_queue(&khugepaged_wait, &wait);
744b46e756fSKirill A. Shutemov }
745b46e756fSKirill A. Shutemov 
746b46e756fSKirill A. Shutemov 
74734d6b470SZach O'Keefe struct collapse_control khugepaged_collapse_control = {
74834d6b470SZach O'Keefe 	.last_target_node = NUMA_NO_NODE,
74934d6b470SZach O'Keefe };
75034d6b470SZach O'Keefe 
75134d6b470SZach O'Keefe static bool khugepaged_scan_abort(int nid, struct collapse_control *cc)
752b46e756fSKirill A. Shutemov {
753b46e756fSKirill A. Shutemov 	int i;
754b46e756fSKirill A. Shutemov 
755b46e756fSKirill A. Shutemov 	/*
756a5f5f91dSMel Gorman 	 * If node_reclaim_mode is disabled, then no extra effort is made to
757b46e756fSKirill A. Shutemov 	 * allocate memory locally.
758b46e756fSKirill A. Shutemov 	 */
759202e35dbSDave Hansen 	if (!node_reclaim_enabled())
760b46e756fSKirill A. Shutemov 		return false;
761b46e756fSKirill A. Shutemov 
762b46e756fSKirill A. Shutemov 	/* If there is a count for this node already, it must be acceptable */
76334d6b470SZach O'Keefe 	if (cc->node_load[nid])
764b46e756fSKirill A. Shutemov 		return false;
765b46e756fSKirill A. Shutemov 
766b46e756fSKirill A. Shutemov 	for (i = 0; i < MAX_NUMNODES; i++) {
76734d6b470SZach O'Keefe 		if (!cc->node_load[i])
768b46e756fSKirill A. Shutemov 			continue;
769a55c7454SMatt Fleming 		if (node_distance(nid, i) > node_reclaim_distance)
770b46e756fSKirill A. Shutemov 			return true;
771b46e756fSKirill A. Shutemov 	}
772b46e756fSKirill A. Shutemov 	return false;
773b46e756fSKirill A. Shutemov }
774b46e756fSKirill A. Shutemov 
7751064026bSYang Shi #define khugepaged_defrag()					\
7761064026bSYang Shi 	(transparent_hugepage_flags &				\
7771064026bSYang Shi 	 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
7781064026bSYang Shi 
779b46e756fSKirill A. Shutemov /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
780b46e756fSKirill A. Shutemov static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
781b46e756fSKirill A. Shutemov {
78225160354SVlastimil Babka 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
783b46e756fSKirill A. Shutemov }
784b46e756fSKirill A. Shutemov 
785b46e756fSKirill A. Shutemov #ifdef CONFIG_NUMA
78634d6b470SZach O'Keefe static int khugepaged_find_target_node(struct collapse_control *cc)
787b46e756fSKirill A. Shutemov {
788b46e756fSKirill A. Shutemov 	int nid, target_node = 0, max_value = 0;
789b46e756fSKirill A. Shutemov 
790b46e756fSKirill A. Shutemov 	/* find first node with max normal pages hit */
791b46e756fSKirill A. Shutemov 	for (nid = 0; nid < MAX_NUMNODES; nid++)
79234d6b470SZach O'Keefe 		if (cc->node_load[nid] > max_value) {
79334d6b470SZach O'Keefe 			max_value = cc->node_load[nid];
794b46e756fSKirill A. Shutemov 			target_node = nid;
795b46e756fSKirill A. Shutemov 		}
796b46e756fSKirill A. Shutemov 
797b46e756fSKirill A. Shutemov 	/* do some balance if several nodes have the same hit record */
79834d6b470SZach O'Keefe 	if (target_node <= cc->last_target_node)
79934d6b470SZach O'Keefe 		for (nid = cc->last_target_node + 1; nid < MAX_NUMNODES;
800b46e756fSKirill A. Shutemov 		     nid++)
80134d6b470SZach O'Keefe 			if (max_value == cc->node_load[nid]) {
802b46e756fSKirill A. Shutemov 				target_node = nid;
803b46e756fSKirill A. Shutemov 				break;
804b46e756fSKirill A. Shutemov 			}
805b46e756fSKirill A. Shutemov 
80634d6b470SZach O'Keefe 	cc->last_target_node = target_node;
807b46e756fSKirill A. Shutemov 	return target_node;
808b46e756fSKirill A. Shutemov }
809c6a7f445SYang Shi #else
81034d6b470SZach O'Keefe static int khugepaged_find_target_node(struct collapse_control *cc)
811b46e756fSKirill A. Shutemov {
812c6a7f445SYang Shi 	return 0;
813b46e756fSKirill A. Shutemov }
814c6a7f445SYang Shi #endif
815b46e756fSKirill A. Shutemov 
816*9710a78aSZach O'Keefe static bool khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
817b46e756fSKirill A. Shutemov {
818b46e756fSKirill A. Shutemov 	*hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
819b46e756fSKirill A. Shutemov 	if (unlikely(!*hpage)) {
820b46e756fSKirill A. Shutemov 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
821b46e756fSKirill A. Shutemov 		*hpage = ERR_PTR(-ENOMEM);
822*9710a78aSZach O'Keefe 		return false;
823b46e756fSKirill A. Shutemov 	}
824b46e756fSKirill A. Shutemov 
825b46e756fSKirill A. Shutemov 	prep_transhuge_page(*hpage);
826b46e756fSKirill A. Shutemov 	count_vm_event(THP_COLLAPSE_ALLOC);
827*9710a78aSZach O'Keefe 	return true;
828b46e756fSKirill A. Shutemov }
829b46e756fSKirill A. Shutemov 
830b46e756fSKirill A. Shutemov /*
831c1e8d7c6SMichel Lespinasse  * If mmap_lock temporarily dropped, revalidate vma
832c1e8d7c6SMichel Lespinasse  * before taking mmap_lock.
833b46e756fSKirill A. Shutemov  * Return 0 if succeeds, otherwise return none-zero
834b46e756fSKirill A. Shutemov  * value (scan code).
835b46e756fSKirill A. Shutemov  */
836b46e756fSKirill A. Shutemov 
837c131f751SKirill A. Shutemov static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
838c131f751SKirill A. Shutemov 		struct vm_area_struct **vmap)
839b46e756fSKirill A. Shutemov {
840b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
841b46e756fSKirill A. Shutemov 
842b46e756fSKirill A. Shutemov 	if (unlikely(khugepaged_test_exit(mm)))
843b46e756fSKirill A. Shutemov 		return SCAN_ANY_PROCESS;
844b46e756fSKirill A. Shutemov 
845c131f751SKirill A. Shutemov 	*vmap = vma = find_vma(mm, address);
846b46e756fSKirill A. Shutemov 	if (!vma)
847b46e756fSKirill A. Shutemov 		return SCAN_VMA_NULL;
848b46e756fSKirill A. Shutemov 
8494fa6893fSYang Shi 	if (!transhuge_vma_suitable(vma, address))
850b46e756fSKirill A. Shutemov 		return SCAN_ADDRESS_RANGE;
8517da4e2cbSYang Shi 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false))
852b46e756fSKirill A. Shutemov 		return SCAN_VMA_CHECK;
853f707fa49SYang Shi 	/*
854f707fa49SYang Shi 	 * Anon VMA expected, the address may be unmapped then
855f707fa49SYang Shi 	 * remapped to file after khugepaged reaquired the mmap_lock.
856f707fa49SYang Shi 	 *
857f707fa49SYang Shi 	 * hugepage_vma_check may return true for qualified file
858f707fa49SYang Shi 	 * vmas.
859f707fa49SYang Shi 	 */
86025fa414aSxu xin 	if (!vma->anon_vma || !vma_is_anonymous(vma))
861594cced1SKirill A. Shutemov 		return SCAN_VMA_CHECK;
862b46e756fSKirill A. Shutemov 	return 0;
863b46e756fSKirill A. Shutemov }
864b46e756fSKirill A. Shutemov 
865b46e756fSKirill A. Shutemov /*
866b46e756fSKirill A. Shutemov  * Bring missing pages in from swap, to complete THP collapse.
867b46e756fSKirill A. Shutemov  * Only done if khugepaged_scan_pmd believes it is worthwhile.
868b46e756fSKirill A. Shutemov  *
8694d928e20SMiaohe Lin  * Called and returns without pte mapped or spinlocks held.
8704d928e20SMiaohe Lin  * Note that if false is returned, mmap_lock will be released.
871b46e756fSKirill A. Shutemov  */
872b46e756fSKirill A. Shutemov 
873b46e756fSKirill A. Shutemov static bool __collapse_huge_page_swapin(struct mm_struct *mm,
874b46e756fSKirill A. Shutemov 					struct vm_area_struct *vma,
8752b635dd3SWill Deacon 					unsigned long haddr, pmd_t *pmd,
8760db501f7SEbru Akagunduz 					int referenced)
877b46e756fSKirill A. Shutemov {
8782b740303SSouptick Joarder 	int swapped_in = 0;
8792b740303SSouptick Joarder 	vm_fault_t ret = 0;
8802b635dd3SWill Deacon 	unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
8812b635dd3SWill Deacon 
8822b635dd3SWill Deacon 	for (address = haddr; address < end; address += PAGE_SIZE) {
88382b0f8c3SJan Kara 		struct vm_fault vmf = {
884b46e756fSKirill A. Shutemov 			.vma = vma,
885b46e756fSKirill A. Shutemov 			.address = address,
8862b635dd3SWill Deacon 			.pgoff = linear_page_index(vma, haddr),
887b46e756fSKirill A. Shutemov 			.flags = FAULT_FLAG_ALLOW_RETRY,
888b46e756fSKirill A. Shutemov 			.pmd = pmd,
889b46e756fSKirill A. Shutemov 		};
890b46e756fSKirill A. Shutemov 
89182b0f8c3SJan Kara 		vmf.pte = pte_offset_map(pmd, address);
8922994302bSJan Kara 		vmf.orig_pte = *vmf.pte;
8932b635dd3SWill Deacon 		if (!is_swap_pte(vmf.orig_pte)) {
8942b635dd3SWill Deacon 			pte_unmap(vmf.pte);
895b46e756fSKirill A. Shutemov 			continue;
8962b635dd3SWill Deacon 		}
8972994302bSJan Kara 		ret = do_swap_page(&vmf);
8980db501f7SEbru Akagunduz 
8994d928e20SMiaohe Lin 		/*
9004d928e20SMiaohe Lin 		 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
9014d928e20SMiaohe Lin 		 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
9024d928e20SMiaohe Lin 		 * we do not retry here and swap entry will remain in pagetable
9034d928e20SMiaohe Lin 		 * resulting in later failure.
9044d928e20SMiaohe Lin 		 */
905b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_RETRY) {
9060db501f7SEbru Akagunduz 			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
907b46e756fSKirill A. Shutemov 			return false;
90847f863eaSEbru Akagunduz 		}
909b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_ERROR) {
9104d928e20SMiaohe Lin 			mmap_read_unlock(mm);
9110db501f7SEbru Akagunduz 			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
912b46e756fSKirill A. Shutemov 			return false;
913b46e756fSKirill A. Shutemov 		}
9144d928e20SMiaohe Lin 		swapped_in++;
915b46e756fSKirill A. Shutemov 	}
916ae2c5d80SKirill A. Shutemov 
917ae2c5d80SKirill A. Shutemov 	/* Drain LRU add pagevec to remove extra pin on the swapped in pages */
918ae2c5d80SKirill A. Shutemov 	if (swapped_in)
919ae2c5d80SKirill A. Shutemov 		lru_add_drain();
920ae2c5d80SKirill A. Shutemov 
9210db501f7SEbru Akagunduz 	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
922b46e756fSKirill A. Shutemov 	return true;
923b46e756fSKirill A. Shutemov }
924b46e756fSKirill A. Shutemov 
925*9710a78aSZach O'Keefe static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
926*9710a78aSZach O'Keefe 			      struct collapse_control *cc)
927*9710a78aSZach O'Keefe {
928*9710a78aSZach O'Keefe 	/* Only allocate from the target node */
929*9710a78aSZach O'Keefe 	gfp_t gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
930*9710a78aSZach O'Keefe 	int node = khugepaged_find_target_node(cc);
931*9710a78aSZach O'Keefe 
932*9710a78aSZach O'Keefe 	if (!khugepaged_alloc_page(hpage, gfp, node))
933*9710a78aSZach O'Keefe 		return SCAN_ALLOC_HUGE_PAGE_FAIL;
934*9710a78aSZach O'Keefe 	if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
935*9710a78aSZach O'Keefe 		return SCAN_CGROUP_CHARGE_FAIL;
936*9710a78aSZach O'Keefe 	count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
937*9710a78aSZach O'Keefe 	return SCAN_SUCCEED;
938*9710a78aSZach O'Keefe }
939*9710a78aSZach O'Keefe 
940*9710a78aSZach O'Keefe static void collapse_huge_page(struct mm_struct *mm, unsigned long address,
941*9710a78aSZach O'Keefe 			       struct page **hpage, int referenced,
942*9710a78aSZach O'Keefe 			       int unmapped, struct collapse_control *cc)
943b46e756fSKirill A. Shutemov {
9445503fbf2SKirill A. Shutemov 	LIST_HEAD(compound_pagelist);
945b46e756fSKirill A. Shutemov 	pmd_t *pmd, _pmd;
946b46e756fSKirill A. Shutemov 	pte_t *pte;
947b46e756fSKirill A. Shutemov 	pgtable_t pgtable;
948b46e756fSKirill A. Shutemov 	struct page *new_page;
949b46e756fSKirill A. Shutemov 	spinlock_t *pmd_ptl, *pte_ptl;
950b46e756fSKirill A. Shutemov 	int isolated = 0, result = 0;
951c131f751SKirill A. Shutemov 	struct vm_area_struct *vma;
952ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
953b46e756fSKirill A. Shutemov 
954b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
955b46e756fSKirill A. Shutemov 
956988ddb71SKirill A. Shutemov 	/*
957c1e8d7c6SMichel Lespinasse 	 * Before allocating the hugepage, release the mmap_lock read lock.
958988ddb71SKirill A. Shutemov 	 * The allocation can take potentially a long time if it involves
959c1e8d7c6SMichel Lespinasse 	 * sync compaction, and we do not need to hold the mmap_lock during
960988ddb71SKirill A. Shutemov 	 * that. We will recheck the vma after taking it again in write mode.
961988ddb71SKirill A. Shutemov 	 */
962d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
963b46e756fSKirill A. Shutemov 
964*9710a78aSZach O'Keefe 	result = alloc_charge_hpage(hpage, mm, cc);
965*9710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
966b46e756fSKirill A. Shutemov 		goto out_nolock;
967*9710a78aSZach O'Keefe 
968*9710a78aSZach O'Keefe 	new_page = *hpage;
969b46e756fSKirill A. Shutemov 
970d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
971c131f751SKirill A. Shutemov 	result = hugepage_vma_revalidate(mm, address, &vma);
972b46e756fSKirill A. Shutemov 	if (result) {
973d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
974b46e756fSKirill A. Shutemov 		goto out_nolock;
975b46e756fSKirill A. Shutemov 	}
976b46e756fSKirill A. Shutemov 
977b46e756fSKirill A. Shutemov 	pmd = mm_find_pmd(mm, address);
978b46e756fSKirill A. Shutemov 	if (!pmd) {
979b46e756fSKirill A. Shutemov 		result = SCAN_PMD_NULL;
980d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
981b46e756fSKirill A. Shutemov 		goto out_nolock;
982b46e756fSKirill A. Shutemov 	}
983b46e756fSKirill A. Shutemov 
984b46e756fSKirill A. Shutemov 	/*
9854d928e20SMiaohe Lin 	 * __collapse_huge_page_swapin will return with mmap_lock released
9864d928e20SMiaohe Lin 	 * when it fails. So we jump out_nolock directly in that case.
987b46e756fSKirill A. Shutemov 	 * Continuing to collapse causes inconsistency.
988b46e756fSKirill A. Shutemov 	 */
989ffe945e6SKirill A. Shutemov 	if (unmapped && !__collapse_huge_page_swapin(mm, vma, address,
990ffe945e6SKirill A. Shutemov 						     pmd, referenced)) {
991b46e756fSKirill A. Shutemov 		goto out_nolock;
992b46e756fSKirill A. Shutemov 	}
993b46e756fSKirill A. Shutemov 
994d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
995b46e756fSKirill A. Shutemov 	/*
996b46e756fSKirill A. Shutemov 	 * Prevent all access to pagetables with the exception of
997b46e756fSKirill A. Shutemov 	 * gup_fast later handled by the ptep_clear_flush and the VM
998b46e756fSKirill A. Shutemov 	 * handled by the anon_vma lock + PG_lock.
999b46e756fSKirill A. Shutemov 	 */
1000d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
1001c131f751SKirill A. Shutemov 	result = hugepage_vma_revalidate(mm, address, &vma);
1002b46e756fSKirill A. Shutemov 	if (result)
100318d24a7cSMiaohe Lin 		goto out_up_write;
1004b46e756fSKirill A. Shutemov 	/* check if the pmd is still valid */
1005b46e756fSKirill A. Shutemov 	if (mm_find_pmd(mm, address) != pmd)
100618d24a7cSMiaohe Lin 		goto out_up_write;
1007b46e756fSKirill A. Shutemov 
1008b46e756fSKirill A. Shutemov 	anon_vma_lock_write(vma->anon_vma);
1009b46e756fSKirill A. Shutemov 
10107269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
10116f4f13e8SJérôme Glisse 				address, address + HPAGE_PMD_SIZE);
1012ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1013ec649c9dSVille Syrjälä 
1014ec649c9dSVille Syrjälä 	pte = pte_offset_map(pmd, address);
1015ec649c9dSVille Syrjälä 	pte_ptl = pte_lockptr(mm, pmd);
1016ec649c9dSVille Syrjälä 
1017b46e756fSKirill A. Shutemov 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1018b46e756fSKirill A. Shutemov 	/*
1019b46e756fSKirill A. Shutemov 	 * After this gup_fast can't run anymore. This also removes
1020b46e756fSKirill A. Shutemov 	 * any huge TLB entry from the CPU so we won't allow
1021b46e756fSKirill A. Shutemov 	 * huge and small TLB entries for the same virtual address
1022b46e756fSKirill A. Shutemov 	 * to avoid the risk of CPU bugs in that area.
1023b46e756fSKirill A. Shutemov 	 */
1024b46e756fSKirill A. Shutemov 	_pmd = pmdp_collapse_flush(vma, address, pmd);
1025b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1026ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
1027b46e756fSKirill A. Shutemov 
1028b46e756fSKirill A. Shutemov 	spin_lock(pte_ptl);
10295503fbf2SKirill A. Shutemov 	isolated = __collapse_huge_page_isolate(vma, address, pte,
10305503fbf2SKirill A. Shutemov 			&compound_pagelist);
1031b46e756fSKirill A. Shutemov 	spin_unlock(pte_ptl);
1032b46e756fSKirill A. Shutemov 
1033b46e756fSKirill A. Shutemov 	if (unlikely(!isolated)) {
1034b46e756fSKirill A. Shutemov 		pte_unmap(pte);
1035b46e756fSKirill A. Shutemov 		spin_lock(pmd_ptl);
1036b46e756fSKirill A. Shutemov 		BUG_ON(!pmd_none(*pmd));
1037b46e756fSKirill A. Shutemov 		/*
1038b46e756fSKirill A. Shutemov 		 * We can only use set_pmd_at when establishing
1039b46e756fSKirill A. Shutemov 		 * hugepmds and never for establishing regular pmds that
1040b46e756fSKirill A. Shutemov 		 * points to regular pagetables. Use pmd_populate for that
1041b46e756fSKirill A. Shutemov 		 */
1042b46e756fSKirill A. Shutemov 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1043b46e756fSKirill A. Shutemov 		spin_unlock(pmd_ptl);
1044b46e756fSKirill A. Shutemov 		anon_vma_unlock_write(vma->anon_vma);
1045b46e756fSKirill A. Shutemov 		result = SCAN_FAIL;
104618d24a7cSMiaohe Lin 		goto out_up_write;
1047b46e756fSKirill A. Shutemov 	}
1048b46e756fSKirill A. Shutemov 
1049b46e756fSKirill A. Shutemov 	/*
1050b46e756fSKirill A. Shutemov 	 * All pages are isolated and locked so anon_vma rmap
1051b46e756fSKirill A. Shutemov 	 * can't run anymore.
1052b46e756fSKirill A. Shutemov 	 */
1053b46e756fSKirill A. Shutemov 	anon_vma_unlock_write(vma->anon_vma);
1054b46e756fSKirill A. Shutemov 
10555503fbf2SKirill A. Shutemov 	__collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl,
10565503fbf2SKirill A. Shutemov 			&compound_pagelist);
1057b46e756fSKirill A. Shutemov 	pte_unmap(pte);
1058588d01f9SMiaohe Lin 	/*
1059588d01f9SMiaohe Lin 	 * spin_lock() below is not the equivalent of smp_wmb(), but
1060588d01f9SMiaohe Lin 	 * the smp_wmb() inside __SetPageUptodate() can be reused to
1061588d01f9SMiaohe Lin 	 * avoid the copy_huge_page writes to become visible after
1062588d01f9SMiaohe Lin 	 * the set_pmd_at() write.
1063588d01f9SMiaohe Lin 	 */
1064b46e756fSKirill A. Shutemov 	__SetPageUptodate(new_page);
1065b46e756fSKirill A. Shutemov 	pgtable = pmd_pgtable(_pmd);
1066b46e756fSKirill A. Shutemov 
1067b46e756fSKirill A. Shutemov 	_pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1068f55e1014SLinus Torvalds 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1069b46e756fSKirill A. Shutemov 
1070b46e756fSKirill A. Shutemov 	spin_lock(pmd_ptl);
1071b46e756fSKirill A. Shutemov 	BUG_ON(!pmd_none(*pmd));
107240f2bbf7SDavid Hildenbrand 	page_add_new_anon_rmap(new_page, vma, address);
1073b518154eSJoonsoo Kim 	lru_cache_add_inactive_or_unevictable(new_page, vma);
1074b46e756fSKirill A. Shutemov 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1075b46e756fSKirill A. Shutemov 	set_pmd_at(mm, address, pmd, _pmd);
1076b46e756fSKirill A. Shutemov 	update_mmu_cache_pmd(vma, address, pmd);
1077b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1078b46e756fSKirill A. Shutemov 
1079b46e756fSKirill A. Shutemov 	*hpage = NULL;
1080b46e756fSKirill A. Shutemov 
1081b46e756fSKirill A. Shutemov 	khugepaged_pages_collapsed++;
1082b46e756fSKirill A. Shutemov 	result = SCAN_SUCCEED;
1083b46e756fSKirill A. Shutemov out_up_write:
1084d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1085b46e756fSKirill A. Shutemov out_nolock:
1086c6a7f445SYang Shi 	if (!IS_ERR_OR_NULL(*hpage)) {
1087bbc6b703SMatthew Wilcox (Oracle) 		mem_cgroup_uncharge(page_folio(*hpage));
1088c6a7f445SYang Shi 		put_page(*hpage);
1089c6a7f445SYang Shi 	}
1090b46e756fSKirill A. Shutemov 	trace_mm_collapse_huge_page(mm, isolated, result);
1091b46e756fSKirill A. Shutemov 	return;
1092b46e756fSKirill A. Shutemov }
1093b46e756fSKirill A. Shutemov 
109434d6b470SZach O'Keefe static int khugepaged_scan_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
109534d6b470SZach O'Keefe 			       unsigned long address, struct page **hpage,
109634d6b470SZach O'Keefe 			       struct collapse_control *cc)
1097b46e756fSKirill A. Shutemov {
1098b46e756fSKirill A. Shutemov 	pmd_t *pmd;
1099b46e756fSKirill A. Shutemov 	pte_t *pte, *_pte;
110071a2c112SKirill A. Shutemov 	int ret = 0, result = 0, referenced = 0;
110171a2c112SKirill A. Shutemov 	int none_or_zero = 0, shared = 0;
1102b46e756fSKirill A. Shutemov 	struct page *page = NULL;
1103b46e756fSKirill A. Shutemov 	unsigned long _address;
1104b46e756fSKirill A. Shutemov 	spinlock_t *ptl;
1105b46e756fSKirill A. Shutemov 	int node = NUMA_NO_NODE, unmapped = 0;
11060db501f7SEbru Akagunduz 	bool writable = false;
1107b46e756fSKirill A. Shutemov 
1108b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1109b46e756fSKirill A. Shutemov 
1110b46e756fSKirill A. Shutemov 	pmd = mm_find_pmd(mm, address);
1111b46e756fSKirill A. Shutemov 	if (!pmd) {
1112b46e756fSKirill A. Shutemov 		result = SCAN_PMD_NULL;
1113b46e756fSKirill A. Shutemov 		goto out;
1114b46e756fSKirill A. Shutemov 	}
1115b46e756fSKirill A. Shutemov 
111634d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1117b46e756fSKirill A. Shutemov 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1118b46e756fSKirill A. Shutemov 	for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1119b46e756fSKirill A. Shutemov 	     _pte++, _address += PAGE_SIZE) {
1120b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
1121b46e756fSKirill A. Shutemov 		if (is_swap_pte(pteval)) {
1122b46e756fSKirill A. Shutemov 			if (++unmapped <= khugepaged_max_ptes_swap) {
1123e1e267c7SPeter Xu 				/*
1124e1e267c7SPeter Xu 				 * Always be strict with uffd-wp
1125e1e267c7SPeter Xu 				 * enabled swap entries.  Please see
1126e1e267c7SPeter Xu 				 * comment below for pte_uffd_wp().
1127e1e267c7SPeter Xu 				 */
1128e1e267c7SPeter Xu 				if (pte_swp_uffd_wp(pteval)) {
1129e1e267c7SPeter Xu 					result = SCAN_PTE_UFFD_WP;
1130e1e267c7SPeter Xu 					goto out_unmap;
1131e1e267c7SPeter Xu 				}
1132b46e756fSKirill A. Shutemov 				continue;
1133b46e756fSKirill A. Shutemov 			} else {
1134b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1135e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1136b46e756fSKirill A. Shutemov 				goto out_unmap;
1137b46e756fSKirill A. Shutemov 			}
1138b46e756fSKirill A. Shutemov 		}
1139b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1140b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
1141b46e756fSKirill A. Shutemov 			    ++none_or_zero <= khugepaged_max_ptes_none) {
1142b46e756fSKirill A. Shutemov 				continue;
1143b46e756fSKirill A. Shutemov 			} else {
1144b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
1145e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1146b46e756fSKirill A. Shutemov 				goto out_unmap;
1147b46e756fSKirill A. Shutemov 			}
1148b46e756fSKirill A. Shutemov 		}
1149e1e267c7SPeter Xu 		if (pte_uffd_wp(pteval)) {
1150e1e267c7SPeter Xu 			/*
1151e1e267c7SPeter Xu 			 * Don't collapse the page if any of the small
1152e1e267c7SPeter Xu 			 * PTEs are armed with uffd write protection.
1153e1e267c7SPeter Xu 			 * Here we can also mark the new huge pmd as
1154e1e267c7SPeter Xu 			 * write protected if any of the small ones is
11558958b249SHaitao Shi 			 * marked but that could bring unknown
1156e1e267c7SPeter Xu 			 * userfault messages that falls outside of
1157e1e267c7SPeter Xu 			 * the registered range.  So, just be simple.
1158e1e267c7SPeter Xu 			 */
1159e1e267c7SPeter Xu 			result = SCAN_PTE_UFFD_WP;
1160e1e267c7SPeter Xu 			goto out_unmap;
1161e1e267c7SPeter Xu 		}
1162b46e756fSKirill A. Shutemov 		if (pte_write(pteval))
1163b46e756fSKirill A. Shutemov 			writable = true;
1164b46e756fSKirill A. Shutemov 
1165b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, _address, pteval);
11663218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1167b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
1168b46e756fSKirill A. Shutemov 			goto out_unmap;
1169b46e756fSKirill A. Shutemov 		}
1170b46e756fSKirill A. Shutemov 
117171a2c112SKirill A. Shutemov 		if (page_mapcount(page) > 1 &&
117271a2c112SKirill A. Shutemov 				++shared > khugepaged_max_ptes_shared) {
117371a2c112SKirill A. Shutemov 			result = SCAN_EXCEED_SHARED_PTE;
1174e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
117571a2c112SKirill A. Shutemov 			goto out_unmap;
117671a2c112SKirill A. Shutemov 		}
117771a2c112SKirill A. Shutemov 
11785503fbf2SKirill A. Shutemov 		page = compound_head(page);
1179b46e756fSKirill A. Shutemov 
1180b46e756fSKirill A. Shutemov 		/*
1181b46e756fSKirill A. Shutemov 		 * Record which node the original page is from and save this
118234d6b470SZach O'Keefe 		 * information to cc->node_load[].
11830b8f0d87SQuanfa Fu 		 * Khugepaged will allocate hugepage from the node has the max
1184b46e756fSKirill A. Shutemov 		 * hit record.
1185b46e756fSKirill A. Shutemov 		 */
1186b46e756fSKirill A. Shutemov 		node = page_to_nid(page);
118734d6b470SZach O'Keefe 		if (khugepaged_scan_abort(node, cc)) {
1188b46e756fSKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1189b46e756fSKirill A. Shutemov 			goto out_unmap;
1190b46e756fSKirill A. Shutemov 		}
119134d6b470SZach O'Keefe 		cc->node_load[node]++;
1192b46e756fSKirill A. Shutemov 		if (!PageLRU(page)) {
1193b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1194b46e756fSKirill A. Shutemov 			goto out_unmap;
1195b46e756fSKirill A. Shutemov 		}
1196b46e756fSKirill A. Shutemov 		if (PageLocked(page)) {
1197b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
1198b46e756fSKirill A. Shutemov 			goto out_unmap;
1199b46e756fSKirill A. Shutemov 		}
1200b46e756fSKirill A. Shutemov 		if (!PageAnon(page)) {
1201b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_ANON;
1202b46e756fSKirill A. Shutemov 			goto out_unmap;
1203b46e756fSKirill A. Shutemov 		}
1204b46e756fSKirill A. Shutemov 
1205b46e756fSKirill A. Shutemov 		/*
12069445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
12079445689fSKirill A. Shutemov 		 *
120836ee2c78SMiaohe Lin 		 * Here the check is racy it may see total_mapcount > refcount
12099445689fSKirill A. Shutemov 		 * in some cases.
12109445689fSKirill A. Shutemov 		 * For example, one process with one forked child process.
12119445689fSKirill A. Shutemov 		 * The parent has the PMD split due to MADV_DONTNEED, then
12129445689fSKirill A. Shutemov 		 * the child is trying unmap the whole PMD, but khugepaged
12139445689fSKirill A. Shutemov 		 * may be scanning the parent between the child has
12149445689fSKirill A. Shutemov 		 * PageDoubleMap flag cleared and dec the mapcount.  So
12159445689fSKirill A. Shutemov 		 * khugepaged may see total_mapcount > refcount.
12169445689fSKirill A. Shutemov 		 *
12179445689fSKirill A. Shutemov 		 * But such case is ephemeral we could always retry collapse
12189445689fSKirill A. Shutemov 		 * later.  However it may report false positive if the page
12199445689fSKirill A. Shutemov 		 * has excessive GUP pins (i.e. 512).  Anyway the same check
12209445689fSKirill A. Shutemov 		 * will be done again later the risk seems low.
1221b46e756fSKirill A. Shutemov 		 */
12229445689fSKirill A. Shutemov 		if (!is_refcount_suitable(page)) {
1223b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1224b46e756fSKirill A. Shutemov 			goto out_unmap;
1225b46e756fSKirill A. Shutemov 		}
1226b46e756fSKirill A. Shutemov 		if (pte_young(pteval) ||
1227b46e756fSKirill A. Shutemov 		    page_is_young(page) || PageReferenced(page) ||
1228b46e756fSKirill A. Shutemov 		    mmu_notifier_test_young(vma->vm_mm, address))
12290db501f7SEbru Akagunduz 			referenced++;
1230b46e756fSKirill A. Shutemov 	}
1231ffe945e6SKirill A. Shutemov 	if (!writable) {
1232ffe945e6SKirill A. Shutemov 		result = SCAN_PAGE_RO;
1233ffe945e6SKirill A. Shutemov 	} else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
1234ffe945e6SKirill A. Shutemov 		result = SCAN_LACK_REFERENCED_PAGE;
1235ffe945e6SKirill A. Shutemov 	} else {
1236b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
1237b46e756fSKirill A. Shutemov 		ret = 1;
1238b46e756fSKirill A. Shutemov 	}
1239b46e756fSKirill A. Shutemov out_unmap:
1240b46e756fSKirill A. Shutemov 	pte_unmap_unlock(pte, ptl);
1241b46e756fSKirill A. Shutemov 	if (ret) {
1242c1e8d7c6SMichel Lespinasse 		/* collapse_huge_page will return with the mmap_lock released */
1243*9710a78aSZach O'Keefe 		collapse_huge_page(mm, address, hpage, referenced, unmapped,
1244*9710a78aSZach O'Keefe 				   cc);
1245b46e756fSKirill A. Shutemov 	}
1246b46e756fSKirill A. Shutemov out:
1247b46e756fSKirill A. Shutemov 	trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1248b46e756fSKirill A. Shutemov 				     none_or_zero, result, unmapped);
1249b46e756fSKirill A. Shutemov 	return ret;
1250b46e756fSKirill A. Shutemov }
1251b46e756fSKirill A. Shutemov 
1252b46e756fSKirill A. Shutemov static void collect_mm_slot(struct mm_slot *mm_slot)
1253b46e756fSKirill A. Shutemov {
1254b46e756fSKirill A. Shutemov 	struct mm_struct *mm = mm_slot->mm;
1255b46e756fSKirill A. Shutemov 
125635f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1257b46e756fSKirill A. Shutemov 
1258b46e756fSKirill A. Shutemov 	if (khugepaged_test_exit(mm)) {
1259b46e756fSKirill A. Shutemov 		/* free mm_slot */
1260b46e756fSKirill A. Shutemov 		hash_del(&mm_slot->hash);
1261b46e756fSKirill A. Shutemov 		list_del(&mm_slot->mm_node);
1262b46e756fSKirill A. Shutemov 
1263b46e756fSKirill A. Shutemov 		/*
1264b46e756fSKirill A. Shutemov 		 * Not strictly needed because the mm exited already.
1265b46e756fSKirill A. Shutemov 		 *
1266b46e756fSKirill A. Shutemov 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1267b46e756fSKirill A. Shutemov 		 */
1268b46e756fSKirill A. Shutemov 
1269b46e756fSKirill A. Shutemov 		/* khugepaged_mm_lock actually not necessary for the below */
1270b46e756fSKirill A. Shutemov 		free_mm_slot(mm_slot);
1271b46e756fSKirill A. Shutemov 		mmdrop(mm);
1272b46e756fSKirill A. Shutemov 	}
1273b46e756fSKirill A. Shutemov }
1274b46e756fSKirill A. Shutemov 
1275396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_SHMEM
127627e1f827SSong Liu /*
127727e1f827SSong Liu  * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
127827e1f827SSong Liu  * khugepaged should try to collapse the page table.
127927e1f827SSong Liu  */
1280081c3256SMiaohe Lin static void khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
128127e1f827SSong Liu 					  unsigned long addr)
128227e1f827SSong Liu {
128327e1f827SSong Liu 	struct mm_slot *mm_slot;
128427e1f827SSong Liu 
128527e1f827SSong Liu 	VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
128627e1f827SSong Liu 
128727e1f827SSong Liu 	spin_lock(&khugepaged_mm_lock);
128827e1f827SSong Liu 	mm_slot = get_mm_slot(mm);
128927e1f827SSong Liu 	if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
129027e1f827SSong Liu 		mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
129127e1f827SSong Liu 	spin_unlock(&khugepaged_mm_lock);
129227e1f827SSong Liu }
129327e1f827SSong Liu 
1294e59a47b8SPasha Tatashin static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1295e59a47b8SPasha Tatashin 				  unsigned long addr, pmd_t *pmdp)
1296e59a47b8SPasha Tatashin {
1297e59a47b8SPasha Tatashin 	spinlock_t *ptl;
1298e59a47b8SPasha Tatashin 	pmd_t pmd;
1299e59a47b8SPasha Tatashin 
130080110bbfSPasha Tatashin 	mmap_assert_write_locked(mm);
1301e59a47b8SPasha Tatashin 	ptl = pmd_lock(vma->vm_mm, pmdp);
1302e59a47b8SPasha Tatashin 	pmd = pmdp_collapse_flush(vma, addr, pmdp);
1303e59a47b8SPasha Tatashin 	spin_unlock(ptl);
1304e59a47b8SPasha Tatashin 	mm_dec_nr_ptes(mm);
130580110bbfSPasha Tatashin 	page_table_check_pte_clear_range(mm, addr, pmd);
1306e59a47b8SPasha Tatashin 	pte_free(mm, pmd_pgtable(pmd));
1307e59a47b8SPasha Tatashin }
1308e59a47b8SPasha Tatashin 
130927e1f827SSong Liu /**
1310336e6b53SAlex Shi  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1311336e6b53SAlex Shi  * address haddr.
1312336e6b53SAlex Shi  *
1313336e6b53SAlex Shi  * @mm: process address space where collapse happens
1314336e6b53SAlex Shi  * @addr: THP collapse address
131527e1f827SSong Liu  *
131627e1f827SSong Liu  * This function checks whether all the PTEs in the PMD are pointing to the
131727e1f827SSong Liu  * right THP. If so, retract the page table so the THP can refault in with
131827e1f827SSong Liu  * as pmd-mapped.
131927e1f827SSong Liu  */
132027e1f827SSong Liu void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
132127e1f827SSong Liu {
132227e1f827SSong Liu 	unsigned long haddr = addr & HPAGE_PMD_MASK;
132327e1f827SSong Liu 	struct vm_area_struct *vma = find_vma(mm, haddr);
1324119a5fc1SHugh Dickins 	struct page *hpage;
132527e1f827SSong Liu 	pte_t *start_pte, *pte;
1326e59a47b8SPasha Tatashin 	pmd_t *pmd;
132727e1f827SSong Liu 	spinlock_t *ptl;
132827e1f827SSong Liu 	int count = 0;
132927e1f827SSong Liu 	int i;
133027e1f827SSong Liu 
133127e1f827SSong Liu 	if (!vma || !vma->vm_file ||
1332fef792a4SMiaohe Lin 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
133327e1f827SSong Liu 		return;
133427e1f827SSong Liu 
133527e1f827SSong Liu 	/*
133627e1f827SSong Liu 	 * This vm_flags may not have VM_HUGEPAGE if the page was not
133727e1f827SSong Liu 	 * collapsed by this mm. But we can still collapse if the page is
133827e1f827SSong Liu 	 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
133927e1f827SSong Liu 	 * will not fail the vma for missing VM_HUGEPAGE
134027e1f827SSong Liu 	 */
13417da4e2cbSYang Shi 	if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE, false, false))
134227e1f827SSong Liu 		return;
134327e1f827SSong Liu 
1344deb4c93aSPeter Xu 	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1345deb4c93aSPeter Xu 	if (userfaultfd_wp(vma))
1346deb4c93aSPeter Xu 		return;
1347deb4c93aSPeter Xu 
1348119a5fc1SHugh Dickins 	hpage = find_lock_page(vma->vm_file->f_mapping,
1349119a5fc1SHugh Dickins 			       linear_page_index(vma, haddr));
1350119a5fc1SHugh Dickins 	if (!hpage)
1351119a5fc1SHugh Dickins 		return;
1352119a5fc1SHugh Dickins 
1353119a5fc1SHugh Dickins 	if (!PageHead(hpage))
1354119a5fc1SHugh Dickins 		goto drop_hpage;
1355119a5fc1SHugh Dickins 
135627e1f827SSong Liu 	pmd = mm_find_pmd(mm, haddr);
135727e1f827SSong Liu 	if (!pmd)
1358119a5fc1SHugh Dickins 		goto drop_hpage;
135927e1f827SSong Liu 
136027e1f827SSong Liu 	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
136127e1f827SSong Liu 
136227e1f827SSong Liu 	/* step 1: check all mapped PTEs are to the right huge page */
136327e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
136427e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
136527e1f827SSong Liu 		struct page *page;
136627e1f827SSong Liu 
136727e1f827SSong Liu 		/* empty pte, skip */
136827e1f827SSong Liu 		if (pte_none(*pte))
136927e1f827SSong Liu 			continue;
137027e1f827SSong Liu 
137127e1f827SSong Liu 		/* page swapped out, abort */
137227e1f827SSong Liu 		if (!pte_present(*pte))
137327e1f827SSong Liu 			goto abort;
137427e1f827SSong Liu 
137527e1f827SSong Liu 		page = vm_normal_page(vma, addr, *pte);
13763218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
13773218f871SAlex Sierra 			page = NULL;
137827e1f827SSong Liu 		/*
1379119a5fc1SHugh Dickins 		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1380119a5fc1SHugh Dickins 		 * page table, but the new page will not be a subpage of hpage.
138127e1f827SSong Liu 		 */
1382119a5fc1SHugh Dickins 		if (hpage + i != page)
138327e1f827SSong Liu 			goto abort;
138427e1f827SSong Liu 		count++;
138527e1f827SSong Liu 	}
138627e1f827SSong Liu 
138727e1f827SSong Liu 	/* step 2: adjust rmap */
138827e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
138927e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
139027e1f827SSong Liu 		struct page *page;
139127e1f827SSong Liu 
139227e1f827SSong Liu 		if (pte_none(*pte))
139327e1f827SSong Liu 			continue;
139427e1f827SSong Liu 		page = vm_normal_page(vma, addr, *pte);
13953218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
13963218f871SAlex Sierra 			goto abort;
1397cea86fe2SHugh Dickins 		page_remove_rmap(page, vma, false);
139827e1f827SSong Liu 	}
139927e1f827SSong Liu 
140027e1f827SSong Liu 	pte_unmap_unlock(start_pte, ptl);
140127e1f827SSong Liu 
140227e1f827SSong Liu 	/* step 3: set proper refcount and mm_counters. */
1403119a5fc1SHugh Dickins 	if (count) {
140427e1f827SSong Liu 		page_ref_sub(hpage, count);
140527e1f827SSong Liu 		add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
140627e1f827SSong Liu 	}
140727e1f827SSong Liu 
140827e1f827SSong Liu 	/* step 4: collapse pmd */
1409e59a47b8SPasha Tatashin 	collapse_and_free_pmd(mm, vma, haddr, pmd);
1410119a5fc1SHugh Dickins drop_hpage:
1411119a5fc1SHugh Dickins 	unlock_page(hpage);
1412119a5fc1SHugh Dickins 	put_page(hpage);
141327e1f827SSong Liu 	return;
141427e1f827SSong Liu 
141527e1f827SSong Liu abort:
141627e1f827SSong Liu 	pte_unmap_unlock(start_pte, ptl);
1417119a5fc1SHugh Dickins 	goto drop_hpage;
141827e1f827SSong Liu }
141927e1f827SSong Liu 
14200edf61e5SMiaohe Lin static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
142127e1f827SSong Liu {
142227e1f827SSong Liu 	struct mm_struct *mm = mm_slot->mm;
142327e1f827SSong Liu 	int i;
142427e1f827SSong Liu 
142527e1f827SSong Liu 	if (likely(mm_slot->nr_pte_mapped_thp == 0))
14260edf61e5SMiaohe Lin 		return;
142727e1f827SSong Liu 
1428d8ed45c5SMichel Lespinasse 	if (!mmap_write_trylock(mm))
14290edf61e5SMiaohe Lin 		return;
143027e1f827SSong Liu 
143127e1f827SSong Liu 	if (unlikely(khugepaged_test_exit(mm)))
143227e1f827SSong Liu 		goto out;
143327e1f827SSong Liu 
143427e1f827SSong Liu 	for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
143527e1f827SSong Liu 		collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
143627e1f827SSong Liu 
143727e1f827SSong Liu out:
143827e1f827SSong Liu 	mm_slot->nr_pte_mapped_thp = 0;
1439d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
144027e1f827SSong Liu }
144127e1f827SSong Liu 
1442f3f0e1d2SKirill A. Shutemov static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1443f3f0e1d2SKirill A. Shutemov {
1444f3f0e1d2SKirill A. Shutemov 	struct vm_area_struct *vma;
144518e77600SHugh Dickins 	struct mm_struct *mm;
1446f3f0e1d2SKirill A. Shutemov 	unsigned long addr;
1447e59a47b8SPasha Tatashin 	pmd_t *pmd;
1448f3f0e1d2SKirill A. Shutemov 
1449f3f0e1d2SKirill A. Shutemov 	i_mmap_lock_write(mapping);
1450f3f0e1d2SKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
145127e1f827SSong Liu 		/*
145227e1f827SSong Liu 		 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
145327e1f827SSong Liu 		 * got written to. These VMAs are likely not worth investing
14543e4e28c5SMichel Lespinasse 		 * mmap_write_lock(mm) as PMD-mapping is likely to be split
145527e1f827SSong Liu 		 * later.
145627e1f827SSong Liu 		 *
145736ee2c78SMiaohe Lin 		 * Note that vma->anon_vma check is racy: it can be set up after
1458c1e8d7c6SMichel Lespinasse 		 * the check but before we took mmap_lock by the fault path.
145927e1f827SSong Liu 		 * But page lock would prevent establishing any new ptes of the
146027e1f827SSong Liu 		 * page, so we are safe.
146127e1f827SSong Liu 		 *
146227e1f827SSong Liu 		 * An alternative would be drop the check, but check that page
146327e1f827SSong Liu 		 * table is clear before calling pmdp_collapse_flush() under
146427e1f827SSong Liu 		 * ptl. It has higher chance to recover THP for the VMA, but
146527e1f827SSong Liu 		 * has higher cost too.
146627e1f827SSong Liu 		 */
1467f3f0e1d2SKirill A. Shutemov 		if (vma->anon_vma)
1468f3f0e1d2SKirill A. Shutemov 			continue;
1469f3f0e1d2SKirill A. Shutemov 		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1470f3f0e1d2SKirill A. Shutemov 		if (addr & ~HPAGE_PMD_MASK)
1471f3f0e1d2SKirill A. Shutemov 			continue;
1472f3f0e1d2SKirill A. Shutemov 		if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1473f3f0e1d2SKirill A. Shutemov 			continue;
147418e77600SHugh Dickins 		mm = vma->vm_mm;
147518e77600SHugh Dickins 		pmd = mm_find_pmd(mm, addr);
1476f3f0e1d2SKirill A. Shutemov 		if (!pmd)
1477f3f0e1d2SKirill A. Shutemov 			continue;
1478f3f0e1d2SKirill A. Shutemov 		/*
1479c1e8d7c6SMichel Lespinasse 		 * We need exclusive mmap_lock to retract page table.
148027e1f827SSong Liu 		 *
148127e1f827SSong Liu 		 * We use trylock due to lock inversion: we need to acquire
1482c1e8d7c6SMichel Lespinasse 		 * mmap_lock while holding page lock. Fault path does it in
148327e1f827SSong Liu 		 * reverse order. Trylock is a way to avoid deadlock.
1484f3f0e1d2SKirill A. Shutemov 		 */
148518e77600SHugh Dickins 		if (mmap_write_trylock(mm)) {
1486deb4c93aSPeter Xu 			/*
1487deb4c93aSPeter Xu 			 * When a vma is registered with uffd-wp, we can't
1488deb4c93aSPeter Xu 			 * recycle the pmd pgtable because there can be pte
1489deb4c93aSPeter Xu 			 * markers installed.  Skip it only, so the rest mm/vma
1490deb4c93aSPeter Xu 			 * can still have the same file mapped hugely, however
1491deb4c93aSPeter Xu 			 * it'll always mapped in small page size for uffd-wp
1492deb4c93aSPeter Xu 			 * registered ranges.
1493deb4c93aSPeter Xu 			 */
1494deb4c93aSPeter Xu 			if (!khugepaged_test_exit(mm) && !userfaultfd_wp(vma))
1495e59a47b8SPasha Tatashin 				collapse_and_free_pmd(mm, vma, addr, pmd);
149618e77600SHugh Dickins 			mmap_write_unlock(mm);
149727e1f827SSong Liu 		} else {
149827e1f827SSong Liu 			/* Try again later */
149918e77600SHugh Dickins 			khugepaged_add_pte_mapped_thp(mm, addr);
1500f3f0e1d2SKirill A. Shutemov 		}
1501f3f0e1d2SKirill A. Shutemov 	}
1502f3f0e1d2SKirill A. Shutemov 	i_mmap_unlock_write(mapping);
1503f3f0e1d2SKirill A. Shutemov }
1504f3f0e1d2SKirill A. Shutemov 
1505f3f0e1d2SKirill A. Shutemov /**
150699cb0dbdSSong Liu  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1507f3f0e1d2SKirill A. Shutemov  *
1508336e6b53SAlex Shi  * @mm: process address space where collapse happens
1509336e6b53SAlex Shi  * @file: file that collapse on
1510336e6b53SAlex Shi  * @start: collapse start address
1511336e6b53SAlex Shi  * @hpage: new allocated huge page for collapse
1512*9710a78aSZach O'Keefe  * @cc: collapse context and scratchpad
1513336e6b53SAlex Shi  *
1514f3f0e1d2SKirill A. Shutemov  * Basic scheme is simple, details are more complex:
151587c460a0SHugh Dickins  *  - allocate and lock a new huge page;
151677da9389SMatthew Wilcox  *  - scan page cache replacing old pages with the new one
151799cb0dbdSSong Liu  *    + swap/gup in pages if necessary;
1518f3f0e1d2SKirill A. Shutemov  *    + fill in gaps;
151977da9389SMatthew Wilcox  *    + keep old pages around in case rollback is required;
152077da9389SMatthew Wilcox  *  - if replacing succeeds:
1521f3f0e1d2SKirill A. Shutemov  *    + copy data over;
1522f3f0e1d2SKirill A. Shutemov  *    + free old pages;
152387c460a0SHugh Dickins  *    + unlock huge page;
1524f3f0e1d2SKirill A. Shutemov  *  - if replacing failed;
1525f3f0e1d2SKirill A. Shutemov  *    + put all pages back and unfreeze them;
152677da9389SMatthew Wilcox  *    + restore gaps in the page cache;
152787c460a0SHugh Dickins  *    + unlock and free huge page;
1528f3f0e1d2SKirill A. Shutemov  */
1529*9710a78aSZach O'Keefe static void collapse_file(struct mm_struct *mm, struct file *file,
1530*9710a78aSZach O'Keefe 			  pgoff_t start, struct page **hpage,
1531*9710a78aSZach O'Keefe 			  struct collapse_control *cc)
1532f3f0e1d2SKirill A. Shutemov {
1533579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
153477da9389SMatthew Wilcox 	struct page *new_page;
1535f3f0e1d2SKirill A. Shutemov 	pgoff_t index, end = start + HPAGE_PMD_NR;
1536f3f0e1d2SKirill A. Shutemov 	LIST_HEAD(pagelist);
153777da9389SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1538f3f0e1d2SKirill A. Shutemov 	int nr_none = 0, result = SCAN_SUCCEED;
153999cb0dbdSSong Liu 	bool is_shmem = shmem_file(file);
1540bf9eceadSMuchun Song 	int nr;
1541f3f0e1d2SKirill A. Shutemov 
154299cb0dbdSSong Liu 	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1543f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1544f3f0e1d2SKirill A. Shutemov 
1545*9710a78aSZach O'Keefe 	result = alloc_charge_hpage(hpage, mm, cc);
1546*9710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1547f3f0e1d2SKirill A. Shutemov 		goto out;
1548f3f0e1d2SKirill A. Shutemov 
1549*9710a78aSZach O'Keefe 	new_page = *hpage;
1550f3f0e1d2SKirill A. Shutemov 
15516b24ca4aSMatthew Wilcox (Oracle) 	/*
15526b24ca4aSMatthew Wilcox (Oracle) 	 * Ensure we have slots for all the pages in the range.  This is
15536b24ca4aSMatthew Wilcox (Oracle) 	 * almost certainly a no-op because most of the pages must be present
15546b24ca4aSMatthew Wilcox (Oracle) 	 */
155595feeabbSHugh Dickins 	do {
155695feeabbSHugh Dickins 		xas_lock_irq(&xas);
155795feeabbSHugh Dickins 		xas_create_range(&xas);
155895feeabbSHugh Dickins 		if (!xas_error(&xas))
155995feeabbSHugh Dickins 			break;
156095feeabbSHugh Dickins 		xas_unlock_irq(&xas);
156195feeabbSHugh Dickins 		if (!xas_nomem(&xas, GFP_KERNEL)) {
156295feeabbSHugh Dickins 			result = SCAN_FAIL;
156395feeabbSHugh Dickins 			goto out;
156495feeabbSHugh Dickins 		}
156595feeabbSHugh Dickins 	} while (1);
156695feeabbSHugh Dickins 
1567042a3082SHugh Dickins 	__SetPageLocked(new_page);
156899cb0dbdSSong Liu 	if (is_shmem)
1569042a3082SHugh Dickins 		__SetPageSwapBacked(new_page);
1570f3f0e1d2SKirill A. Shutemov 	new_page->index = start;
1571f3f0e1d2SKirill A. Shutemov 	new_page->mapping = mapping;
1572f3f0e1d2SKirill A. Shutemov 
1573f3f0e1d2SKirill A. Shutemov 	/*
157487c460a0SHugh Dickins 	 * At this point the new_page is locked and not up-to-date.
157587c460a0SHugh Dickins 	 * It's safe to insert it into the page cache, because nobody would
157687c460a0SHugh Dickins 	 * be able to map it or use it in another way until we unlock it.
1577f3f0e1d2SKirill A. Shutemov 	 */
1578f3f0e1d2SKirill A. Shutemov 
157977da9389SMatthew Wilcox 	xas_set(&xas, start);
158077da9389SMatthew Wilcox 	for (index = start; index < end; index++) {
158177da9389SMatthew Wilcox 		struct page *page = xas_next(&xas);
158277da9389SMatthew Wilcox 
158377da9389SMatthew Wilcox 		VM_BUG_ON(index != xas.xa_index);
158499cb0dbdSSong Liu 		if (is_shmem) {
158577da9389SMatthew Wilcox 			if (!page) {
1586701270faSHugh Dickins 				/*
158799cb0dbdSSong Liu 				 * Stop if extent has been truncated or
158899cb0dbdSSong Liu 				 * hole-punched, and is now completely
158999cb0dbdSSong Liu 				 * empty.
1590701270faSHugh Dickins 				 */
1591701270faSHugh Dickins 				if (index == start) {
1592701270faSHugh Dickins 					if (!xas_next_entry(&xas, end - 1)) {
1593701270faSHugh Dickins 						result = SCAN_TRUNCATED;
1594042a3082SHugh Dickins 						goto xa_locked;
1595701270faSHugh Dickins 					}
1596701270faSHugh Dickins 					xas_set(&xas, index);
1597701270faSHugh Dickins 				}
159877da9389SMatthew Wilcox 				if (!shmem_charge(mapping->host, 1)) {
1599f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
1600042a3082SHugh Dickins 					goto xa_locked;
1601f3f0e1d2SKirill A. Shutemov 				}
16024101196bSMatthew Wilcox (Oracle) 				xas_store(&xas, new_page);
160377da9389SMatthew Wilcox 				nr_none++;
160477da9389SMatthew Wilcox 				continue;
1605f3f0e1d2SKirill A. Shutemov 			}
1606f3f0e1d2SKirill A. Shutemov 
16073159f943SMatthew Wilcox 			if (xa_is_value(page) || !PageUptodate(page)) {
160877da9389SMatthew Wilcox 				xas_unlock_irq(&xas);
1609f3f0e1d2SKirill A. Shutemov 				/* swap in or instantiate fallocated page */
1610f3f0e1d2SKirill A. Shutemov 				if (shmem_getpage(mapping->host, index, &page,
1611acdd9f8eSHugh Dickins 						  SGP_NOALLOC)) {
1612f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
161377da9389SMatthew Wilcox 					goto xa_unlocked;
1614f3f0e1d2SKirill A. Shutemov 				}
1615f3f0e1d2SKirill A. Shutemov 			} else if (trylock_page(page)) {
1616f3f0e1d2SKirill A. Shutemov 				get_page(page);
1617042a3082SHugh Dickins 				xas_unlock_irq(&xas);
1618f3f0e1d2SKirill A. Shutemov 			} else {
1619f3f0e1d2SKirill A. Shutemov 				result = SCAN_PAGE_LOCK;
1620042a3082SHugh Dickins 				goto xa_locked;
1621f3f0e1d2SKirill A. Shutemov 			}
162299cb0dbdSSong Liu 		} else {	/* !is_shmem */
162399cb0dbdSSong Liu 			if (!page || xa_is_value(page)) {
162499cb0dbdSSong Liu 				xas_unlock_irq(&xas);
162599cb0dbdSSong Liu 				page_cache_sync_readahead(mapping, &file->f_ra,
162699cb0dbdSSong Liu 							  file, index,
1627e5a59d30SDavid Howells 							  end - index);
162899cb0dbdSSong Liu 				/* drain pagevecs to help isolate_lru_page() */
162999cb0dbdSSong Liu 				lru_add_drain();
163099cb0dbdSSong Liu 				page = find_lock_page(mapping, index);
163199cb0dbdSSong Liu 				if (unlikely(page == NULL)) {
163299cb0dbdSSong Liu 					result = SCAN_FAIL;
163399cb0dbdSSong Liu 					goto xa_unlocked;
163499cb0dbdSSong Liu 				}
163575f36069SSong Liu 			} else if (PageDirty(page)) {
163675f36069SSong Liu 				/*
163775f36069SSong Liu 				 * khugepaged only works on read-only fd,
163875f36069SSong Liu 				 * so this page is dirty because it hasn't
163975f36069SSong Liu 				 * been flushed since first write. There
164075f36069SSong Liu 				 * won't be new dirty pages.
164175f36069SSong Liu 				 *
164275f36069SSong Liu 				 * Trigger async flush here and hope the
164375f36069SSong Liu 				 * writeback is done when khugepaged
164475f36069SSong Liu 				 * revisits this page.
164575f36069SSong Liu 				 *
164675f36069SSong Liu 				 * This is a one-off situation. We are not
164775f36069SSong Liu 				 * forcing writeback in loop.
164875f36069SSong Liu 				 */
164975f36069SSong Liu 				xas_unlock_irq(&xas);
165075f36069SSong Liu 				filemap_flush(mapping);
165175f36069SSong Liu 				result = SCAN_FAIL;
165275f36069SSong Liu 				goto xa_unlocked;
165374c42e1bSRongwei Wang 			} else if (PageWriteback(page)) {
165474c42e1bSRongwei Wang 				xas_unlock_irq(&xas);
165574c42e1bSRongwei Wang 				result = SCAN_FAIL;
165674c42e1bSRongwei Wang 				goto xa_unlocked;
165799cb0dbdSSong Liu 			} else if (trylock_page(page)) {
165899cb0dbdSSong Liu 				get_page(page);
165999cb0dbdSSong Liu 				xas_unlock_irq(&xas);
166099cb0dbdSSong Liu 			} else {
166199cb0dbdSSong Liu 				result = SCAN_PAGE_LOCK;
166299cb0dbdSSong Liu 				goto xa_locked;
166399cb0dbdSSong Liu 			}
166499cb0dbdSSong Liu 		}
1665f3f0e1d2SKirill A. Shutemov 
1666f3f0e1d2SKirill A. Shutemov 		/*
1667b93b0163SMatthew Wilcox 		 * The page must be locked, so we can drop the i_pages lock
1668f3f0e1d2SKirill A. Shutemov 		 * without racing with truncate.
1669f3f0e1d2SKirill A. Shutemov 		 */
1670f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
16714655e5e5SSong Liu 
16724655e5e5SSong Liu 		/* make sure the page is up to date */
16734655e5e5SSong Liu 		if (unlikely(!PageUptodate(page))) {
16744655e5e5SSong Liu 			result = SCAN_FAIL;
16754655e5e5SSong Liu 			goto out_unlock;
16764655e5e5SSong Liu 		}
167706a5e126SHugh Dickins 
167806a5e126SHugh Dickins 		/*
167906a5e126SHugh Dickins 		 * If file was truncated then extended, or hole-punched, before
168006a5e126SHugh Dickins 		 * we locked the first page, then a THP might be there already.
168106a5e126SHugh Dickins 		 */
168206a5e126SHugh Dickins 		if (PageTransCompound(page)) {
168306a5e126SHugh Dickins 			result = SCAN_PAGE_COMPOUND;
168406a5e126SHugh Dickins 			goto out_unlock;
168506a5e126SHugh Dickins 		}
1686f3f0e1d2SKirill A. Shutemov 
1687f3f0e1d2SKirill A. Shutemov 		if (page_mapping(page) != mapping) {
1688f3f0e1d2SKirill A. Shutemov 			result = SCAN_TRUNCATED;
1689f3f0e1d2SKirill A. Shutemov 			goto out_unlock;
1690f3f0e1d2SKirill A. Shutemov 		}
1691f3f0e1d2SKirill A. Shutemov 
169274c42e1bSRongwei Wang 		if (!is_shmem && (PageDirty(page) ||
169374c42e1bSRongwei Wang 				  PageWriteback(page))) {
16944655e5e5SSong Liu 			/*
16954655e5e5SSong Liu 			 * khugepaged only works on read-only fd, so this
16964655e5e5SSong Liu 			 * page is dirty because it hasn't been flushed
16974655e5e5SSong Liu 			 * since first write.
16984655e5e5SSong Liu 			 */
16994655e5e5SSong Liu 			result = SCAN_FAIL;
17004655e5e5SSong Liu 			goto out_unlock;
17014655e5e5SSong Liu 		}
17024655e5e5SSong Liu 
1703f3f0e1d2SKirill A. Shutemov 		if (isolate_lru_page(page)) {
1704f3f0e1d2SKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
1705042a3082SHugh Dickins 			goto out_unlock;
1706f3f0e1d2SKirill A. Shutemov 		}
1707f3f0e1d2SKirill A. Shutemov 
170899cb0dbdSSong Liu 		if (page_has_private(page) &&
170999cb0dbdSSong Liu 		    !try_to_release_page(page, GFP_KERNEL)) {
171099cb0dbdSSong Liu 			result = SCAN_PAGE_HAS_PRIVATE;
17112f33a706SHugh Dickins 			putback_lru_page(page);
171299cb0dbdSSong Liu 			goto out_unlock;
171399cb0dbdSSong Liu 		}
171499cb0dbdSSong Liu 
1715f3f0e1d2SKirill A. Shutemov 		if (page_mapped(page))
1716869f7ee6SMatthew Wilcox (Oracle) 			try_to_unmap(page_folio(page),
1717869f7ee6SMatthew Wilcox (Oracle) 					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1718f3f0e1d2SKirill A. Shutemov 
171977da9389SMatthew Wilcox 		xas_lock_irq(&xas);
172077da9389SMatthew Wilcox 		xas_set(&xas, index);
1721f3f0e1d2SKirill A. Shutemov 
172277da9389SMatthew Wilcox 		VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1723f3f0e1d2SKirill A. Shutemov 
1724f3f0e1d2SKirill A. Shutemov 		/*
1725f3f0e1d2SKirill A. Shutemov 		 * The page is expected to have page_count() == 3:
1726f3f0e1d2SKirill A. Shutemov 		 *  - we hold a pin on it;
172777da9389SMatthew Wilcox 		 *  - one reference from page cache;
1728f3f0e1d2SKirill A. Shutemov 		 *  - one from isolate_lru_page;
1729f3f0e1d2SKirill A. Shutemov 		 */
1730f3f0e1d2SKirill A. Shutemov 		if (!page_ref_freeze(page, 3)) {
1731f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1732042a3082SHugh Dickins 			xas_unlock_irq(&xas);
1733042a3082SHugh Dickins 			putback_lru_page(page);
1734042a3082SHugh Dickins 			goto out_unlock;
1735f3f0e1d2SKirill A. Shutemov 		}
1736f3f0e1d2SKirill A. Shutemov 
1737f3f0e1d2SKirill A. Shutemov 		/*
1738f3f0e1d2SKirill A. Shutemov 		 * Add the page to the list to be able to undo the collapse if
1739f3f0e1d2SKirill A. Shutemov 		 * something go wrong.
1740f3f0e1d2SKirill A. Shutemov 		 */
1741f3f0e1d2SKirill A. Shutemov 		list_add_tail(&page->lru, &pagelist);
1742f3f0e1d2SKirill A. Shutemov 
1743f3f0e1d2SKirill A. Shutemov 		/* Finally, replace with the new page. */
17444101196bSMatthew Wilcox (Oracle) 		xas_store(&xas, new_page);
1745f3f0e1d2SKirill A. Shutemov 		continue;
1746f3f0e1d2SKirill A. Shutemov out_unlock:
1747f3f0e1d2SKirill A. Shutemov 		unlock_page(page);
1748f3f0e1d2SKirill A. Shutemov 		put_page(page);
1749042a3082SHugh Dickins 		goto xa_unlocked;
1750f3f0e1d2SKirill A. Shutemov 	}
1751bf9eceadSMuchun Song 	nr = thp_nr_pages(new_page);
1752f3f0e1d2SKirill A. Shutemov 
175399cb0dbdSSong Liu 	if (is_shmem)
175457b2847dSMuchun Song 		__mod_lruvec_page_state(new_page, NR_SHMEM_THPS, nr);
175509d91cdaSSong Liu 	else {
1756bf9eceadSMuchun Song 		__mod_lruvec_page_state(new_page, NR_FILE_THPS, nr);
175709d91cdaSSong Liu 		filemap_nr_thps_inc(mapping);
1758eb6ecbedSCollin Fijalkovich 		/*
1759eb6ecbedSCollin Fijalkovich 		 * Paired with smp_mb() in do_dentry_open() to ensure
1760eb6ecbedSCollin Fijalkovich 		 * i_writecount is up to date and the update to nr_thps is
1761eb6ecbedSCollin Fijalkovich 		 * visible. Ensures the page cache will be truncated if the
1762eb6ecbedSCollin Fijalkovich 		 * file is opened writable.
1763eb6ecbedSCollin Fijalkovich 		 */
1764eb6ecbedSCollin Fijalkovich 		smp_mb();
1765eb6ecbedSCollin Fijalkovich 		if (inode_is_open_for_write(mapping->host)) {
1766eb6ecbedSCollin Fijalkovich 			result = SCAN_FAIL;
1767eb6ecbedSCollin Fijalkovich 			__mod_lruvec_page_state(new_page, NR_FILE_THPS, -nr);
1768eb6ecbedSCollin Fijalkovich 			filemap_nr_thps_dec(mapping);
1769eb6ecbedSCollin Fijalkovich 			goto xa_locked;
1770eb6ecbedSCollin Fijalkovich 		}
177109d91cdaSSong Liu 	}
177299cb0dbdSSong Liu 
1773042a3082SHugh Dickins 	if (nr_none) {
17749d82c694SJohannes Weiner 		__mod_lruvec_page_state(new_page, NR_FILE_PAGES, nr_none);
17752f55f070SMiaohe Lin 		/* nr_none is always 0 for non-shmem. */
17769d82c694SJohannes Weiner 		__mod_lruvec_page_state(new_page, NR_SHMEM, nr_none);
1777042a3082SHugh Dickins 	}
1778042a3082SHugh Dickins 
17796b24ca4aSMatthew Wilcox (Oracle) 	/* Join all the small entries into a single multi-index entry */
17806b24ca4aSMatthew Wilcox (Oracle) 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
17816b24ca4aSMatthew Wilcox (Oracle) 	xas_store(&xas, new_page);
1782042a3082SHugh Dickins xa_locked:
1783042a3082SHugh Dickins 	xas_unlock_irq(&xas);
178477da9389SMatthew Wilcox xa_unlocked:
1785042a3082SHugh Dickins 
17866d9df8a5SHugh Dickins 	/*
17876d9df8a5SHugh Dickins 	 * If collapse is successful, flush must be done now before copying.
17886d9df8a5SHugh Dickins 	 * If collapse is unsuccessful, does flush actually need to be done?
17896d9df8a5SHugh Dickins 	 * Do it anyway, to clear the state.
17906d9df8a5SHugh Dickins 	 */
17916d9df8a5SHugh Dickins 	try_to_unmap_flush();
17926d9df8a5SHugh Dickins 
1793f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
179477da9389SMatthew Wilcox 		struct page *page, *tmp;
1795f3f0e1d2SKirill A. Shutemov 
1796f3f0e1d2SKirill A. Shutemov 		/*
179777da9389SMatthew Wilcox 		 * Replacing old pages with new one has succeeded, now we
179877da9389SMatthew Wilcox 		 * need to copy the content and free the old pages.
1799f3f0e1d2SKirill A. Shutemov 		 */
18002af8ff29SHugh Dickins 		index = start;
1801f3f0e1d2SKirill A. Shutemov 		list_for_each_entry_safe(page, tmp, &pagelist, lru) {
18022af8ff29SHugh Dickins 			while (index < page->index) {
18032af8ff29SHugh Dickins 				clear_highpage(new_page + (index % HPAGE_PMD_NR));
18042af8ff29SHugh Dickins 				index++;
18052af8ff29SHugh Dickins 			}
1806f3f0e1d2SKirill A. Shutemov 			copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1807f3f0e1d2SKirill A. Shutemov 					page);
1808f3f0e1d2SKirill A. Shutemov 			list_del(&page->lru);
1809f3f0e1d2SKirill A. Shutemov 			page->mapping = NULL;
1810042a3082SHugh Dickins 			page_ref_unfreeze(page, 1);
1811f3f0e1d2SKirill A. Shutemov 			ClearPageActive(page);
1812f3f0e1d2SKirill A. Shutemov 			ClearPageUnevictable(page);
1813042a3082SHugh Dickins 			unlock_page(page);
1814f3f0e1d2SKirill A. Shutemov 			put_page(page);
18152af8ff29SHugh Dickins 			index++;
18162af8ff29SHugh Dickins 		}
18172af8ff29SHugh Dickins 		while (index < end) {
18182af8ff29SHugh Dickins 			clear_highpage(new_page + (index % HPAGE_PMD_NR));
18192af8ff29SHugh Dickins 			index++;
1820f3f0e1d2SKirill A. Shutemov 		}
1821f3f0e1d2SKirill A. Shutemov 
1822f3f0e1d2SKirill A. Shutemov 		SetPageUptodate(new_page);
182387c460a0SHugh Dickins 		page_ref_add(new_page, HPAGE_PMD_NR - 1);
18246058eaecSJohannes Weiner 		if (is_shmem)
182599cb0dbdSSong Liu 			set_page_dirty(new_page);
18266058eaecSJohannes Weiner 		lru_cache_add(new_page);
1827f3f0e1d2SKirill A. Shutemov 
1828042a3082SHugh Dickins 		/*
1829042a3082SHugh Dickins 		 * Remove pte page tables, so we can re-fault the page as huge.
1830042a3082SHugh Dickins 		 */
1831042a3082SHugh Dickins 		retract_page_tables(mapping, start);
1832f3f0e1d2SKirill A. Shutemov 		*hpage = NULL;
183387aa7529SYang Shi 
183487aa7529SYang Shi 		khugepaged_pages_collapsed++;
1835f3f0e1d2SKirill A. Shutemov 	} else {
183677da9389SMatthew Wilcox 		struct page *page;
1837aaa52e34SHugh Dickins 
183877da9389SMatthew Wilcox 		/* Something went wrong: roll back page cache changes */
183977da9389SMatthew Wilcox 		xas_lock_irq(&xas);
18402f55f070SMiaohe Lin 		if (nr_none) {
1841aaa52e34SHugh Dickins 			mapping->nrpages -= nr_none;
1842aaa52e34SHugh Dickins 			shmem_uncharge(mapping->host, nr_none);
18432f55f070SMiaohe Lin 		}
1844aaa52e34SHugh Dickins 
184577da9389SMatthew Wilcox 		xas_set(&xas, start);
184677da9389SMatthew Wilcox 		xas_for_each(&xas, page, end - 1) {
1847f3f0e1d2SKirill A. Shutemov 			page = list_first_entry_or_null(&pagelist,
1848f3f0e1d2SKirill A. Shutemov 					struct page, lru);
184977da9389SMatthew Wilcox 			if (!page || xas.xa_index < page->index) {
1850f3f0e1d2SKirill A. Shutemov 				if (!nr_none)
1851f3f0e1d2SKirill A. Shutemov 					break;
1852f3f0e1d2SKirill A. Shutemov 				nr_none--;
185359749e6cSJohannes Weiner 				/* Put holes back where they were */
185477da9389SMatthew Wilcox 				xas_store(&xas, NULL);
1855f3f0e1d2SKirill A. Shutemov 				continue;
1856f3f0e1d2SKirill A. Shutemov 			}
1857f3f0e1d2SKirill A. Shutemov 
185877da9389SMatthew Wilcox 			VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1859f3f0e1d2SKirill A. Shutemov 
1860f3f0e1d2SKirill A. Shutemov 			/* Unfreeze the page. */
1861f3f0e1d2SKirill A. Shutemov 			list_del(&page->lru);
1862f3f0e1d2SKirill A. Shutemov 			page_ref_unfreeze(page, 2);
186377da9389SMatthew Wilcox 			xas_store(&xas, page);
186477da9389SMatthew Wilcox 			xas_pause(&xas);
186577da9389SMatthew Wilcox 			xas_unlock_irq(&xas);
1866f3f0e1d2SKirill A. Shutemov 			unlock_page(page);
1867042a3082SHugh Dickins 			putback_lru_page(page);
186877da9389SMatthew Wilcox 			xas_lock_irq(&xas);
1869f3f0e1d2SKirill A. Shutemov 		}
1870f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON(nr_none);
187177da9389SMatthew Wilcox 		xas_unlock_irq(&xas);
1872f3f0e1d2SKirill A. Shutemov 
1873f3f0e1d2SKirill A. Shutemov 		new_page->mapping = NULL;
1874f3f0e1d2SKirill A. Shutemov 	}
1875042a3082SHugh Dickins 
1876042a3082SHugh Dickins 	unlock_page(new_page);
1877f3f0e1d2SKirill A. Shutemov out:
1878f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(!list_empty(&pagelist));
1879c6a7f445SYang Shi 	if (!IS_ERR_OR_NULL(*hpage)) {
1880bbc6b703SMatthew Wilcox (Oracle) 		mem_cgroup_uncharge(page_folio(*hpage));
1881c6a7f445SYang Shi 		put_page(*hpage);
1882c6a7f445SYang Shi 	}
1883f3f0e1d2SKirill A. Shutemov 	/* TODO: tracepoints */
1884f3f0e1d2SKirill A. Shutemov }
1885f3f0e1d2SKirill A. Shutemov 
188634d6b470SZach O'Keefe static void khugepaged_scan_file(struct mm_struct *mm, struct file *file,
188734d6b470SZach O'Keefe 				 pgoff_t start, struct page **hpage,
188834d6b470SZach O'Keefe 				 struct collapse_control *cc)
1889f3f0e1d2SKirill A. Shutemov {
1890f3f0e1d2SKirill A. Shutemov 	struct page *page = NULL;
1891579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
189285b392dbSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
1893f3f0e1d2SKirill A. Shutemov 	int present, swap;
1894f3f0e1d2SKirill A. Shutemov 	int node = NUMA_NO_NODE;
1895f3f0e1d2SKirill A. Shutemov 	int result = SCAN_SUCCEED;
1896f3f0e1d2SKirill A. Shutemov 
1897f3f0e1d2SKirill A. Shutemov 	present = 0;
1898f3f0e1d2SKirill A. Shutemov 	swap = 0;
189934d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1900f3f0e1d2SKirill A. Shutemov 	rcu_read_lock();
190185b392dbSMatthew Wilcox 	xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
190285b392dbSMatthew Wilcox 		if (xas_retry(&xas, page))
1903f3f0e1d2SKirill A. Shutemov 			continue;
1904f3f0e1d2SKirill A. Shutemov 
190585b392dbSMatthew Wilcox 		if (xa_is_value(page)) {
1906f3f0e1d2SKirill A. Shutemov 			if (++swap > khugepaged_max_ptes_swap) {
1907f3f0e1d2SKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1908e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1909f3f0e1d2SKirill A. Shutemov 				break;
1910f3f0e1d2SKirill A. Shutemov 			}
1911f3f0e1d2SKirill A. Shutemov 			continue;
1912f3f0e1d2SKirill A. Shutemov 		}
1913f3f0e1d2SKirill A. Shutemov 
19146b24ca4aSMatthew Wilcox (Oracle) 		/*
19156b24ca4aSMatthew Wilcox (Oracle) 		 * XXX: khugepaged should compact smaller compound pages
19166b24ca4aSMatthew Wilcox (Oracle) 		 * into a PMD sized page
19176b24ca4aSMatthew Wilcox (Oracle) 		 */
1918f3f0e1d2SKirill A. Shutemov 		if (PageTransCompound(page)) {
1919f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COMPOUND;
1920f3f0e1d2SKirill A. Shutemov 			break;
1921f3f0e1d2SKirill A. Shutemov 		}
1922f3f0e1d2SKirill A. Shutemov 
1923f3f0e1d2SKirill A. Shutemov 		node = page_to_nid(page);
192434d6b470SZach O'Keefe 		if (khugepaged_scan_abort(node, cc)) {
1925f3f0e1d2SKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1926f3f0e1d2SKirill A. Shutemov 			break;
1927f3f0e1d2SKirill A. Shutemov 		}
192834d6b470SZach O'Keefe 		cc->node_load[node]++;
1929f3f0e1d2SKirill A. Shutemov 
1930f3f0e1d2SKirill A. Shutemov 		if (!PageLRU(page)) {
1931f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1932f3f0e1d2SKirill A. Shutemov 			break;
1933f3f0e1d2SKirill A. Shutemov 		}
1934f3f0e1d2SKirill A. Shutemov 
193599cb0dbdSSong Liu 		if (page_count(page) !=
193699cb0dbdSSong Liu 		    1 + page_mapcount(page) + page_has_private(page)) {
1937f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1938f3f0e1d2SKirill A. Shutemov 			break;
1939f3f0e1d2SKirill A. Shutemov 		}
1940f3f0e1d2SKirill A. Shutemov 
1941f3f0e1d2SKirill A. Shutemov 		/*
1942f3f0e1d2SKirill A. Shutemov 		 * We probably should check if the page is referenced here, but
1943f3f0e1d2SKirill A. Shutemov 		 * nobody would transfer pte_young() to PageReferenced() for us.
1944f3f0e1d2SKirill A. Shutemov 		 * And rmap walk here is just too costly...
1945f3f0e1d2SKirill A. Shutemov 		 */
1946f3f0e1d2SKirill A. Shutemov 
1947f3f0e1d2SKirill A. Shutemov 		present++;
1948f3f0e1d2SKirill A. Shutemov 
1949f3f0e1d2SKirill A. Shutemov 		if (need_resched()) {
195085b392dbSMatthew Wilcox 			xas_pause(&xas);
1951f3f0e1d2SKirill A. Shutemov 			cond_resched_rcu();
1952f3f0e1d2SKirill A. Shutemov 		}
1953f3f0e1d2SKirill A. Shutemov 	}
1954f3f0e1d2SKirill A. Shutemov 	rcu_read_unlock();
1955f3f0e1d2SKirill A. Shutemov 
1956f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
1957f3f0e1d2SKirill A. Shutemov 		if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
1958f3f0e1d2SKirill A. Shutemov 			result = SCAN_EXCEED_NONE_PTE;
1959e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1960f3f0e1d2SKirill A. Shutemov 		} else {
1961*9710a78aSZach O'Keefe 			collapse_file(mm, file, start, hpage, cc);
1962f3f0e1d2SKirill A. Shutemov 		}
1963f3f0e1d2SKirill A. Shutemov 	}
1964f3f0e1d2SKirill A. Shutemov 
1965f3f0e1d2SKirill A. Shutemov 	/* TODO: tracepoints */
1966f3f0e1d2SKirill A. Shutemov }
1967f3f0e1d2SKirill A. Shutemov #else
196834d6b470SZach O'Keefe static void khugepaged_scan_file(struct mm_struct *mm, struct file *file,
196934d6b470SZach O'Keefe 				 pgoff_t start, struct page **hpage,
197034d6b470SZach O'Keefe 				 struct collapse_control *cc)
1971f3f0e1d2SKirill A. Shutemov {
1972f3f0e1d2SKirill A. Shutemov 	BUILD_BUG();
1973f3f0e1d2SKirill A. Shutemov }
197427e1f827SSong Liu 
19750edf61e5SMiaohe Lin static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
197627e1f827SSong Liu {
197727e1f827SSong Liu }
1978f3f0e1d2SKirill A. Shutemov #endif
1979f3f0e1d2SKirill A. Shutemov 
1980b46e756fSKirill A. Shutemov static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
198134d6b470SZach O'Keefe 					    struct page **hpage,
198234d6b470SZach O'Keefe 					    struct collapse_control *cc)
1983b46e756fSKirill A. Shutemov 	__releases(&khugepaged_mm_lock)
1984b46e756fSKirill A. Shutemov 	__acquires(&khugepaged_mm_lock)
1985b46e756fSKirill A. Shutemov {
1986b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
1987b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
1988b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
1989b46e756fSKirill A. Shutemov 	int progress = 0;
1990b46e756fSKirill A. Shutemov 
1991b46e756fSKirill A. Shutemov 	VM_BUG_ON(!pages);
199235f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1993b46e756fSKirill A. Shutemov 
1994b46e756fSKirill A. Shutemov 	if (khugepaged_scan.mm_slot)
1995b46e756fSKirill A. Shutemov 		mm_slot = khugepaged_scan.mm_slot;
1996b46e756fSKirill A. Shutemov 	else {
1997b46e756fSKirill A. Shutemov 		mm_slot = list_entry(khugepaged_scan.mm_head.next,
1998b46e756fSKirill A. Shutemov 				     struct mm_slot, mm_node);
1999b46e756fSKirill A. Shutemov 		khugepaged_scan.address = 0;
2000b46e756fSKirill A. Shutemov 		khugepaged_scan.mm_slot = mm_slot;
2001b46e756fSKirill A. Shutemov 	}
2002b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
200327e1f827SSong Liu 	khugepaged_collapse_pte_mapped_thps(mm_slot);
2004b46e756fSKirill A. Shutemov 
2005b46e756fSKirill A. Shutemov 	mm = mm_slot->mm;
20063b454ad3SYang Shi 	/*
20073b454ad3SYang Shi 	 * Don't wait for semaphore (to avoid long wait times).  Just move to
20083b454ad3SYang Shi 	 * the next mm on the list.
20093b454ad3SYang Shi 	 */
2010b46e756fSKirill A. Shutemov 	vma = NULL;
2011d8ed45c5SMichel Lespinasse 	if (unlikely(!mmap_read_trylock(mm)))
2012c1e8d7c6SMichel Lespinasse 		goto breakouterloop_mmap_lock;
20133b454ad3SYang Shi 	if (likely(!khugepaged_test_exit(mm)))
2014b46e756fSKirill A. Shutemov 		vma = find_vma(mm, khugepaged_scan.address);
2015b46e756fSKirill A. Shutemov 
2016b46e756fSKirill A. Shutemov 	progress++;
2017b46e756fSKirill A. Shutemov 	for (; vma; vma = vma->vm_next) {
2018b46e756fSKirill A. Shutemov 		unsigned long hstart, hend;
2019b46e756fSKirill A. Shutemov 
2020b46e756fSKirill A. Shutemov 		cond_resched();
2021b46e756fSKirill A. Shutemov 		if (unlikely(khugepaged_test_exit(mm))) {
2022b46e756fSKirill A. Shutemov 			progress++;
2023b46e756fSKirill A. Shutemov 			break;
2024b46e756fSKirill A. Shutemov 		}
20257da4e2cbSYang Shi 		if (!hugepage_vma_check(vma, vma->vm_flags, false, false)) {
2026b46e756fSKirill A. Shutemov skip:
2027b46e756fSKirill A. Shutemov 			progress++;
2028b46e756fSKirill A. Shutemov 			continue;
2029b46e756fSKirill A. Shutemov 		}
20304fa6893fSYang Shi 		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
20314fa6893fSYang Shi 		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2032b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address > hend)
2033b46e756fSKirill A. Shutemov 			goto skip;
2034b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address < hstart)
2035b46e756fSKirill A. Shutemov 			khugepaged_scan.address = hstart;
2036b46e756fSKirill A. Shutemov 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2037b46e756fSKirill A. Shutemov 
2038b46e756fSKirill A. Shutemov 		while (khugepaged_scan.address < hend) {
2039b46e756fSKirill A. Shutemov 			int ret;
2040b46e756fSKirill A. Shutemov 			cond_resched();
2041b46e756fSKirill A. Shutemov 			if (unlikely(khugepaged_test_exit(mm)))
2042b46e756fSKirill A. Shutemov 				goto breakouterloop;
2043b46e756fSKirill A. Shutemov 
2044b46e756fSKirill A. Shutemov 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2045b46e756fSKirill A. Shutemov 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2046b46e756fSKirill A. Shutemov 				  hend);
204799cb0dbdSSong Liu 			if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2048396bcc52SMatthew Wilcox (Oracle) 				struct file *file = get_file(vma->vm_file);
2049f3f0e1d2SKirill A. Shutemov 				pgoff_t pgoff = linear_page_index(vma,
2050f3f0e1d2SKirill A. Shutemov 						khugepaged_scan.address);
205199cb0dbdSSong Liu 
2052d8ed45c5SMichel Lespinasse 				mmap_read_unlock(mm);
2053f3f0e1d2SKirill A. Shutemov 				ret = 1;
205434d6b470SZach O'Keefe 				khugepaged_scan_file(mm, file, pgoff, hpage,
205534d6b470SZach O'Keefe 						     cc);
2056f3f0e1d2SKirill A. Shutemov 				fput(file);
2057f3f0e1d2SKirill A. Shutemov 			} else {
2058b46e756fSKirill A. Shutemov 				ret = khugepaged_scan_pmd(mm, vma,
2059b46e756fSKirill A. Shutemov 						khugepaged_scan.address,
206034d6b470SZach O'Keefe 						hpage, cc);
2061f3f0e1d2SKirill A. Shutemov 			}
2062b46e756fSKirill A. Shutemov 			/* move to next address */
2063b46e756fSKirill A. Shutemov 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2064b46e756fSKirill A. Shutemov 			progress += HPAGE_PMD_NR;
2065b46e756fSKirill A. Shutemov 			if (ret)
2066c1e8d7c6SMichel Lespinasse 				/* we released mmap_lock so break loop */
2067c1e8d7c6SMichel Lespinasse 				goto breakouterloop_mmap_lock;
2068b46e756fSKirill A. Shutemov 			if (progress >= pages)
2069b46e756fSKirill A. Shutemov 				goto breakouterloop;
2070b46e756fSKirill A. Shutemov 		}
2071b46e756fSKirill A. Shutemov 	}
2072b46e756fSKirill A. Shutemov breakouterloop:
2073d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2074c1e8d7c6SMichel Lespinasse breakouterloop_mmap_lock:
2075b46e756fSKirill A. Shutemov 
2076b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2077b46e756fSKirill A. Shutemov 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2078b46e756fSKirill A. Shutemov 	/*
2079b46e756fSKirill A. Shutemov 	 * Release the current mm_slot if this mm is about to die, or
2080b46e756fSKirill A. Shutemov 	 * if we scanned all vmas of this mm.
2081b46e756fSKirill A. Shutemov 	 */
2082b46e756fSKirill A. Shutemov 	if (khugepaged_test_exit(mm) || !vma) {
2083b46e756fSKirill A. Shutemov 		/*
2084b46e756fSKirill A. Shutemov 		 * Make sure that if mm_users is reaching zero while
2085b46e756fSKirill A. Shutemov 		 * khugepaged runs here, khugepaged_exit will find
2086b46e756fSKirill A. Shutemov 		 * mm_slot not pointing to the exiting mm.
2087b46e756fSKirill A. Shutemov 		 */
2088b46e756fSKirill A. Shutemov 		if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2089b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = list_entry(
2090b46e756fSKirill A. Shutemov 				mm_slot->mm_node.next,
2091b46e756fSKirill A. Shutemov 				struct mm_slot, mm_node);
2092b46e756fSKirill A. Shutemov 			khugepaged_scan.address = 0;
2093b46e756fSKirill A. Shutemov 		} else {
2094b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = NULL;
2095b46e756fSKirill A. Shutemov 			khugepaged_full_scans++;
2096b46e756fSKirill A. Shutemov 		}
2097b46e756fSKirill A. Shutemov 
2098b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2099b46e756fSKirill A. Shutemov 	}
2100b46e756fSKirill A. Shutemov 
2101b46e756fSKirill A. Shutemov 	return progress;
2102b46e756fSKirill A. Shutemov }
2103b46e756fSKirill A. Shutemov 
2104b46e756fSKirill A. Shutemov static int khugepaged_has_work(void)
2105b46e756fSKirill A. Shutemov {
2106b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) &&
21071064026bSYang Shi 		hugepage_flags_enabled();
2108b46e756fSKirill A. Shutemov }
2109b46e756fSKirill A. Shutemov 
2110b46e756fSKirill A. Shutemov static int khugepaged_wait_event(void)
2111b46e756fSKirill A. Shutemov {
2112b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) ||
2113b46e756fSKirill A. Shutemov 		kthread_should_stop();
2114b46e756fSKirill A. Shutemov }
2115b46e756fSKirill A. Shutemov 
211634d6b470SZach O'Keefe static void khugepaged_do_scan(struct collapse_control *cc)
2117b46e756fSKirill A. Shutemov {
2118b46e756fSKirill A. Shutemov 	struct page *hpage = NULL;
2119b46e756fSKirill A. Shutemov 	unsigned int progress = 0, pass_through_head = 0;
212089dc6a96SYanfei Xu 	unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2121b46e756fSKirill A. Shutemov 	bool wait = true;
2122b46e756fSKirill A. Shutemov 
2123a980df33SKirill A. Shutemov 	lru_add_drain_all();
2124a980df33SKirill A. Shutemov 
2125c6a7f445SYang Shi 	while (true) {
2126b46e756fSKirill A. Shutemov 		cond_resched();
2127b46e756fSKirill A. Shutemov 
2128b46e756fSKirill A. Shutemov 		if (unlikely(kthread_should_stop() || try_to_freeze()))
2129b46e756fSKirill A. Shutemov 			break;
2130b46e756fSKirill A. Shutemov 
2131b46e756fSKirill A. Shutemov 		spin_lock(&khugepaged_mm_lock);
2132b46e756fSKirill A. Shutemov 		if (!khugepaged_scan.mm_slot)
2133b46e756fSKirill A. Shutemov 			pass_through_head++;
2134b46e756fSKirill A. Shutemov 		if (khugepaged_has_work() &&
2135b46e756fSKirill A. Shutemov 		    pass_through_head < 2)
2136b46e756fSKirill A. Shutemov 			progress += khugepaged_scan_mm_slot(pages - progress,
213734d6b470SZach O'Keefe 							    &hpage, cc);
2138b46e756fSKirill A. Shutemov 		else
2139b46e756fSKirill A. Shutemov 			progress = pages;
2140b46e756fSKirill A. Shutemov 		spin_unlock(&khugepaged_mm_lock);
2141b46e756fSKirill A. Shutemov 
2142c6a7f445SYang Shi 		if (progress >= pages)
2143c6a7f445SYang Shi 			break;
2144c6a7f445SYang Shi 
2145c6a7f445SYang Shi 		if (IS_ERR(hpage)) {
2146c6a7f445SYang Shi 			/*
2147c6a7f445SYang Shi 			 * If fail to allocate the first time, try to sleep for
2148c6a7f445SYang Shi 			 * a while.  When hit again, cancel the scan.
2149c6a7f445SYang Shi 			 */
2150c6a7f445SYang Shi 			if (!wait)
2151c6a7f445SYang Shi 				break;
2152c6a7f445SYang Shi 			wait = false;
2153c6a7f445SYang Shi 			hpage = NULL;
2154c6a7f445SYang Shi 			khugepaged_alloc_sleep();
2155c6a7f445SYang Shi 		}
2156c6a7f445SYang Shi 	}
2157b46e756fSKirill A. Shutemov }
2158b46e756fSKirill A. Shutemov 
2159b46e756fSKirill A. Shutemov static bool khugepaged_should_wakeup(void)
2160b46e756fSKirill A. Shutemov {
2161b46e756fSKirill A. Shutemov 	return kthread_should_stop() ||
2162b46e756fSKirill A. Shutemov 	       time_after_eq(jiffies, khugepaged_sleep_expire);
2163b46e756fSKirill A. Shutemov }
2164b46e756fSKirill A. Shutemov 
2165b46e756fSKirill A. Shutemov static void khugepaged_wait_work(void)
2166b46e756fSKirill A. Shutemov {
2167b46e756fSKirill A. Shutemov 	if (khugepaged_has_work()) {
2168b46e756fSKirill A. Shutemov 		const unsigned long scan_sleep_jiffies =
2169b46e756fSKirill A. Shutemov 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2170b46e756fSKirill A. Shutemov 
2171b46e756fSKirill A. Shutemov 		if (!scan_sleep_jiffies)
2172b46e756fSKirill A. Shutemov 			return;
2173b46e756fSKirill A. Shutemov 
2174b46e756fSKirill A. Shutemov 		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2175b46e756fSKirill A. Shutemov 		wait_event_freezable_timeout(khugepaged_wait,
2176b46e756fSKirill A. Shutemov 					     khugepaged_should_wakeup(),
2177b46e756fSKirill A. Shutemov 					     scan_sleep_jiffies);
2178b46e756fSKirill A. Shutemov 		return;
2179b46e756fSKirill A. Shutemov 	}
2180b46e756fSKirill A. Shutemov 
21811064026bSYang Shi 	if (hugepage_flags_enabled())
2182b46e756fSKirill A. Shutemov 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2183b46e756fSKirill A. Shutemov }
2184b46e756fSKirill A. Shutemov 
2185b46e756fSKirill A. Shutemov static int khugepaged(void *none)
2186b46e756fSKirill A. Shutemov {
2187b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
2188b46e756fSKirill A. Shutemov 
2189b46e756fSKirill A. Shutemov 	set_freezable();
2190b46e756fSKirill A. Shutemov 	set_user_nice(current, MAX_NICE);
2191b46e756fSKirill A. Shutemov 
2192b46e756fSKirill A. Shutemov 	while (!kthread_should_stop()) {
219334d6b470SZach O'Keefe 		khugepaged_do_scan(&khugepaged_collapse_control);
2194b46e756fSKirill A. Shutemov 		khugepaged_wait_work();
2195b46e756fSKirill A. Shutemov 	}
2196b46e756fSKirill A. Shutemov 
2197b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2198b46e756fSKirill A. Shutemov 	mm_slot = khugepaged_scan.mm_slot;
2199b46e756fSKirill A. Shutemov 	khugepaged_scan.mm_slot = NULL;
2200b46e756fSKirill A. Shutemov 	if (mm_slot)
2201b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2202b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2203b46e756fSKirill A. Shutemov 	return 0;
2204b46e756fSKirill A. Shutemov }
2205b46e756fSKirill A. Shutemov 
2206b46e756fSKirill A. Shutemov static void set_recommended_min_free_kbytes(void)
2207b46e756fSKirill A. Shutemov {
2208b46e756fSKirill A. Shutemov 	struct zone *zone;
2209b46e756fSKirill A. Shutemov 	int nr_zones = 0;
2210b46e756fSKirill A. Shutemov 	unsigned long recommended_min;
2211b46e756fSKirill A. Shutemov 
22121064026bSYang Shi 	if (!hugepage_flags_enabled()) {
2213bd3400eaSLiangcai Fan 		calculate_min_free_kbytes();
2214bd3400eaSLiangcai Fan 		goto update_wmarks;
2215bd3400eaSLiangcai Fan 	}
2216bd3400eaSLiangcai Fan 
2217b7d349c7SJoonsoo Kim 	for_each_populated_zone(zone) {
2218b7d349c7SJoonsoo Kim 		/*
2219b7d349c7SJoonsoo Kim 		 * We don't need to worry about fragmentation of
2220b7d349c7SJoonsoo Kim 		 * ZONE_MOVABLE since it only has movable pages.
2221b7d349c7SJoonsoo Kim 		 */
2222b7d349c7SJoonsoo Kim 		if (zone_idx(zone) > gfp_zone(GFP_USER))
2223b7d349c7SJoonsoo Kim 			continue;
2224b7d349c7SJoonsoo Kim 
2225b46e756fSKirill A. Shutemov 		nr_zones++;
2226b7d349c7SJoonsoo Kim 	}
2227b46e756fSKirill A. Shutemov 
2228b46e756fSKirill A. Shutemov 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2229b46e756fSKirill A. Shutemov 	recommended_min = pageblock_nr_pages * nr_zones * 2;
2230b46e756fSKirill A. Shutemov 
2231b46e756fSKirill A. Shutemov 	/*
2232b46e756fSKirill A. Shutemov 	 * Make sure that on average at least two pageblocks are almost free
2233b46e756fSKirill A. Shutemov 	 * of another type, one for a migratetype to fall back to and a
2234b46e756fSKirill A. Shutemov 	 * second to avoid subsequent fallbacks of other types There are 3
2235b46e756fSKirill A. Shutemov 	 * MIGRATE_TYPES we care about.
2236b46e756fSKirill A. Shutemov 	 */
2237b46e756fSKirill A. Shutemov 	recommended_min += pageblock_nr_pages * nr_zones *
2238b46e756fSKirill A. Shutemov 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2239b46e756fSKirill A. Shutemov 
2240b46e756fSKirill A. Shutemov 	/* don't ever allow to reserve more than 5% of the lowmem */
2241b46e756fSKirill A. Shutemov 	recommended_min = min(recommended_min,
2242b46e756fSKirill A. Shutemov 			      (unsigned long) nr_free_buffer_pages() / 20);
2243b46e756fSKirill A. Shutemov 	recommended_min <<= (PAGE_SHIFT-10);
2244b46e756fSKirill A. Shutemov 
2245b46e756fSKirill A. Shutemov 	if (recommended_min > min_free_kbytes) {
2246b46e756fSKirill A. Shutemov 		if (user_min_free_kbytes >= 0)
2247b46e756fSKirill A. Shutemov 			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2248b46e756fSKirill A. Shutemov 				min_free_kbytes, recommended_min);
2249b46e756fSKirill A. Shutemov 
2250b46e756fSKirill A. Shutemov 		min_free_kbytes = recommended_min;
2251b46e756fSKirill A. Shutemov 	}
2252bd3400eaSLiangcai Fan 
2253bd3400eaSLiangcai Fan update_wmarks:
2254b46e756fSKirill A. Shutemov 	setup_per_zone_wmarks();
2255b46e756fSKirill A. Shutemov }
2256b46e756fSKirill A. Shutemov 
2257b46e756fSKirill A. Shutemov int start_stop_khugepaged(void)
2258b46e756fSKirill A. Shutemov {
2259b46e756fSKirill A. Shutemov 	int err = 0;
2260b46e756fSKirill A. Shutemov 
2261b46e756fSKirill A. Shutemov 	mutex_lock(&khugepaged_mutex);
22621064026bSYang Shi 	if (hugepage_flags_enabled()) {
2263b46e756fSKirill A. Shutemov 		if (!khugepaged_thread)
2264b46e756fSKirill A. Shutemov 			khugepaged_thread = kthread_run(khugepaged, NULL,
2265b46e756fSKirill A. Shutemov 							"khugepaged");
2266b46e756fSKirill A. Shutemov 		if (IS_ERR(khugepaged_thread)) {
2267b46e756fSKirill A. Shutemov 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2268b46e756fSKirill A. Shutemov 			err = PTR_ERR(khugepaged_thread);
2269b46e756fSKirill A. Shutemov 			khugepaged_thread = NULL;
2270b46e756fSKirill A. Shutemov 			goto fail;
2271b46e756fSKirill A. Shutemov 		}
2272b46e756fSKirill A. Shutemov 
2273b46e756fSKirill A. Shutemov 		if (!list_empty(&khugepaged_scan.mm_head))
2274b46e756fSKirill A. Shutemov 			wake_up_interruptible(&khugepaged_wait);
2275b46e756fSKirill A. Shutemov 	} else if (khugepaged_thread) {
2276b46e756fSKirill A. Shutemov 		kthread_stop(khugepaged_thread);
2277b46e756fSKirill A. Shutemov 		khugepaged_thread = NULL;
2278b46e756fSKirill A. Shutemov 	}
2279bd3400eaSLiangcai Fan 	set_recommended_min_free_kbytes();
2280b46e756fSKirill A. Shutemov fail:
2281b46e756fSKirill A. Shutemov 	mutex_unlock(&khugepaged_mutex);
2282b46e756fSKirill A. Shutemov 	return err;
2283b46e756fSKirill A. Shutemov }
22844aab2be0SVijay Balakrishna 
22854aab2be0SVijay Balakrishna void khugepaged_min_free_kbytes_update(void)
22864aab2be0SVijay Balakrishna {
22874aab2be0SVijay Balakrishna 	mutex_lock(&khugepaged_mutex);
22881064026bSYang Shi 	if (hugepage_flags_enabled() && khugepaged_thread)
22894aab2be0SVijay Balakrishna 		set_recommended_min_free_kbytes();
22904aab2be0SVijay Balakrishna 	mutex_unlock(&khugepaged_mutex);
22914aab2be0SVijay Balakrishna }
2292