xref: /linux/mm/khugepaged.c (revision 92644f583d5124b60bc20a3dd21b0bc9142f020c)
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"
26b26e2701SQi Zheng #include "mm_slot.h"
27b46e756fSKirill A. Shutemov 
28b46e756fSKirill A. Shutemov enum scan_result {
29b46e756fSKirill A. Shutemov 	SCAN_FAIL,
30b46e756fSKirill A. Shutemov 	SCAN_SUCCEED,
31b46e756fSKirill A. Shutemov 	SCAN_PMD_NULL,
3234488399SZach O'Keefe 	SCAN_PMD_NONE,
3350722804SZach O'Keefe 	SCAN_PMD_MAPPED,
34b46e756fSKirill A. Shutemov 	SCAN_EXCEED_NONE_PTE,
3571a2c112SKirill A. Shutemov 	SCAN_EXCEED_SWAP_PTE,
3671a2c112SKirill A. Shutemov 	SCAN_EXCEED_SHARED_PTE,
37b46e756fSKirill A. Shutemov 	SCAN_PTE_NON_PRESENT,
38e1e267c7SPeter Xu 	SCAN_PTE_UFFD_WP,
3958ac9a89SZach O'Keefe 	SCAN_PTE_MAPPED_HUGEPAGE,
40b46e756fSKirill A. Shutemov 	SCAN_PAGE_RO,
410db501f7SEbru Akagunduz 	SCAN_LACK_REFERENCED_PAGE,
42b46e756fSKirill A. Shutemov 	SCAN_PAGE_NULL,
43b46e756fSKirill A. Shutemov 	SCAN_SCAN_ABORT,
44b46e756fSKirill A. Shutemov 	SCAN_PAGE_COUNT,
45b46e756fSKirill A. Shutemov 	SCAN_PAGE_LRU,
46b46e756fSKirill A. Shutemov 	SCAN_PAGE_LOCK,
47b46e756fSKirill A. Shutemov 	SCAN_PAGE_ANON,
48b46e756fSKirill A. Shutemov 	SCAN_PAGE_COMPOUND,
49b46e756fSKirill A. Shutemov 	SCAN_ANY_PROCESS,
50b46e756fSKirill A. Shutemov 	SCAN_VMA_NULL,
51b46e756fSKirill A. Shutemov 	SCAN_VMA_CHECK,
52b46e756fSKirill A. Shutemov 	SCAN_ADDRESS_RANGE,
53b46e756fSKirill A. Shutemov 	SCAN_DEL_PAGE_LRU,
54b46e756fSKirill A. Shutemov 	SCAN_ALLOC_HUGE_PAGE_FAIL,
55b46e756fSKirill A. Shutemov 	SCAN_CGROUP_CHARGE_FAIL,
56f3f0e1d2SKirill A. Shutemov 	SCAN_TRUNCATED,
5799cb0dbdSSong Liu 	SCAN_PAGE_HAS_PRIVATE,
58b46e756fSKirill A. Shutemov };
59b46e756fSKirill A. Shutemov 
60b46e756fSKirill A. Shutemov #define CREATE_TRACE_POINTS
61b46e756fSKirill A. Shutemov #include <trace/events/huge_memory.h>
62b46e756fSKirill A. Shutemov 
634aab2be0SVijay Balakrishna static struct task_struct *khugepaged_thread __read_mostly;
644aab2be0SVijay Balakrishna static DEFINE_MUTEX(khugepaged_mutex);
654aab2be0SVijay Balakrishna 
66b46e756fSKirill A. Shutemov /* default scan 8*512 pte (or vmas) every 30 second */
67b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_to_scan __read_mostly;
68b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_collapsed;
69b46e756fSKirill A. Shutemov static unsigned int khugepaged_full_scans;
70b46e756fSKirill A. Shutemov static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
71b46e756fSKirill A. Shutemov /* during fragmentation poll the hugepage allocator once every minute */
72b46e756fSKirill A. Shutemov static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
73b46e756fSKirill A. Shutemov static unsigned long khugepaged_sleep_expire;
74b46e756fSKirill A. Shutemov static DEFINE_SPINLOCK(khugepaged_mm_lock);
75b46e756fSKirill A. Shutemov static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
76b46e756fSKirill A. Shutemov /*
77b46e756fSKirill A. Shutemov  * default collapse hugepages if there is at least one pte mapped like
78b46e756fSKirill A. Shutemov  * it would have happened if the vma was large enough during page
79b46e756fSKirill A. Shutemov  * fault.
80d8ea7cc8SZach O'Keefe  *
81d8ea7cc8SZach O'Keefe  * Note that these are only respected if collapse was initiated by khugepaged.
82b46e756fSKirill A. Shutemov  */
83b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_none __read_mostly;
84b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_swap __read_mostly;
8571a2c112SKirill A. Shutemov static unsigned int khugepaged_max_ptes_shared __read_mostly;
86b46e756fSKirill A. Shutemov 
87b46e756fSKirill A. Shutemov #define MM_SLOTS_HASH_BITS 10
88b46e756fSKirill A. Shutemov static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
89b46e756fSKirill A. Shutemov 
90b46e756fSKirill A. Shutemov static struct kmem_cache *mm_slot_cache __read_mostly;
91b46e756fSKirill A. Shutemov 
9227e1f827SSong Liu #define MAX_PTE_MAPPED_THP 8
9327e1f827SSong Liu 
9434d6b470SZach O'Keefe struct collapse_control {
95d8ea7cc8SZach O'Keefe 	bool is_khugepaged;
96d8ea7cc8SZach O'Keefe 
9734d6b470SZach O'Keefe 	/* Num pages scanned per node */
9834d6b470SZach O'Keefe 	u32 node_load[MAX_NUMNODES];
9934d6b470SZach O'Keefe 
100e031ff96SYang Shi 	/* nodemask for allocation fallback */
101e031ff96SYang Shi 	nodemask_t alloc_nmask;
10234d6b470SZach O'Keefe };
10334d6b470SZach O'Keefe 
104b46e756fSKirill A. Shutemov /**
105b26e2701SQi Zheng  * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
106b26e2701SQi Zheng  * @slot: hash lookup from mm to mm_slot
107336e6b53SAlex Shi  * @nr_pte_mapped_thp: number of pte mapped THP
108336e6b53SAlex Shi  * @pte_mapped_thp: address array corresponding pte mapped THP
109b46e756fSKirill A. Shutemov  */
110b26e2701SQi Zheng struct khugepaged_mm_slot {
111b26e2701SQi Zheng 	struct mm_slot slot;
11227e1f827SSong Liu 
11327e1f827SSong Liu 	/* pte-mapped THP in this mm */
11427e1f827SSong Liu 	int nr_pte_mapped_thp;
11527e1f827SSong Liu 	unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
116b46e756fSKirill A. Shutemov };
117b46e756fSKirill A. Shutemov 
118b46e756fSKirill A. Shutemov /**
119b46e756fSKirill A. Shutemov  * struct khugepaged_scan - cursor for scanning
120b46e756fSKirill A. Shutemov  * @mm_head: the head of the mm list to scan
121b46e756fSKirill A. Shutemov  * @mm_slot: the current mm_slot we are scanning
122b46e756fSKirill A. Shutemov  * @address: the next address inside that to be scanned
123b46e756fSKirill A. Shutemov  *
124b46e756fSKirill A. Shutemov  * There is only the one khugepaged_scan instance of this cursor structure.
125b46e756fSKirill A. Shutemov  */
126b46e756fSKirill A. Shutemov struct khugepaged_scan {
127b46e756fSKirill A. Shutemov 	struct list_head mm_head;
128b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
129b46e756fSKirill A. Shutemov 	unsigned long address;
130b46e756fSKirill A. Shutemov };
131b46e756fSKirill A. Shutemov 
132b46e756fSKirill A. Shutemov static struct khugepaged_scan khugepaged_scan = {
133b46e756fSKirill A. Shutemov 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
134b46e756fSKirill A. Shutemov };
135b46e756fSKirill A. Shutemov 
136e1465d12SJérémy Lefaure #ifdef CONFIG_SYSFS
137b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
138b46e756fSKirill A. Shutemov 					 struct kobj_attribute *attr,
139b46e756fSKirill A. Shutemov 					 char *buf)
140b46e756fSKirill A. Shutemov {
141ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
142b46e756fSKirill A. Shutemov }
143b46e756fSKirill A. Shutemov 
144b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
145b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
146b46e756fSKirill A. Shutemov 					  const char *buf, size_t count)
147b46e756fSKirill A. Shutemov {
148dfefd226SAlexey Dobriyan 	unsigned int msecs;
149b46e756fSKirill A. Shutemov 	int err;
150b46e756fSKirill A. Shutemov 
151dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
152dfefd226SAlexey Dobriyan 	if (err)
153b46e756fSKirill A. Shutemov 		return -EINVAL;
154b46e756fSKirill A. Shutemov 
155b46e756fSKirill A. Shutemov 	khugepaged_scan_sleep_millisecs = msecs;
156b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
157b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
158b46e756fSKirill A. Shutemov 
159b46e756fSKirill A. Shutemov 	return count;
160b46e756fSKirill A. Shutemov }
161b46e756fSKirill A. Shutemov static struct kobj_attribute scan_sleep_millisecs_attr =
1626dcdc94dSMiaohe Lin 	__ATTR_RW(scan_sleep_millisecs);
163b46e756fSKirill A. Shutemov 
164b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
165b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
166b46e756fSKirill A. Shutemov 					  char *buf)
167b46e756fSKirill A. Shutemov {
168ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
169b46e756fSKirill A. Shutemov }
170b46e756fSKirill A. Shutemov 
171b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
172b46e756fSKirill A. Shutemov 					   struct kobj_attribute *attr,
173b46e756fSKirill A. Shutemov 					   const char *buf, size_t count)
174b46e756fSKirill A. Shutemov {
175dfefd226SAlexey Dobriyan 	unsigned int msecs;
176b46e756fSKirill A. Shutemov 	int err;
177b46e756fSKirill A. Shutemov 
178dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
179dfefd226SAlexey Dobriyan 	if (err)
180b46e756fSKirill A. Shutemov 		return -EINVAL;
181b46e756fSKirill A. Shutemov 
182b46e756fSKirill A. Shutemov 	khugepaged_alloc_sleep_millisecs = msecs;
183b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
184b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
185b46e756fSKirill A. Shutemov 
186b46e756fSKirill A. Shutemov 	return count;
187b46e756fSKirill A. Shutemov }
188b46e756fSKirill A. Shutemov static struct kobj_attribute alloc_sleep_millisecs_attr =
1896dcdc94dSMiaohe Lin 	__ATTR_RW(alloc_sleep_millisecs);
190b46e756fSKirill A. Shutemov 
191b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_show(struct kobject *kobj,
192b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
193b46e756fSKirill A. Shutemov 				  char *buf)
194b46e756fSKirill A. Shutemov {
195ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
196b46e756fSKirill A. Shutemov }
197b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_store(struct kobject *kobj,
198b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
199b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
200b46e756fSKirill A. Shutemov {
201dfefd226SAlexey Dobriyan 	unsigned int pages;
202b46e756fSKirill A. Shutemov 	int err;
203b46e756fSKirill A. Shutemov 
204dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &pages);
205dfefd226SAlexey Dobriyan 	if (err || !pages)
206b46e756fSKirill A. Shutemov 		return -EINVAL;
207b46e756fSKirill A. Shutemov 
208b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = pages;
209b46e756fSKirill A. Shutemov 
210b46e756fSKirill A. Shutemov 	return count;
211b46e756fSKirill A. Shutemov }
212b46e756fSKirill A. Shutemov static struct kobj_attribute pages_to_scan_attr =
2136dcdc94dSMiaohe Lin 	__ATTR_RW(pages_to_scan);
214b46e756fSKirill A. Shutemov 
215b46e756fSKirill A. Shutemov static ssize_t pages_collapsed_show(struct kobject *kobj,
216b46e756fSKirill A. Shutemov 				    struct kobj_attribute *attr,
217b46e756fSKirill A. Shutemov 				    char *buf)
218b46e756fSKirill A. Shutemov {
219ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
220b46e756fSKirill A. Shutemov }
221b46e756fSKirill A. Shutemov static struct kobj_attribute pages_collapsed_attr =
222b46e756fSKirill A. Shutemov 	__ATTR_RO(pages_collapsed);
223b46e756fSKirill A. Shutemov 
224b46e756fSKirill A. Shutemov static ssize_t full_scans_show(struct kobject *kobj,
225b46e756fSKirill A. Shutemov 			       struct kobj_attribute *attr,
226b46e756fSKirill A. Shutemov 			       char *buf)
227b46e756fSKirill A. Shutemov {
228ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
229b46e756fSKirill A. Shutemov }
230b46e756fSKirill A. Shutemov static struct kobj_attribute full_scans_attr =
231b46e756fSKirill A. Shutemov 	__ATTR_RO(full_scans);
232b46e756fSKirill A. Shutemov 
2336dcdc94dSMiaohe Lin static ssize_t defrag_show(struct kobject *kobj,
234b46e756fSKirill A. Shutemov 			   struct kobj_attribute *attr, char *buf)
235b46e756fSKirill A. Shutemov {
236b46e756fSKirill A. Shutemov 	return single_hugepage_flag_show(kobj, attr, buf,
237b46e756fSKirill A. Shutemov 					 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
238b46e756fSKirill A. Shutemov }
2396dcdc94dSMiaohe Lin static ssize_t defrag_store(struct kobject *kobj,
240b46e756fSKirill A. Shutemov 			    struct kobj_attribute *attr,
241b46e756fSKirill A. Shutemov 			    const char *buf, size_t count)
242b46e756fSKirill A. Shutemov {
243b46e756fSKirill A. Shutemov 	return single_hugepage_flag_store(kobj, attr, buf, count,
244b46e756fSKirill A. Shutemov 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
245b46e756fSKirill A. Shutemov }
246b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_defrag_attr =
2476dcdc94dSMiaohe Lin 	__ATTR_RW(defrag);
248b46e756fSKirill A. Shutemov 
249b46e756fSKirill A. Shutemov /*
250b46e756fSKirill A. Shutemov  * max_ptes_none controls if khugepaged should collapse hugepages over
251b46e756fSKirill A. Shutemov  * any unmapped ptes in turn potentially increasing the memory
252b46e756fSKirill A. Shutemov  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
253b46e756fSKirill A. Shutemov  * reduce the available free memory in the system as it
254b46e756fSKirill A. Shutemov  * runs. Increasing max_ptes_none will instead potentially reduce the
255b46e756fSKirill A. Shutemov  * free memory in the system during the khugepaged scan.
256b46e756fSKirill A. Shutemov  */
2576dcdc94dSMiaohe Lin static ssize_t max_ptes_none_show(struct kobject *kobj,
258b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
259b46e756fSKirill A. Shutemov 				  char *buf)
260b46e756fSKirill A. Shutemov {
261ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
262b46e756fSKirill A. Shutemov }
2636dcdc94dSMiaohe Lin static ssize_t max_ptes_none_store(struct kobject *kobj,
264b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
265b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
266b46e756fSKirill A. Shutemov {
267b46e756fSKirill A. Shutemov 	int err;
268b46e756fSKirill A. Shutemov 	unsigned long max_ptes_none;
269b46e756fSKirill A. Shutemov 
270b46e756fSKirill A. Shutemov 	err = kstrtoul(buf, 10, &max_ptes_none);
271b46e756fSKirill A. Shutemov 	if (err || max_ptes_none > HPAGE_PMD_NR - 1)
272b46e756fSKirill A. Shutemov 		return -EINVAL;
273b46e756fSKirill A. Shutemov 
274b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = max_ptes_none;
275b46e756fSKirill A. Shutemov 
276b46e756fSKirill A. Shutemov 	return count;
277b46e756fSKirill A. Shutemov }
278b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_none_attr =
2796dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_none);
280b46e756fSKirill A. Shutemov 
2816dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_show(struct kobject *kobj,
282b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
283b46e756fSKirill A. Shutemov 				  char *buf)
284b46e756fSKirill A. Shutemov {
285ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
286b46e756fSKirill A. Shutemov }
287b46e756fSKirill A. Shutemov 
2886dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_store(struct kobject *kobj,
289b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
290b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
291b46e756fSKirill A. Shutemov {
292b46e756fSKirill A. Shutemov 	int err;
293b46e756fSKirill A. Shutemov 	unsigned long max_ptes_swap;
294b46e756fSKirill A. Shutemov 
295b46e756fSKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_swap);
296b46e756fSKirill A. Shutemov 	if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
297b46e756fSKirill A. Shutemov 		return -EINVAL;
298b46e756fSKirill A. Shutemov 
299b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = max_ptes_swap;
300b46e756fSKirill A. Shutemov 
301b46e756fSKirill A. Shutemov 	return count;
302b46e756fSKirill A. Shutemov }
303b46e756fSKirill A. Shutemov 
304b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_swap_attr =
3056dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_swap);
306b46e756fSKirill A. Shutemov 
3076dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_show(struct kobject *kobj,
30871a2c112SKirill A. Shutemov 				    struct kobj_attribute *attr,
30971a2c112SKirill A. Shutemov 				    char *buf)
31071a2c112SKirill A. Shutemov {
311ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
31271a2c112SKirill A. Shutemov }
31371a2c112SKirill A. Shutemov 
3146dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_store(struct kobject *kobj,
31571a2c112SKirill A. Shutemov 				     struct kobj_attribute *attr,
31671a2c112SKirill A. Shutemov 				     const char *buf, size_t count)
31771a2c112SKirill A. Shutemov {
31871a2c112SKirill A. Shutemov 	int err;
31971a2c112SKirill A. Shutemov 	unsigned long max_ptes_shared;
32071a2c112SKirill A. Shutemov 
32171a2c112SKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_shared);
32271a2c112SKirill A. Shutemov 	if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
32371a2c112SKirill A. Shutemov 		return -EINVAL;
32471a2c112SKirill A. Shutemov 
32571a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = max_ptes_shared;
32671a2c112SKirill A. Shutemov 
32771a2c112SKirill A. Shutemov 	return count;
32871a2c112SKirill A. Shutemov }
32971a2c112SKirill A. Shutemov 
33071a2c112SKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_shared_attr =
3316dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_shared);
33271a2c112SKirill A. Shutemov 
333b46e756fSKirill A. Shutemov static struct attribute *khugepaged_attr[] = {
334b46e756fSKirill A. Shutemov 	&khugepaged_defrag_attr.attr,
335b46e756fSKirill A. Shutemov 	&khugepaged_max_ptes_none_attr.attr,
33671a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_swap_attr.attr,
33771a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_shared_attr.attr,
338b46e756fSKirill A. Shutemov 	&pages_to_scan_attr.attr,
339b46e756fSKirill A. Shutemov 	&pages_collapsed_attr.attr,
340b46e756fSKirill A. Shutemov 	&full_scans_attr.attr,
341b46e756fSKirill A. Shutemov 	&scan_sleep_millisecs_attr.attr,
342b46e756fSKirill A. Shutemov 	&alloc_sleep_millisecs_attr.attr,
343b46e756fSKirill A. Shutemov 	NULL,
344b46e756fSKirill A. Shutemov };
345b46e756fSKirill A. Shutemov 
346b46e756fSKirill A. Shutemov struct attribute_group khugepaged_attr_group = {
347b46e756fSKirill A. Shutemov 	.attrs = khugepaged_attr,
348b46e756fSKirill A. Shutemov 	.name = "khugepaged",
349b46e756fSKirill A. Shutemov };
350e1465d12SJérémy Lefaure #endif /* CONFIG_SYSFS */
351b46e756fSKirill A. Shutemov 
352b46e756fSKirill A. Shutemov int hugepage_madvise(struct vm_area_struct *vma,
353b46e756fSKirill A. Shutemov 		     unsigned long *vm_flags, int advice)
354b46e756fSKirill A. Shutemov {
355b46e756fSKirill A. Shutemov 	switch (advice) {
356b46e756fSKirill A. Shutemov 	case MADV_HUGEPAGE:
357b46e756fSKirill A. Shutemov #ifdef CONFIG_S390
358b46e756fSKirill A. Shutemov 		/*
359b46e756fSKirill A. Shutemov 		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
360b46e756fSKirill A. Shutemov 		 * can't handle this properly after s390_enable_sie, so we simply
361b46e756fSKirill A. Shutemov 		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
362b46e756fSKirill A. Shutemov 		 */
363b46e756fSKirill A. Shutemov 		if (mm_has_pgste(vma->vm_mm))
364b46e756fSKirill A. Shutemov 			return 0;
365b46e756fSKirill A. Shutemov #endif
366b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_NOHUGEPAGE;
367b46e756fSKirill A. Shutemov 		*vm_flags |= VM_HUGEPAGE;
368b46e756fSKirill A. Shutemov 		/*
369b46e756fSKirill A. Shutemov 		 * If the vma become good for khugepaged to scan,
370b46e756fSKirill A. Shutemov 		 * register it here without waiting a page fault that
371b46e756fSKirill A. Shutemov 		 * may not happen any time soon.
372b46e756fSKirill A. Shutemov 		 */
373c791576cSYang Shi 		khugepaged_enter_vma(vma, *vm_flags);
374b46e756fSKirill A. Shutemov 		break;
375b46e756fSKirill A. Shutemov 	case MADV_NOHUGEPAGE:
376b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_HUGEPAGE;
377b46e756fSKirill A. Shutemov 		*vm_flags |= VM_NOHUGEPAGE;
378b46e756fSKirill A. Shutemov 		/*
379b46e756fSKirill A. Shutemov 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
380b46e756fSKirill A. Shutemov 		 * this vma even if we leave the mm registered in khugepaged if
381b46e756fSKirill A. Shutemov 		 * it got registered before VM_NOHUGEPAGE was set.
382b46e756fSKirill A. Shutemov 		 */
383b46e756fSKirill A. Shutemov 		break;
384b46e756fSKirill A. Shutemov 	}
385b46e756fSKirill A. Shutemov 
386b46e756fSKirill A. Shutemov 	return 0;
387b46e756fSKirill A. Shutemov }
388b46e756fSKirill A. Shutemov 
389b46e756fSKirill A. Shutemov int __init khugepaged_init(void)
390b46e756fSKirill A. Shutemov {
391b46e756fSKirill A. Shutemov 	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
392b26e2701SQi Zheng 					  sizeof(struct khugepaged_mm_slot),
393b26e2701SQi Zheng 					  __alignof__(struct khugepaged_mm_slot),
394b26e2701SQi Zheng 					  0, NULL);
395b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)
396b46e756fSKirill A. Shutemov 		return -ENOMEM;
397b46e756fSKirill A. Shutemov 
398b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
399b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
400b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
40171a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
402b46e756fSKirill A. Shutemov 
403b46e756fSKirill A. Shutemov 	return 0;
404b46e756fSKirill A. Shutemov }
405b46e756fSKirill A. Shutemov 
406b46e756fSKirill A. Shutemov void __init khugepaged_destroy(void)
407b46e756fSKirill A. Shutemov {
408b46e756fSKirill A. Shutemov 	kmem_cache_destroy(mm_slot_cache);
409b46e756fSKirill A. Shutemov }
410b46e756fSKirill A. Shutemov 
4117d2c4385SZach O'Keefe static inline int hpage_collapse_test_exit(struct mm_struct *mm)
412b46e756fSKirill A. Shutemov {
4134d45e75aSJann Horn 	return atomic_read(&mm->mm_users) == 0;
414b46e756fSKirill A. Shutemov }
415b46e756fSKirill A. Shutemov 
416d2081b2bSYang Shi void __khugepaged_enter(struct mm_struct *mm)
417b46e756fSKirill A. Shutemov {
418b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
419b26e2701SQi Zheng 	struct mm_slot *slot;
420b46e756fSKirill A. Shutemov 	int wakeup;
421b46e756fSKirill A. Shutemov 
422b26e2701SQi Zheng 	mm_slot = mm_slot_alloc(mm_slot_cache);
423b46e756fSKirill A. Shutemov 	if (!mm_slot)
424d2081b2bSYang Shi 		return;
425b46e756fSKirill A. Shutemov 
426b26e2701SQi Zheng 	slot = &mm_slot->slot;
427b26e2701SQi Zheng 
428b46e756fSKirill A. Shutemov 	/* __khugepaged_exit() must not run from under us */
4297d2c4385SZach O'Keefe 	VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
430b46e756fSKirill A. Shutemov 	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
431b26e2701SQi Zheng 		mm_slot_free(mm_slot_cache, mm_slot);
432d2081b2bSYang Shi 		return;
433b46e756fSKirill A. Shutemov 	}
434b46e756fSKirill A. Shutemov 
435b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
436b26e2701SQi Zheng 	mm_slot_insert(mm_slots_hash, mm, slot);
437b46e756fSKirill A. Shutemov 	/*
438b46e756fSKirill A. Shutemov 	 * Insert just behind the scanning cursor, to let the area settle
439b46e756fSKirill A. Shutemov 	 * down a little.
440b46e756fSKirill A. Shutemov 	 */
441b46e756fSKirill A. Shutemov 	wakeup = list_empty(&khugepaged_scan.mm_head);
442b26e2701SQi Zheng 	list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
443b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
444b46e756fSKirill A. Shutemov 
445f1f10076SVegard Nossum 	mmgrab(mm);
446b46e756fSKirill A. Shutemov 	if (wakeup)
447b46e756fSKirill A. Shutemov 		wake_up_interruptible(&khugepaged_wait);
448b46e756fSKirill A. Shutemov }
449b46e756fSKirill A. Shutemov 
450c791576cSYang Shi void khugepaged_enter_vma(struct vm_area_struct *vma,
451b46e756fSKirill A. Shutemov 			  unsigned long vm_flags)
452b46e756fSKirill A. Shutemov {
4532647d11bSYang Shi 	if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
4541064026bSYang Shi 	    hugepage_flags_enabled()) {
455a7f4e6e4SZach O'Keefe 		if (hugepage_vma_check(vma, vm_flags, false, false, true))
4562647d11bSYang Shi 			__khugepaged_enter(vma->vm_mm);
4572647d11bSYang Shi 	}
458b46e756fSKirill A. Shutemov }
459b46e756fSKirill A. Shutemov 
460b46e756fSKirill A. Shutemov void __khugepaged_exit(struct mm_struct *mm)
461b46e756fSKirill A. Shutemov {
462b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
463b26e2701SQi Zheng 	struct mm_slot *slot;
464b46e756fSKirill A. Shutemov 	int free = 0;
465b46e756fSKirill A. Shutemov 
466b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
467b26e2701SQi Zheng 	slot = mm_slot_lookup(mm_slots_hash, mm);
468b26e2701SQi Zheng 	mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
469b46e756fSKirill A. Shutemov 	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
470b26e2701SQi Zheng 		hash_del(&slot->hash);
471b26e2701SQi Zheng 		list_del(&slot->mm_node);
472b46e756fSKirill A. Shutemov 		free = 1;
473b46e756fSKirill A. Shutemov 	}
474b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
475b46e756fSKirill A. Shutemov 
476b46e756fSKirill A. Shutemov 	if (free) {
477b46e756fSKirill A. Shutemov 		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
478b26e2701SQi Zheng 		mm_slot_free(mm_slot_cache, mm_slot);
479b46e756fSKirill A. Shutemov 		mmdrop(mm);
480b46e756fSKirill A. Shutemov 	} else if (mm_slot) {
481b46e756fSKirill A. Shutemov 		/*
482b46e756fSKirill A. Shutemov 		 * This is required to serialize against
4837d2c4385SZach O'Keefe 		 * hpage_collapse_test_exit() (which is guaranteed to run
4847d2c4385SZach O'Keefe 		 * under mmap sem read mode). Stop here (after we return all
4857d2c4385SZach O'Keefe 		 * pagetables will be destroyed) until khugepaged has finished
4867d2c4385SZach O'Keefe 		 * working on the pagetables under the mmap_lock.
487b46e756fSKirill A. Shutemov 		 */
488d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
489d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
490b46e756fSKirill A. Shutemov 	}
491b46e756fSKirill A. Shutemov }
492b46e756fSKirill A. Shutemov 
493*92644f58SVishal Moola (Oracle) static void release_pte_folio(struct folio *folio)
494*92644f58SVishal Moola (Oracle) {
495*92644f58SVishal Moola (Oracle) 	node_stat_mod_folio(folio,
496*92644f58SVishal Moola (Oracle) 			NR_ISOLATED_ANON + folio_is_file_lru(folio),
497*92644f58SVishal Moola (Oracle) 			-folio_nr_pages(folio));
498*92644f58SVishal Moola (Oracle) 	folio_unlock(folio);
499*92644f58SVishal Moola (Oracle) 	folio_putback_lru(folio);
500*92644f58SVishal Moola (Oracle) }
501*92644f58SVishal Moola (Oracle) 
502b46e756fSKirill A. Shutemov static void release_pte_page(struct page *page)
503b46e756fSKirill A. Shutemov {
504*92644f58SVishal Moola (Oracle) 	release_pte_folio(page_folio(page));
505b46e756fSKirill A. Shutemov }
506b46e756fSKirill A. Shutemov 
5075503fbf2SKirill A. Shutemov static void release_pte_pages(pte_t *pte, pte_t *_pte,
5085503fbf2SKirill A. Shutemov 		struct list_head *compound_pagelist)
509b46e756fSKirill A. Shutemov {
5105503fbf2SKirill A. Shutemov 	struct page *page, *tmp;
5115503fbf2SKirill A. Shutemov 
512b46e756fSKirill A. Shutemov 	while (--_pte >= pte) {
513b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
5145503fbf2SKirill A. Shutemov 
5155503fbf2SKirill A. Shutemov 		page = pte_page(pteval);
5165503fbf2SKirill A. Shutemov 		if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
5175503fbf2SKirill A. Shutemov 				!PageCompound(page))
5185503fbf2SKirill A. Shutemov 			release_pte_page(page);
5195503fbf2SKirill A. Shutemov 	}
5205503fbf2SKirill A. Shutemov 
5215503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
5225503fbf2SKirill A. Shutemov 		list_del(&page->lru);
5235503fbf2SKirill A. Shutemov 		release_pte_page(page);
524b46e756fSKirill A. Shutemov 	}
525b46e756fSKirill A. Shutemov }
526b46e756fSKirill A. Shutemov 
5279445689fSKirill A. Shutemov static bool is_refcount_suitable(struct page *page)
5289445689fSKirill A. Shutemov {
5299445689fSKirill A. Shutemov 	int expected_refcount;
5309445689fSKirill A. Shutemov 
5319445689fSKirill A. Shutemov 	expected_refcount = total_mapcount(page);
5329445689fSKirill A. Shutemov 	if (PageSwapCache(page))
5339445689fSKirill A. Shutemov 		expected_refcount += compound_nr(page);
5349445689fSKirill A. Shutemov 
5359445689fSKirill A. Shutemov 	return page_count(page) == expected_refcount;
5369445689fSKirill A. Shutemov }
5379445689fSKirill A. Shutemov 
538b46e756fSKirill A. Shutemov static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
539b46e756fSKirill A. Shutemov 					unsigned long address,
5405503fbf2SKirill A. Shutemov 					pte_t *pte,
541d8ea7cc8SZach O'Keefe 					struct collapse_control *cc,
5425503fbf2SKirill A. Shutemov 					struct list_head *compound_pagelist)
543b46e756fSKirill A. Shutemov {
544b46e756fSKirill A. Shutemov 	struct page *page = NULL;
545b46e756fSKirill A. Shutemov 	pte_t *_pte;
54650ad2f24SZach O'Keefe 	int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
5470db501f7SEbru Akagunduz 	bool writable = false;
548b46e756fSKirill A. Shutemov 
549b46e756fSKirill A. Shutemov 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
550b46e756fSKirill A. Shutemov 	     _pte++, address += PAGE_SIZE) {
551b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
552b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || (pte_present(pteval) &&
553b46e756fSKirill A. Shutemov 				is_zero_pfn(pte_pfn(pteval)))) {
554d8ea7cc8SZach O'Keefe 			++none_or_zero;
555b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
556d8ea7cc8SZach O'Keefe 			    (!cc->is_khugepaged ||
557d8ea7cc8SZach O'Keefe 			     none_or_zero <= khugepaged_max_ptes_none)) {
558b46e756fSKirill A. Shutemov 				continue;
559b46e756fSKirill A. Shutemov 			} else {
560b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
561e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
562b46e756fSKirill A. Shutemov 				goto out;
563b46e756fSKirill A. Shutemov 			}
564b46e756fSKirill A. Shutemov 		}
565b46e756fSKirill A. Shutemov 		if (!pte_present(pteval)) {
566b46e756fSKirill A. Shutemov 			result = SCAN_PTE_NON_PRESENT;
567b46e756fSKirill A. Shutemov 			goto out;
568b46e756fSKirill A. Shutemov 		}
569b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, address, pteval);
5703218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
571b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
572b46e756fSKirill A. Shutemov 			goto out;
573b46e756fSKirill A. Shutemov 		}
574b46e756fSKirill A. Shutemov 
575b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageAnon(page), page);
576b46e756fSKirill A. Shutemov 
577d8ea7cc8SZach O'Keefe 		if (page_mapcount(page) > 1) {
578d8ea7cc8SZach O'Keefe 			++shared;
579d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
580d8ea7cc8SZach O'Keefe 			    shared > khugepaged_max_ptes_shared) {
58171a2c112SKirill A. Shutemov 				result = SCAN_EXCEED_SHARED_PTE;
582e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
58371a2c112SKirill A. Shutemov 				goto out;
58471a2c112SKirill A. Shutemov 			}
585d8ea7cc8SZach O'Keefe 		}
58671a2c112SKirill A. Shutemov 
5875503fbf2SKirill A. Shutemov 		if (PageCompound(page)) {
5885503fbf2SKirill A. Shutemov 			struct page *p;
5895503fbf2SKirill A. Shutemov 			page = compound_head(page);
5905503fbf2SKirill A. Shutemov 
5915503fbf2SKirill A. Shutemov 			/*
5925503fbf2SKirill A. Shutemov 			 * Check if we have dealt with the compound page
5935503fbf2SKirill A. Shutemov 			 * already
5945503fbf2SKirill A. Shutemov 			 */
5955503fbf2SKirill A. Shutemov 			list_for_each_entry(p, compound_pagelist, lru) {
5965503fbf2SKirill A. Shutemov 				if (page == p)
5975503fbf2SKirill A. Shutemov 					goto next;
5985503fbf2SKirill A. Shutemov 			}
5995503fbf2SKirill A. Shutemov 		}
6005503fbf2SKirill A. Shutemov 
601b46e756fSKirill A. Shutemov 		/*
602b46e756fSKirill A. Shutemov 		 * We can do it before isolate_lru_page because the
603b46e756fSKirill A. Shutemov 		 * page can't be freed from under us. NOTE: PG_lock
604b46e756fSKirill A. Shutemov 		 * is needed to serialize against split_huge_page
605b46e756fSKirill A. Shutemov 		 * when invoked from the VM.
606b46e756fSKirill A. Shutemov 		 */
607b46e756fSKirill A. Shutemov 		if (!trylock_page(page)) {
608b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
609b46e756fSKirill A. Shutemov 			goto out;
610b46e756fSKirill A. Shutemov 		}
611b46e756fSKirill A. Shutemov 
612b46e756fSKirill A. Shutemov 		/*
6139445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
6149445689fSKirill A. Shutemov 		 *
6159445689fSKirill A. Shutemov 		 * The page table that maps the page has been already unlinked
6169445689fSKirill A. Shutemov 		 * from the page table tree and this process cannot get
617f0953a1bSIngo Molnar 		 * an additional pin on the page.
6189445689fSKirill A. Shutemov 		 *
6199445689fSKirill A. Shutemov 		 * New pins can come later if the page is shared across fork,
6209445689fSKirill A. Shutemov 		 * but not from this process. The other process cannot write to
6219445689fSKirill A. Shutemov 		 * the page, only trigger CoW.
622b46e756fSKirill A. Shutemov 		 */
6239445689fSKirill A. Shutemov 		if (!is_refcount_suitable(page)) {
624b46e756fSKirill A. Shutemov 			unlock_page(page);
625b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
626b46e756fSKirill A. Shutemov 			goto out;
627b46e756fSKirill A. Shutemov 		}
628b46e756fSKirill A. Shutemov 
629b46e756fSKirill A. Shutemov 		/*
630b46e756fSKirill A. Shutemov 		 * Isolate the page to avoid collapsing an hugepage
631b46e756fSKirill A. Shutemov 		 * currently in use by the VM.
632b46e756fSKirill A. Shutemov 		 */
633b46e756fSKirill A. Shutemov 		if (isolate_lru_page(page)) {
634b46e756fSKirill A. Shutemov 			unlock_page(page);
635b46e756fSKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
636b46e756fSKirill A. Shutemov 			goto out;
637b46e756fSKirill A. Shutemov 		}
6385503fbf2SKirill A. Shutemov 		mod_node_page_state(page_pgdat(page),
6395503fbf2SKirill A. Shutemov 				NR_ISOLATED_ANON + page_is_file_lru(page),
6405503fbf2SKirill A. Shutemov 				compound_nr(page));
641b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
642b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageLRU(page), page);
643b46e756fSKirill A. Shutemov 
6445503fbf2SKirill A. Shutemov 		if (PageCompound(page))
6455503fbf2SKirill A. Shutemov 			list_add_tail(&page->lru, compound_pagelist);
6465503fbf2SKirill A. Shutemov next:
647d8ea7cc8SZach O'Keefe 		/*
648d8ea7cc8SZach O'Keefe 		 * If collapse was initiated by khugepaged, check that there is
649d8ea7cc8SZach O'Keefe 		 * enough young pte to justify collapsing the page
650d8ea7cc8SZach O'Keefe 		 */
651d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
652d8ea7cc8SZach O'Keefe 		    (pte_young(pteval) || page_is_young(page) ||
653d8ea7cc8SZach O'Keefe 		     PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
654d8ea7cc8SZach O'Keefe 								     address)))
6550db501f7SEbru Akagunduz 			referenced++;
6565503fbf2SKirill A. Shutemov 
6575503fbf2SKirill A. Shutemov 		if (pte_write(pteval))
6585503fbf2SKirill A. Shutemov 			writable = true;
659b46e756fSKirill A. Shutemov 	}
66074e579bfSMiaohe Lin 
66174e579bfSMiaohe Lin 	if (unlikely(!writable)) {
66274e579bfSMiaohe Lin 		result = SCAN_PAGE_RO;
663d8ea7cc8SZach O'Keefe 	} else if (unlikely(cc->is_khugepaged && !referenced)) {
66474e579bfSMiaohe Lin 		result = SCAN_LACK_REFERENCED_PAGE;
66574e579bfSMiaohe Lin 	} else {
666b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
667b46e756fSKirill A. Shutemov 		trace_mm_collapse_huge_page_isolate(page, none_or_zero,
668b46e756fSKirill A. Shutemov 						    referenced, writable, result);
66950ad2f24SZach O'Keefe 		return result;
670b46e756fSKirill A. Shutemov 	}
671b46e756fSKirill A. Shutemov out:
6725503fbf2SKirill A. Shutemov 	release_pte_pages(pte, _pte, compound_pagelist);
673b46e756fSKirill A. Shutemov 	trace_mm_collapse_huge_page_isolate(page, none_or_zero,
674b46e756fSKirill A. Shutemov 					    referenced, writable, result);
67550ad2f24SZach O'Keefe 	return result;
676b46e756fSKirill A. Shutemov }
677b46e756fSKirill A. Shutemov 
678b46e756fSKirill A. Shutemov static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
679b46e756fSKirill A. Shutemov 				      struct vm_area_struct *vma,
680b46e756fSKirill A. Shutemov 				      unsigned long address,
6815503fbf2SKirill A. Shutemov 				      spinlock_t *ptl,
6825503fbf2SKirill A. Shutemov 				      struct list_head *compound_pagelist)
683b46e756fSKirill A. Shutemov {
6845503fbf2SKirill A. Shutemov 	struct page *src_page, *tmp;
685b46e756fSKirill A. Shutemov 	pte_t *_pte;
686338a16baSDavid Rientjes 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
687338a16baSDavid Rientjes 				_pte++, page++, address += PAGE_SIZE) {
688b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
689b46e756fSKirill A. Shutemov 
690b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
691b46e756fSKirill A. Shutemov 			clear_user_highpage(page, address);
692b46e756fSKirill A. Shutemov 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
693b46e756fSKirill A. Shutemov 			if (is_zero_pfn(pte_pfn(pteval))) {
694b46e756fSKirill A. Shutemov 				/*
695b46e756fSKirill A. Shutemov 				 * ptl mostly unnecessary.
696b46e756fSKirill A. Shutemov 				 */
697b46e756fSKirill A. Shutemov 				spin_lock(ptl);
69808d5b29eSPasha Tatashin 				ptep_clear(vma->vm_mm, address, _pte);
699b46e756fSKirill A. Shutemov 				spin_unlock(ptl);
700b46e756fSKirill A. Shutemov 			}
701b46e756fSKirill A. Shutemov 		} else {
702b46e756fSKirill A. Shutemov 			src_page = pte_page(pteval);
703b46e756fSKirill A. Shutemov 			copy_user_highpage(page, src_page, address, vma);
7045503fbf2SKirill A. Shutemov 			if (!PageCompound(src_page))
705b46e756fSKirill A. Shutemov 				release_pte_page(src_page);
706b46e756fSKirill A. Shutemov 			/*
707b46e756fSKirill A. Shutemov 			 * ptl mostly unnecessary, but preempt has to
708b46e756fSKirill A. Shutemov 			 * be disabled to update the per-cpu stats
709b46e756fSKirill A. Shutemov 			 * inside page_remove_rmap().
710b46e756fSKirill A. Shutemov 			 */
711b46e756fSKirill A. Shutemov 			spin_lock(ptl);
71208d5b29eSPasha Tatashin 			ptep_clear(vma->vm_mm, address, _pte);
713cea86fe2SHugh Dickins 			page_remove_rmap(src_page, vma, false);
714b46e756fSKirill A. Shutemov 			spin_unlock(ptl);
715b46e756fSKirill A. Shutemov 			free_page_and_swap_cache(src_page);
716b46e756fSKirill A. Shutemov 		}
717b46e756fSKirill A. Shutemov 	}
7185503fbf2SKirill A. Shutemov 
7195503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
7205503fbf2SKirill A. Shutemov 		list_del(&src_page->lru);
7211baec203SMiaohe Lin 		mod_node_page_state(page_pgdat(src_page),
7221baec203SMiaohe Lin 				    NR_ISOLATED_ANON + page_is_file_lru(src_page),
7231baec203SMiaohe Lin 				    -compound_nr(src_page));
7241baec203SMiaohe Lin 		unlock_page(src_page);
7251baec203SMiaohe Lin 		free_swap_cache(src_page);
7261baec203SMiaohe Lin 		putback_lru_page(src_page);
7275503fbf2SKirill A. Shutemov 	}
728b46e756fSKirill A. Shutemov }
729b46e756fSKirill A. Shutemov 
730b46e756fSKirill A. Shutemov static void khugepaged_alloc_sleep(void)
731b46e756fSKirill A. Shutemov {
732b46e756fSKirill A. Shutemov 	DEFINE_WAIT(wait);
733b46e756fSKirill A. Shutemov 
734b46e756fSKirill A. Shutemov 	add_wait_queue(&khugepaged_wait, &wait);
735f5d39b02SPeter Zijlstra 	__set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
736f5d39b02SPeter Zijlstra 	schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
737b46e756fSKirill A. Shutemov 	remove_wait_queue(&khugepaged_wait, &wait);
738b46e756fSKirill A. Shutemov }
739b46e756fSKirill A. Shutemov 
74034d6b470SZach O'Keefe struct collapse_control khugepaged_collapse_control = {
741d8ea7cc8SZach O'Keefe 	.is_khugepaged = true,
74234d6b470SZach O'Keefe };
743b46e756fSKirill A. Shutemov 
7447d2c4385SZach O'Keefe static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
745b46e756fSKirill A. Shutemov {
746b46e756fSKirill A. Shutemov 	int i;
747b46e756fSKirill A. Shutemov 
748b46e756fSKirill A. Shutemov 	/*
749a5f5f91dSMel Gorman 	 * If node_reclaim_mode is disabled, then no extra effort is made to
750b46e756fSKirill A. Shutemov 	 * allocate memory locally.
751b46e756fSKirill A. Shutemov 	 */
752202e35dbSDave Hansen 	if (!node_reclaim_enabled())
753b46e756fSKirill A. Shutemov 		return false;
754b46e756fSKirill A. Shutemov 
755b46e756fSKirill A. Shutemov 	/* If there is a count for this node already, it must be acceptable */
75634d6b470SZach O'Keefe 	if (cc->node_load[nid])
757b46e756fSKirill A. Shutemov 		return false;
758b46e756fSKirill A. Shutemov 
759b46e756fSKirill A. Shutemov 	for (i = 0; i < MAX_NUMNODES; i++) {
76034d6b470SZach O'Keefe 		if (!cc->node_load[i])
761b46e756fSKirill A. Shutemov 			continue;
762a55c7454SMatt Fleming 		if (node_distance(nid, i) > node_reclaim_distance)
763b46e756fSKirill A. Shutemov 			return true;
764b46e756fSKirill A. Shutemov 	}
765b46e756fSKirill A. Shutemov 	return false;
766b46e756fSKirill A. Shutemov }
767b46e756fSKirill A. Shutemov 
7681064026bSYang Shi #define khugepaged_defrag()					\
7691064026bSYang Shi 	(transparent_hugepage_flags &				\
7701064026bSYang Shi 	 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
7711064026bSYang Shi 
772b46e756fSKirill A. Shutemov /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
773b46e756fSKirill A. Shutemov static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
774b46e756fSKirill A. Shutemov {
77525160354SVlastimil Babka 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
776b46e756fSKirill A. Shutemov }
777b46e756fSKirill A. Shutemov 
778b46e756fSKirill A. Shutemov #ifdef CONFIG_NUMA
7797d2c4385SZach O'Keefe static int hpage_collapse_find_target_node(struct collapse_control *cc)
780b46e756fSKirill A. Shutemov {
781b46e756fSKirill A. Shutemov 	int nid, target_node = 0, max_value = 0;
782b46e756fSKirill A. Shutemov 
783b46e756fSKirill A. Shutemov 	/* find first node with max normal pages hit */
784b46e756fSKirill A. Shutemov 	for (nid = 0; nid < MAX_NUMNODES; nid++)
78534d6b470SZach O'Keefe 		if (cc->node_load[nid] > max_value) {
78634d6b470SZach O'Keefe 			max_value = cc->node_load[nid];
787b46e756fSKirill A. Shutemov 			target_node = nid;
788b46e756fSKirill A. Shutemov 		}
789b46e756fSKirill A. Shutemov 
790e031ff96SYang Shi 	for_each_online_node(nid) {
791e031ff96SYang Shi 		if (max_value == cc->node_load[nid])
792e031ff96SYang Shi 			node_set(nid, cc->alloc_nmask);
793b46e756fSKirill A. Shutemov 	}
794b46e756fSKirill A. Shutemov 
795b46e756fSKirill A. Shutemov 	return target_node;
796b46e756fSKirill A. Shutemov }
797c6a7f445SYang Shi #else
7987d2c4385SZach O'Keefe static int hpage_collapse_find_target_node(struct collapse_control *cc)
799b46e756fSKirill A. Shutemov {
800c6a7f445SYang Shi 	return 0;
801b46e756fSKirill A. Shutemov }
802c6a7f445SYang Shi #endif
803b46e756fSKirill A. Shutemov 
804e031ff96SYang Shi static bool hpage_collapse_alloc_page(struct page **hpage, gfp_t gfp, int node,
805e031ff96SYang Shi 				      nodemask_t *nmask)
806b46e756fSKirill A. Shutemov {
807e031ff96SYang Shi 	*hpage = __alloc_pages(gfp, HPAGE_PMD_ORDER, node, nmask);
808b46e756fSKirill A. Shutemov 	if (unlikely(!*hpage)) {
809b46e756fSKirill A. Shutemov 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
8109710a78aSZach O'Keefe 		return false;
811b46e756fSKirill A. Shutemov 	}
812b46e756fSKirill A. Shutemov 
813b46e756fSKirill A. Shutemov 	prep_transhuge_page(*hpage);
814b46e756fSKirill A. Shutemov 	count_vm_event(THP_COLLAPSE_ALLOC);
815b46e756fSKirill A. Shutemov 	return true;
816b46e756fSKirill A. Shutemov }
817b46e756fSKirill A. Shutemov 
818b46e756fSKirill A. Shutemov /*
819c1e8d7c6SMichel Lespinasse  * If mmap_lock temporarily dropped, revalidate vma
820c1e8d7c6SMichel Lespinasse  * before taking mmap_lock.
82150ad2f24SZach O'Keefe  * Returns enum scan_result value.
822b46e756fSKirill A. Shutemov  */
823b46e756fSKirill A. Shutemov 
824c131f751SKirill A. Shutemov static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
82534488399SZach O'Keefe 				   bool expect_anon,
826a7f4e6e4SZach O'Keefe 				   struct vm_area_struct **vmap,
827a7f4e6e4SZach O'Keefe 				   struct collapse_control *cc)
828b46e756fSKirill A. Shutemov {
829b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
830b46e756fSKirill A. Shutemov 
8317d2c4385SZach O'Keefe 	if (unlikely(hpage_collapse_test_exit(mm)))
832b46e756fSKirill A. Shutemov 		return SCAN_ANY_PROCESS;
833b46e756fSKirill A. Shutemov 
834c131f751SKirill A. Shutemov 	*vmap = vma = find_vma(mm, address);
835b46e756fSKirill A. Shutemov 	if (!vma)
836b46e756fSKirill A. Shutemov 		return SCAN_VMA_NULL;
837b46e756fSKirill A. Shutemov 
8384fa6893fSYang Shi 	if (!transhuge_vma_suitable(vma, address))
839b46e756fSKirill A. Shutemov 		return SCAN_ADDRESS_RANGE;
840a7f4e6e4SZach O'Keefe 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
841a7f4e6e4SZach O'Keefe 				cc->is_khugepaged))
842b46e756fSKirill A. Shutemov 		return SCAN_VMA_CHECK;
843f707fa49SYang Shi 	/*
844f707fa49SYang Shi 	 * Anon VMA expected, the address may be unmapped then
845f707fa49SYang Shi 	 * remapped to file after khugepaged reaquired the mmap_lock.
846f707fa49SYang Shi 	 *
847f707fa49SYang Shi 	 * hugepage_vma_check may return true for qualified file
848f707fa49SYang Shi 	 * vmas.
849f707fa49SYang Shi 	 */
85034488399SZach O'Keefe 	if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
85134488399SZach O'Keefe 		return SCAN_PAGE_ANON;
85250ad2f24SZach O'Keefe 	return SCAN_SUCCEED;
853b46e756fSKirill A. Shutemov }
854b46e756fSKirill A. Shutemov 
855edb5d0cfSZach O'Keefe /*
856edb5d0cfSZach O'Keefe  * See pmd_trans_unstable() for how the result may change out from
857edb5d0cfSZach O'Keefe  * underneath us, even if we hold mmap_lock in read.
858edb5d0cfSZach O'Keefe  */
85950722804SZach O'Keefe static int find_pmd_or_thp_or_none(struct mm_struct *mm,
86050722804SZach O'Keefe 				   unsigned long address,
86150722804SZach O'Keefe 				   pmd_t **pmd)
86250722804SZach O'Keefe {
86350722804SZach O'Keefe 	pmd_t pmde;
86450722804SZach O'Keefe 
86550722804SZach O'Keefe 	*pmd = mm_find_pmd(mm, address);
86650722804SZach O'Keefe 	if (!*pmd)
86750722804SZach O'Keefe 		return SCAN_PMD_NULL;
86850722804SZach O'Keefe 
869dab6e717SPeter Zijlstra 	pmde = pmdp_get_lockless(*pmd);
87050722804SZach O'Keefe 
87150722804SZach O'Keefe #ifdef CONFIG_TRANSPARENT_HUGEPAGE
87250722804SZach O'Keefe 	/* See comments in pmd_none_or_trans_huge_or_clear_bad() */
87350722804SZach O'Keefe 	barrier();
87450722804SZach O'Keefe #endif
87534488399SZach O'Keefe 	if (pmd_none(pmde))
87634488399SZach O'Keefe 		return SCAN_PMD_NONE;
877edb5d0cfSZach O'Keefe 	if (!pmd_present(pmde))
878edb5d0cfSZach O'Keefe 		return SCAN_PMD_NULL;
87950722804SZach O'Keefe 	if (pmd_trans_huge(pmde))
88050722804SZach O'Keefe 		return SCAN_PMD_MAPPED;
881edb5d0cfSZach O'Keefe 	if (pmd_devmap(pmde))
882edb5d0cfSZach O'Keefe 		return SCAN_PMD_NULL;
88350722804SZach O'Keefe 	if (pmd_bad(pmde))
88450722804SZach O'Keefe 		return SCAN_PMD_NULL;
88550722804SZach O'Keefe 	return SCAN_SUCCEED;
88650722804SZach O'Keefe }
88750722804SZach O'Keefe 
88850722804SZach O'Keefe static int check_pmd_still_valid(struct mm_struct *mm,
88950722804SZach O'Keefe 				 unsigned long address,
89050722804SZach O'Keefe 				 pmd_t *pmd)
89150722804SZach O'Keefe {
89250722804SZach O'Keefe 	pmd_t *new_pmd;
89350722804SZach O'Keefe 	int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
89450722804SZach O'Keefe 
89550722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
89650722804SZach O'Keefe 		return result;
89750722804SZach O'Keefe 	if (new_pmd != pmd)
89850722804SZach O'Keefe 		return SCAN_FAIL;
89950722804SZach O'Keefe 	return SCAN_SUCCEED;
900b46e756fSKirill A. Shutemov }
901b46e756fSKirill A. Shutemov 
902b46e756fSKirill A. Shutemov /*
903b46e756fSKirill A. Shutemov  * Bring missing pages in from swap, to complete THP collapse.
9047d2c4385SZach O'Keefe  * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
905b46e756fSKirill A. Shutemov  *
9064d928e20SMiaohe Lin  * Called and returns without pte mapped or spinlocks held.
9074d928e20SMiaohe Lin  * Note that if false is returned, mmap_lock will be released.
908b46e756fSKirill A. Shutemov  */
909b46e756fSKirill A. Shutemov 
91050ad2f24SZach O'Keefe static int __collapse_huge_page_swapin(struct mm_struct *mm,
911b46e756fSKirill A. Shutemov 				       struct vm_area_struct *vma,
9122b635dd3SWill Deacon 				       unsigned long haddr, pmd_t *pmd,
9130db501f7SEbru Akagunduz 				       int referenced)
914b46e756fSKirill A. Shutemov {
9152b740303SSouptick Joarder 	int swapped_in = 0;
9162b740303SSouptick Joarder 	vm_fault_t ret = 0;
9172b635dd3SWill Deacon 	unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
9182b635dd3SWill Deacon 
9192b635dd3SWill Deacon 	for (address = haddr; address < end; address += PAGE_SIZE) {
92082b0f8c3SJan Kara 		struct vm_fault vmf = {
921b46e756fSKirill A. Shutemov 			.vma = vma,
922b46e756fSKirill A. Shutemov 			.address = address,
9232b635dd3SWill Deacon 			.pgoff = linear_page_index(vma, haddr),
924b46e756fSKirill A. Shutemov 			.flags = FAULT_FLAG_ALLOW_RETRY,
925b46e756fSKirill A. Shutemov 			.pmd = pmd,
926b46e756fSKirill A. Shutemov 		};
927b46e756fSKirill A. Shutemov 
92882b0f8c3SJan Kara 		vmf.pte = pte_offset_map(pmd, address);
9292994302bSJan Kara 		vmf.orig_pte = *vmf.pte;
9302b635dd3SWill Deacon 		if (!is_swap_pte(vmf.orig_pte)) {
9312b635dd3SWill Deacon 			pte_unmap(vmf.pte);
932b46e756fSKirill A. Shutemov 			continue;
9332b635dd3SWill Deacon 		}
9342994302bSJan Kara 		ret = do_swap_page(&vmf);
9350db501f7SEbru Akagunduz 
9364d928e20SMiaohe Lin 		/*
9374d928e20SMiaohe Lin 		 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
9384d928e20SMiaohe Lin 		 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
9394d928e20SMiaohe Lin 		 * we do not retry here and swap entry will remain in pagetable
9404d928e20SMiaohe Lin 		 * resulting in later failure.
9414d928e20SMiaohe Lin 		 */
942b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_RETRY) {
9430db501f7SEbru Akagunduz 			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
94450ad2f24SZach O'Keefe 			/* Likely, but not guaranteed, that page lock failed */
94550ad2f24SZach O'Keefe 			return SCAN_PAGE_LOCK;
94647f863eaSEbru Akagunduz 		}
947b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_ERROR) {
9484d928e20SMiaohe Lin 			mmap_read_unlock(mm);
9490db501f7SEbru Akagunduz 			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
95050ad2f24SZach O'Keefe 			return SCAN_FAIL;
951b46e756fSKirill A. Shutemov 		}
9524d928e20SMiaohe Lin 		swapped_in++;
953b46e756fSKirill A. Shutemov 	}
954ae2c5d80SKirill A. Shutemov 
955ae2c5d80SKirill A. Shutemov 	/* Drain LRU add pagevec to remove extra pin on the swapped in pages */
956ae2c5d80SKirill A. Shutemov 	if (swapped_in)
957ae2c5d80SKirill A. Shutemov 		lru_add_drain();
958ae2c5d80SKirill A. Shutemov 
9590db501f7SEbru Akagunduz 	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
96050ad2f24SZach O'Keefe 	return SCAN_SUCCEED;
961b46e756fSKirill A. Shutemov }
962b46e756fSKirill A. Shutemov 
9639710a78aSZach O'Keefe static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
9649710a78aSZach O'Keefe 			      struct collapse_control *cc)
9659710a78aSZach O'Keefe {
9667d8faaf1SZach O'Keefe 	gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
967e031ff96SYang Shi 		     GFP_TRANSHUGE);
9687d2c4385SZach O'Keefe 	int node = hpage_collapse_find_target_node(cc);
9699710a78aSZach O'Keefe 
970e031ff96SYang Shi 	if (!hpage_collapse_alloc_page(hpage, gfp, node, &cc->alloc_nmask))
9719710a78aSZach O'Keefe 		return SCAN_ALLOC_HUGE_PAGE_FAIL;
9729710a78aSZach O'Keefe 	if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
9739710a78aSZach O'Keefe 		return SCAN_CGROUP_CHARGE_FAIL;
9749710a78aSZach O'Keefe 	count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
9759710a78aSZach O'Keefe 	return SCAN_SUCCEED;
9769710a78aSZach O'Keefe }
9779710a78aSZach O'Keefe 
97850ad2f24SZach O'Keefe static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
97950ad2f24SZach O'Keefe 			      int referenced, int unmapped,
98050ad2f24SZach O'Keefe 			      struct collapse_control *cc)
981b46e756fSKirill A. Shutemov {
9825503fbf2SKirill A. Shutemov 	LIST_HEAD(compound_pagelist);
983b46e756fSKirill A. Shutemov 	pmd_t *pmd, _pmd;
984b46e756fSKirill A. Shutemov 	pte_t *pte;
985b46e756fSKirill A. Shutemov 	pgtable_t pgtable;
98650ad2f24SZach O'Keefe 	struct page *hpage;
987b46e756fSKirill A. Shutemov 	spinlock_t *pmd_ptl, *pte_ptl;
98850ad2f24SZach O'Keefe 	int result = SCAN_FAIL;
989c131f751SKirill A. Shutemov 	struct vm_area_struct *vma;
990ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
991b46e756fSKirill A. Shutemov 
992b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
993b46e756fSKirill A. Shutemov 
994988ddb71SKirill A. Shutemov 	/*
995c1e8d7c6SMichel Lespinasse 	 * Before allocating the hugepage, release the mmap_lock read lock.
996988ddb71SKirill A. Shutemov 	 * The allocation can take potentially a long time if it involves
997c1e8d7c6SMichel Lespinasse 	 * sync compaction, and we do not need to hold the mmap_lock during
998988ddb71SKirill A. Shutemov 	 * that. We will recheck the vma after taking it again in write mode.
999988ddb71SKirill A. Shutemov 	 */
1000d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
1001b46e756fSKirill A. Shutemov 
100250ad2f24SZach O'Keefe 	result = alloc_charge_hpage(&hpage, mm, cc);
10039710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1004b46e756fSKirill A. Shutemov 		goto out_nolock;
1005b46e756fSKirill A. Shutemov 
1006d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
100734488399SZach O'Keefe 	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
100850ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED) {
1009d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
1010b46e756fSKirill A. Shutemov 		goto out_nolock;
1011b46e756fSKirill A. Shutemov 	}
1012b46e756fSKirill A. Shutemov 
101350722804SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, address, &pmd);
101450722804SZach O'Keefe 	if (result != SCAN_SUCCEED) {
1015d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
1016b46e756fSKirill A. Shutemov 		goto out_nolock;
1017b46e756fSKirill A. Shutemov 	}
1018b46e756fSKirill A. Shutemov 
101950ad2f24SZach O'Keefe 	if (unmapped) {
1020b46e756fSKirill A. Shutemov 		/*
102150ad2f24SZach O'Keefe 		 * __collapse_huge_page_swapin will return with mmap_lock
102250ad2f24SZach O'Keefe 		 * released when it fails. So we jump out_nolock directly in
102350ad2f24SZach O'Keefe 		 * that case.  Continuing to collapse causes inconsistency.
1024b46e756fSKirill A. Shutemov 		 */
102550ad2f24SZach O'Keefe 		result = __collapse_huge_page_swapin(mm, vma, address, pmd,
102650ad2f24SZach O'Keefe 						     referenced);
102750ad2f24SZach O'Keefe 		if (result != SCAN_SUCCEED)
1028b46e756fSKirill A. Shutemov 			goto out_nolock;
1029b46e756fSKirill A. Shutemov 	}
1030b46e756fSKirill A. Shutemov 
1031d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
1032b46e756fSKirill A. Shutemov 	/*
1033b46e756fSKirill A. Shutemov 	 * Prevent all access to pagetables with the exception of
1034b46e756fSKirill A. Shutemov 	 * gup_fast later handled by the ptep_clear_flush and the VM
1035b46e756fSKirill A. Shutemov 	 * handled by the anon_vma lock + PG_lock.
1036b46e756fSKirill A. Shutemov 	 */
1037d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
103834488399SZach O'Keefe 	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
103950ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED)
104018d24a7cSMiaohe Lin 		goto out_up_write;
1041b46e756fSKirill A. Shutemov 	/* check if the pmd is still valid */
104250722804SZach O'Keefe 	result = check_pmd_still_valid(mm, address, pmd);
104350722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
104418d24a7cSMiaohe Lin 		goto out_up_write;
1045b46e756fSKirill A. Shutemov 
1046b46e756fSKirill A. Shutemov 	anon_vma_lock_write(vma->anon_vma);
1047b46e756fSKirill A. Shutemov 
10487d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
10497d4a8be0SAlistair Popple 				address + HPAGE_PMD_SIZE);
1050ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1051ec649c9dSVille Syrjälä 
1052ec649c9dSVille Syrjälä 	pte = pte_offset_map(pmd, address);
1053ec649c9dSVille Syrjälä 	pte_ptl = pte_lockptr(mm, pmd);
1054ec649c9dSVille Syrjälä 
1055b46e756fSKirill A. Shutemov 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1056b46e756fSKirill A. Shutemov 	/*
105770cbc3ccSYang Shi 	 * This removes any huge TLB entry from the CPU so we won't allow
105870cbc3ccSYang Shi 	 * huge and small TLB entries for the same virtual address to
105970cbc3ccSYang Shi 	 * avoid the risk of CPU bugs in that area.
106070cbc3ccSYang Shi 	 *
106170cbc3ccSYang Shi 	 * Parallel fast GUP is fine since fast GUP will back off when
106270cbc3ccSYang Shi 	 * it detects PMD is changed.
1063b46e756fSKirill A. Shutemov 	 */
1064b46e756fSKirill A. Shutemov 	_pmd = pmdp_collapse_flush(vma, address, pmd);
1065b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1066ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
10672ba99c5eSJann Horn 	tlb_remove_table_sync_one();
1068b46e756fSKirill A. Shutemov 
1069b46e756fSKirill A. Shutemov 	spin_lock(pte_ptl);
1070d8ea7cc8SZach O'Keefe 	result =  __collapse_huge_page_isolate(vma, address, pte, cc,
10715503fbf2SKirill A. Shutemov 					       &compound_pagelist);
1072b46e756fSKirill A. Shutemov 	spin_unlock(pte_ptl);
1073b46e756fSKirill A. Shutemov 
107450ad2f24SZach O'Keefe 	if (unlikely(result != SCAN_SUCCEED)) {
1075b46e756fSKirill A. Shutemov 		pte_unmap(pte);
1076b46e756fSKirill A. Shutemov 		spin_lock(pmd_ptl);
1077b46e756fSKirill A. Shutemov 		BUG_ON(!pmd_none(*pmd));
1078b46e756fSKirill A. Shutemov 		/*
1079b46e756fSKirill A. Shutemov 		 * We can only use set_pmd_at when establishing
1080b46e756fSKirill A. Shutemov 		 * hugepmds and never for establishing regular pmds that
1081b46e756fSKirill A. Shutemov 		 * points to regular pagetables. Use pmd_populate for that
1082b46e756fSKirill A. Shutemov 		 */
1083b46e756fSKirill A. Shutemov 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1084b46e756fSKirill A. Shutemov 		spin_unlock(pmd_ptl);
1085b46e756fSKirill A. Shutemov 		anon_vma_unlock_write(vma->anon_vma);
108618d24a7cSMiaohe Lin 		goto out_up_write;
1087b46e756fSKirill A. Shutemov 	}
1088b46e756fSKirill A. Shutemov 
1089b46e756fSKirill A. Shutemov 	/*
1090b46e756fSKirill A. Shutemov 	 * All pages are isolated and locked so anon_vma rmap
1091b46e756fSKirill A. Shutemov 	 * can't run anymore.
1092b46e756fSKirill A. Shutemov 	 */
1093b46e756fSKirill A. Shutemov 	anon_vma_unlock_write(vma->anon_vma);
1094b46e756fSKirill A. Shutemov 
109550ad2f24SZach O'Keefe 	__collapse_huge_page_copy(pte, hpage, vma, address, pte_ptl,
10965503fbf2SKirill A. Shutemov 				  &compound_pagelist);
1097b46e756fSKirill A. Shutemov 	pte_unmap(pte);
1098588d01f9SMiaohe Lin 	/*
1099588d01f9SMiaohe Lin 	 * spin_lock() below is not the equivalent of smp_wmb(), but
1100588d01f9SMiaohe Lin 	 * the smp_wmb() inside __SetPageUptodate() can be reused to
1101588d01f9SMiaohe Lin 	 * avoid the copy_huge_page writes to become visible after
1102588d01f9SMiaohe Lin 	 * the set_pmd_at() write.
1103588d01f9SMiaohe Lin 	 */
110450ad2f24SZach O'Keefe 	__SetPageUptodate(hpage);
1105b46e756fSKirill A. Shutemov 	pgtable = pmd_pgtable(_pmd);
1106b46e756fSKirill A. Shutemov 
110750ad2f24SZach O'Keefe 	_pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1108f55e1014SLinus Torvalds 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1109b46e756fSKirill A. Shutemov 
1110b46e756fSKirill A. Shutemov 	spin_lock(pmd_ptl);
1111b46e756fSKirill A. Shutemov 	BUG_ON(!pmd_none(*pmd));
111250ad2f24SZach O'Keefe 	page_add_new_anon_rmap(hpage, vma, address);
111350ad2f24SZach O'Keefe 	lru_cache_add_inactive_or_unevictable(hpage, vma);
1114b46e756fSKirill A. Shutemov 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1115b46e756fSKirill A. Shutemov 	set_pmd_at(mm, address, pmd, _pmd);
1116b46e756fSKirill A. Shutemov 	update_mmu_cache_pmd(vma, address, pmd);
1117b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1118b46e756fSKirill A. Shutemov 
111950ad2f24SZach O'Keefe 	hpage = NULL;
1120b46e756fSKirill A. Shutemov 
1121b46e756fSKirill A. Shutemov 	result = SCAN_SUCCEED;
1122b46e756fSKirill A. Shutemov out_up_write:
1123d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1124b46e756fSKirill A. Shutemov out_nolock:
112550ad2f24SZach O'Keefe 	if (hpage) {
112650ad2f24SZach O'Keefe 		mem_cgroup_uncharge(page_folio(hpage));
112750ad2f24SZach O'Keefe 		put_page(hpage);
1128c6a7f445SYang Shi 	}
112950ad2f24SZach O'Keefe 	trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
113050ad2f24SZach O'Keefe 	return result;
1131b46e756fSKirill A. Shutemov }
1132b46e756fSKirill A. Shutemov 
11337d2c4385SZach O'Keefe static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1134b46e756fSKirill A. Shutemov 				   struct vm_area_struct *vma,
113550ad2f24SZach O'Keefe 				   unsigned long address, bool *mmap_locked,
113634d6b470SZach O'Keefe 				   struct collapse_control *cc)
1137b46e756fSKirill A. Shutemov {
1138b46e756fSKirill A. Shutemov 	pmd_t *pmd;
1139b46e756fSKirill A. Shutemov 	pte_t *pte, *_pte;
114050ad2f24SZach O'Keefe 	int result = SCAN_FAIL, referenced = 0;
114171a2c112SKirill A. Shutemov 	int none_or_zero = 0, shared = 0;
1142b46e756fSKirill A. Shutemov 	struct page *page = NULL;
1143b46e756fSKirill A. Shutemov 	unsigned long _address;
1144b46e756fSKirill A. Shutemov 	spinlock_t *ptl;
1145b46e756fSKirill A. Shutemov 	int node = NUMA_NO_NODE, unmapped = 0;
11460db501f7SEbru Akagunduz 	bool writable = false;
1147b46e756fSKirill A. Shutemov 
1148b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1149b46e756fSKirill A. Shutemov 
115050722804SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, address, &pmd);
115150722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
1152b46e756fSKirill A. Shutemov 		goto out;
1153b46e756fSKirill A. Shutemov 
115434d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1155e031ff96SYang Shi 	nodes_clear(cc->alloc_nmask);
1156b46e756fSKirill A. Shutemov 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1157b46e756fSKirill A. Shutemov 	for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1158b46e756fSKirill A. Shutemov 	     _pte++, _address += PAGE_SIZE) {
1159b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
1160b46e756fSKirill A. Shutemov 		if (is_swap_pte(pteval)) {
1161d8ea7cc8SZach O'Keefe 			++unmapped;
1162d8ea7cc8SZach O'Keefe 			if (!cc->is_khugepaged ||
1163d8ea7cc8SZach O'Keefe 			    unmapped <= khugepaged_max_ptes_swap) {
1164e1e267c7SPeter Xu 				/*
1165e1e267c7SPeter Xu 				 * Always be strict with uffd-wp
1166e1e267c7SPeter Xu 				 * enabled swap entries.  Please see
1167e1e267c7SPeter Xu 				 * comment below for pte_uffd_wp().
1168e1e267c7SPeter Xu 				 */
1169e1e267c7SPeter Xu 				if (pte_swp_uffd_wp(pteval)) {
1170e1e267c7SPeter Xu 					result = SCAN_PTE_UFFD_WP;
1171e1e267c7SPeter Xu 					goto out_unmap;
1172e1e267c7SPeter Xu 				}
1173b46e756fSKirill A. Shutemov 				continue;
1174b46e756fSKirill A. Shutemov 			} else {
1175b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1176e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1177b46e756fSKirill A. Shutemov 				goto out_unmap;
1178b46e756fSKirill A. Shutemov 			}
1179b46e756fSKirill A. Shutemov 		}
1180b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1181d8ea7cc8SZach O'Keefe 			++none_or_zero;
1182b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
1183d8ea7cc8SZach O'Keefe 			    (!cc->is_khugepaged ||
1184d8ea7cc8SZach O'Keefe 			     none_or_zero <= khugepaged_max_ptes_none)) {
1185b46e756fSKirill A. Shutemov 				continue;
1186b46e756fSKirill A. Shutemov 			} else {
1187b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
1188e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1189b46e756fSKirill A. Shutemov 				goto out_unmap;
1190b46e756fSKirill A. Shutemov 			}
1191b46e756fSKirill A. Shutemov 		}
1192e1e267c7SPeter Xu 		if (pte_uffd_wp(pteval)) {
1193e1e267c7SPeter Xu 			/*
1194e1e267c7SPeter Xu 			 * Don't collapse the page if any of the small
1195e1e267c7SPeter Xu 			 * PTEs are armed with uffd write protection.
1196e1e267c7SPeter Xu 			 * Here we can also mark the new huge pmd as
1197e1e267c7SPeter Xu 			 * write protected if any of the small ones is
11988958b249SHaitao Shi 			 * marked but that could bring unknown
1199e1e267c7SPeter Xu 			 * userfault messages that falls outside of
1200e1e267c7SPeter Xu 			 * the registered range.  So, just be simple.
1201e1e267c7SPeter Xu 			 */
1202e1e267c7SPeter Xu 			result = SCAN_PTE_UFFD_WP;
1203e1e267c7SPeter Xu 			goto out_unmap;
1204e1e267c7SPeter Xu 		}
1205b46e756fSKirill A. Shutemov 		if (pte_write(pteval))
1206b46e756fSKirill A. Shutemov 			writable = true;
1207b46e756fSKirill A. Shutemov 
1208b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, _address, pteval);
12093218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1210b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
1211b46e756fSKirill A. Shutemov 			goto out_unmap;
1212b46e756fSKirill A. Shutemov 		}
1213b46e756fSKirill A. Shutemov 
1214d8ea7cc8SZach O'Keefe 		if (page_mapcount(page) > 1) {
1215d8ea7cc8SZach O'Keefe 			++shared;
1216d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
1217d8ea7cc8SZach O'Keefe 			    shared > khugepaged_max_ptes_shared) {
121871a2c112SKirill A. Shutemov 				result = SCAN_EXCEED_SHARED_PTE;
1219e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
122071a2c112SKirill A. Shutemov 				goto out_unmap;
122171a2c112SKirill A. Shutemov 			}
1222d8ea7cc8SZach O'Keefe 		}
122371a2c112SKirill A. Shutemov 
12245503fbf2SKirill A. Shutemov 		page = compound_head(page);
1225b46e756fSKirill A. Shutemov 
1226b46e756fSKirill A. Shutemov 		/*
1227b46e756fSKirill A. Shutemov 		 * Record which node the original page is from and save this
122834d6b470SZach O'Keefe 		 * information to cc->node_load[].
12290b8f0d87SQuanfa Fu 		 * Khugepaged will allocate hugepage from the node has the max
1230b46e756fSKirill A. Shutemov 		 * hit record.
1231b46e756fSKirill A. Shutemov 		 */
1232b46e756fSKirill A. Shutemov 		node = page_to_nid(page);
12337d2c4385SZach O'Keefe 		if (hpage_collapse_scan_abort(node, cc)) {
1234b46e756fSKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1235b46e756fSKirill A. Shutemov 			goto out_unmap;
1236b46e756fSKirill A. Shutemov 		}
123734d6b470SZach O'Keefe 		cc->node_load[node]++;
1238b46e756fSKirill A. Shutemov 		if (!PageLRU(page)) {
1239b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1240b46e756fSKirill A. Shutemov 			goto out_unmap;
1241b46e756fSKirill A. Shutemov 		}
1242b46e756fSKirill A. Shutemov 		if (PageLocked(page)) {
1243b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
1244b46e756fSKirill A. Shutemov 			goto out_unmap;
1245b46e756fSKirill A. Shutemov 		}
1246b46e756fSKirill A. Shutemov 		if (!PageAnon(page)) {
1247b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_ANON;
1248b46e756fSKirill A. Shutemov 			goto out_unmap;
1249b46e756fSKirill A. Shutemov 		}
1250b46e756fSKirill A. Shutemov 
1251b46e756fSKirill A. Shutemov 		/*
12529445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
12539445689fSKirill A. Shutemov 		 *
1254cb67f428SHugh Dickins 		 * Here the check may be racy:
1255cb67f428SHugh Dickins 		 * it may see total_mapcount > refcount in some cases?
12569445689fSKirill A. Shutemov 		 * But such case is ephemeral we could always retry collapse
12579445689fSKirill A. Shutemov 		 * later.  However it may report false positive if the page
12589445689fSKirill A. Shutemov 		 * has excessive GUP pins (i.e. 512).  Anyway the same check
12599445689fSKirill A. Shutemov 		 * will be done again later the risk seems low.
1260b46e756fSKirill A. Shutemov 		 */
12619445689fSKirill A. Shutemov 		if (!is_refcount_suitable(page)) {
1262b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1263b46e756fSKirill A. Shutemov 			goto out_unmap;
1264b46e756fSKirill A. Shutemov 		}
1265d8ea7cc8SZach O'Keefe 
1266d8ea7cc8SZach O'Keefe 		/*
1267d8ea7cc8SZach O'Keefe 		 * If collapse was initiated by khugepaged, check that there is
1268d8ea7cc8SZach O'Keefe 		 * enough young pte to justify collapsing the page
1269d8ea7cc8SZach O'Keefe 		 */
1270d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
1271d8ea7cc8SZach O'Keefe 		    (pte_young(pteval) || page_is_young(page) ||
1272d8ea7cc8SZach O'Keefe 		     PageReferenced(page) || mmu_notifier_test_young(vma->vm_mm,
1273d8ea7cc8SZach O'Keefe 								     address)))
12740db501f7SEbru Akagunduz 			referenced++;
1275b46e756fSKirill A. Shutemov 	}
1276ffe945e6SKirill A. Shutemov 	if (!writable) {
1277ffe945e6SKirill A. Shutemov 		result = SCAN_PAGE_RO;
1278d8ea7cc8SZach O'Keefe 	} else if (cc->is_khugepaged &&
1279d8ea7cc8SZach O'Keefe 		   (!referenced ||
1280d8ea7cc8SZach O'Keefe 		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1281ffe945e6SKirill A. Shutemov 		result = SCAN_LACK_REFERENCED_PAGE;
1282ffe945e6SKirill A. Shutemov 	} else {
1283b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
1284b46e756fSKirill A. Shutemov 	}
1285b46e756fSKirill A. Shutemov out_unmap:
1286b46e756fSKirill A. Shutemov 	pte_unmap_unlock(pte, ptl);
128750ad2f24SZach O'Keefe 	if (result == SCAN_SUCCEED) {
128850ad2f24SZach O'Keefe 		result = collapse_huge_page(mm, address, referenced,
128950ad2f24SZach O'Keefe 					    unmapped, cc);
1290c1e8d7c6SMichel Lespinasse 		/* collapse_huge_page will return with the mmap_lock released */
129150ad2f24SZach O'Keefe 		*mmap_locked = false;
1292b46e756fSKirill A. Shutemov 	}
1293b46e756fSKirill A. Shutemov out:
1294b46e756fSKirill A. Shutemov 	trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1295b46e756fSKirill A. Shutemov 				     none_or_zero, result, unmapped);
129650ad2f24SZach O'Keefe 	return result;
1297b46e756fSKirill A. Shutemov }
1298b46e756fSKirill A. Shutemov 
1299b26e2701SQi Zheng static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1300b46e756fSKirill A. Shutemov {
1301b26e2701SQi Zheng 	struct mm_slot *slot = &mm_slot->slot;
1302b26e2701SQi Zheng 	struct mm_struct *mm = slot->mm;
1303b46e756fSKirill A. Shutemov 
130435f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1305b46e756fSKirill A. Shutemov 
13067d2c4385SZach O'Keefe 	if (hpage_collapse_test_exit(mm)) {
1307b46e756fSKirill A. Shutemov 		/* free mm_slot */
1308b26e2701SQi Zheng 		hash_del(&slot->hash);
1309b26e2701SQi Zheng 		list_del(&slot->mm_node);
1310b46e756fSKirill A. Shutemov 
1311b46e756fSKirill A. Shutemov 		/*
1312b46e756fSKirill A. Shutemov 		 * Not strictly needed because the mm exited already.
1313b46e756fSKirill A. Shutemov 		 *
1314b46e756fSKirill A. Shutemov 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1315b46e756fSKirill A. Shutemov 		 */
1316b46e756fSKirill A. Shutemov 
1317b46e756fSKirill A. Shutemov 		/* khugepaged_mm_lock actually not necessary for the below */
1318b26e2701SQi Zheng 		mm_slot_free(mm_slot_cache, mm_slot);
1319b46e756fSKirill A. Shutemov 		mmdrop(mm);
1320b46e756fSKirill A. Shutemov 	}
1321b46e756fSKirill A. Shutemov }
1322b46e756fSKirill A. Shutemov 
1323396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_SHMEM
132427e1f827SSong Liu /*
132527e1f827SSong Liu  * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
132627e1f827SSong Liu  * khugepaged should try to collapse the page table.
132734488399SZach O'Keefe  *
132834488399SZach O'Keefe  * Note that following race exists:
132934488399SZach O'Keefe  * (1) khugepaged calls khugepaged_collapse_pte_mapped_thps() for mm_struct A,
133034488399SZach O'Keefe  *     emptying the A's ->pte_mapped_thp[] array.
133134488399SZach O'Keefe  * (2) MADV_COLLAPSE collapses some file extent with target mm_struct B, and
133234488399SZach O'Keefe  *     retract_page_tables() finds a VMA in mm_struct A mapping the same extent
133334488399SZach O'Keefe  *     (at virtual address X) and adds an entry (for X) into mm_struct A's
133434488399SZach O'Keefe  *     ->pte-mapped_thp[] array.
133534488399SZach O'Keefe  * (3) khugepaged calls khugepaged_collapse_scan_file() for mm_struct A at X,
133634488399SZach O'Keefe  *     sees a pte-mapped THP (SCAN_PTE_MAPPED_HUGEPAGE) and adds an entry
133734488399SZach O'Keefe  *     (for X) into mm_struct A's ->pte-mapped_thp[] array.
133834488399SZach O'Keefe  * Thus, it's possible the same address is added multiple times for the same
133934488399SZach O'Keefe  * mm_struct.  Should this happen, we'll simply attempt
134034488399SZach O'Keefe  * collapse_pte_mapped_thp() multiple times for the same address, under the same
134134488399SZach O'Keefe  * exclusive mmap_lock, and assuming the first call is successful, subsequent
134234488399SZach O'Keefe  * attempts will return quickly (without grabbing any additional locks) when
134334488399SZach O'Keefe  * a huge pmd is found in find_pmd_or_thp_or_none().  Since this is a cheap
134434488399SZach O'Keefe  * check, and since this is a rare occurrence, the cost of preventing this
134534488399SZach O'Keefe  * "multiple-add" is thought to be more expensive than just handling it, should
134634488399SZach O'Keefe  * it occur.
134727e1f827SSong Liu  */
134858ac9a89SZach O'Keefe static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
134927e1f827SSong Liu 					  unsigned long addr)
135027e1f827SSong Liu {
1351b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
1352b26e2701SQi Zheng 	struct mm_slot *slot;
135358ac9a89SZach O'Keefe 	bool ret = false;
135427e1f827SSong Liu 
135527e1f827SSong Liu 	VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
135627e1f827SSong Liu 
135727e1f827SSong Liu 	spin_lock(&khugepaged_mm_lock);
1358b26e2701SQi Zheng 	slot = mm_slot_lookup(mm_slots_hash, mm);
1359b26e2701SQi Zheng 	mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
136058ac9a89SZach O'Keefe 	if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) {
136127e1f827SSong Liu 		mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
136258ac9a89SZach O'Keefe 		ret = true;
136358ac9a89SZach O'Keefe 	}
136427e1f827SSong Liu 	spin_unlock(&khugepaged_mm_lock);
136558ac9a89SZach O'Keefe 	return ret;
136627e1f827SSong Liu }
136727e1f827SSong Liu 
136834488399SZach O'Keefe /* hpage must be locked, and mmap_lock must be held in write */
136934488399SZach O'Keefe static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
137034488399SZach O'Keefe 			pmd_t *pmdp, struct page *hpage)
137134488399SZach O'Keefe {
137234488399SZach O'Keefe 	struct vm_fault vmf = {
137334488399SZach O'Keefe 		.vma = vma,
137434488399SZach O'Keefe 		.address = addr,
137534488399SZach O'Keefe 		.flags = 0,
137634488399SZach O'Keefe 		.pmd = pmdp,
137734488399SZach O'Keefe 	};
137834488399SZach O'Keefe 
137934488399SZach O'Keefe 	VM_BUG_ON(!PageTransHuge(hpage));
138034488399SZach O'Keefe 	mmap_assert_write_locked(vma->vm_mm);
138134488399SZach O'Keefe 
138234488399SZach O'Keefe 	if (do_set_pmd(&vmf, hpage))
138334488399SZach O'Keefe 		return SCAN_FAIL;
138434488399SZach O'Keefe 
138534488399SZach O'Keefe 	get_page(hpage);
138634488399SZach O'Keefe 	return SCAN_SUCCEED;
138727e1f827SSong Liu }
138827e1f827SSong Liu 
13898d3c106eSJann Horn /*
13908d3c106eSJann Horn  * A note about locking:
13918d3c106eSJann Horn  * Trying to take the page table spinlocks would be useless here because those
13928d3c106eSJann Horn  * are only used to synchronize:
13938d3c106eSJann Horn  *
13948d3c106eSJann Horn  *  - modifying terminal entries (ones that point to a data page, not to another
13958d3c106eSJann Horn  *    page table)
13968d3c106eSJann Horn  *  - installing *new* non-terminal entries
13978d3c106eSJann Horn  *
13988d3c106eSJann Horn  * Instead, we need roughly the same kind of protection as free_pgtables() or
13998d3c106eSJann Horn  * mm_take_all_locks() (but only for a single VMA):
14008d3c106eSJann Horn  * The mmap lock together with this VMA's rmap locks covers all paths towards
14018d3c106eSJann Horn  * the page table entries we're messing with here, except for hardware page
14028d3c106eSJann Horn  * table walks and lockless_pages_from_mm().
14038d3c106eSJann Horn  */
1404e59a47b8SPasha Tatashin static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1405e59a47b8SPasha Tatashin 				  unsigned long addr, pmd_t *pmdp)
1406e59a47b8SPasha Tatashin {
1407e59a47b8SPasha Tatashin 	pmd_t pmd;
1408f268f6cfSJann Horn 	struct mmu_notifier_range range;
1409e59a47b8SPasha Tatashin 
141080110bbfSPasha Tatashin 	mmap_assert_write_locked(mm);
14118d3c106eSJann Horn 	if (vma->vm_file)
14128d3c106eSJann Horn 		lockdep_assert_held_write(&vma->vm_file->f_mapping->i_mmap_rwsem);
14138d3c106eSJann Horn 	/*
14148d3c106eSJann Horn 	 * All anon_vmas attached to the VMA have the same root and are
14158d3c106eSJann Horn 	 * therefore locked by the same lock.
14168d3c106eSJann Horn 	 */
14178d3c106eSJann Horn 	if (vma->anon_vma)
14188d3c106eSJann Horn 		lockdep_assert_held_write(&vma->anon_vma->root->rwsem);
14198d3c106eSJann Horn 
14207d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
1421f268f6cfSJann Horn 				addr + HPAGE_PMD_SIZE);
1422f268f6cfSJann Horn 	mmu_notifier_invalidate_range_start(&range);
1423e59a47b8SPasha Tatashin 	pmd = pmdp_collapse_flush(vma, addr, pmdp);
14242ba99c5eSJann Horn 	tlb_remove_table_sync_one();
1425f268f6cfSJann Horn 	mmu_notifier_invalidate_range_end(&range);
1426e59a47b8SPasha Tatashin 	mm_dec_nr_ptes(mm);
142780110bbfSPasha Tatashin 	page_table_check_pte_clear_range(mm, addr, pmd);
1428e59a47b8SPasha Tatashin 	pte_free(mm, pmd_pgtable(pmd));
1429e59a47b8SPasha Tatashin }
1430e59a47b8SPasha Tatashin 
143127e1f827SSong Liu /**
1432336e6b53SAlex Shi  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1433336e6b53SAlex Shi  * address haddr.
1434336e6b53SAlex Shi  *
1435336e6b53SAlex Shi  * @mm: process address space where collapse happens
1436336e6b53SAlex Shi  * @addr: THP collapse address
143734488399SZach O'Keefe  * @install_pmd: If a huge PMD should be installed
143827e1f827SSong Liu  *
143927e1f827SSong Liu  * This function checks whether all the PTEs in the PMD are pointing to the
144027e1f827SSong Liu  * right THP. If so, retract the page table so the THP can refault in with
144134488399SZach O'Keefe  * as pmd-mapped. Possibly install a huge PMD mapping the THP.
144227e1f827SSong Liu  */
144334488399SZach O'Keefe int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
144434488399SZach O'Keefe 			    bool install_pmd)
144527e1f827SSong Liu {
144627e1f827SSong Liu 	unsigned long haddr = addr & HPAGE_PMD_MASK;
144794d815b2SLiam R. Howlett 	struct vm_area_struct *vma = vma_lookup(mm, haddr);
1448119a5fc1SHugh Dickins 	struct page *hpage;
144927e1f827SSong Liu 	pte_t *start_pte, *pte;
1450e59a47b8SPasha Tatashin 	pmd_t *pmd;
145127e1f827SSong Liu 	spinlock_t *ptl;
145258ac9a89SZach O'Keefe 	int count = 0, result = SCAN_FAIL;
145327e1f827SSong Liu 	int i;
145427e1f827SSong Liu 
145558ac9a89SZach O'Keefe 	mmap_assert_write_locked(mm);
145658ac9a89SZach O'Keefe 
145734488399SZach O'Keefe 	/* Fast check before locking page if already PMD-mapped */
145858ac9a89SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
145934488399SZach O'Keefe 	if (result == SCAN_PMD_MAPPED)
146034488399SZach O'Keefe 		return result;
146158ac9a89SZach O'Keefe 
146227e1f827SSong Liu 	if (!vma || !vma->vm_file ||
1463fef792a4SMiaohe Lin 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
146434488399SZach O'Keefe 		return SCAN_VMA_CHECK;
146527e1f827SSong Liu 
146627e1f827SSong Liu 	/*
1467a7f4e6e4SZach O'Keefe 	 * If we are here, we've succeeded in replacing all the native pages
1468a7f4e6e4SZach O'Keefe 	 * in the page cache with a single hugepage. If a mm were to fault-in
1469a7f4e6e4SZach O'Keefe 	 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1470a7f4e6e4SZach O'Keefe 	 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1471a7f4e6e4SZach O'Keefe 	 * analogously elide sysfs THP settings here.
147227e1f827SSong Liu 	 */
1473a7f4e6e4SZach O'Keefe 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
147434488399SZach O'Keefe 		return SCAN_VMA_CHECK;
147527e1f827SSong Liu 
1476deb4c93aSPeter Xu 	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1477deb4c93aSPeter Xu 	if (userfaultfd_wp(vma))
147834488399SZach O'Keefe 		return SCAN_PTE_UFFD_WP;
1479deb4c93aSPeter Xu 
1480119a5fc1SHugh Dickins 	hpage = find_lock_page(vma->vm_file->f_mapping,
1481119a5fc1SHugh Dickins 			       linear_page_index(vma, haddr));
1482119a5fc1SHugh Dickins 	if (!hpage)
148334488399SZach O'Keefe 		return SCAN_PAGE_NULL;
1484119a5fc1SHugh Dickins 
148534488399SZach O'Keefe 	if (!PageHead(hpage)) {
148634488399SZach O'Keefe 		result = SCAN_FAIL;
1487119a5fc1SHugh Dickins 		goto drop_hpage;
148834488399SZach O'Keefe 	}
1489119a5fc1SHugh Dickins 
149034488399SZach O'Keefe 	if (compound_order(hpage) != HPAGE_PMD_ORDER) {
149134488399SZach O'Keefe 		result = SCAN_PAGE_COMPOUND;
1492119a5fc1SHugh Dickins 		goto drop_hpage;
149334488399SZach O'Keefe 	}
1494780a4b6fSZach O'Keefe 
149534488399SZach O'Keefe 	switch (result) {
149634488399SZach O'Keefe 	case SCAN_SUCCEED:
149734488399SZach O'Keefe 		break;
149834488399SZach O'Keefe 	case SCAN_PMD_NONE:
149934488399SZach O'Keefe 		/*
150034488399SZach O'Keefe 		 * In MADV_COLLAPSE path, possible race with khugepaged where
150134488399SZach O'Keefe 		 * all pte entries have been removed and pmd cleared.  If so,
150234488399SZach O'Keefe 		 * skip all the pte checks and just update the pmd mapping.
150334488399SZach O'Keefe 		 */
150434488399SZach O'Keefe 		goto maybe_install_pmd;
150534488399SZach O'Keefe 	default:
150627e1f827SSong Liu 		goto drop_hpage;
150734488399SZach O'Keefe 	}
150827e1f827SSong Liu 
15098d3c106eSJann Horn 	/*
15108d3c106eSJann Horn 	 * We need to lock the mapping so that from here on, only GUP-fast and
15118d3c106eSJann Horn 	 * hardware page walks can access the parts of the page tables that
15128d3c106eSJann Horn 	 * we're operating on.
15138d3c106eSJann Horn 	 * See collapse_and_free_pmd().
15148d3c106eSJann Horn 	 */
15158d3c106eSJann Horn 	i_mmap_lock_write(vma->vm_file->f_mapping);
15168d3c106eSJann Horn 
15178d3c106eSJann Horn 	/*
15188d3c106eSJann Horn 	 * This spinlock should be unnecessary: Nobody else should be accessing
15198d3c106eSJann Horn 	 * the page tables under spinlock protection here, only
15208d3c106eSJann Horn 	 * lockless_pages_from_mm() and the hardware page walker can access page
15218d3c106eSJann Horn 	 * tables while all the high-level locks are held in write mode.
15228d3c106eSJann Horn 	 */
152327e1f827SSong Liu 	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
152434488399SZach O'Keefe 	result = SCAN_FAIL;
152527e1f827SSong Liu 
152627e1f827SSong Liu 	/* step 1: check all mapped PTEs are to the right huge page */
152727e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
152827e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
152927e1f827SSong Liu 		struct page *page;
153027e1f827SSong Liu 
153127e1f827SSong Liu 		/* empty pte, skip */
153227e1f827SSong Liu 		if (pte_none(*pte))
153327e1f827SSong Liu 			continue;
153427e1f827SSong Liu 
153527e1f827SSong Liu 		/* page swapped out, abort */
153634488399SZach O'Keefe 		if (!pte_present(*pte)) {
153734488399SZach O'Keefe 			result = SCAN_PTE_NON_PRESENT;
153827e1f827SSong Liu 			goto abort;
153934488399SZach O'Keefe 		}
154027e1f827SSong Liu 
154127e1f827SSong Liu 		page = vm_normal_page(vma, addr, *pte);
15423218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
15433218f871SAlex Sierra 			page = NULL;
154427e1f827SSong Liu 		/*
1545119a5fc1SHugh Dickins 		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1546119a5fc1SHugh Dickins 		 * page table, but the new page will not be a subpage of hpage.
154727e1f827SSong Liu 		 */
1548119a5fc1SHugh Dickins 		if (hpage + i != page)
154927e1f827SSong Liu 			goto abort;
155027e1f827SSong Liu 		count++;
155127e1f827SSong Liu 	}
155227e1f827SSong Liu 
155327e1f827SSong Liu 	/* step 2: adjust rmap */
155427e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
155527e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
155627e1f827SSong Liu 		struct page *page;
155727e1f827SSong Liu 
155827e1f827SSong Liu 		if (pte_none(*pte))
155927e1f827SSong Liu 			continue;
156027e1f827SSong Liu 		page = vm_normal_page(vma, addr, *pte);
15613218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
15623218f871SAlex Sierra 			goto abort;
1563cea86fe2SHugh Dickins 		page_remove_rmap(page, vma, false);
156427e1f827SSong Liu 	}
156527e1f827SSong Liu 
156627e1f827SSong Liu 	pte_unmap_unlock(start_pte, ptl);
156727e1f827SSong Liu 
156827e1f827SSong Liu 	/* step 3: set proper refcount and mm_counters. */
1569119a5fc1SHugh Dickins 	if (count) {
157027e1f827SSong Liu 		page_ref_sub(hpage, count);
157127e1f827SSong Liu 		add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
157227e1f827SSong Liu 	}
157327e1f827SSong Liu 
157434488399SZach O'Keefe 	/* step 4: remove pte entries */
1575ab0c3f12SHugh Dickins 	/* we make no change to anon, but protect concurrent anon page lookup */
1576ab0c3f12SHugh Dickins 	if (vma->anon_vma)
1577ab0c3f12SHugh Dickins 		anon_vma_lock_write(vma->anon_vma);
1578ab0c3f12SHugh Dickins 
1579e59a47b8SPasha Tatashin 	collapse_and_free_pmd(mm, vma, haddr, pmd);
158034488399SZach O'Keefe 
1581ab0c3f12SHugh Dickins 	if (vma->anon_vma)
1582ab0c3f12SHugh Dickins 		anon_vma_unlock_write(vma->anon_vma);
15838d3c106eSJann Horn 	i_mmap_unlock_write(vma->vm_file->f_mapping);
15848d3c106eSJann Horn 
158534488399SZach O'Keefe maybe_install_pmd:
158634488399SZach O'Keefe 	/* step 5: install pmd entry */
158734488399SZach O'Keefe 	result = install_pmd
158834488399SZach O'Keefe 			? set_huge_pmd(vma, haddr, pmd, hpage)
158934488399SZach O'Keefe 			: SCAN_SUCCEED;
159034488399SZach O'Keefe 
1591119a5fc1SHugh Dickins drop_hpage:
1592119a5fc1SHugh Dickins 	unlock_page(hpage);
1593119a5fc1SHugh Dickins 	put_page(hpage);
159434488399SZach O'Keefe 	return result;
159527e1f827SSong Liu 
159627e1f827SSong Liu abort:
159727e1f827SSong Liu 	pte_unmap_unlock(start_pte, ptl);
15988d3c106eSJann Horn 	i_mmap_unlock_write(vma->vm_file->f_mapping);
1599119a5fc1SHugh Dickins 	goto drop_hpage;
160027e1f827SSong Liu }
160127e1f827SSong Liu 
1602b26e2701SQi Zheng static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
160327e1f827SSong Liu {
1604b26e2701SQi Zheng 	struct mm_slot *slot = &mm_slot->slot;
1605b26e2701SQi Zheng 	struct mm_struct *mm = slot->mm;
160627e1f827SSong Liu 	int i;
160727e1f827SSong Liu 
160827e1f827SSong Liu 	if (likely(mm_slot->nr_pte_mapped_thp == 0))
16090edf61e5SMiaohe Lin 		return;
161027e1f827SSong Liu 
1611d8ed45c5SMichel Lespinasse 	if (!mmap_write_trylock(mm))
16120edf61e5SMiaohe Lin 		return;
161327e1f827SSong Liu 
16147d2c4385SZach O'Keefe 	if (unlikely(hpage_collapse_test_exit(mm)))
161527e1f827SSong Liu 		goto out;
161627e1f827SSong Liu 
161727e1f827SSong Liu 	for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
161834488399SZach O'Keefe 		collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i], false);
161927e1f827SSong Liu 
162027e1f827SSong Liu out:
162127e1f827SSong Liu 	mm_slot->nr_pte_mapped_thp = 0;
1622d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
162327e1f827SSong Liu }
162427e1f827SSong Liu 
162534488399SZach O'Keefe static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff,
162634488399SZach O'Keefe 			       struct mm_struct *target_mm,
162734488399SZach O'Keefe 			       unsigned long target_addr, struct page *hpage,
162834488399SZach O'Keefe 			       struct collapse_control *cc)
1629f3f0e1d2SKirill A. Shutemov {
1630f3f0e1d2SKirill A. Shutemov 	struct vm_area_struct *vma;
163134488399SZach O'Keefe 	int target_result = SCAN_FAIL;
1632f3f0e1d2SKirill A. Shutemov 
1633f3f0e1d2SKirill A. Shutemov 	i_mmap_lock_write(mapping);
1634f3f0e1d2SKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
163534488399SZach O'Keefe 		int result = SCAN_FAIL;
163634488399SZach O'Keefe 		struct mm_struct *mm = NULL;
163734488399SZach O'Keefe 		unsigned long addr = 0;
163834488399SZach O'Keefe 		pmd_t *pmd;
163934488399SZach O'Keefe 		bool is_target = false;
164034488399SZach O'Keefe 
164127e1f827SSong Liu 		/*
164227e1f827SSong Liu 		 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
164327e1f827SSong Liu 		 * got written to. These VMAs are likely not worth investing
16443e4e28c5SMichel Lespinasse 		 * mmap_write_lock(mm) as PMD-mapping is likely to be split
164527e1f827SSong Liu 		 * later.
164627e1f827SSong Liu 		 *
164736ee2c78SMiaohe Lin 		 * Note that vma->anon_vma check is racy: it can be set up after
1648c1e8d7c6SMichel Lespinasse 		 * the check but before we took mmap_lock by the fault path.
164927e1f827SSong Liu 		 * But page lock would prevent establishing any new ptes of the
165027e1f827SSong Liu 		 * page, so we are safe.
165127e1f827SSong Liu 		 *
165227e1f827SSong Liu 		 * An alternative would be drop the check, but check that page
165327e1f827SSong Liu 		 * table is clear before calling pmdp_collapse_flush() under
165427e1f827SSong Liu 		 * ptl. It has higher chance to recover THP for the VMA, but
16558d3c106eSJann Horn 		 * has higher cost too. It would also probably require locking
16568d3c106eSJann Horn 		 * the anon_vma.
165727e1f827SSong Liu 		 */
1658023f47a8SJann Horn 		if (READ_ONCE(vma->anon_vma)) {
165934488399SZach O'Keefe 			result = SCAN_PAGE_ANON;
166034488399SZach O'Keefe 			goto next;
166134488399SZach O'Keefe 		}
1662f3f0e1d2SKirill A. Shutemov 		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
166334488399SZach O'Keefe 		if (addr & ~HPAGE_PMD_MASK ||
166434488399SZach O'Keefe 		    vma->vm_end < addr + HPAGE_PMD_SIZE) {
166534488399SZach O'Keefe 			result = SCAN_VMA_CHECK;
166634488399SZach O'Keefe 			goto next;
166734488399SZach O'Keefe 		}
166818e77600SHugh Dickins 		mm = vma->vm_mm;
166934488399SZach O'Keefe 		is_target = mm == target_mm && addr == target_addr;
167034488399SZach O'Keefe 		result = find_pmd_or_thp_or_none(mm, addr, &pmd);
167134488399SZach O'Keefe 		if (result != SCAN_SUCCEED)
167234488399SZach O'Keefe 			goto next;
1673f3f0e1d2SKirill A. Shutemov 		/*
1674c1e8d7c6SMichel Lespinasse 		 * We need exclusive mmap_lock to retract page table.
167527e1f827SSong Liu 		 *
167627e1f827SSong Liu 		 * We use trylock due to lock inversion: we need to acquire
1677c1e8d7c6SMichel Lespinasse 		 * mmap_lock while holding page lock. Fault path does it in
167827e1f827SSong Liu 		 * reverse order. Trylock is a way to avoid deadlock.
167934488399SZach O'Keefe 		 *
168034488399SZach O'Keefe 		 * Also, it's not MADV_COLLAPSE's job to collapse other
168134488399SZach O'Keefe 		 * mappings - let khugepaged take care of them later.
1682f3f0e1d2SKirill A. Shutemov 		 */
168334488399SZach O'Keefe 		result = SCAN_PTE_MAPPED_HUGEPAGE;
168434488399SZach O'Keefe 		if ((cc->is_khugepaged || is_target) &&
168534488399SZach O'Keefe 		    mmap_write_trylock(mm)) {
1686deb4c93aSPeter Xu 			/*
1687023f47a8SJann Horn 			 * Re-check whether we have an ->anon_vma, because
1688023f47a8SJann Horn 			 * collapse_and_free_pmd() requires that either no
1689023f47a8SJann Horn 			 * ->anon_vma exists or the anon_vma is locked.
1690023f47a8SJann Horn 			 * We already checked ->anon_vma above, but that check
1691023f47a8SJann Horn 			 * is racy because ->anon_vma can be populated under the
1692023f47a8SJann Horn 			 * mmap lock in read mode.
1693023f47a8SJann Horn 			 */
1694023f47a8SJann Horn 			if (vma->anon_vma) {
1695023f47a8SJann Horn 				result = SCAN_PAGE_ANON;
1696023f47a8SJann Horn 				goto unlock_next;
1697023f47a8SJann Horn 			}
1698023f47a8SJann Horn 			/*
1699deb4c93aSPeter Xu 			 * When a vma is registered with uffd-wp, we can't
1700deb4c93aSPeter Xu 			 * recycle the pmd pgtable because there can be pte
1701deb4c93aSPeter Xu 			 * markers installed.  Skip it only, so the rest mm/vma
1702deb4c93aSPeter Xu 			 * can still have the same file mapped hugely, however
1703deb4c93aSPeter Xu 			 * it'll always mapped in small page size for uffd-wp
1704deb4c93aSPeter Xu 			 * registered ranges.
1705deb4c93aSPeter Xu 			 */
170634488399SZach O'Keefe 			if (hpage_collapse_test_exit(mm)) {
170734488399SZach O'Keefe 				result = SCAN_ANY_PROCESS;
170834488399SZach O'Keefe 				goto unlock_next;
1709f3f0e1d2SKirill A. Shutemov 			}
171034488399SZach O'Keefe 			if (userfaultfd_wp(vma)) {
171134488399SZach O'Keefe 				result = SCAN_PTE_UFFD_WP;
171234488399SZach O'Keefe 				goto unlock_next;
171334488399SZach O'Keefe 			}
171434488399SZach O'Keefe 			collapse_and_free_pmd(mm, vma, addr, pmd);
171534488399SZach O'Keefe 			if (!cc->is_khugepaged && is_target)
171634488399SZach O'Keefe 				result = set_huge_pmd(vma, addr, pmd, hpage);
171734488399SZach O'Keefe 			else
171834488399SZach O'Keefe 				result = SCAN_SUCCEED;
171934488399SZach O'Keefe 
172034488399SZach O'Keefe unlock_next:
172134488399SZach O'Keefe 			mmap_write_unlock(mm);
172234488399SZach O'Keefe 			goto next;
172334488399SZach O'Keefe 		}
172434488399SZach O'Keefe 		/*
172534488399SZach O'Keefe 		 * Calling context will handle target mm/addr. Otherwise, let
172634488399SZach O'Keefe 		 * khugepaged try again later.
172734488399SZach O'Keefe 		 */
172834488399SZach O'Keefe 		if (!is_target) {
172934488399SZach O'Keefe 			khugepaged_add_pte_mapped_thp(mm, addr);
173034488399SZach O'Keefe 			continue;
173134488399SZach O'Keefe 		}
173234488399SZach O'Keefe next:
173334488399SZach O'Keefe 		if (is_target)
173434488399SZach O'Keefe 			target_result = result;
1735f3f0e1d2SKirill A. Shutemov 	}
1736f3f0e1d2SKirill A. Shutemov 	i_mmap_unlock_write(mapping);
173734488399SZach O'Keefe 	return target_result;
1738f3f0e1d2SKirill A. Shutemov }
1739f3f0e1d2SKirill A. Shutemov 
1740f3f0e1d2SKirill A. Shutemov /**
174199cb0dbdSSong Liu  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1742f3f0e1d2SKirill A. Shutemov  *
1743336e6b53SAlex Shi  * @mm: process address space where collapse happens
174434488399SZach O'Keefe  * @addr: virtual collapse start address
1745336e6b53SAlex Shi  * @file: file that collapse on
1746336e6b53SAlex Shi  * @start: collapse start address
17479710a78aSZach O'Keefe  * @cc: collapse context and scratchpad
1748336e6b53SAlex Shi  *
1749f3f0e1d2SKirill A. Shutemov  * Basic scheme is simple, details are more complex:
175087c460a0SHugh Dickins  *  - allocate and lock a new huge page;
175177da9389SMatthew Wilcox  *  - scan page cache replacing old pages with the new one
175299cb0dbdSSong Liu  *    + swap/gup in pages if necessary;
1753f3f0e1d2SKirill A. Shutemov  *    + fill in gaps;
175477da9389SMatthew Wilcox  *    + keep old pages around in case rollback is required;
175577da9389SMatthew Wilcox  *  - if replacing succeeds:
1756f3f0e1d2SKirill A. Shutemov  *    + copy data over;
1757f3f0e1d2SKirill A. Shutemov  *    + free old pages;
175887c460a0SHugh Dickins  *    + unlock huge page;
1759f3f0e1d2SKirill A. Shutemov  *  - if replacing failed;
1760f3f0e1d2SKirill A. Shutemov  *    + put all pages back and unfreeze them;
176177da9389SMatthew Wilcox  *    + restore gaps in the page cache;
176287c460a0SHugh Dickins  *    + unlock and free huge page;
1763f3f0e1d2SKirill A. Shutemov  */
176434488399SZach O'Keefe static int collapse_file(struct mm_struct *mm, unsigned long addr,
1765579c571eSSong Liu 			 struct file *file, pgoff_t start,
176634488399SZach O'Keefe 			 struct collapse_control *cc)
1767f3f0e1d2SKirill A. Shutemov {
1768579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
176950ad2f24SZach O'Keefe 	struct page *hpage;
17704c9473e8SGautam Menghani 	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1771f3f0e1d2SKirill A. Shutemov 	LIST_HEAD(pagelist);
177277da9389SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1773f3f0e1d2SKirill A. Shutemov 	int nr_none = 0, result = SCAN_SUCCEED;
177499cb0dbdSSong Liu 	bool is_shmem = shmem_file(file);
17754c9473e8SGautam Menghani 	int nr = 0;
1776f3f0e1d2SKirill A. Shutemov 
177799cb0dbdSSong Liu 	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1778f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1779f3f0e1d2SKirill A. Shutemov 
178050ad2f24SZach O'Keefe 	result = alloc_charge_hpage(&hpage, mm, cc);
17819710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1782f3f0e1d2SKirill A. Shutemov 		goto out;
1783f3f0e1d2SKirill A. Shutemov 
17846b24ca4aSMatthew Wilcox (Oracle) 	/*
17856b24ca4aSMatthew Wilcox (Oracle) 	 * Ensure we have slots for all the pages in the range.  This is
17866b24ca4aSMatthew Wilcox (Oracle) 	 * almost certainly a no-op because most of the pages must be present
17876b24ca4aSMatthew Wilcox (Oracle) 	 */
178895feeabbSHugh Dickins 	do {
178995feeabbSHugh Dickins 		xas_lock_irq(&xas);
179095feeabbSHugh Dickins 		xas_create_range(&xas);
179195feeabbSHugh Dickins 		if (!xas_error(&xas))
179295feeabbSHugh Dickins 			break;
179395feeabbSHugh Dickins 		xas_unlock_irq(&xas);
179495feeabbSHugh Dickins 		if (!xas_nomem(&xas, GFP_KERNEL)) {
179595feeabbSHugh Dickins 			result = SCAN_FAIL;
179695feeabbSHugh Dickins 			goto out;
179795feeabbSHugh Dickins 		}
179895feeabbSHugh Dickins 	} while (1);
179995feeabbSHugh Dickins 
180050ad2f24SZach O'Keefe 	__SetPageLocked(hpage);
180199cb0dbdSSong Liu 	if (is_shmem)
180250ad2f24SZach O'Keefe 		__SetPageSwapBacked(hpage);
180350ad2f24SZach O'Keefe 	hpage->index = start;
180450ad2f24SZach O'Keefe 	hpage->mapping = mapping;
1805f3f0e1d2SKirill A. Shutemov 
1806f3f0e1d2SKirill A. Shutemov 	/*
180750ad2f24SZach O'Keefe 	 * At this point the hpage is locked and not up-to-date.
180887c460a0SHugh Dickins 	 * It's safe to insert it into the page cache, because nobody would
180987c460a0SHugh Dickins 	 * be able to map it or use it in another way until we unlock it.
1810f3f0e1d2SKirill A. Shutemov 	 */
1811f3f0e1d2SKirill A. Shutemov 
181277da9389SMatthew Wilcox 	xas_set(&xas, start);
181377da9389SMatthew Wilcox 	for (index = start; index < end; index++) {
181477da9389SMatthew Wilcox 		struct page *page = xas_next(&xas);
181564ab3195SVishal Moola (Oracle) 		struct folio *folio;
181677da9389SMatthew Wilcox 
181777da9389SMatthew Wilcox 		VM_BUG_ON(index != xas.xa_index);
181899cb0dbdSSong Liu 		if (is_shmem) {
181977da9389SMatthew Wilcox 			if (!page) {
1820701270faSHugh Dickins 				/*
182199cb0dbdSSong Liu 				 * Stop if extent has been truncated or
182299cb0dbdSSong Liu 				 * hole-punched, and is now completely
182399cb0dbdSSong Liu 				 * empty.
1824701270faSHugh Dickins 				 */
1825701270faSHugh Dickins 				if (index == start) {
1826701270faSHugh Dickins 					if (!xas_next_entry(&xas, end - 1)) {
1827701270faSHugh Dickins 						result = SCAN_TRUNCATED;
1828042a3082SHugh Dickins 						goto xa_locked;
1829701270faSHugh Dickins 					}
1830701270faSHugh Dickins 					xas_set(&xas, index);
1831701270faSHugh Dickins 				}
183277da9389SMatthew Wilcox 				if (!shmem_charge(mapping->host, 1)) {
1833f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
1834042a3082SHugh Dickins 					goto xa_locked;
1835f3f0e1d2SKirill A. Shutemov 				}
183650ad2f24SZach O'Keefe 				xas_store(&xas, hpage);
183777da9389SMatthew Wilcox 				nr_none++;
183877da9389SMatthew Wilcox 				continue;
1839f3f0e1d2SKirill A. Shutemov 			}
1840f3f0e1d2SKirill A. Shutemov 
18413159f943SMatthew Wilcox 			if (xa_is_value(page) || !PageUptodate(page)) {
184277da9389SMatthew Wilcox 				xas_unlock_irq(&xas);
1843f3f0e1d2SKirill A. Shutemov 				/* swap in or instantiate fallocated page */
18447459c149SMatthew Wilcox (Oracle) 				if (shmem_get_folio(mapping->host, index,
18457459c149SMatthew Wilcox (Oracle) 						&folio, SGP_NOALLOC)) {
1846f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
184777da9389SMatthew Wilcox 					goto xa_unlocked;
1848f3f0e1d2SKirill A. Shutemov 				}
18497459c149SMatthew Wilcox (Oracle) 				page = folio_file_page(folio, index);
1850f3f0e1d2SKirill A. Shutemov 			} else if (trylock_page(page)) {
1851f3f0e1d2SKirill A. Shutemov 				get_page(page);
1852042a3082SHugh Dickins 				xas_unlock_irq(&xas);
1853f3f0e1d2SKirill A. Shutemov 			} else {
1854f3f0e1d2SKirill A. Shutemov 				result = SCAN_PAGE_LOCK;
1855042a3082SHugh Dickins 				goto xa_locked;
1856f3f0e1d2SKirill A. Shutemov 			}
185799cb0dbdSSong Liu 		} else {	/* !is_shmem */
185899cb0dbdSSong Liu 			if (!page || xa_is_value(page)) {
185999cb0dbdSSong Liu 				xas_unlock_irq(&xas);
186099cb0dbdSSong Liu 				page_cache_sync_readahead(mapping, &file->f_ra,
186199cb0dbdSSong Liu 							  file, index,
1862e5a59d30SDavid Howells 							  end - index);
186399cb0dbdSSong Liu 				/* drain pagevecs to help isolate_lru_page() */
186499cb0dbdSSong Liu 				lru_add_drain();
186599cb0dbdSSong Liu 				page = find_lock_page(mapping, index);
186699cb0dbdSSong Liu 				if (unlikely(page == NULL)) {
186799cb0dbdSSong Liu 					result = SCAN_FAIL;
186899cb0dbdSSong Liu 					goto xa_unlocked;
186999cb0dbdSSong Liu 				}
187075f36069SSong Liu 			} else if (PageDirty(page)) {
187175f36069SSong Liu 				/*
187275f36069SSong Liu 				 * khugepaged only works on read-only fd,
187375f36069SSong Liu 				 * so this page is dirty because it hasn't
187475f36069SSong Liu 				 * been flushed since first write. There
187575f36069SSong Liu 				 * won't be new dirty pages.
187675f36069SSong Liu 				 *
187775f36069SSong Liu 				 * Trigger async flush here and hope the
187875f36069SSong Liu 				 * writeback is done when khugepaged
187975f36069SSong Liu 				 * revisits this page.
188075f36069SSong Liu 				 *
188175f36069SSong Liu 				 * This is a one-off situation. We are not
188275f36069SSong Liu 				 * forcing writeback in loop.
188375f36069SSong Liu 				 */
188475f36069SSong Liu 				xas_unlock_irq(&xas);
188575f36069SSong Liu 				filemap_flush(mapping);
188675f36069SSong Liu 				result = SCAN_FAIL;
188775f36069SSong Liu 				goto xa_unlocked;
188874c42e1bSRongwei Wang 			} else if (PageWriteback(page)) {
188974c42e1bSRongwei Wang 				xas_unlock_irq(&xas);
189074c42e1bSRongwei Wang 				result = SCAN_FAIL;
189174c42e1bSRongwei Wang 				goto xa_unlocked;
189299cb0dbdSSong Liu 			} else if (trylock_page(page)) {
189399cb0dbdSSong Liu 				get_page(page);
189499cb0dbdSSong Liu 				xas_unlock_irq(&xas);
189599cb0dbdSSong Liu 			} else {
189699cb0dbdSSong Liu 				result = SCAN_PAGE_LOCK;
189799cb0dbdSSong Liu 				goto xa_locked;
189899cb0dbdSSong Liu 			}
189999cb0dbdSSong Liu 		}
1900f3f0e1d2SKirill A. Shutemov 
1901f3f0e1d2SKirill A. Shutemov 		/*
1902b93b0163SMatthew Wilcox 		 * The page must be locked, so we can drop the i_pages lock
1903f3f0e1d2SKirill A. Shutemov 		 * without racing with truncate.
1904f3f0e1d2SKirill A. Shutemov 		 */
1905f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
19064655e5e5SSong Liu 
19074655e5e5SSong Liu 		/* make sure the page is up to date */
19084655e5e5SSong Liu 		if (unlikely(!PageUptodate(page))) {
19094655e5e5SSong Liu 			result = SCAN_FAIL;
19104655e5e5SSong Liu 			goto out_unlock;
19114655e5e5SSong Liu 		}
191206a5e126SHugh Dickins 
191306a5e126SHugh Dickins 		/*
191406a5e126SHugh Dickins 		 * If file was truncated then extended, or hole-punched, before
191506a5e126SHugh Dickins 		 * we locked the first page, then a THP might be there already.
191658ac9a89SZach O'Keefe 		 * This will be discovered on the first iteration.
191706a5e126SHugh Dickins 		 */
191806a5e126SHugh Dickins 		if (PageTransCompound(page)) {
191958ac9a89SZach O'Keefe 			struct page *head = compound_head(page);
192058ac9a89SZach O'Keefe 
192158ac9a89SZach O'Keefe 			result = compound_order(head) == HPAGE_PMD_ORDER &&
192258ac9a89SZach O'Keefe 					head->index == start
192358ac9a89SZach O'Keefe 					/* Maybe PMD-mapped */
192458ac9a89SZach O'Keefe 					? SCAN_PTE_MAPPED_HUGEPAGE
192558ac9a89SZach O'Keefe 					: SCAN_PAGE_COMPOUND;
192606a5e126SHugh Dickins 			goto out_unlock;
192706a5e126SHugh Dickins 		}
1928f3f0e1d2SKirill A. Shutemov 
192964ab3195SVishal Moola (Oracle) 		folio = page_folio(page);
193064ab3195SVishal Moola (Oracle) 
193164ab3195SVishal Moola (Oracle) 		if (folio_mapping(folio) != mapping) {
1932f3f0e1d2SKirill A. Shutemov 			result = SCAN_TRUNCATED;
1933f3f0e1d2SKirill A. Shutemov 			goto out_unlock;
1934f3f0e1d2SKirill A. Shutemov 		}
1935f3f0e1d2SKirill A. Shutemov 
193664ab3195SVishal Moola (Oracle) 		if (!is_shmem && (folio_test_dirty(folio) ||
193764ab3195SVishal Moola (Oracle) 				  folio_test_writeback(folio))) {
19384655e5e5SSong Liu 			/*
19394655e5e5SSong Liu 			 * khugepaged only works on read-only fd, so this
19404655e5e5SSong Liu 			 * page is dirty because it hasn't been flushed
19414655e5e5SSong Liu 			 * since first write.
19424655e5e5SSong Liu 			 */
19434655e5e5SSong Liu 			result = SCAN_FAIL;
19444655e5e5SSong Liu 			goto out_unlock;
19454655e5e5SSong Liu 		}
19464655e5e5SSong Liu 
194764ab3195SVishal Moola (Oracle) 		if (folio_isolate_lru(folio)) {
1948f3f0e1d2SKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
1949042a3082SHugh Dickins 			goto out_unlock;
1950f3f0e1d2SKirill A. Shutemov 		}
1951f3f0e1d2SKirill A. Shutemov 
195264ab3195SVishal Moola (Oracle) 		if (folio_has_private(folio) &&
195364ab3195SVishal Moola (Oracle) 		    !filemap_release_folio(folio, GFP_KERNEL)) {
195499cb0dbdSSong Liu 			result = SCAN_PAGE_HAS_PRIVATE;
195564ab3195SVishal Moola (Oracle) 			folio_putback_lru(folio);
195699cb0dbdSSong Liu 			goto out_unlock;
195799cb0dbdSSong Liu 		}
195899cb0dbdSSong Liu 
195964ab3195SVishal Moola (Oracle) 		if (folio_mapped(folio))
196064ab3195SVishal Moola (Oracle) 			try_to_unmap(folio,
1961869f7ee6SMatthew Wilcox (Oracle) 					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1962f3f0e1d2SKirill A. Shutemov 
196377da9389SMatthew Wilcox 		xas_lock_irq(&xas);
196477da9389SMatthew Wilcox 		xas_set(&xas, index);
1965f3f0e1d2SKirill A. Shutemov 
196677da9389SMatthew Wilcox 		VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1967f3f0e1d2SKirill A. Shutemov 
1968f3f0e1d2SKirill A. Shutemov 		/*
1969f3f0e1d2SKirill A. Shutemov 		 * The page is expected to have page_count() == 3:
1970f3f0e1d2SKirill A. Shutemov 		 *  - we hold a pin on it;
197177da9389SMatthew Wilcox 		 *  - one reference from page cache;
1972f3f0e1d2SKirill A. Shutemov 		 *  - one from isolate_lru_page;
1973f3f0e1d2SKirill A. Shutemov 		 */
1974f3f0e1d2SKirill A. Shutemov 		if (!page_ref_freeze(page, 3)) {
1975f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1976042a3082SHugh Dickins 			xas_unlock_irq(&xas);
1977042a3082SHugh Dickins 			putback_lru_page(page);
1978042a3082SHugh Dickins 			goto out_unlock;
1979f3f0e1d2SKirill A. Shutemov 		}
1980f3f0e1d2SKirill A. Shutemov 
1981f3f0e1d2SKirill A. Shutemov 		/*
1982f3f0e1d2SKirill A. Shutemov 		 * Add the page to the list to be able to undo the collapse if
1983f3f0e1d2SKirill A. Shutemov 		 * something go wrong.
1984f3f0e1d2SKirill A. Shutemov 		 */
1985f3f0e1d2SKirill A. Shutemov 		list_add_tail(&page->lru, &pagelist);
1986f3f0e1d2SKirill A. Shutemov 
1987f3f0e1d2SKirill A. Shutemov 		/* Finally, replace with the new page. */
198850ad2f24SZach O'Keefe 		xas_store(&xas, hpage);
1989f3f0e1d2SKirill A. Shutemov 		continue;
1990f3f0e1d2SKirill A. Shutemov out_unlock:
1991f3f0e1d2SKirill A. Shutemov 		unlock_page(page);
1992f3f0e1d2SKirill A. Shutemov 		put_page(page);
1993042a3082SHugh Dickins 		goto xa_unlocked;
1994f3f0e1d2SKirill A. Shutemov 	}
199550ad2f24SZach O'Keefe 	nr = thp_nr_pages(hpage);
1996f3f0e1d2SKirill A. Shutemov 
199799cb0dbdSSong Liu 	if (is_shmem)
199850ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
199909d91cdaSSong Liu 	else {
200050ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
200109d91cdaSSong Liu 		filemap_nr_thps_inc(mapping);
2002eb6ecbedSCollin Fijalkovich 		/*
2003eb6ecbedSCollin Fijalkovich 		 * Paired with smp_mb() in do_dentry_open() to ensure
2004eb6ecbedSCollin Fijalkovich 		 * i_writecount is up to date and the update to nr_thps is
2005eb6ecbedSCollin Fijalkovich 		 * visible. Ensures the page cache will be truncated if the
2006eb6ecbedSCollin Fijalkovich 		 * file is opened writable.
2007eb6ecbedSCollin Fijalkovich 		 */
2008eb6ecbedSCollin Fijalkovich 		smp_mb();
2009eb6ecbedSCollin Fijalkovich 		if (inode_is_open_for_write(mapping->host)) {
2010eb6ecbedSCollin Fijalkovich 			result = SCAN_FAIL;
201150ad2f24SZach O'Keefe 			__mod_lruvec_page_state(hpage, NR_FILE_THPS, -nr);
2012eb6ecbedSCollin Fijalkovich 			filemap_nr_thps_dec(mapping);
2013eb6ecbedSCollin Fijalkovich 			goto xa_locked;
2014eb6ecbedSCollin Fijalkovich 		}
201509d91cdaSSong Liu 	}
201699cb0dbdSSong Liu 
2017042a3082SHugh Dickins 	if (nr_none) {
201850ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
20192f55f070SMiaohe Lin 		/* nr_none is always 0 for non-shmem. */
202050ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2021042a3082SHugh Dickins 	}
2022042a3082SHugh Dickins 
20236b24ca4aSMatthew Wilcox (Oracle) 	/* Join all the small entries into a single multi-index entry */
20246b24ca4aSMatthew Wilcox (Oracle) 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
202550ad2f24SZach O'Keefe 	xas_store(&xas, hpage);
2026042a3082SHugh Dickins xa_locked:
2027042a3082SHugh Dickins 	xas_unlock_irq(&xas);
202877da9389SMatthew Wilcox xa_unlocked:
2029042a3082SHugh Dickins 
20306d9df8a5SHugh Dickins 	/*
20316d9df8a5SHugh Dickins 	 * If collapse is successful, flush must be done now before copying.
20326d9df8a5SHugh Dickins 	 * If collapse is unsuccessful, does flush actually need to be done?
20336d9df8a5SHugh Dickins 	 * Do it anyway, to clear the state.
20346d9df8a5SHugh Dickins 	 */
20356d9df8a5SHugh Dickins 	try_to_unmap_flush();
20366d9df8a5SHugh Dickins 
2037f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
203877da9389SMatthew Wilcox 		struct page *page, *tmp;
2039284a344eSVishal Moola (Oracle) 		struct folio *folio;
2040f3f0e1d2SKirill A. Shutemov 
2041f3f0e1d2SKirill A. Shutemov 		/*
204277da9389SMatthew Wilcox 		 * Replacing old pages with new one has succeeded, now we
204377da9389SMatthew Wilcox 		 * need to copy the content and free the old pages.
2044f3f0e1d2SKirill A. Shutemov 		 */
20452af8ff29SHugh Dickins 		index = start;
2046f3f0e1d2SKirill A. Shutemov 		list_for_each_entry_safe(page, tmp, &pagelist, lru) {
20472af8ff29SHugh Dickins 			while (index < page->index) {
204850ad2f24SZach O'Keefe 				clear_highpage(hpage + (index % HPAGE_PMD_NR));
20492af8ff29SHugh Dickins 				index++;
20502af8ff29SHugh Dickins 			}
205150ad2f24SZach O'Keefe 			copy_highpage(hpage + (page->index % HPAGE_PMD_NR),
2052f3f0e1d2SKirill A. Shutemov 				      page);
2053f3f0e1d2SKirill A. Shutemov 			list_del(&page->lru);
2054f3f0e1d2SKirill A. Shutemov 			page->mapping = NULL;
2055042a3082SHugh Dickins 			page_ref_unfreeze(page, 1);
2056f3f0e1d2SKirill A. Shutemov 			ClearPageActive(page);
2057f3f0e1d2SKirill A. Shutemov 			ClearPageUnevictable(page);
2058042a3082SHugh Dickins 			unlock_page(page);
2059f3f0e1d2SKirill A. Shutemov 			put_page(page);
20602af8ff29SHugh Dickins 			index++;
20612af8ff29SHugh Dickins 		}
20622af8ff29SHugh Dickins 		while (index < end) {
206350ad2f24SZach O'Keefe 			clear_highpage(hpage + (index % HPAGE_PMD_NR));
20642af8ff29SHugh Dickins 			index++;
2065f3f0e1d2SKirill A. Shutemov 		}
2066f3f0e1d2SKirill A. Shutemov 
2067284a344eSVishal Moola (Oracle) 		folio = page_folio(hpage);
2068284a344eSVishal Moola (Oracle) 		folio_mark_uptodate(folio);
2069284a344eSVishal Moola (Oracle) 		folio_ref_add(folio, HPAGE_PMD_NR - 1);
2070284a344eSVishal Moola (Oracle) 
20716058eaecSJohannes Weiner 		if (is_shmem)
2072284a344eSVishal Moola (Oracle) 			folio_mark_dirty(folio);
2073284a344eSVishal Moola (Oracle) 		folio_add_lru(folio);
2074f3f0e1d2SKirill A. Shutemov 
2075042a3082SHugh Dickins 		/*
2076042a3082SHugh Dickins 		 * Remove pte page tables, so we can re-fault the page as huge.
2077042a3082SHugh Dickins 		 */
207834488399SZach O'Keefe 		result = retract_page_tables(mapping, start, mm, addr, hpage,
207934488399SZach O'Keefe 					     cc);
208050ad2f24SZach O'Keefe 		unlock_page(hpage);
208150ad2f24SZach O'Keefe 		hpage = NULL;
2082f3f0e1d2SKirill A. Shutemov 	} else {
208377da9389SMatthew Wilcox 		struct page *page;
2084aaa52e34SHugh Dickins 
208577da9389SMatthew Wilcox 		/* Something went wrong: roll back page cache changes */
208677da9389SMatthew Wilcox 		xas_lock_irq(&xas);
20872f55f070SMiaohe Lin 		if (nr_none) {
2088aaa52e34SHugh Dickins 			mapping->nrpages -= nr_none;
2089aaa52e34SHugh Dickins 			shmem_uncharge(mapping->host, nr_none);
20902f55f070SMiaohe Lin 		}
2091aaa52e34SHugh Dickins 
209277da9389SMatthew Wilcox 		xas_set(&xas, start);
209377da9389SMatthew Wilcox 		xas_for_each(&xas, page, end - 1) {
2094f3f0e1d2SKirill A. Shutemov 			page = list_first_entry_or_null(&pagelist,
2095f3f0e1d2SKirill A. Shutemov 					struct page, lru);
209677da9389SMatthew Wilcox 			if (!page || xas.xa_index < page->index) {
2097f3f0e1d2SKirill A. Shutemov 				if (!nr_none)
2098f3f0e1d2SKirill A. Shutemov 					break;
2099f3f0e1d2SKirill A. Shutemov 				nr_none--;
210059749e6cSJohannes Weiner 				/* Put holes back where they were */
210177da9389SMatthew Wilcox 				xas_store(&xas, NULL);
2102f3f0e1d2SKirill A. Shutemov 				continue;
2103f3f0e1d2SKirill A. Shutemov 			}
2104f3f0e1d2SKirill A. Shutemov 
210577da9389SMatthew Wilcox 			VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2106f3f0e1d2SKirill A. Shutemov 
2107f3f0e1d2SKirill A. Shutemov 			/* Unfreeze the page. */
2108f3f0e1d2SKirill A. Shutemov 			list_del(&page->lru);
2109f3f0e1d2SKirill A. Shutemov 			page_ref_unfreeze(page, 2);
211077da9389SMatthew Wilcox 			xas_store(&xas, page);
211177da9389SMatthew Wilcox 			xas_pause(&xas);
211277da9389SMatthew Wilcox 			xas_unlock_irq(&xas);
2113f3f0e1d2SKirill A. Shutemov 			unlock_page(page);
2114042a3082SHugh Dickins 			putback_lru_page(page);
211577da9389SMatthew Wilcox 			xas_lock_irq(&xas);
2116f3f0e1d2SKirill A. Shutemov 		}
2117f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON(nr_none);
211877da9389SMatthew Wilcox 		xas_unlock_irq(&xas);
2119f3f0e1d2SKirill A. Shutemov 
212050ad2f24SZach O'Keefe 		hpage->mapping = NULL;
2121f3f0e1d2SKirill A. Shutemov 	}
2122042a3082SHugh Dickins 
212350ad2f24SZach O'Keefe 	if (hpage)
212450ad2f24SZach O'Keefe 		unlock_page(hpage);
2125f3f0e1d2SKirill A. Shutemov out:
2126f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(!list_empty(&pagelist));
212750ad2f24SZach O'Keefe 	if (hpage) {
212850ad2f24SZach O'Keefe 		mem_cgroup_uncharge(page_folio(hpage));
212950ad2f24SZach O'Keefe 		put_page(hpage);
2130c6a7f445SYang Shi 	}
21314c9473e8SGautam Menghani 
21324c9473e8SGautam Menghani 	trace_mm_khugepaged_collapse_file(mm, hpage, index, is_shmem, addr, file, nr, result);
213350ad2f24SZach O'Keefe 	return result;
2134f3f0e1d2SKirill A. Shutemov }
2135f3f0e1d2SKirill A. Shutemov 
213634488399SZach O'Keefe static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
213734488399SZach O'Keefe 				    struct file *file, pgoff_t start,
213834488399SZach O'Keefe 				    struct collapse_control *cc)
2139f3f0e1d2SKirill A. Shutemov {
2140f3f0e1d2SKirill A. Shutemov 	struct page *page = NULL;
2141579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
214285b392dbSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
2143f3f0e1d2SKirill A. Shutemov 	int present, swap;
2144f3f0e1d2SKirill A. Shutemov 	int node = NUMA_NO_NODE;
2145f3f0e1d2SKirill A. Shutemov 	int result = SCAN_SUCCEED;
2146f3f0e1d2SKirill A. Shutemov 
2147f3f0e1d2SKirill A. Shutemov 	present = 0;
2148f3f0e1d2SKirill A. Shutemov 	swap = 0;
214934d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
2150e031ff96SYang Shi 	nodes_clear(cc->alloc_nmask);
2151f3f0e1d2SKirill A. Shutemov 	rcu_read_lock();
215285b392dbSMatthew Wilcox 	xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
215385b392dbSMatthew Wilcox 		if (xas_retry(&xas, page))
2154f3f0e1d2SKirill A. Shutemov 			continue;
2155f3f0e1d2SKirill A. Shutemov 
215685b392dbSMatthew Wilcox 		if (xa_is_value(page)) {
2157d8ea7cc8SZach O'Keefe 			++swap;
2158d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
2159d8ea7cc8SZach O'Keefe 			    swap > khugepaged_max_ptes_swap) {
2160f3f0e1d2SKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
2161e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2162f3f0e1d2SKirill A. Shutemov 				break;
2163f3f0e1d2SKirill A. Shutemov 			}
2164f3f0e1d2SKirill A. Shutemov 			continue;
2165f3f0e1d2SKirill A. Shutemov 		}
2166f3f0e1d2SKirill A. Shutemov 
21676b24ca4aSMatthew Wilcox (Oracle) 		/*
216858ac9a89SZach O'Keefe 		 * TODO: khugepaged should compact smaller compound pages
21696b24ca4aSMatthew Wilcox (Oracle) 		 * into a PMD sized page
21706b24ca4aSMatthew Wilcox (Oracle) 		 */
2171f3f0e1d2SKirill A. Shutemov 		if (PageTransCompound(page)) {
217258ac9a89SZach O'Keefe 			struct page *head = compound_head(page);
217358ac9a89SZach O'Keefe 
217458ac9a89SZach O'Keefe 			result = compound_order(head) == HPAGE_PMD_ORDER &&
217558ac9a89SZach O'Keefe 					head->index == start
217658ac9a89SZach O'Keefe 					/* Maybe PMD-mapped */
217758ac9a89SZach O'Keefe 					? SCAN_PTE_MAPPED_HUGEPAGE
217858ac9a89SZach O'Keefe 					: SCAN_PAGE_COMPOUND;
217958ac9a89SZach O'Keefe 			/*
218058ac9a89SZach O'Keefe 			 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
218158ac9a89SZach O'Keefe 			 * by the caller won't touch the page cache, and so
218258ac9a89SZach O'Keefe 			 * it's safe to skip LRU and refcount checks before
218358ac9a89SZach O'Keefe 			 * returning.
218458ac9a89SZach O'Keefe 			 */
2185f3f0e1d2SKirill A. Shutemov 			break;
2186f3f0e1d2SKirill A. Shutemov 		}
2187f3f0e1d2SKirill A. Shutemov 
2188f3f0e1d2SKirill A. Shutemov 		node = page_to_nid(page);
21897d2c4385SZach O'Keefe 		if (hpage_collapse_scan_abort(node, cc)) {
2190f3f0e1d2SKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
2191f3f0e1d2SKirill A. Shutemov 			break;
2192f3f0e1d2SKirill A. Shutemov 		}
219334d6b470SZach O'Keefe 		cc->node_load[node]++;
2194f3f0e1d2SKirill A. Shutemov 
2195f3f0e1d2SKirill A. Shutemov 		if (!PageLRU(page)) {
2196f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_LRU;
2197f3f0e1d2SKirill A. Shutemov 			break;
2198f3f0e1d2SKirill A. Shutemov 		}
2199f3f0e1d2SKirill A. Shutemov 
220099cb0dbdSSong Liu 		if (page_count(page) !=
220199cb0dbdSSong Liu 		    1 + page_mapcount(page) + page_has_private(page)) {
2202f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
2203f3f0e1d2SKirill A. Shutemov 			break;
2204f3f0e1d2SKirill A. Shutemov 		}
2205f3f0e1d2SKirill A. Shutemov 
2206f3f0e1d2SKirill A. Shutemov 		/*
2207f3f0e1d2SKirill A. Shutemov 		 * We probably should check if the page is referenced here, but
2208f3f0e1d2SKirill A. Shutemov 		 * nobody would transfer pte_young() to PageReferenced() for us.
2209f3f0e1d2SKirill A. Shutemov 		 * And rmap walk here is just too costly...
2210f3f0e1d2SKirill A. Shutemov 		 */
2211f3f0e1d2SKirill A. Shutemov 
2212f3f0e1d2SKirill A. Shutemov 		present++;
2213f3f0e1d2SKirill A. Shutemov 
2214f3f0e1d2SKirill A. Shutemov 		if (need_resched()) {
221585b392dbSMatthew Wilcox 			xas_pause(&xas);
2216f3f0e1d2SKirill A. Shutemov 			cond_resched_rcu();
2217f3f0e1d2SKirill A. Shutemov 		}
2218f3f0e1d2SKirill A. Shutemov 	}
2219f3f0e1d2SKirill A. Shutemov 	rcu_read_unlock();
2220f3f0e1d2SKirill A. Shutemov 
2221f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
2222d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
2223d8ea7cc8SZach O'Keefe 		    present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2224f3f0e1d2SKirill A. Shutemov 			result = SCAN_EXCEED_NONE_PTE;
2225e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2226f3f0e1d2SKirill A. Shutemov 		} else {
222734488399SZach O'Keefe 			result = collapse_file(mm, addr, file, start, cc);
2228f3f0e1d2SKirill A. Shutemov 		}
2229f3f0e1d2SKirill A. Shutemov 	}
2230f3f0e1d2SKirill A. Shutemov 
2231045634ffSGautam Menghani 	trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
223250ad2f24SZach O'Keefe 	return result;
2233f3f0e1d2SKirill A. Shutemov }
2234f3f0e1d2SKirill A. Shutemov #else
223534488399SZach O'Keefe static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
223634488399SZach O'Keefe 				    struct file *file, pgoff_t start,
223734488399SZach O'Keefe 				    struct collapse_control *cc)
2238f3f0e1d2SKirill A. Shutemov {
2239f3f0e1d2SKirill A. Shutemov 	BUILD_BUG();
2240f3f0e1d2SKirill A. Shutemov }
224127e1f827SSong Liu 
2242b26e2701SQi Zheng static void khugepaged_collapse_pte_mapped_thps(struct khugepaged_mm_slot *mm_slot)
224327e1f827SSong Liu {
224427e1f827SSong Liu }
224558ac9a89SZach O'Keefe 
224658ac9a89SZach O'Keefe static bool khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
224758ac9a89SZach O'Keefe 					  unsigned long addr)
224858ac9a89SZach O'Keefe {
224958ac9a89SZach O'Keefe 	return false;
225058ac9a89SZach O'Keefe }
2251f3f0e1d2SKirill A. Shutemov #endif
2252f3f0e1d2SKirill A. Shutemov 
225350ad2f24SZach O'Keefe static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
225434d6b470SZach O'Keefe 					    struct collapse_control *cc)
2255b46e756fSKirill A. Shutemov 	__releases(&khugepaged_mm_lock)
2256b46e756fSKirill A. Shutemov 	__acquires(&khugepaged_mm_lock)
2257b46e756fSKirill A. Shutemov {
225868540502SMatthew Wilcox (Oracle) 	struct vma_iterator vmi;
2259b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
2260b26e2701SQi Zheng 	struct mm_slot *slot;
2261b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
2262b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
2263b46e756fSKirill A. Shutemov 	int progress = 0;
2264b46e756fSKirill A. Shutemov 
2265b46e756fSKirill A. Shutemov 	VM_BUG_ON(!pages);
226635f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
226750ad2f24SZach O'Keefe 	*result = SCAN_FAIL;
2268b46e756fSKirill A. Shutemov 
2269b26e2701SQi Zheng 	if (khugepaged_scan.mm_slot) {
2270b46e756fSKirill A. Shutemov 		mm_slot = khugepaged_scan.mm_slot;
2271b26e2701SQi Zheng 		slot = &mm_slot->slot;
2272b26e2701SQi Zheng 	} else {
2273b26e2701SQi Zheng 		slot = list_entry(khugepaged_scan.mm_head.next,
2274b46e756fSKirill A. Shutemov 				     struct mm_slot, mm_node);
2275b26e2701SQi Zheng 		mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2276b46e756fSKirill A. Shutemov 		khugepaged_scan.address = 0;
2277b46e756fSKirill A. Shutemov 		khugepaged_scan.mm_slot = mm_slot;
2278b46e756fSKirill A. Shutemov 	}
2279b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
228027e1f827SSong Liu 	khugepaged_collapse_pte_mapped_thps(mm_slot);
2281b46e756fSKirill A. Shutemov 
2282b26e2701SQi Zheng 	mm = slot->mm;
22833b454ad3SYang Shi 	/*
22843b454ad3SYang Shi 	 * Don't wait for semaphore (to avoid long wait times).  Just move to
22853b454ad3SYang Shi 	 * the next mm on the list.
22863b454ad3SYang Shi 	 */
2287b46e756fSKirill A. Shutemov 	vma = NULL;
2288d8ed45c5SMichel Lespinasse 	if (unlikely(!mmap_read_trylock(mm)))
2289c1e8d7c6SMichel Lespinasse 		goto breakouterloop_mmap_lock;
2290b46e756fSKirill A. Shutemov 
2291b46e756fSKirill A. Shutemov 	progress++;
229268540502SMatthew Wilcox (Oracle) 	if (unlikely(hpage_collapse_test_exit(mm)))
229368540502SMatthew Wilcox (Oracle) 		goto breakouterloop;
229468540502SMatthew Wilcox (Oracle) 
229568540502SMatthew Wilcox (Oracle) 	vma_iter_init(&vmi, mm, khugepaged_scan.address);
229668540502SMatthew Wilcox (Oracle) 	for_each_vma(vmi, vma) {
2297b46e756fSKirill A. Shutemov 		unsigned long hstart, hend;
2298b46e756fSKirill A. Shutemov 
2299b46e756fSKirill A. Shutemov 		cond_resched();
23007d2c4385SZach O'Keefe 		if (unlikely(hpage_collapse_test_exit(mm))) {
2301b46e756fSKirill A. Shutemov 			progress++;
2302b46e756fSKirill A. Shutemov 			break;
2303b46e756fSKirill A. Shutemov 		}
2304a7f4e6e4SZach O'Keefe 		if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2305b46e756fSKirill A. Shutemov skip:
2306b46e756fSKirill A. Shutemov 			progress++;
2307b46e756fSKirill A. Shutemov 			continue;
2308b46e756fSKirill A. Shutemov 		}
23094fa6893fSYang Shi 		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
23104fa6893fSYang Shi 		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2311b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address > hend)
2312b46e756fSKirill A. Shutemov 			goto skip;
2313b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address < hstart)
2314b46e756fSKirill A. Shutemov 			khugepaged_scan.address = hstart;
2315b46e756fSKirill A. Shutemov 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2316b46e756fSKirill A. Shutemov 
2317b46e756fSKirill A. Shutemov 		while (khugepaged_scan.address < hend) {
231850ad2f24SZach O'Keefe 			bool mmap_locked = true;
231950ad2f24SZach O'Keefe 
2320b46e756fSKirill A. Shutemov 			cond_resched();
23217d2c4385SZach O'Keefe 			if (unlikely(hpage_collapse_test_exit(mm)))
2322b46e756fSKirill A. Shutemov 				goto breakouterloop;
2323b46e756fSKirill A. Shutemov 
2324b46e756fSKirill A. Shutemov 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2325b46e756fSKirill A. Shutemov 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2326b46e756fSKirill A. Shutemov 				  hend);
232799cb0dbdSSong Liu 			if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2328396bcc52SMatthew Wilcox (Oracle) 				struct file *file = get_file(vma->vm_file);
2329f3f0e1d2SKirill A. Shutemov 				pgoff_t pgoff = linear_page_index(vma,
2330f3f0e1d2SKirill A. Shutemov 						khugepaged_scan.address);
233199cb0dbdSSong Liu 
2332d8ed45c5SMichel Lespinasse 				mmap_read_unlock(mm);
233334488399SZach O'Keefe 				*result = hpage_collapse_scan_file(mm,
233434488399SZach O'Keefe 								   khugepaged_scan.address,
233534488399SZach O'Keefe 								   file, pgoff, cc);
233650ad2f24SZach O'Keefe 				mmap_locked = false;
2337f3f0e1d2SKirill A. Shutemov 				fput(file);
2338f3f0e1d2SKirill A. Shutemov 			} else {
23397d2c4385SZach O'Keefe 				*result = hpage_collapse_scan_pmd(mm, vma,
2340b46e756fSKirill A. Shutemov 								  khugepaged_scan.address,
23417d2c4385SZach O'Keefe 								  &mmap_locked,
23427d2c4385SZach O'Keefe 								  cc);
2343f3f0e1d2SKirill A. Shutemov 			}
234458ac9a89SZach O'Keefe 			switch (*result) {
234558ac9a89SZach O'Keefe 			case SCAN_PTE_MAPPED_HUGEPAGE: {
234658ac9a89SZach O'Keefe 				pmd_t *pmd;
234758ac9a89SZach O'Keefe 
234858ac9a89SZach O'Keefe 				*result = find_pmd_or_thp_or_none(mm,
234958ac9a89SZach O'Keefe 								  khugepaged_scan.address,
235058ac9a89SZach O'Keefe 								  &pmd);
235158ac9a89SZach O'Keefe 				if (*result != SCAN_SUCCEED)
235258ac9a89SZach O'Keefe 					break;
235358ac9a89SZach O'Keefe 				if (!khugepaged_add_pte_mapped_thp(mm,
235458ac9a89SZach O'Keefe 								   khugepaged_scan.address))
235558ac9a89SZach O'Keefe 					break;
235658ac9a89SZach O'Keefe 			} fallthrough;
235758ac9a89SZach O'Keefe 			case SCAN_SUCCEED:
235850ad2f24SZach O'Keefe 				++khugepaged_pages_collapsed;
235958ac9a89SZach O'Keefe 				break;
236058ac9a89SZach O'Keefe 			default:
236158ac9a89SZach O'Keefe 				break;
236258ac9a89SZach O'Keefe 			}
236358ac9a89SZach O'Keefe 
2364b46e756fSKirill A. Shutemov 			/* move to next address */
2365b46e756fSKirill A. Shutemov 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2366b46e756fSKirill A. Shutemov 			progress += HPAGE_PMD_NR;
236750ad2f24SZach O'Keefe 			if (!mmap_locked)
236850ad2f24SZach O'Keefe 				/*
236950ad2f24SZach O'Keefe 				 * We released mmap_lock so break loop.  Note
237050ad2f24SZach O'Keefe 				 * that we drop mmap_lock before all hugepage
237150ad2f24SZach O'Keefe 				 * allocations, so if allocation fails, we are
237250ad2f24SZach O'Keefe 				 * guaranteed to break here and report the
237350ad2f24SZach O'Keefe 				 * correct result back to caller.
237450ad2f24SZach O'Keefe 				 */
2375c1e8d7c6SMichel Lespinasse 				goto breakouterloop_mmap_lock;
2376b46e756fSKirill A. Shutemov 			if (progress >= pages)
2377b46e756fSKirill A. Shutemov 				goto breakouterloop;
2378b46e756fSKirill A. Shutemov 		}
2379b46e756fSKirill A. Shutemov 	}
2380b46e756fSKirill A. Shutemov breakouterloop:
2381d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2382c1e8d7c6SMichel Lespinasse breakouterloop_mmap_lock:
2383b46e756fSKirill A. Shutemov 
2384b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2385b46e756fSKirill A. Shutemov 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2386b46e756fSKirill A. Shutemov 	/*
2387b46e756fSKirill A. Shutemov 	 * Release the current mm_slot if this mm is about to die, or
2388b46e756fSKirill A. Shutemov 	 * if we scanned all vmas of this mm.
2389b46e756fSKirill A. Shutemov 	 */
23907d2c4385SZach O'Keefe 	if (hpage_collapse_test_exit(mm) || !vma) {
2391b46e756fSKirill A. Shutemov 		/*
2392b46e756fSKirill A. Shutemov 		 * Make sure that if mm_users is reaching zero while
2393b46e756fSKirill A. Shutemov 		 * khugepaged runs here, khugepaged_exit will find
2394b46e756fSKirill A. Shutemov 		 * mm_slot not pointing to the exiting mm.
2395b46e756fSKirill A. Shutemov 		 */
2396b26e2701SQi Zheng 		if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2397b26e2701SQi Zheng 			slot = list_entry(slot->mm_node.next,
2398b46e756fSKirill A. Shutemov 					  struct mm_slot, mm_node);
2399b26e2701SQi Zheng 			khugepaged_scan.mm_slot =
2400b26e2701SQi Zheng 				mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2401b46e756fSKirill A. Shutemov 			khugepaged_scan.address = 0;
2402b46e756fSKirill A. Shutemov 		} else {
2403b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = NULL;
2404b46e756fSKirill A. Shutemov 			khugepaged_full_scans++;
2405b46e756fSKirill A. Shutemov 		}
2406b46e756fSKirill A. Shutemov 
2407b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2408b46e756fSKirill A. Shutemov 	}
2409b46e756fSKirill A. Shutemov 
2410b46e756fSKirill A. Shutemov 	return progress;
2411b46e756fSKirill A. Shutemov }
2412b46e756fSKirill A. Shutemov 
2413b46e756fSKirill A. Shutemov static int khugepaged_has_work(void)
2414b46e756fSKirill A. Shutemov {
2415b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) &&
24161064026bSYang Shi 		hugepage_flags_enabled();
2417b46e756fSKirill A. Shutemov }
2418b46e756fSKirill A. Shutemov 
2419b46e756fSKirill A. Shutemov static int khugepaged_wait_event(void)
2420b46e756fSKirill A. Shutemov {
2421b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) ||
2422b46e756fSKirill A. Shutemov 		kthread_should_stop();
2423b46e756fSKirill A. Shutemov }
2424b46e756fSKirill A. Shutemov 
242534d6b470SZach O'Keefe static void khugepaged_do_scan(struct collapse_control *cc)
2426b46e756fSKirill A. Shutemov {
2427b46e756fSKirill A. Shutemov 	unsigned int progress = 0, pass_through_head = 0;
242889dc6a96SYanfei Xu 	unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2429b46e756fSKirill A. Shutemov 	bool wait = true;
243050ad2f24SZach O'Keefe 	int result = SCAN_SUCCEED;
2431b46e756fSKirill A. Shutemov 
2432a980df33SKirill A. Shutemov 	lru_add_drain_all();
2433a980df33SKirill A. Shutemov 
2434c6a7f445SYang Shi 	while (true) {
2435b46e756fSKirill A. Shutemov 		cond_resched();
2436b46e756fSKirill A. Shutemov 
2437b46e756fSKirill A. Shutemov 		if (unlikely(kthread_should_stop() || try_to_freeze()))
2438b46e756fSKirill A. Shutemov 			break;
2439b46e756fSKirill A. Shutemov 
2440b46e756fSKirill A. Shutemov 		spin_lock(&khugepaged_mm_lock);
2441b46e756fSKirill A. Shutemov 		if (!khugepaged_scan.mm_slot)
2442b46e756fSKirill A. Shutemov 			pass_through_head++;
2443b46e756fSKirill A. Shutemov 		if (khugepaged_has_work() &&
2444b46e756fSKirill A. Shutemov 		    pass_through_head < 2)
2445b46e756fSKirill A. Shutemov 			progress += khugepaged_scan_mm_slot(pages - progress,
244650ad2f24SZach O'Keefe 							    &result, cc);
2447b46e756fSKirill A. Shutemov 		else
2448b46e756fSKirill A. Shutemov 			progress = pages;
2449b46e756fSKirill A. Shutemov 		spin_unlock(&khugepaged_mm_lock);
2450b46e756fSKirill A. Shutemov 
2451c6a7f445SYang Shi 		if (progress >= pages)
2452c6a7f445SYang Shi 			break;
2453c6a7f445SYang Shi 
245450ad2f24SZach O'Keefe 		if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2455c6a7f445SYang Shi 			/*
2456c6a7f445SYang Shi 			 * If fail to allocate the first time, try to sleep for
2457c6a7f445SYang Shi 			 * a while.  When hit again, cancel the scan.
2458c6a7f445SYang Shi 			 */
2459c6a7f445SYang Shi 			if (!wait)
2460c6a7f445SYang Shi 				break;
2461c6a7f445SYang Shi 			wait = false;
2462c6a7f445SYang Shi 			khugepaged_alloc_sleep();
2463c6a7f445SYang Shi 		}
2464c6a7f445SYang Shi 	}
2465b46e756fSKirill A. Shutemov }
2466b46e756fSKirill A. Shutemov 
2467b46e756fSKirill A. Shutemov static bool khugepaged_should_wakeup(void)
2468b46e756fSKirill A. Shutemov {
2469b46e756fSKirill A. Shutemov 	return kthread_should_stop() ||
2470b46e756fSKirill A. Shutemov 	       time_after_eq(jiffies, khugepaged_sleep_expire);
2471b46e756fSKirill A. Shutemov }
2472b46e756fSKirill A. Shutemov 
2473b46e756fSKirill A. Shutemov static void khugepaged_wait_work(void)
2474b46e756fSKirill A. Shutemov {
2475b46e756fSKirill A. Shutemov 	if (khugepaged_has_work()) {
2476b46e756fSKirill A. Shutemov 		const unsigned long scan_sleep_jiffies =
2477b46e756fSKirill A. Shutemov 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2478b46e756fSKirill A. Shutemov 
2479b46e756fSKirill A. Shutemov 		if (!scan_sleep_jiffies)
2480b46e756fSKirill A. Shutemov 			return;
2481b46e756fSKirill A. Shutemov 
2482b46e756fSKirill A. Shutemov 		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2483b46e756fSKirill A. Shutemov 		wait_event_freezable_timeout(khugepaged_wait,
2484b46e756fSKirill A. Shutemov 					     khugepaged_should_wakeup(),
2485b46e756fSKirill A. Shutemov 					     scan_sleep_jiffies);
2486b46e756fSKirill A. Shutemov 		return;
2487b46e756fSKirill A. Shutemov 	}
2488b46e756fSKirill A. Shutemov 
24891064026bSYang Shi 	if (hugepage_flags_enabled())
2490b46e756fSKirill A. Shutemov 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2491b46e756fSKirill A. Shutemov }
2492b46e756fSKirill A. Shutemov 
2493b46e756fSKirill A. Shutemov static int khugepaged(void *none)
2494b46e756fSKirill A. Shutemov {
2495b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
2496b46e756fSKirill A. Shutemov 
2497b46e756fSKirill A. Shutemov 	set_freezable();
2498b46e756fSKirill A. Shutemov 	set_user_nice(current, MAX_NICE);
2499b46e756fSKirill A. Shutemov 
2500b46e756fSKirill A. Shutemov 	while (!kthread_should_stop()) {
250134d6b470SZach O'Keefe 		khugepaged_do_scan(&khugepaged_collapse_control);
2502b46e756fSKirill A. Shutemov 		khugepaged_wait_work();
2503b46e756fSKirill A. Shutemov 	}
2504b46e756fSKirill A. Shutemov 
2505b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2506b46e756fSKirill A. Shutemov 	mm_slot = khugepaged_scan.mm_slot;
2507b46e756fSKirill A. Shutemov 	khugepaged_scan.mm_slot = NULL;
2508b46e756fSKirill A. Shutemov 	if (mm_slot)
2509b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2510b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2511b46e756fSKirill A. Shutemov 	return 0;
2512b46e756fSKirill A. Shutemov }
2513b46e756fSKirill A. Shutemov 
2514b46e756fSKirill A. Shutemov static void set_recommended_min_free_kbytes(void)
2515b46e756fSKirill A. Shutemov {
2516b46e756fSKirill A. Shutemov 	struct zone *zone;
2517b46e756fSKirill A. Shutemov 	int nr_zones = 0;
2518b46e756fSKirill A. Shutemov 	unsigned long recommended_min;
2519b46e756fSKirill A. Shutemov 
25201064026bSYang Shi 	if (!hugepage_flags_enabled()) {
2521bd3400eaSLiangcai Fan 		calculate_min_free_kbytes();
2522bd3400eaSLiangcai Fan 		goto update_wmarks;
2523bd3400eaSLiangcai Fan 	}
2524bd3400eaSLiangcai Fan 
2525b7d349c7SJoonsoo Kim 	for_each_populated_zone(zone) {
2526b7d349c7SJoonsoo Kim 		/*
2527b7d349c7SJoonsoo Kim 		 * We don't need to worry about fragmentation of
2528b7d349c7SJoonsoo Kim 		 * ZONE_MOVABLE since it only has movable pages.
2529b7d349c7SJoonsoo Kim 		 */
2530b7d349c7SJoonsoo Kim 		if (zone_idx(zone) > gfp_zone(GFP_USER))
2531b7d349c7SJoonsoo Kim 			continue;
2532b7d349c7SJoonsoo Kim 
2533b46e756fSKirill A. Shutemov 		nr_zones++;
2534b7d349c7SJoonsoo Kim 	}
2535b46e756fSKirill A. Shutemov 
2536b46e756fSKirill A. Shutemov 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2537b46e756fSKirill A. Shutemov 	recommended_min = pageblock_nr_pages * nr_zones * 2;
2538b46e756fSKirill A. Shutemov 
2539b46e756fSKirill A. Shutemov 	/*
2540b46e756fSKirill A. Shutemov 	 * Make sure that on average at least two pageblocks are almost free
2541b46e756fSKirill A. Shutemov 	 * of another type, one for a migratetype to fall back to and a
2542b46e756fSKirill A. Shutemov 	 * second to avoid subsequent fallbacks of other types There are 3
2543b46e756fSKirill A. Shutemov 	 * MIGRATE_TYPES we care about.
2544b46e756fSKirill A. Shutemov 	 */
2545b46e756fSKirill A. Shutemov 	recommended_min += pageblock_nr_pages * nr_zones *
2546b46e756fSKirill A. Shutemov 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2547b46e756fSKirill A. Shutemov 
2548b46e756fSKirill A. Shutemov 	/* don't ever allow to reserve more than 5% of the lowmem */
2549b46e756fSKirill A. Shutemov 	recommended_min = min(recommended_min,
2550b46e756fSKirill A. Shutemov 			      (unsigned long) nr_free_buffer_pages() / 20);
2551b46e756fSKirill A. Shutemov 	recommended_min <<= (PAGE_SHIFT-10);
2552b46e756fSKirill A. Shutemov 
2553b46e756fSKirill A. Shutemov 	if (recommended_min > min_free_kbytes) {
2554b46e756fSKirill A. Shutemov 		if (user_min_free_kbytes >= 0)
2555b46e756fSKirill A. Shutemov 			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2556b46e756fSKirill A. Shutemov 				min_free_kbytes, recommended_min);
2557b46e756fSKirill A. Shutemov 
2558b46e756fSKirill A. Shutemov 		min_free_kbytes = recommended_min;
2559b46e756fSKirill A. Shutemov 	}
2560bd3400eaSLiangcai Fan 
2561bd3400eaSLiangcai Fan update_wmarks:
2562b46e756fSKirill A. Shutemov 	setup_per_zone_wmarks();
2563b46e756fSKirill A. Shutemov }
2564b46e756fSKirill A. Shutemov 
2565b46e756fSKirill A. Shutemov int start_stop_khugepaged(void)
2566b46e756fSKirill A. Shutemov {
2567b46e756fSKirill A. Shutemov 	int err = 0;
2568b46e756fSKirill A. Shutemov 
2569b46e756fSKirill A. Shutemov 	mutex_lock(&khugepaged_mutex);
25701064026bSYang Shi 	if (hugepage_flags_enabled()) {
2571b46e756fSKirill A. Shutemov 		if (!khugepaged_thread)
2572b46e756fSKirill A. Shutemov 			khugepaged_thread = kthread_run(khugepaged, NULL,
2573b46e756fSKirill A. Shutemov 							"khugepaged");
2574b46e756fSKirill A. Shutemov 		if (IS_ERR(khugepaged_thread)) {
2575b46e756fSKirill A. Shutemov 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2576b46e756fSKirill A. Shutemov 			err = PTR_ERR(khugepaged_thread);
2577b46e756fSKirill A. Shutemov 			khugepaged_thread = NULL;
2578b46e756fSKirill A. Shutemov 			goto fail;
2579b46e756fSKirill A. Shutemov 		}
2580b46e756fSKirill A. Shutemov 
2581b46e756fSKirill A. Shutemov 		if (!list_empty(&khugepaged_scan.mm_head))
2582b46e756fSKirill A. Shutemov 			wake_up_interruptible(&khugepaged_wait);
2583b46e756fSKirill A. Shutemov 	} else if (khugepaged_thread) {
2584b46e756fSKirill A. Shutemov 		kthread_stop(khugepaged_thread);
2585b46e756fSKirill A. Shutemov 		khugepaged_thread = NULL;
2586b46e756fSKirill A. Shutemov 	}
2587bd3400eaSLiangcai Fan 	set_recommended_min_free_kbytes();
2588b46e756fSKirill A. Shutemov fail:
2589b46e756fSKirill A. Shutemov 	mutex_unlock(&khugepaged_mutex);
2590b46e756fSKirill A. Shutemov 	return err;
2591b46e756fSKirill A. Shutemov }
25924aab2be0SVijay Balakrishna 
25934aab2be0SVijay Balakrishna void khugepaged_min_free_kbytes_update(void)
25944aab2be0SVijay Balakrishna {
25954aab2be0SVijay Balakrishna 	mutex_lock(&khugepaged_mutex);
25961064026bSYang Shi 	if (hugepage_flags_enabled() && khugepaged_thread)
25974aab2be0SVijay Balakrishna 		set_recommended_min_free_kbytes();
25984aab2be0SVijay Balakrishna 	mutex_unlock(&khugepaged_mutex);
25994aab2be0SVijay Balakrishna }
26007d8faaf1SZach O'Keefe 
260157e9cc50SJohannes Weiner bool current_is_khugepaged(void)
260257e9cc50SJohannes Weiner {
260357e9cc50SJohannes Weiner 	return kthread_func(current) == khugepaged;
260457e9cc50SJohannes Weiner }
260557e9cc50SJohannes Weiner 
26067d8faaf1SZach O'Keefe static int madvise_collapse_errno(enum scan_result r)
26077d8faaf1SZach O'Keefe {
26087d8faaf1SZach O'Keefe 	/*
26097d8faaf1SZach O'Keefe 	 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
26107d8faaf1SZach O'Keefe 	 * actionable feedback to caller, so they may take an appropriate
26117d8faaf1SZach O'Keefe 	 * fallback measure depending on the nature of the failure.
26127d8faaf1SZach O'Keefe 	 */
26137d8faaf1SZach O'Keefe 	switch (r) {
26147d8faaf1SZach O'Keefe 	case SCAN_ALLOC_HUGE_PAGE_FAIL:
26157d8faaf1SZach O'Keefe 		return -ENOMEM;
26167d8faaf1SZach O'Keefe 	case SCAN_CGROUP_CHARGE_FAIL:
26177d8faaf1SZach O'Keefe 		return -EBUSY;
26187d8faaf1SZach O'Keefe 	/* Resource temporary unavailable - trying again might succeed */
26197d8faaf1SZach O'Keefe 	case SCAN_PAGE_LOCK:
26207d8faaf1SZach O'Keefe 	case SCAN_PAGE_LRU:
26210f3e2a2cSZach O'Keefe 	case SCAN_DEL_PAGE_LRU:
26227d8faaf1SZach O'Keefe 		return -EAGAIN;
26237d8faaf1SZach O'Keefe 	/*
26247d8faaf1SZach O'Keefe 	 * Other: Trying again likely not to succeed / error intrinsic to
26257d8faaf1SZach O'Keefe 	 * specified memory range. khugepaged likely won't be able to collapse
26267d8faaf1SZach O'Keefe 	 * either.
26277d8faaf1SZach O'Keefe 	 */
26287d8faaf1SZach O'Keefe 	default:
26297d8faaf1SZach O'Keefe 		return -EINVAL;
26307d8faaf1SZach O'Keefe 	}
26317d8faaf1SZach O'Keefe }
26327d8faaf1SZach O'Keefe 
26337d8faaf1SZach O'Keefe int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
26347d8faaf1SZach O'Keefe 		     unsigned long start, unsigned long end)
26357d8faaf1SZach O'Keefe {
26367d8faaf1SZach O'Keefe 	struct collapse_control *cc;
26377d8faaf1SZach O'Keefe 	struct mm_struct *mm = vma->vm_mm;
26387d8faaf1SZach O'Keefe 	unsigned long hstart, hend, addr;
26397d8faaf1SZach O'Keefe 	int thps = 0, last_fail = SCAN_FAIL;
26407d8faaf1SZach O'Keefe 	bool mmap_locked = true;
26417d8faaf1SZach O'Keefe 
26427d8faaf1SZach O'Keefe 	BUG_ON(vma->vm_start > start);
26437d8faaf1SZach O'Keefe 	BUG_ON(vma->vm_end < end);
26447d8faaf1SZach O'Keefe 
26457d8faaf1SZach O'Keefe 	*prev = vma;
26467d8faaf1SZach O'Keefe 
26477d8faaf1SZach O'Keefe 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
26487d8faaf1SZach O'Keefe 		return -EINVAL;
26497d8faaf1SZach O'Keefe 
26507d8faaf1SZach O'Keefe 	cc = kmalloc(sizeof(*cc), GFP_KERNEL);
26517d8faaf1SZach O'Keefe 	if (!cc)
26527d8faaf1SZach O'Keefe 		return -ENOMEM;
26537d8faaf1SZach O'Keefe 	cc->is_khugepaged = false;
26547d8faaf1SZach O'Keefe 
26557d8faaf1SZach O'Keefe 	mmgrab(mm);
26567d8faaf1SZach O'Keefe 	lru_add_drain_all();
26577d8faaf1SZach O'Keefe 
26587d8faaf1SZach O'Keefe 	hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
26597d8faaf1SZach O'Keefe 	hend = end & HPAGE_PMD_MASK;
26607d8faaf1SZach O'Keefe 
26617d8faaf1SZach O'Keefe 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
26627d8faaf1SZach O'Keefe 		int result = SCAN_FAIL;
26637d8faaf1SZach O'Keefe 
26647d8faaf1SZach O'Keefe 		if (!mmap_locked) {
26657d8faaf1SZach O'Keefe 			cond_resched();
26667d8faaf1SZach O'Keefe 			mmap_read_lock(mm);
26677d8faaf1SZach O'Keefe 			mmap_locked = true;
266834488399SZach O'Keefe 			result = hugepage_vma_revalidate(mm, addr, false, &vma,
266934488399SZach O'Keefe 							 cc);
26707d8faaf1SZach O'Keefe 			if (result  != SCAN_SUCCEED) {
26717d8faaf1SZach O'Keefe 				last_fail = result;
26727d8faaf1SZach O'Keefe 				goto out_nolock;
26737d8faaf1SZach O'Keefe 			}
26744d24de94SYang Shi 
267552dc0310SZach O'Keefe 			hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
26767d8faaf1SZach O'Keefe 		}
26777d8faaf1SZach O'Keefe 		mmap_assert_locked(mm);
26787d8faaf1SZach O'Keefe 		memset(cc->node_load, 0, sizeof(cc->node_load));
2679e031ff96SYang Shi 		nodes_clear(cc->alloc_nmask);
268034488399SZach O'Keefe 		if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
268134488399SZach O'Keefe 			struct file *file = get_file(vma->vm_file);
268234488399SZach O'Keefe 			pgoff_t pgoff = linear_page_index(vma, addr);
268334488399SZach O'Keefe 
268434488399SZach O'Keefe 			mmap_read_unlock(mm);
268534488399SZach O'Keefe 			mmap_locked = false;
268634488399SZach O'Keefe 			result = hpage_collapse_scan_file(mm, addr, file, pgoff,
26877d2c4385SZach O'Keefe 							  cc);
268834488399SZach O'Keefe 			fput(file);
268934488399SZach O'Keefe 		} else {
269034488399SZach O'Keefe 			result = hpage_collapse_scan_pmd(mm, vma, addr,
269134488399SZach O'Keefe 							 &mmap_locked, cc);
269234488399SZach O'Keefe 		}
26937d8faaf1SZach O'Keefe 		if (!mmap_locked)
26947d8faaf1SZach O'Keefe 			*prev = NULL;  /* Tell caller we dropped mmap_lock */
26957d8faaf1SZach O'Keefe 
269634488399SZach O'Keefe handle_result:
26977d8faaf1SZach O'Keefe 		switch (result) {
26987d8faaf1SZach O'Keefe 		case SCAN_SUCCEED:
26997d8faaf1SZach O'Keefe 		case SCAN_PMD_MAPPED:
27007d8faaf1SZach O'Keefe 			++thps;
27017d8faaf1SZach O'Keefe 			break;
270234488399SZach O'Keefe 		case SCAN_PTE_MAPPED_HUGEPAGE:
270334488399SZach O'Keefe 			BUG_ON(mmap_locked);
270434488399SZach O'Keefe 			BUG_ON(*prev);
270534488399SZach O'Keefe 			mmap_write_lock(mm);
270634488399SZach O'Keefe 			result = collapse_pte_mapped_thp(mm, addr, true);
270734488399SZach O'Keefe 			mmap_write_unlock(mm);
270834488399SZach O'Keefe 			goto handle_result;
27097d8faaf1SZach O'Keefe 		/* Whitelisted set of results where continuing OK */
27107d8faaf1SZach O'Keefe 		case SCAN_PMD_NULL:
27117d8faaf1SZach O'Keefe 		case SCAN_PTE_NON_PRESENT:
27127d8faaf1SZach O'Keefe 		case SCAN_PTE_UFFD_WP:
27137d8faaf1SZach O'Keefe 		case SCAN_PAGE_RO:
27147d8faaf1SZach O'Keefe 		case SCAN_LACK_REFERENCED_PAGE:
27157d8faaf1SZach O'Keefe 		case SCAN_PAGE_NULL:
27167d8faaf1SZach O'Keefe 		case SCAN_PAGE_COUNT:
27177d8faaf1SZach O'Keefe 		case SCAN_PAGE_LOCK:
27187d8faaf1SZach O'Keefe 		case SCAN_PAGE_COMPOUND:
27197d8faaf1SZach O'Keefe 		case SCAN_PAGE_LRU:
27200f3e2a2cSZach O'Keefe 		case SCAN_DEL_PAGE_LRU:
27217d8faaf1SZach O'Keefe 			last_fail = result;
27227d8faaf1SZach O'Keefe 			break;
27237d8faaf1SZach O'Keefe 		default:
27247d8faaf1SZach O'Keefe 			last_fail = result;
27257d8faaf1SZach O'Keefe 			/* Other error, exit */
27267d8faaf1SZach O'Keefe 			goto out_maybelock;
27277d8faaf1SZach O'Keefe 		}
27287d8faaf1SZach O'Keefe 	}
27297d8faaf1SZach O'Keefe 
27307d8faaf1SZach O'Keefe out_maybelock:
27317d8faaf1SZach O'Keefe 	/* Caller expects us to hold mmap_lock on return */
27327d8faaf1SZach O'Keefe 	if (!mmap_locked)
27337d8faaf1SZach O'Keefe 		mmap_read_lock(mm);
27347d8faaf1SZach O'Keefe out_nolock:
27357d8faaf1SZach O'Keefe 	mmap_assert_locked(mm);
27367d8faaf1SZach O'Keefe 	mmdrop(mm);
27377d8faaf1SZach O'Keefe 	kfree(cc);
27387d8faaf1SZach O'Keefe 
27397d8faaf1SZach O'Keefe 	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
27407d8faaf1SZach O'Keefe 			: madvise_collapse_errno(last_fail);
27417d8faaf1SZach O'Keefe }
2742