xref: /linux/mm/khugepaged.c (revision 0fc8f6200d2313278fbf4539bbab74677c685531)
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>
7b46e756fSKirill A. Shutemov #include <linux/mmu_notifier.h>
8b46e756fSKirill A. Shutemov #include <linux/rmap.h>
9b46e756fSKirill A. Shutemov #include <linux/swap.h>
10b46e756fSKirill A. Shutemov #include <linux/mm_inline.h>
11b46e756fSKirill A. Shutemov #include <linux/kthread.h>
12b46e756fSKirill A. Shutemov #include <linux/khugepaged.h>
13b46e756fSKirill A. Shutemov #include <linux/freezer.h>
14b46e756fSKirill A. Shutemov #include <linux/mman.h>
15b46e756fSKirill A. Shutemov #include <linux/hashtable.h>
16b46e756fSKirill A. Shutemov #include <linux/userfaultfd_k.h>
17b46e756fSKirill A. Shutemov #include <linux/page_idle.h>
1880110bbfSPasha Tatashin #include <linux/page_table_check.h>
191e2f2d31SKent Overstreet #include <linux/rcupdate_wait.h>
200ac881efSLorenzo Stoakes #include <linux/leafops.h>
21f3f0e1d2SKirill A. Shutemov #include <linux/shmem_fs.h>
2262e72d2cSKairui Song #include <linux/dax.h>
23e2942062Sxu xin #include <linux/ksm.h>
24ad8b2e09SHarry Yoo #include <linux/pgalloc.h>
2539855657SShivank Garg #include <linux/backing-dev.h>
26b46e756fSKirill A. Shutemov 
27b46e756fSKirill A. Shutemov #include <asm/tlb.h>
28b46e756fSKirill A. Shutemov #include "internal.h"
29b26e2701SQi Zheng #include "mm_slot.h"
30b46e756fSKirill A. Shutemov 
31b46e756fSKirill A. Shutemov enum scan_result {
32b46e756fSKirill A. Shutemov 	SCAN_FAIL,
33b46e756fSKirill A. Shutemov 	SCAN_SUCCEED,
349e014077SWei Yang 	SCAN_NO_PTE_TABLE,
3550722804SZach O'Keefe 	SCAN_PMD_MAPPED,
36b46e756fSKirill A. Shutemov 	SCAN_EXCEED_NONE_PTE,
3771a2c112SKirill A. Shutemov 	SCAN_EXCEED_SWAP_PTE,
3871a2c112SKirill A. Shutemov 	SCAN_EXCEED_SHARED_PTE,
39b46e756fSKirill A. Shutemov 	SCAN_PTE_NON_PRESENT,
40e1e267c7SPeter Xu 	SCAN_PTE_UFFD_WP,
4158ac9a89SZach O'Keefe 	SCAN_PTE_MAPPED_HUGEPAGE,
420db501f7SEbru Akagunduz 	SCAN_LACK_REFERENCED_PAGE,
43b46e756fSKirill A. Shutemov 	SCAN_PAGE_NULL,
44b46e756fSKirill A. Shutemov 	SCAN_SCAN_ABORT,
45b46e756fSKirill A. Shutemov 	SCAN_PAGE_COUNT,
46b46e756fSKirill A. Shutemov 	SCAN_PAGE_LRU,
47b46e756fSKirill A. Shutemov 	SCAN_PAGE_LOCK,
48b46e756fSKirill A. Shutemov 	SCAN_PAGE_ANON,
4905620419SVernon Yang 	SCAN_PAGE_LAZYFREE,
50b46e756fSKirill A. Shutemov 	SCAN_PAGE_COMPOUND,
51b46e756fSKirill A. Shutemov 	SCAN_ANY_PROCESS,
52b46e756fSKirill A. Shutemov 	SCAN_VMA_NULL,
53b46e756fSKirill A. Shutemov 	SCAN_VMA_CHECK,
54b46e756fSKirill A. Shutemov 	SCAN_ADDRESS_RANGE,
55b46e756fSKirill A. Shutemov 	SCAN_DEL_PAGE_LRU,
56b46e756fSKirill A. Shutemov 	SCAN_ALLOC_HUGE_PAGE_FAIL,
57b46e756fSKirill A. Shutemov 	SCAN_CGROUP_CHARGE_FAIL,
58f3f0e1d2SKirill A. Shutemov 	SCAN_TRUNCATED,
5999cb0dbdSSong Liu 	SCAN_PAGE_HAS_PRIVATE,
602ce0bdfeSIvan Orlov 	SCAN_STORE_FAILED,
6198c76c9fSJiaqi Yan 	SCAN_COPY_MC,
62ac492b9cSDavid Stevens 	SCAN_PAGE_FILLED,
635173ae0aSShivank Garg 	SCAN_PAGE_DIRTY_OR_WRITEBACK,
64b46e756fSKirill A. Shutemov };
65b46e756fSKirill A. Shutemov 
66b46e756fSKirill A. Shutemov #define CREATE_TRACE_POINTS
67b46e756fSKirill A. Shutemov #include <trace/events/huge_memory.h>
68b46e756fSKirill A. Shutemov 
694aab2be0SVijay Balakrishna static struct task_struct *khugepaged_thread __read_mostly;
704aab2be0SVijay Balakrishna static DEFINE_MUTEX(khugepaged_mutex);
714aab2be0SVijay Balakrishna 
72eeeb79d5SVernon Yang /*
7334c1f77eSVernon Yang  * default scan 8*HPAGE_PMD_NR ptes, pte_mapped_hugepage, pmd_mapped,
7434c1f77eSVernon Yang  * no_pte_table or vmas every 10 second.
75eeeb79d5SVernon Yang  */
76b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_to_scan __read_mostly;
77b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_collapsed;
78b46e756fSKirill A. Shutemov static unsigned int khugepaged_full_scans;
79b46e756fSKirill A. Shutemov static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
80b46e756fSKirill A. Shutemov /* during fragmentation poll the hugepage allocator once every minute */
81b46e756fSKirill A. Shutemov static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
82b46e756fSKirill A. Shutemov static unsigned long khugepaged_sleep_expire;
83b46e756fSKirill A. Shutemov static DEFINE_SPINLOCK(khugepaged_mm_lock);
84b46e756fSKirill A. Shutemov static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
85b46e756fSKirill A. Shutemov /*
86b46e756fSKirill A. Shutemov  * default collapse hugepages if there is at least one pte mapped like
87b46e756fSKirill A. Shutemov  * it would have happened if the vma was large enough during page
88b46e756fSKirill A. Shutemov  * fault.
89d8ea7cc8SZach O'Keefe  *
90d8ea7cc8SZach O'Keefe  * Note that these are only respected if collapse was initiated by khugepaged.
91b46e756fSKirill A. Shutemov  */
9236da8a88SNico Pache #define KHUGEPAGED_MAX_PTES_LIMIT (HPAGE_PMD_NR - 1)
93dafff3f4SUsama Arif unsigned int khugepaged_max_ptes_none __read_mostly;
94b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_swap __read_mostly;
9571a2c112SKirill A. Shutemov static unsigned int khugepaged_max_ptes_shared __read_mostly;
96b46e756fSKirill A. Shutemov 
97b46e756fSKirill A. Shutemov #define MM_SLOTS_HASH_BITS 10
98e1ad3e66SNick Desaulniers static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
99b46e756fSKirill A. Shutemov 
10068279f9cSAlexey Dobriyan static struct kmem_cache *mm_slot_cache __ro_after_init;
101b46e756fSKirill A. Shutemov 
10234d6b470SZach O'Keefe struct collapse_control {
103d8ea7cc8SZach O'Keefe 	bool is_khugepaged;
104d8ea7cc8SZach O'Keefe 
10534d6b470SZach O'Keefe 	/* Num pages scanned per node */
10634d6b470SZach O'Keefe 	u32 node_load[MAX_NUMNODES];
10734d6b470SZach O'Keefe 
10834c1f77eSVernon Yang 	/* Num pages scanned (see khugepaged_pages_to_scan) */
10934c1f77eSVernon Yang 	unsigned int progress;
11034c1f77eSVernon Yang 
111e031ff96SYang Shi 	/* nodemask for allocation fallback */
112e031ff96SYang Shi 	nodemask_t alloc_nmask;
11334d6b470SZach O'Keefe };
11434d6b470SZach O'Keefe 
115b46e756fSKirill A. Shutemov /**
116b46e756fSKirill A. Shutemov  * struct khugepaged_scan - cursor for scanning
117b46e756fSKirill A. Shutemov  * @mm_head: the head of the mm list to scan
118b46e756fSKirill A. Shutemov  * @mm_slot: the current mm_slot we are scanning
119b46e756fSKirill A. Shutemov  * @address: the next address inside that to be scanned
120b46e756fSKirill A. Shutemov  *
121b46e756fSKirill A. Shutemov  * There is only the one khugepaged_scan instance of this cursor structure.
122b46e756fSKirill A. Shutemov  */
123b46e756fSKirill A. Shutemov struct khugepaged_scan {
124b46e756fSKirill A. Shutemov 	struct list_head mm_head;
125b4c9ffb5SWei Yang 	struct mm_slot *mm_slot;
126b46e756fSKirill A. Shutemov 	unsigned long address;
127b46e756fSKirill A. Shutemov };
128b46e756fSKirill A. Shutemov 
129b46e756fSKirill A. Shutemov static struct khugepaged_scan khugepaged_scan = {
130b46e756fSKirill A. Shutemov 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
131b46e756fSKirill A. Shutemov };
132b46e756fSKirill A. Shutemov 
133e1465d12SJérémy Lefaure #ifdef CONFIG_SYSFS
scan_sleep_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)134b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
135b46e756fSKirill A. Shutemov 					 struct kobj_attribute *attr,
136b46e756fSKirill A. Shutemov 					 char *buf)
137b46e756fSKirill A. Shutemov {
138ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
139b46e756fSKirill A. Shutemov }
140b46e756fSKirill A. Shutemov 
__sleep_millisecs_store(const char * buf,size_t count,unsigned int * millisecs)1412da6fe91SLeon Hwang static ssize_t __sleep_millisecs_store(const char *buf, size_t count,
1422da6fe91SLeon Hwang 				       unsigned int *millisecs)
143b46e756fSKirill A. Shutemov {
144dfefd226SAlexey Dobriyan 	unsigned int msecs;
145b46e756fSKirill A. Shutemov 	int err;
146b46e756fSKirill A. Shutemov 
147dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
148dfefd226SAlexey Dobriyan 	if (err)
149b46e756fSKirill A. Shutemov 		return -EINVAL;
150b46e756fSKirill A. Shutemov 
1512da6fe91SLeon Hwang 	*millisecs = msecs;
152b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
153b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
154b46e756fSKirill A. Shutemov 
155b46e756fSKirill A. Shutemov 	return count;
156b46e756fSKirill A. Shutemov }
1572da6fe91SLeon Hwang 
scan_sleep_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)1582da6fe91SLeon Hwang static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
1592da6fe91SLeon Hwang 					  struct kobj_attribute *attr,
1602da6fe91SLeon Hwang 					  const char *buf, size_t count)
1612da6fe91SLeon Hwang {
1622da6fe91SLeon Hwang 	return __sleep_millisecs_store(buf, count, &khugepaged_scan_sleep_millisecs);
1632da6fe91SLeon Hwang }
164b46e756fSKirill A. Shutemov static struct kobj_attribute scan_sleep_millisecs_attr =
1656dcdc94dSMiaohe Lin 	__ATTR_RW(scan_sleep_millisecs);
166b46e756fSKirill A. Shutemov 
alloc_sleep_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)167b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
168b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
169b46e756fSKirill A. Shutemov 					  char *buf)
170b46e756fSKirill A. Shutemov {
171ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
172b46e756fSKirill A. Shutemov }
173b46e756fSKirill A. Shutemov 
alloc_sleep_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)174b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
175b46e756fSKirill A. Shutemov 					   struct kobj_attribute *attr,
176b46e756fSKirill A. Shutemov 					   const char *buf, size_t count)
177b46e756fSKirill A. Shutemov {
1782da6fe91SLeon Hwang 	return __sleep_millisecs_store(buf, count, &khugepaged_alloc_sleep_millisecs);
179b46e756fSKirill A. Shutemov }
180b46e756fSKirill A. Shutemov static struct kobj_attribute alloc_sleep_millisecs_attr =
1816dcdc94dSMiaohe Lin 	__ATTR_RW(alloc_sleep_millisecs);
182b46e756fSKirill A. Shutemov 
pages_to_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)183b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_show(struct kobject *kobj,
184b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
185b46e756fSKirill A. Shutemov 				  char *buf)
186b46e756fSKirill A. Shutemov {
187ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
188b46e756fSKirill A. Shutemov }
pages_to_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)189b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_store(struct kobject *kobj,
190b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
191b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
192b46e756fSKirill A. Shutemov {
193dfefd226SAlexey Dobriyan 	unsigned int pages;
194b46e756fSKirill A. Shutemov 	int err;
195b46e756fSKirill A. Shutemov 
196dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &pages);
197dfefd226SAlexey Dobriyan 	if (err || !pages)
198b46e756fSKirill A. Shutemov 		return -EINVAL;
199b46e756fSKirill A. Shutemov 
200b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = pages;
201b46e756fSKirill A. Shutemov 
202b46e756fSKirill A. Shutemov 	return count;
203b46e756fSKirill A. Shutemov }
204b46e756fSKirill A. Shutemov static struct kobj_attribute pages_to_scan_attr =
2056dcdc94dSMiaohe Lin 	__ATTR_RW(pages_to_scan);
206b46e756fSKirill A. Shutemov 
pages_collapsed_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)207b46e756fSKirill A. Shutemov static ssize_t pages_collapsed_show(struct kobject *kobj,
208b46e756fSKirill A. Shutemov 				    struct kobj_attribute *attr,
209b46e756fSKirill A. Shutemov 				    char *buf)
210b46e756fSKirill A. Shutemov {
211ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
212b46e756fSKirill A. Shutemov }
213b46e756fSKirill A. Shutemov static struct kobj_attribute pages_collapsed_attr =
214b46e756fSKirill A. Shutemov 	__ATTR_RO(pages_collapsed);
215b46e756fSKirill A. Shutemov 
full_scans_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)216b46e756fSKirill A. Shutemov static ssize_t full_scans_show(struct kobject *kobj,
217b46e756fSKirill A. Shutemov 			       struct kobj_attribute *attr,
218b46e756fSKirill A. Shutemov 			       char *buf)
219b46e756fSKirill A. Shutemov {
220ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
221b46e756fSKirill A. Shutemov }
222b46e756fSKirill A. Shutemov static struct kobj_attribute full_scans_attr =
223b46e756fSKirill A. Shutemov 	__ATTR_RO(full_scans);
224b46e756fSKirill A. Shutemov 
defrag_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2256dcdc94dSMiaohe Lin static ssize_t defrag_show(struct kobject *kobj,
226b46e756fSKirill A. Shutemov 			   struct kobj_attribute *attr, char *buf)
227b46e756fSKirill A. Shutemov {
228b46e756fSKirill A. Shutemov 	return single_hugepage_flag_show(kobj, attr, buf,
229b46e756fSKirill A. Shutemov 					 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
230b46e756fSKirill A. Shutemov }
defrag_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2316dcdc94dSMiaohe Lin static ssize_t defrag_store(struct kobject *kobj,
232b46e756fSKirill A. Shutemov 			    struct kobj_attribute *attr,
233b46e756fSKirill A. Shutemov 			    const char *buf, size_t count)
234b46e756fSKirill A. Shutemov {
235b46e756fSKirill A. Shutemov 	return single_hugepage_flag_store(kobj, attr, buf, count,
236b46e756fSKirill A. Shutemov 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
237b46e756fSKirill A. Shutemov }
238b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_defrag_attr =
2396dcdc94dSMiaohe Lin 	__ATTR_RW(defrag);
240b46e756fSKirill A. Shutemov 
241b46e756fSKirill A. Shutemov /*
242b46e756fSKirill A. Shutemov  * max_ptes_none controls if khugepaged should collapse hugepages over
243b46e756fSKirill A. Shutemov  * any unmapped ptes in turn potentially increasing the memory
244b46e756fSKirill A. Shutemov  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
245b46e756fSKirill A. Shutemov  * reduce the available free memory in the system as it
246b46e756fSKirill A. Shutemov  * runs. Increasing max_ptes_none will instead potentially reduce the
247b46e756fSKirill A. Shutemov  * free memory in the system during the khugepaged scan.
248b46e756fSKirill A. Shutemov  */
max_ptes_none_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2496dcdc94dSMiaohe Lin static ssize_t max_ptes_none_show(struct kobject *kobj,
250b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
251b46e756fSKirill A. Shutemov 				  char *buf)
252b46e756fSKirill A. Shutemov {
253ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
254b46e756fSKirill A. Shutemov }
max_ptes_none_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2556dcdc94dSMiaohe Lin static ssize_t max_ptes_none_store(struct kobject *kobj,
256b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
257b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
258b46e756fSKirill A. Shutemov {
259b46e756fSKirill A. Shutemov 	int err;
260b46e756fSKirill A. Shutemov 	unsigned long max_ptes_none;
261b46e756fSKirill A. Shutemov 
262b46e756fSKirill A. Shutemov 	err = kstrtoul(buf, 10, &max_ptes_none);
26336da8a88SNico Pache 	if (err || max_ptes_none > KHUGEPAGED_MAX_PTES_LIMIT)
264b46e756fSKirill A. Shutemov 		return -EINVAL;
265b46e756fSKirill A. Shutemov 
266b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = max_ptes_none;
267b46e756fSKirill A. Shutemov 
268b46e756fSKirill A. Shutemov 	return count;
269b46e756fSKirill A. Shutemov }
270b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_none_attr =
2716dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_none);
272b46e756fSKirill A. Shutemov 
max_ptes_swap_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2736dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_show(struct kobject *kobj,
274b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
275b46e756fSKirill A. Shutemov 				  char *buf)
276b46e756fSKirill A. Shutemov {
277ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
278b46e756fSKirill A. Shutemov }
279b46e756fSKirill A. Shutemov 
max_ptes_swap_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2806dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_store(struct kobject *kobj,
281b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
282b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
283b46e756fSKirill A. Shutemov {
284b46e756fSKirill A. Shutemov 	int err;
285b46e756fSKirill A. Shutemov 	unsigned long max_ptes_swap;
286b46e756fSKirill A. Shutemov 
287b46e756fSKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_swap);
28836da8a88SNico Pache 	if (err || max_ptes_swap > KHUGEPAGED_MAX_PTES_LIMIT)
289b46e756fSKirill A. Shutemov 		return -EINVAL;
290b46e756fSKirill A. Shutemov 
291b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = max_ptes_swap;
292b46e756fSKirill A. Shutemov 
293b46e756fSKirill A. Shutemov 	return count;
294b46e756fSKirill A. Shutemov }
295b46e756fSKirill A. Shutemov 
296b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_swap_attr =
2976dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_swap);
298b46e756fSKirill A. Shutemov 
max_ptes_shared_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2996dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_show(struct kobject *kobj,
30071a2c112SKirill A. Shutemov 				    struct kobj_attribute *attr,
30171a2c112SKirill A. Shutemov 				    char *buf)
30271a2c112SKirill A. Shutemov {
303ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
30471a2c112SKirill A. Shutemov }
30571a2c112SKirill A. Shutemov 
max_ptes_shared_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3066dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_store(struct kobject *kobj,
30771a2c112SKirill A. Shutemov 				     struct kobj_attribute *attr,
30871a2c112SKirill A. Shutemov 				     const char *buf, size_t count)
30971a2c112SKirill A. Shutemov {
31071a2c112SKirill A. Shutemov 	int err;
31171a2c112SKirill A. Shutemov 	unsigned long max_ptes_shared;
31271a2c112SKirill A. Shutemov 
31371a2c112SKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_shared);
31436da8a88SNico Pache 	if (err || max_ptes_shared > KHUGEPAGED_MAX_PTES_LIMIT)
31571a2c112SKirill A. Shutemov 		return -EINVAL;
31671a2c112SKirill A. Shutemov 
31771a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = max_ptes_shared;
31871a2c112SKirill A. Shutemov 
31971a2c112SKirill A. Shutemov 	return count;
32071a2c112SKirill A. Shutemov }
32171a2c112SKirill A. Shutemov 
32271a2c112SKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_shared_attr =
3236dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_shared);
32471a2c112SKirill A. Shutemov 
325b46e756fSKirill A. Shutemov static struct attribute *khugepaged_attr[] = {
326b46e756fSKirill A. Shutemov 	&khugepaged_defrag_attr.attr,
327b46e756fSKirill A. Shutemov 	&khugepaged_max_ptes_none_attr.attr,
32871a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_swap_attr.attr,
32971a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_shared_attr.attr,
330b46e756fSKirill A. Shutemov 	&pages_to_scan_attr.attr,
331b46e756fSKirill A. Shutemov 	&pages_collapsed_attr.attr,
332b46e756fSKirill A. Shutemov 	&full_scans_attr.attr,
333b46e756fSKirill A. Shutemov 	&scan_sleep_millisecs_attr.attr,
334b46e756fSKirill A. Shutemov 	&alloc_sleep_millisecs_attr.attr,
335b46e756fSKirill A. Shutemov 	NULL,
336b46e756fSKirill A. Shutemov };
337b46e756fSKirill A. Shutemov 
338b46e756fSKirill A. Shutemov struct attribute_group khugepaged_attr_group = {
339b46e756fSKirill A. Shutemov 	.attrs = khugepaged_attr,
340b46e756fSKirill A. Shutemov 	.name = "khugepaged",
341b46e756fSKirill A. Shutemov };
342e1465d12SJérémy Lefaure #endif /* CONFIG_SYSFS */
343b46e756fSKirill A. Shutemov 
pte_none_or_zero(pte_t pte)344074f027dSLance Yang static bool pte_none_or_zero(pte_t pte)
345074f027dSLance Yang {
346074f027dSLance Yang 	if (pte_none(pte))
347074f027dSLance Yang 		return true;
348074f027dSLance Yang 	return pte_present(pte) && is_zero_pfn(pte_pfn(pte));
349074f027dSLance Yang }
350074f027dSLance Yang 
hugepage_madvise(struct vm_area_struct * vma,vm_flags_t * vm_flags,int advice)351b46e756fSKirill A. Shutemov int hugepage_madvise(struct vm_area_struct *vma,
352bfbe7110SLorenzo Stoakes 		     vm_flags_t *vm_flags, int advice)
353b46e756fSKirill A. Shutemov {
354b46e756fSKirill A. Shutemov 	switch (advice) {
355b46e756fSKirill A. Shutemov 	case MADV_HUGEPAGE:
356b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_NOHUGEPAGE;
357b46e756fSKirill A. Shutemov 		*vm_flags |= VM_HUGEPAGE;
358b46e756fSKirill A. Shutemov 		/*
359b46e756fSKirill A. Shutemov 		 * If the vma become good for khugepaged to scan,
360b46e756fSKirill A. Shutemov 		 * register it here without waiting a page fault that
361b46e756fSKirill A. Shutemov 		 * may not happen any time soon.
362b46e756fSKirill A. Shutemov 		 */
363c791576cSYang Shi 		khugepaged_enter_vma(vma, *vm_flags);
364b46e756fSKirill A. Shutemov 		break;
365b46e756fSKirill A. Shutemov 	case MADV_NOHUGEPAGE:
366b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_HUGEPAGE;
367b46e756fSKirill A. Shutemov 		*vm_flags |= VM_NOHUGEPAGE;
368b46e756fSKirill A. Shutemov 		/*
369b46e756fSKirill A. Shutemov 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
370b46e756fSKirill A. Shutemov 		 * this vma even if we leave the mm registered in khugepaged if
371b46e756fSKirill A. Shutemov 		 * it got registered before VM_NOHUGEPAGE was set.
372b46e756fSKirill A. Shutemov 		 */
373b46e756fSKirill A. Shutemov 		break;
374b46e756fSKirill A. Shutemov 	}
375b46e756fSKirill A. Shutemov 
376b46e756fSKirill A. Shutemov 	return 0;
377b46e756fSKirill A. Shutemov }
378b46e756fSKirill A. Shutemov 
khugepaged_init(void)379b46e756fSKirill A. Shutemov int __init khugepaged_init(void)
380b46e756fSKirill A. Shutemov {
381c14bdcc9SWei Yang 	mm_slot_cache = KMEM_CACHE(mm_slot, 0);
382b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)
383b46e756fSKirill A. Shutemov 		return -ENOMEM;
384b46e756fSKirill A. Shutemov 
385b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
38636da8a88SNico Pache 	khugepaged_max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;
387b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
38871a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
389b46e756fSKirill A. Shutemov 
390b46e756fSKirill A. Shutemov 	return 0;
391b46e756fSKirill A. Shutemov }
392b46e756fSKirill A. Shutemov 
khugepaged_destroy(void)393b46e756fSKirill A. Shutemov void __init khugepaged_destroy(void)
394b46e756fSKirill A. Shutemov {
395b46e756fSKirill A. Shutemov 	kmem_cache_destroy(mm_slot_cache);
396b46e756fSKirill A. Shutemov }
397b46e756fSKirill A. Shutemov 
collapse_test_exit(struct mm_struct * mm)398ff7e03a8SNico Pache static inline int collapse_test_exit(struct mm_struct *mm)
399b46e756fSKirill A. Shutemov {
4004d45e75aSJann Horn 	return atomic_read(&mm->mm_users) == 0;
401b46e756fSKirill A. Shutemov }
402b46e756fSKirill A. Shutemov 
collapse_test_exit_or_disable(struct mm_struct * mm)403ff7e03a8SNico Pache static inline int collapse_test_exit_or_disable(struct mm_struct *mm)
404879c6000SLance Yang {
405ff7e03a8SNico Pache 	return collapse_test_exit(mm) ||
4069dc21bbdSDavid Hildenbrand 		mm_flags_test(MMF_DISABLE_THP_COMPLETELY, mm);
407879c6000SLance Yang }
408879c6000SLance Yang 
hugepage_pmd_enabled(void)40900f58104SRyan Roberts static bool hugepage_pmd_enabled(void)
41000f58104SRyan Roberts {
41100f58104SRyan Roberts 	/*
412d2d243dfSBaolin Wang 	 * We cover the anon, shmem and the file-backed case here; file-backed
41300f58104SRyan Roberts 	 * hugepages, when configured in, are determined by the global control.
41400f58104SRyan Roberts 	 * Anon pmd-sized hugepages are determined by the pmd-size control.
415d2d243dfSBaolin Wang 	 * Shmem pmd-sized hugepages are also determined by its pmd-size control,
416d2d243dfSBaolin Wang 	 * except when the global shmem_huge is set to SHMEM_HUGE_DENY.
41700f58104SRyan Roberts 	 */
41800f58104SRyan Roberts 	if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
41900f58104SRyan Roberts 	    hugepage_global_enabled())
42000f58104SRyan Roberts 		return true;
42100f58104SRyan Roberts 	if (test_bit(PMD_ORDER, &huge_anon_orders_always))
42200f58104SRyan Roberts 		return true;
42300f58104SRyan Roberts 	if (test_bit(PMD_ORDER, &huge_anon_orders_madvise))
42400f58104SRyan Roberts 		return true;
42500f58104SRyan Roberts 	if (test_bit(PMD_ORDER, &huge_anon_orders_inherit) &&
42600f58104SRyan Roberts 	    hugepage_global_enabled())
42700f58104SRyan Roberts 		return true;
428d2d243dfSBaolin Wang 	if (IS_ENABLED(CONFIG_SHMEM) && shmem_hpage_pmd_enabled())
429d2d243dfSBaolin Wang 		return true;
43000f58104SRyan Roberts 	return false;
43100f58104SRyan Roberts }
43200f58104SRyan Roberts 
__khugepaged_enter(struct mm_struct * mm)433d2081b2bSYang Shi void __khugepaged_enter(struct mm_struct *mm)
434b46e756fSKirill A. Shutemov {
435b26e2701SQi Zheng 	struct mm_slot *slot;
436b46e756fSKirill A. Shutemov 	int wakeup;
437b46e756fSKirill A. Shutemov 
43816618670SXin Hao 	/* __khugepaged_exit() must not run from under us */
439ff7e03a8SNico Pache 	VM_BUG_ON_MM(collapse_test_exit(mm), mm);
44012e423baSLorenzo Stoakes 	if (unlikely(mm_flags_test_and_set(MMF_VM_HUGEPAGE, mm)))
44116618670SXin Hao 		return;
44216618670SXin Hao 
443b4c9ffb5SWei Yang 	slot = mm_slot_alloc(mm_slot_cache);
444b4c9ffb5SWei Yang 	if (!slot)
445d2081b2bSYang Shi 		return;
446b46e756fSKirill A. Shutemov 
447b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
448b26e2701SQi Zheng 	mm_slot_insert(mm_slots_hash, mm, slot);
449b46e756fSKirill A. Shutemov 	/*
450b46e756fSKirill A. Shutemov 	 * Insert just behind the scanning cursor, to let the area settle
451b46e756fSKirill A. Shutemov 	 * down a little.
452b46e756fSKirill A. Shutemov 	 */
453b46e756fSKirill A. Shutemov 	wakeup = list_empty(&khugepaged_scan.mm_head);
454b26e2701SQi Zheng 	list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
455b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
456b46e756fSKirill A. Shutemov 
457f1f10076SVegard Nossum 	mmgrab(mm);
458b46e756fSKirill A. Shutemov 	if (wakeup)
459b46e756fSKirill A. Shutemov 		wake_up_interruptible(&khugepaged_wait);
460b46e756fSKirill A. Shutemov }
461b46e756fSKirill A. Shutemov 
khugepaged_enter_vma(struct vm_area_struct * vma,vm_flags_t vm_flags)462c791576cSYang Shi void khugepaged_enter_vma(struct vm_area_struct *vma,
463bfbe7110SLorenzo Stoakes 			  vm_flags_t vm_flags)
464b46e756fSKirill A. Shutemov {
46512e423baSLorenzo Stoakes 	if (!mm_flags_test(MMF_VM_HUGEPAGE, vma->vm_mm) &&
46600f58104SRyan Roberts 	    hugepage_pmd_enabled()) {
4671f1c0610SDavid Hildenbrand 		if (thp_vma_allowable_order(vma, vm_flags, TVA_KHUGEPAGED, PMD_ORDER))
4682647d11bSYang Shi 			__khugepaged_enter(vma->vm_mm);
4692647d11bSYang Shi 	}
470b46e756fSKirill A. Shutemov }
471b46e756fSKirill A. Shutemov 
__khugepaged_exit(struct mm_struct * mm)472b46e756fSKirill A. Shutemov void __khugepaged_exit(struct mm_struct *mm)
473b46e756fSKirill A. Shutemov {
474b26e2701SQi Zheng 	struct mm_slot *slot;
475b46e756fSKirill A. Shutemov 	int free = 0;
476b46e756fSKirill A. Shutemov 
477b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
478b26e2701SQi Zheng 	slot = mm_slot_lookup(mm_slots_hash, mm);
479b4c9ffb5SWei Yang 	if (slot && khugepaged_scan.mm_slot != slot) {
480b26e2701SQi Zheng 		hash_del(&slot->hash);
481b26e2701SQi Zheng 		list_del(&slot->mm_node);
482b46e756fSKirill A. Shutemov 		free = 1;
483b46e756fSKirill A. Shutemov 	}
484b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
485b46e756fSKirill A. Shutemov 
486b46e756fSKirill A. Shutemov 	if (free) {
48712e423baSLorenzo Stoakes 		mm_flags_clear(MMF_VM_HUGEPAGE, mm);
488b4c9ffb5SWei Yang 		mm_slot_free(mm_slot_cache, slot);
489b46e756fSKirill A. Shutemov 		mmdrop(mm);
490b4c9ffb5SWei Yang 	} else if (slot) {
491b46e756fSKirill A. Shutemov 		/*
492b46e756fSKirill A. Shutemov 		 * This is required to serialize against
493ff7e03a8SNico Pache 		 * collapse_test_exit() (which is guaranteed to run
4947d2c4385SZach O'Keefe 		 * under mmap sem read mode). Stop here (after we return all
4957d2c4385SZach O'Keefe 		 * pagetables will be destroyed) until khugepaged has finished
4967d2c4385SZach O'Keefe 		 * working on the pagetables under the mmap_lock.
497b46e756fSKirill A. Shutemov 		 */
498d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
499d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
500b46e756fSKirill A. Shutemov 	}
501b46e756fSKirill A. Shutemov }
502b46e756fSKirill A. Shutemov 
release_pte_folio(struct folio * folio)50392644f58SVishal Moola (Oracle) static void release_pte_folio(struct folio *folio)
50492644f58SVishal Moola (Oracle) {
50592644f58SVishal Moola (Oracle) 	node_stat_mod_folio(folio,
50692644f58SVishal Moola (Oracle) 			NR_ISOLATED_ANON + folio_is_file_lru(folio),
50792644f58SVishal Moola (Oracle) 			-folio_nr_pages(folio));
50892644f58SVishal Moola (Oracle) 	folio_unlock(folio);
50992644f58SVishal Moola (Oracle) 	folio_putback_lru(folio);
51092644f58SVishal Moola (Oracle) }
51192644f58SVishal Moola (Oracle) 
release_pte_pages(pte_t * pte,pte_t * _pte,struct list_head * compound_pagelist)5125503fbf2SKirill A. Shutemov static void release_pte_pages(pte_t *pte, pte_t *_pte,
5135503fbf2SKirill A. Shutemov 		struct list_head *compound_pagelist)
514b46e756fSKirill A. Shutemov {
5159bdfeea4SVishal Moola (Oracle) 	struct folio *folio, *tmp;
5165503fbf2SKirill A. Shutemov 
517b46e756fSKirill A. Shutemov 	while (--_pte >= pte) {
518c33c7948SRyan Roberts 		pte_t pteval = ptep_get(_pte);
519f528260bSVishal Moola (Oracle) 		unsigned long pfn;
5205503fbf2SKirill A. Shutemov 
521f528260bSVishal Moola (Oracle) 		if (pte_none(pteval))
522f528260bSVishal Moola (Oracle) 			continue;
523074f027dSLance Yang 		VM_WARN_ON_ONCE(!pte_present(pteval));
524f528260bSVishal Moola (Oracle) 		pfn = pte_pfn(pteval);
525f528260bSVishal Moola (Oracle) 		if (is_zero_pfn(pfn))
526f528260bSVishal Moola (Oracle) 			continue;
527f528260bSVishal Moola (Oracle) 		folio = pfn_folio(pfn);
528f528260bSVishal Moola (Oracle) 		if (folio_test_large(folio))
529f528260bSVishal Moola (Oracle) 			continue;
5309bdfeea4SVishal Moola (Oracle) 		release_pte_folio(folio);
5315503fbf2SKirill A. Shutemov 	}
5325503fbf2SKirill A. Shutemov 
5339bdfeea4SVishal Moola (Oracle) 	list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
5349bdfeea4SVishal Moola (Oracle) 		list_del(&folio->lru);
5359bdfeea4SVishal Moola (Oracle) 		release_pte_folio(folio);
536b46e756fSKirill A. Shutemov 	}
537b46e756fSKirill A. Shutemov }
538b46e756fSKirill A. Shutemov 
__collapse_huge_page_isolate(struct vm_area_struct * vma,unsigned long start_addr,pte_t * pte,struct collapse_control * cc,struct list_head * compound_pagelist)53940bd4ff0SShivank Garg static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,
54040bd4ff0SShivank Garg 		unsigned long start_addr, pte_t *pte, struct collapse_control *cc,
5415503fbf2SKirill A. Shutemov 		struct list_head *compound_pagelist)
542b46e756fSKirill A. Shutemov {
543b46e756fSKirill A. Shutemov 	struct page *page = NULL;
5448dd1e896SVishal Moola (Oracle) 	struct folio *folio = NULL;
5451acc3693SWei Yang 	unsigned long addr = start_addr;
546b46e756fSKirill A. Shutemov 	pte_t *_pte;
54740bd4ff0SShivank Garg 	int none_or_zero = 0, shared = 0, referenced = 0;
54840bd4ff0SShivank Garg 	enum scan_result result = SCAN_FAIL;
549b46e756fSKirill A. Shutemov 
550b46e756fSKirill A. Shutemov 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
5511acc3693SWei Yang 	     _pte++, addr += PAGE_SIZE) {
552c33c7948SRyan Roberts 		pte_t pteval = ptep_get(_pte);
553074f027dSLance Yang 		if (pte_none_or_zero(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 		}
569dd47ac42SPeter Xu 		if (pte_uffd_wp(pteval)) {
570dd47ac42SPeter Xu 			result = SCAN_PTE_UFFD_WP;
571dd47ac42SPeter Xu 			goto out;
572dd47ac42SPeter Xu 		}
5731acc3693SWei Yang 		page = vm_normal_page(vma, addr, pteval);
5743218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
575b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
576b46e756fSKirill A. Shutemov 			goto out;
577b46e756fSKirill A. Shutemov 		}
578b46e756fSKirill A. Shutemov 
5798dd1e896SVishal Moola (Oracle) 		folio = page_folio(page);
5808dd1e896SVishal Moola (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_anon(folio), folio);
581b46e756fSKirill A. Shutemov 
58205620419SVernon Yang 		/*
58305620419SVernon Yang 		 * If the vma has the VM_DROPPABLE flag, the collapse will
58405620419SVernon Yang 		 * preserve the lazyfree property without needing to skip.
58505620419SVernon Yang 		 */
58605620419SVernon Yang 		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
58705620419SVernon Yang 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
58805620419SVernon Yang 			result = SCAN_PAGE_LAZYFREE;
58905620419SVernon Yang 			goto out;
59005620419SVernon Yang 		}
59105620419SVernon Yang 
592ff7e03a8SNico Pache 		/* See collapse_scan_pmd(). */
593003fde44SDavid Hildenbrand 		if (folio_maybe_mapped_shared(folio)) {
594d8ea7cc8SZach O'Keefe 			++shared;
595d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
596d8ea7cc8SZach O'Keefe 			    shared > khugepaged_max_ptes_shared) {
59771a2c112SKirill A. Shutemov 				result = SCAN_EXCEED_SHARED_PTE;
598e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
59971a2c112SKirill A. Shutemov 				goto out;
60071a2c112SKirill A. Shutemov 			}
601d8ea7cc8SZach O'Keefe 		}
60271a2c112SKirill A. Shutemov 
6038dd1e896SVishal Moola (Oracle) 		if (folio_test_large(folio)) {
6048dd1e896SVishal Moola (Oracle) 			struct folio *f;
6055503fbf2SKirill A. Shutemov 
6065503fbf2SKirill A. Shutemov 			/*
6075503fbf2SKirill A. Shutemov 			 * Check if we have dealt with the compound page
6085503fbf2SKirill A. Shutemov 			 * already
6095503fbf2SKirill A. Shutemov 			 */
6108dd1e896SVishal Moola (Oracle) 			list_for_each_entry(f, compound_pagelist, lru) {
6118dd1e896SVishal Moola (Oracle) 				if (folio == f)
6125503fbf2SKirill A. Shutemov 					goto next;
6135503fbf2SKirill A. Shutemov 			}
6145503fbf2SKirill A. Shutemov 		}
6155503fbf2SKirill A. Shutemov 
616b46e756fSKirill A. Shutemov 		/*
617775d28fdSKefeng Wang 		 * We can do it before folio_isolate_lru because the
618775d28fdSKefeng Wang 		 * folio can't be freed from under us. NOTE: PG_lock
619b46e756fSKirill A. Shutemov 		 * is needed to serialize against split_huge_page
620b46e756fSKirill A. Shutemov 		 * when invoked from the VM.
621b46e756fSKirill A. Shutemov 		 */
6228dd1e896SVishal Moola (Oracle) 		if (!folio_trylock(folio)) {
623b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
624b46e756fSKirill A. Shutemov 			goto out;
625b46e756fSKirill A. Shutemov 		}
626b46e756fSKirill A. Shutemov 
627b46e756fSKirill A. Shutemov 		/*
6289445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
6299445689fSKirill A. Shutemov 		 *
6309445689fSKirill A. Shutemov 		 * The page table that maps the page has been already unlinked
6319445689fSKirill A. Shutemov 		 * from the page table tree and this process cannot get
632f0953a1bSIngo Molnar 		 * an additional pin on the page.
6339445689fSKirill A. Shutemov 		 *
6349445689fSKirill A. Shutemov 		 * New pins can come later if the page is shared across fork,
6359445689fSKirill A. Shutemov 		 * but not from this process. The other process cannot write to
6369445689fSKirill A. Shutemov 		 * the page, only trigger CoW.
637b46e756fSKirill A. Shutemov 		 */
6380b43b8bcSShivank Garg 		if (folio_expected_ref_count(folio) != folio_ref_count(folio)) {
6398dd1e896SVishal Moola (Oracle) 			folio_unlock(folio);
640b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
641b46e756fSKirill A. Shutemov 			goto out;
642b46e756fSKirill A. Shutemov 		}
643b46e756fSKirill A. Shutemov 
644b46e756fSKirill A. Shutemov 		/*
645b46e756fSKirill A. Shutemov 		 * Isolate the page to avoid collapsing an hugepage
646b46e756fSKirill A. Shutemov 		 * currently in use by the VM.
647b46e756fSKirill A. Shutemov 		 */
6488dd1e896SVishal Moola (Oracle) 		if (!folio_isolate_lru(folio)) {
6498dd1e896SVishal Moola (Oracle) 			folio_unlock(folio);
650b46e756fSKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
651b46e756fSKirill A. Shutemov 			goto out;
652b46e756fSKirill A. Shutemov 		}
6538dd1e896SVishal Moola (Oracle) 		node_stat_mod_folio(folio,
6548dd1e896SVishal Moola (Oracle) 				NR_ISOLATED_ANON + folio_is_file_lru(folio),
6558dd1e896SVishal Moola (Oracle) 				folio_nr_pages(folio));
6568dd1e896SVishal Moola (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
6578dd1e896SVishal Moola (Oracle) 		VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
658b46e756fSKirill A. Shutemov 
6598dd1e896SVishal Moola (Oracle) 		if (folio_test_large(folio))
6608dd1e896SVishal Moola (Oracle) 			list_add_tail(&folio->lru, compound_pagelist);
6615503fbf2SKirill A. Shutemov next:
662d8ea7cc8SZach O'Keefe 		/*
663d8ea7cc8SZach O'Keefe 		 * If collapse was initiated by khugepaged, check that there is
664d8ea7cc8SZach O'Keefe 		 * enough young pte to justify collapsing the page
665d8ea7cc8SZach O'Keefe 		 */
666d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
6678dd1e896SVishal Moola (Oracle) 		    (pte_young(pteval) || folio_test_young(folio) ||
6681acc3693SWei Yang 		     folio_test_referenced(folio) ||
6691acc3693SWei Yang 		     mmu_notifier_test_young(vma->vm_mm, addr)))
6700db501f7SEbru Akagunduz 			referenced++;
671b46e756fSKirill A. Shutemov 	}
67274e579bfSMiaohe Lin 
67362b98015SDev Jain 	if (unlikely(cc->is_khugepaged && !referenced)) {
67474e579bfSMiaohe Lin 		result = SCAN_LACK_REFERENCED_PAGE;
67574e579bfSMiaohe Lin 	} else {
676b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
67750dbe531SFan Ni 		trace_mm_collapse_huge_page_isolate(folio, none_or_zero,
678473b7322SDev Jain 						    referenced, result);
67950ad2f24SZach O'Keefe 		return result;
680b46e756fSKirill A. Shutemov 	}
681b46e756fSKirill A. Shutemov out:
6825503fbf2SKirill A. Shutemov 	release_pte_pages(pte, _pte, compound_pagelist);
68350dbe531SFan Ni 	trace_mm_collapse_huge_page_isolate(folio, none_or_zero,
684473b7322SDev Jain 					    referenced, result);
68550ad2f24SZach O'Keefe 	return result;
686b46e756fSKirill A. Shutemov }
687b46e756fSKirill A. Shutemov 
__collapse_huge_page_copy_succeeded(pte_t * pte,struct vm_area_struct * vma,unsigned long address,spinlock_t * ptl,struct list_head * compound_pagelist)68898c76c9fSJiaqi Yan static void __collapse_huge_page_copy_succeeded(pte_t *pte,
689b46e756fSKirill A. Shutemov 						struct vm_area_struct *vma,
690b46e756fSKirill A. Shutemov 						unsigned long address,
6915503fbf2SKirill A. Shutemov 						spinlock_t *ptl,
6925503fbf2SKirill A. Shutemov 						struct list_head *compound_pagelist)
693b46e756fSKirill A. Shutemov {
6944ea3594aSDev Jain 	unsigned long end = address + HPAGE_PMD_SIZE;
695d4111eecSMatthew Wilcox (Oracle) 	struct folio *src, *tmp;
69698c76c9fSJiaqi Yan 	pte_t pteval;
6974ea3594aSDev Jain 	pte_t *_pte;
6984ea3594aSDev Jain 	unsigned int nr_ptes;
699b46e756fSKirill A. Shutemov 
7004ea3594aSDev Jain 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR; _pte += nr_ptes,
7014ea3594aSDev Jain 	     address += nr_ptes * PAGE_SIZE) {
7024ea3594aSDev Jain 		nr_ptes = 1;
703c33c7948SRyan Roberts 		pteval = ptep_get(_pte);
704074f027dSLance Yang 		if (pte_none_or_zero(pteval)) {
705b46e756fSKirill A. Shutemov 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
706074f027dSLance Yang 			if (pte_none(pteval))
707074f027dSLance Yang 				continue;
708b46e756fSKirill A. Shutemov 			/*
709b46e756fSKirill A. Shutemov 			 * ptl mostly unnecessary.
710b46e756fSKirill A. Shutemov 			 */
711b46e756fSKirill A. Shutemov 			spin_lock(ptl);
71208d5b29eSPasha Tatashin 			ptep_clear(vma->vm_mm, address, _pte);
713b46e756fSKirill A. Shutemov 			spin_unlock(ptl);
7146080d19fSxu xin 			ksm_might_unmap_zero_page(vma->vm_mm, pteval);
715b46e756fSKirill A. Shutemov 		} else {
716d4111eecSMatthew Wilcox (Oracle) 			struct page *src_page = pte_page(pteval);
717d4111eecSMatthew Wilcox (Oracle) 
718d4111eecSMatthew Wilcox (Oracle) 			src = page_folio(src_page);
7194ea3594aSDev Jain 
7204ea3594aSDev Jain 			if (folio_test_large(src)) {
7214ea3594aSDev Jain 				unsigned int max_nr_ptes = (end - address) >> PAGE_SHIFT;
7224ea3594aSDev Jain 
7234ea3594aSDev Jain 				nr_ptes = folio_pte_batch(src, _pte, pteval, max_nr_ptes);
7244ea3594aSDev Jain 			} else {
725d4111eecSMatthew Wilcox (Oracle) 				release_pte_folio(src);
7264ea3594aSDev Jain 			}
7274ea3594aSDev Jain 
728b46e756fSKirill A. Shutemov 			/*
729b46e756fSKirill A. Shutemov 			 * ptl mostly unnecessary, but preempt has to
730b46e756fSKirill A. Shutemov 			 * be disabled to update the per-cpu stats
73135668a43SDavid Hildenbrand 			 * inside folio_remove_rmap_pte().
732b46e756fSKirill A. Shutemov 			 */
733b46e756fSKirill A. Shutemov 			spin_lock(ptl);
7344ea3594aSDev Jain 			clear_ptes(vma->vm_mm, address, _pte, nr_ptes);
7354ea3594aSDev Jain 			folio_remove_rmap_ptes(src, src_page, nr_ptes, vma);
736b46e756fSKirill A. Shutemov 			spin_unlock(ptl);
7374ea3594aSDev Jain 			free_swap_cache(src);
7384ea3594aSDev Jain 			folio_put_refs(src, nr_ptes);
739b46e756fSKirill A. Shutemov 		}
740b46e756fSKirill A. Shutemov 	}
7415503fbf2SKirill A. Shutemov 
742d4111eecSMatthew Wilcox (Oracle) 	list_for_each_entry_safe(src, tmp, compound_pagelist, lru) {
743d4111eecSMatthew Wilcox (Oracle) 		list_del(&src->lru);
744d4111eecSMatthew Wilcox (Oracle) 		node_stat_sub_folio(src, NR_ISOLATED_ANON +
745d4111eecSMatthew Wilcox (Oracle) 				folio_is_file_lru(src));
746d4111eecSMatthew Wilcox (Oracle) 		folio_unlock(src);
74763b77499SMatthew Wilcox (Oracle) 		free_swap_cache(src);
748d4111eecSMatthew Wilcox (Oracle) 		folio_putback_lru(src);
7495503fbf2SKirill A. Shutemov 	}
750b46e756fSKirill A. Shutemov }
751b46e756fSKirill A. Shutemov 
__collapse_huge_page_copy_failed(pte_t * pte,pmd_t * pmd,pmd_t orig_pmd,struct vm_area_struct * vma,struct list_head * compound_pagelist)75298c76c9fSJiaqi Yan static void __collapse_huge_page_copy_failed(pte_t *pte,
75398c76c9fSJiaqi Yan 					     pmd_t *pmd,
75498c76c9fSJiaqi Yan 					     pmd_t orig_pmd,
75598c76c9fSJiaqi Yan 					     struct vm_area_struct *vma,
75698c76c9fSJiaqi Yan 					     struct list_head *compound_pagelist)
75798c76c9fSJiaqi Yan {
75898c76c9fSJiaqi Yan 	spinlock_t *pmd_ptl;
75998c76c9fSJiaqi Yan 
76098c76c9fSJiaqi Yan 	/*
76198c76c9fSJiaqi Yan 	 * Re-establish the PMD to point to the original page table
76298c76c9fSJiaqi Yan 	 * entry. Restoring PMD needs to be done prior to releasing
76398c76c9fSJiaqi Yan 	 * pages. Since pages are still isolated and locked here,
76498c76c9fSJiaqi Yan 	 * acquiring anon_vma_lock_write is unnecessary.
76598c76c9fSJiaqi Yan 	 */
76698c76c9fSJiaqi Yan 	pmd_ptl = pmd_lock(vma->vm_mm, pmd);
76798c76c9fSJiaqi Yan 	pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd));
76898c76c9fSJiaqi Yan 	spin_unlock(pmd_ptl);
76998c76c9fSJiaqi Yan 	/*
77098c76c9fSJiaqi Yan 	 * Release both raw and compound pages isolated
77198c76c9fSJiaqi Yan 	 * in __collapse_huge_page_isolate.
77298c76c9fSJiaqi Yan 	 */
77398c76c9fSJiaqi Yan 	release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist);
77498c76c9fSJiaqi Yan }
77598c76c9fSJiaqi Yan 
77698c76c9fSJiaqi Yan /*
77798c76c9fSJiaqi Yan  * __collapse_huge_page_copy - attempts to copy memory contents from raw
77898c76c9fSJiaqi Yan  * pages to a hugepage. Cleans up the raw pages if copying succeeds;
77998c76c9fSJiaqi Yan  * otherwise restores the original page table and releases isolated raw pages.
78098c76c9fSJiaqi Yan  * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC.
78198c76c9fSJiaqi Yan  *
78298c76c9fSJiaqi Yan  * @pte: starting of the PTEs to copy from
7838eca68e2SMatthew Wilcox (Oracle)  * @folio: the new hugepage to copy contents to
78498c76c9fSJiaqi Yan  * @pmd: pointer to the new hugepage's PMD
78598c76c9fSJiaqi Yan  * @orig_pmd: the original raw pages' PMD
78698c76c9fSJiaqi Yan  * @vma: the original raw pages' virtual memory area
78798c76c9fSJiaqi Yan  * @address: starting address to copy
78898c76c9fSJiaqi Yan  * @ptl: lock on raw pages' PTEs
78998c76c9fSJiaqi Yan  * @compound_pagelist: list that stores compound pages
79098c76c9fSJiaqi Yan  */
__collapse_huge_page_copy(pte_t * pte,struct folio * folio,pmd_t * pmd,pmd_t orig_pmd,struct vm_area_struct * vma,unsigned long address,spinlock_t * ptl,struct list_head * compound_pagelist)79140bd4ff0SShivank Garg static enum scan_result __collapse_huge_page_copy(pte_t *pte, struct folio *folio,
7928eca68e2SMatthew Wilcox (Oracle) 		pmd_t *pmd, pmd_t orig_pmd, struct vm_area_struct *vma,
7938eca68e2SMatthew Wilcox (Oracle) 		unsigned long address, spinlock_t *ptl,
79498c76c9fSJiaqi Yan 		struct list_head *compound_pagelist)
79598c76c9fSJiaqi Yan {
7968eca68e2SMatthew Wilcox (Oracle) 	unsigned int i;
79740bd4ff0SShivank Garg 	enum scan_result result = SCAN_SUCCEED;
79898c76c9fSJiaqi Yan 
79998c76c9fSJiaqi Yan 	/*
80098c76c9fSJiaqi Yan 	 * Copying pages' contents is subject to memory poison at any iteration.
80198c76c9fSJiaqi Yan 	 */
8028eca68e2SMatthew Wilcox (Oracle) 	for (i = 0; i < HPAGE_PMD_NR; i++) {
8038eca68e2SMatthew Wilcox (Oracle) 		pte_t pteval = ptep_get(pte + i);
8048eca68e2SMatthew Wilcox (Oracle) 		struct page *page = folio_page(folio, i);
8058eca68e2SMatthew Wilcox (Oracle) 		unsigned long src_addr = address + i * PAGE_SIZE;
8068eca68e2SMatthew Wilcox (Oracle) 		struct page *src_page;
8078eca68e2SMatthew Wilcox (Oracle) 
808074f027dSLance Yang 		if (pte_none_or_zero(pteval)) {
8098eca68e2SMatthew Wilcox (Oracle) 			clear_user_highpage(page, src_addr);
81098c76c9fSJiaqi Yan 			continue;
81198c76c9fSJiaqi Yan 		}
81298c76c9fSJiaqi Yan 		src_page = pte_page(pteval);
8138eca68e2SMatthew Wilcox (Oracle) 		if (copy_mc_user_highpage(page, src_page, src_addr, vma) > 0) {
81498c76c9fSJiaqi Yan 			result = SCAN_COPY_MC;
81598c76c9fSJiaqi Yan 			break;
81698c76c9fSJiaqi Yan 		}
81798c76c9fSJiaqi Yan 	}
81898c76c9fSJiaqi Yan 
81998c76c9fSJiaqi Yan 	if (likely(result == SCAN_SUCCEED))
82098c76c9fSJiaqi Yan 		__collapse_huge_page_copy_succeeded(pte, vma, address, ptl,
82198c76c9fSJiaqi Yan 						    compound_pagelist);
82298c76c9fSJiaqi Yan 	else
82398c76c9fSJiaqi Yan 		__collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma,
82498c76c9fSJiaqi Yan 						 compound_pagelist);
82598c76c9fSJiaqi Yan 
82698c76c9fSJiaqi Yan 	return result;
82798c76c9fSJiaqi Yan }
82898c76c9fSJiaqi Yan 
khugepaged_alloc_sleep(void)829b46e756fSKirill A. Shutemov static void khugepaged_alloc_sleep(void)
830b46e756fSKirill A. Shutemov {
831b46e756fSKirill A. Shutemov 	DEFINE_WAIT(wait);
832b46e756fSKirill A. Shutemov 
833b46e756fSKirill A. Shutemov 	add_wait_queue(&khugepaged_wait, &wait);
834f5d39b02SPeter Zijlstra 	__set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
835f5d39b02SPeter Zijlstra 	schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
836b46e756fSKirill A. Shutemov 	remove_wait_queue(&khugepaged_wait, &wait);
837b46e756fSKirill A. Shutemov }
838b46e756fSKirill A. Shutemov 
8399c284c91SShivank Garg static struct collapse_control khugepaged_collapse_control = {
840d8ea7cc8SZach O'Keefe 	.is_khugepaged = true,
84134d6b470SZach O'Keefe };
842b46e756fSKirill A. Shutemov 
collapse_scan_abort(int nid,struct collapse_control * cc)843ff7e03a8SNico Pache static bool collapse_scan_abort(int nid, struct collapse_control *cc)
844b46e756fSKirill A. Shutemov {
845b46e756fSKirill A. Shutemov 	int i;
846b46e756fSKirill A. Shutemov 
847b46e756fSKirill A. Shutemov 	/*
848a5f5f91dSMel Gorman 	 * If node_reclaim_mode is disabled, then no extra effort is made to
849b46e756fSKirill A. Shutemov 	 * allocate memory locally.
850b46e756fSKirill A. Shutemov 	 */
851202e35dbSDave Hansen 	if (!node_reclaim_enabled())
852b46e756fSKirill A. Shutemov 		return false;
853b46e756fSKirill A. Shutemov 
854b46e756fSKirill A. Shutemov 	/* If there is a count for this node already, it must be acceptable */
85534d6b470SZach O'Keefe 	if (cc->node_load[nid])
856b46e756fSKirill A. Shutemov 		return false;
857b46e756fSKirill A. Shutemov 
858b46e756fSKirill A. Shutemov 	for (i = 0; i < MAX_NUMNODES; i++) {
85934d6b470SZach O'Keefe 		if (!cc->node_load[i])
860b46e756fSKirill A. Shutemov 			continue;
861a55c7454SMatt Fleming 		if (node_distance(nid, i) > node_reclaim_distance)
862b46e756fSKirill A. Shutemov 			return true;
863b46e756fSKirill A. Shutemov 	}
864b46e756fSKirill A. Shutemov 	return false;
865b46e756fSKirill A. Shutemov }
866b46e756fSKirill A. Shutemov 
8671064026bSYang Shi #define khugepaged_defrag()					\
8681064026bSYang Shi 	(transparent_hugepage_flags &				\
8691064026bSYang Shi 	 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
8701064026bSYang Shi 
871b46e756fSKirill A. Shutemov /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
alloc_hugepage_khugepaged_gfpmask(void)872b46e756fSKirill A. Shutemov static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
873b46e756fSKirill A. Shutemov {
87425160354SVlastimil Babka 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
875b46e756fSKirill A. Shutemov }
876b46e756fSKirill A. Shutemov 
877b46e756fSKirill A. Shutemov #ifdef CONFIG_NUMA
collapse_find_target_node(struct collapse_control * cc)878ff7e03a8SNico Pache static int collapse_find_target_node(struct collapse_control *cc)
879b46e756fSKirill A. Shutemov {
880b46e756fSKirill A. Shutemov 	int nid, target_node = 0, max_value = 0;
881b46e756fSKirill A. Shutemov 
882b46e756fSKirill A. Shutemov 	/* find first node with max normal pages hit */
883b46e756fSKirill A. Shutemov 	for (nid = 0; nid < MAX_NUMNODES; nid++)
88434d6b470SZach O'Keefe 		if (cc->node_load[nid] > max_value) {
88534d6b470SZach O'Keefe 			max_value = cc->node_load[nid];
886b46e756fSKirill A. Shutemov 			target_node = nid;
887b46e756fSKirill A. Shutemov 		}
888b46e756fSKirill A. Shutemov 
889e031ff96SYang Shi 	for_each_online_node(nid) {
890e031ff96SYang Shi 		if (max_value == cc->node_load[nid])
891e031ff96SYang Shi 			node_set(nid, cc->alloc_nmask);
892b46e756fSKirill A. Shutemov 	}
893b46e756fSKirill A. Shutemov 
894b46e756fSKirill A. Shutemov 	return target_node;
895b46e756fSKirill A. Shutemov }
896c6a7f445SYang Shi #else
collapse_find_target_node(struct collapse_control * cc)897ff7e03a8SNico Pache static int collapse_find_target_node(struct collapse_control *cc)
898b46e756fSKirill A. Shutemov {
899c6a7f445SYang Shi 	return 0;
900b46e756fSKirill A. Shutemov }
901c6a7f445SYang Shi #endif
902b46e756fSKirill A. Shutemov 
903b46e756fSKirill A. Shutemov /*
904c1e8d7c6SMichel Lespinasse  * If mmap_lock temporarily dropped, revalidate vma
905c1e8d7c6SMichel Lespinasse  * before taking mmap_lock.
90650ad2f24SZach O'Keefe  * Returns enum scan_result value.
907b46e756fSKirill A. Shutemov  */
908b46e756fSKirill A. Shutemov 
hugepage_vma_revalidate(struct mm_struct * mm,unsigned long address,bool expect_anon,struct vm_area_struct ** vmap,struct collapse_control * cc)90940bd4ff0SShivank Garg static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
91040bd4ff0SShivank Garg 		bool expect_anon, struct vm_area_struct **vmap, struct collapse_control *cc)
911b46e756fSKirill A. Shutemov {
912b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
9131f1c0610SDavid Hildenbrand 	enum tva_type type = cc->is_khugepaged ? TVA_KHUGEPAGED :
9141f1c0610SDavid Hildenbrand 				 TVA_FORCED_COLLAPSE;
915b46e756fSKirill A. Shutemov 
916ff7e03a8SNico Pache 	if (unlikely(collapse_test_exit_or_disable(mm)))
917b46e756fSKirill A. Shutemov 		return SCAN_ANY_PROCESS;
918b46e756fSKirill A. Shutemov 
919c131f751SKirill A. Shutemov 	*vmap = vma = find_vma(mm, address);
920b46e756fSKirill A. Shutemov 	if (!vma)
921b46e756fSKirill A. Shutemov 		return SCAN_VMA_NULL;
922b46e756fSKirill A. Shutemov 
9233485b883SRyan Roberts 	if (!thp_vma_suitable_order(vma, address, PMD_ORDER))
924b46e756fSKirill A. Shutemov 		return SCAN_ADDRESS_RANGE;
9251f1c0610SDavid Hildenbrand 	if (!thp_vma_allowable_order(vma, vma->vm_flags, type, PMD_ORDER))
926b46e756fSKirill A. Shutemov 		return SCAN_VMA_CHECK;
927f707fa49SYang Shi 	/*
928f707fa49SYang Shi 	 * Anon VMA expected, the address may be unmapped then
929f707fa49SYang Shi 	 * remapped to file after khugepaged reaquired the mmap_lock.
930f707fa49SYang Shi 	 *
9313485b883SRyan Roberts 	 * thp_vma_allowable_order may return true for qualified file
932f707fa49SYang Shi 	 * vmas.
933f707fa49SYang Shi 	 */
93434488399SZach O'Keefe 	if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
93534488399SZach O'Keefe 		return SCAN_PAGE_ANON;
93650ad2f24SZach O'Keefe 	return SCAN_SUCCEED;
937b46e756fSKirill A. Shutemov }
938b46e756fSKirill A. Shutemov 
check_pmd_state(pmd_t * pmd)93940bd4ff0SShivank Garg static inline enum scan_result check_pmd_state(pmd_t *pmd)
94050722804SZach O'Keefe {
9416c18ec9aSQi Zheng 	pmd_t pmde = pmdp_get_lockless(pmd);
94250722804SZach O'Keefe 
94334488399SZach O'Keefe 	if (pmd_none(pmde))
9449e014077SWei Yang 		return SCAN_NO_PTE_TABLE;
9457f810385SDev Jain 
9467f810385SDev Jain 	/*
9477f810385SDev Jain 	 * The folio may be under migration when khugepaged is trying to
9487f810385SDev Jain 	 * collapse it. Migration success or failure will eventually end
9497f810385SDev Jain 	 * up with a present PMD mapping a folio again.
9507f810385SDev Jain 	 */
9510ac881efSLorenzo Stoakes 	if (pmd_is_migration_entry(pmde))
9527f810385SDev Jain 		return SCAN_PMD_MAPPED;
953edb5d0cfSZach O'Keefe 	if (!pmd_present(pmde))
9549e014077SWei Yang 		return SCAN_NO_PTE_TABLE;
95550722804SZach O'Keefe 	if (pmd_trans_huge(pmde))
95650722804SZach O'Keefe 		return SCAN_PMD_MAPPED;
95750722804SZach O'Keefe 	if (pmd_bad(pmde))
9589e014077SWei Yang 		return SCAN_NO_PTE_TABLE;
95950722804SZach O'Keefe 	return SCAN_SUCCEED;
96050722804SZach O'Keefe }
96150722804SZach O'Keefe 
find_pmd_or_thp_or_none(struct mm_struct * mm,unsigned long address,pmd_t ** pmd)96240bd4ff0SShivank Garg static enum scan_result find_pmd_or_thp_or_none(struct mm_struct *mm,
96340bd4ff0SShivank Garg 		unsigned long address, pmd_t **pmd)
9646c18ec9aSQi Zheng {
9656c18ec9aSQi Zheng 	*pmd = mm_find_pmd(mm, address);
9666c18ec9aSQi Zheng 	if (!*pmd)
9679e014077SWei Yang 		return SCAN_NO_PTE_TABLE;
9686c18ec9aSQi Zheng 
9696c18ec9aSQi Zheng 	return check_pmd_state(*pmd);
9706c18ec9aSQi Zheng }
9716c18ec9aSQi Zheng 
check_pmd_still_valid(struct mm_struct * mm,unsigned long address,pmd_t * pmd)97240bd4ff0SShivank Garg static enum scan_result check_pmd_still_valid(struct mm_struct *mm,
97340bd4ff0SShivank Garg 		unsigned long address, pmd_t *pmd)
97450722804SZach O'Keefe {
97550722804SZach O'Keefe 	pmd_t *new_pmd;
97640bd4ff0SShivank Garg 	enum scan_result result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
97750722804SZach O'Keefe 
97850722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
97950722804SZach O'Keefe 		return result;
98050722804SZach O'Keefe 	if (new_pmd != pmd)
98150722804SZach O'Keefe 		return SCAN_FAIL;
98250722804SZach O'Keefe 	return SCAN_SUCCEED;
983b46e756fSKirill A. Shutemov }
984b46e756fSKirill A. Shutemov 
985b46e756fSKirill A. Shutemov /*
986b46e756fSKirill A. Shutemov  * Bring missing pages in from swap, to complete THP collapse.
987ff7e03a8SNico Pache  * Only done if khugepaged_scan_pmd believes it is worthwhile.
988b46e756fSKirill A. Shutemov  *
9894d928e20SMiaohe Lin  * Called and returns without pte mapped or spinlocks held.
990895f5ee4SHugh Dickins  * Returns result: if not SCAN_SUCCEED, mmap_lock has been released.
991b46e756fSKirill A. Shutemov  */
__collapse_huge_page_swapin(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long start_addr,pmd_t * pmd,int referenced)99240bd4ff0SShivank Garg static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,
99340bd4ff0SShivank Garg 		struct vm_area_struct *vma, unsigned long start_addr, pmd_t *pmd,
9940db501f7SEbru Akagunduz 		int referenced)
995b46e756fSKirill A. Shutemov {
9962b740303SSouptick Joarder 	int swapped_in = 0;
9972b740303SSouptick Joarder 	vm_fault_t ret = 0;
9981acc3693SWei Yang 	unsigned long addr, end = start_addr + (HPAGE_PMD_NR * PAGE_SIZE);
99940bd4ff0SShivank Garg 	enum scan_result result;
1000895f5ee4SHugh Dickins 	pte_t *pte = NULL;
1001c7ad0880SHugh Dickins 	spinlock_t *ptl;
10022b635dd3SWill Deacon 
10031acc3693SWei Yang 	for (addr = start_addr; addr < end; addr += PAGE_SIZE) {
100482b0f8c3SJan Kara 		struct vm_fault vmf = {
1005b46e756fSKirill A. Shutemov 			.vma = vma,
10061acc3693SWei Yang 			.address = addr,
10071acc3693SWei Yang 			.pgoff = linear_page_index(vma, addr),
1008b46e756fSKirill A. Shutemov 			.flags = FAULT_FLAG_ALLOW_RETRY,
1009b46e756fSKirill A. Shutemov 			.pmd = pmd,
1010b46e756fSKirill A. Shutemov 		};
1011b46e756fSKirill A. Shutemov 
1012895f5ee4SHugh Dickins 		if (!pte++) {
1013c8550785SQi Zheng 			/*
1014c8550785SQi Zheng 			 * Here the ptl is only used to check pte_same() in
1015c8550785SQi Zheng 			 * do_swap_page(), so readonly version is enough.
1016c8550785SQi Zheng 			 */
10171acc3693SWei Yang 			pte = pte_offset_map_ro_nolock(mm, pmd, addr, &ptl);
1018895f5ee4SHugh Dickins 			if (!pte) {
1019895f5ee4SHugh Dickins 				mmap_read_unlock(mm);
10209e014077SWei Yang 				result = SCAN_NO_PTE_TABLE;
1021895f5ee4SHugh Dickins 				goto out;
10222b635dd3SWill Deacon 			}
1023895f5ee4SHugh Dickins 		}
1024895f5ee4SHugh Dickins 
1025c7ad0880SHugh Dickins 		vmf.orig_pte = ptep_get_lockless(pte);
1026fb888710SLorenzo Stoakes 		if (pte_none(vmf.orig_pte) ||
1027fb888710SLorenzo Stoakes 		    pte_present(vmf.orig_pte))
1028895f5ee4SHugh Dickins 			continue;
1029895f5ee4SHugh Dickins 
1030895f5ee4SHugh Dickins 		vmf.pte = pte;
1031c7ad0880SHugh Dickins 		vmf.ptl = ptl;
10322994302bSJan Kara 		ret = do_swap_page(&vmf);
1033895f5ee4SHugh Dickins 		/* Which unmaps pte (after perhaps re-checking the entry) */
1034895f5ee4SHugh Dickins 		pte = NULL;
10350db501f7SEbru Akagunduz 
10364d928e20SMiaohe Lin 		/*
10374d928e20SMiaohe Lin 		 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
10384d928e20SMiaohe Lin 		 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
10394d928e20SMiaohe Lin 		 * we do not retry here and swap entry will remain in pagetable
10404d928e20SMiaohe Lin 		 * resulting in later failure.
10414d928e20SMiaohe Lin 		 */
1042b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_RETRY) {
104350ad2f24SZach O'Keefe 			/* Likely, but not guaranteed, that page lock failed */
1044895f5ee4SHugh Dickins 			result = SCAN_PAGE_LOCK;
1045895f5ee4SHugh Dickins 			goto out;
104647f863eaSEbru Akagunduz 		}
1047b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_ERROR) {
10484d928e20SMiaohe Lin 			mmap_read_unlock(mm);
1049895f5ee4SHugh Dickins 			result = SCAN_FAIL;
1050895f5ee4SHugh Dickins 			goto out;
1051b46e756fSKirill A. Shutemov 		}
10524d928e20SMiaohe Lin 		swapped_in++;
1053b46e756fSKirill A. Shutemov 	}
1054ae2c5d80SKirill A. Shutemov 
1055895f5ee4SHugh Dickins 	if (pte)
1056895f5ee4SHugh Dickins 		pte_unmap(pte);
1057895f5ee4SHugh Dickins 
10581fec6890SMatthew Wilcox (Oracle) 	/* Drain LRU cache to remove extra pin on the swapped in pages */
1059ae2c5d80SKirill A. Shutemov 	if (swapped_in)
1060ae2c5d80SKirill A. Shutemov 		lru_add_drain();
1061ae2c5d80SKirill A. Shutemov 
1062895f5ee4SHugh Dickins 	result = SCAN_SUCCEED;
1063895f5ee4SHugh Dickins out:
1064895f5ee4SHugh Dickins 	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, result);
1065895f5ee4SHugh Dickins 	return result;
1066b46e756fSKirill A. Shutemov }
1067b46e756fSKirill A. Shutemov 
alloc_charge_folio(struct folio ** foliop,struct mm_struct * mm,struct collapse_control * cc)106840bd4ff0SShivank Garg static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,
10699710a78aSZach O'Keefe 		struct collapse_control *cc)
10709710a78aSZach O'Keefe {
10717d8faaf1SZach O'Keefe 	gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
1072e031ff96SYang Shi 		     GFP_TRANSHUGE);
1073ff7e03a8SNico Pache 	int node = collapse_find_target_node(cc);
107494c02ad7SPeter Xu 	struct folio *folio;
10759710a78aSZach O'Keefe 
10764746f5ceSMatthew Wilcox (Oracle) 	folio = __folio_alloc(gfp, HPAGE_PMD_ORDER, node, &cc->alloc_nmask);
10774746f5ceSMatthew Wilcox (Oracle) 	if (!folio) {
1078d5ab50b9SMatthew Wilcox (Oracle) 		*foliop = NULL;
10794746f5ceSMatthew Wilcox (Oracle) 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
10809710a78aSZach O'Keefe 		return SCAN_ALLOC_HUGE_PAGE_FAIL;
1081b455f39dSVishal Moola (Oracle) 	}
108294c02ad7SPeter Xu 
10834746f5ceSMatthew Wilcox (Oracle) 	count_vm_event(THP_COLLAPSE_ALLOC);
108494c02ad7SPeter Xu 	if (unlikely(mem_cgroup_charge(folio, mm, gfp))) {
108594c02ad7SPeter Xu 		folio_put(folio);
1086d5ab50b9SMatthew Wilcox (Oracle) 		*foliop = NULL;
10879710a78aSZach O'Keefe 		return SCAN_CGROUP_CHARGE_FAIL;
108894c02ad7SPeter Xu 	}
108994c02ad7SPeter Xu 
1090b455f39dSVishal Moola (Oracle) 	count_memcg_folio_events(folio, THP_COLLAPSE_ALLOC, 1);
1091b455f39dSVishal Moola (Oracle) 
1092d5ab50b9SMatthew Wilcox (Oracle) 	*foliop = folio;
10939710a78aSZach O'Keefe 	return SCAN_SUCCEED;
10949710a78aSZach O'Keefe }
10959710a78aSZach O'Keefe 
collapse_huge_page(struct mm_struct * mm,unsigned long address,int referenced,int unmapped,struct collapse_control * cc)109640bd4ff0SShivank Garg static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long address,
109740bd4ff0SShivank Garg 		int referenced, int unmapped, struct collapse_control *cc)
1098b46e756fSKirill A. Shutemov {
10995503fbf2SKirill A. Shutemov 	LIST_HEAD(compound_pagelist);
1100b46e756fSKirill A. Shutemov 	pmd_t *pmd, _pmd;
1101b46e756fSKirill A. Shutemov 	pte_t *pte;
1102b46e756fSKirill A. Shutemov 	pgtable_t pgtable;
110354327268SMatthew Wilcox (Oracle) 	struct folio *folio;
1104b46e756fSKirill A. Shutemov 	spinlock_t *pmd_ptl, *pte_ptl;
110540bd4ff0SShivank Garg 	enum scan_result result = SCAN_FAIL;
1106c131f751SKirill A. Shutemov 	struct vm_area_struct *vma;
1107ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
1108b46e756fSKirill A. Shutemov 
1109b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1110b46e756fSKirill A. Shutemov 
1111988ddb71SKirill A. Shutemov 	/*
1112c1e8d7c6SMichel Lespinasse 	 * Before allocating the hugepage, release the mmap_lock read lock.
1113988ddb71SKirill A. Shutemov 	 * The allocation can take potentially a long time if it involves
1114c1e8d7c6SMichel Lespinasse 	 * sync compaction, and we do not need to hold the mmap_lock during
1115988ddb71SKirill A. Shutemov 	 * that. We will recheck the vma after taking it again in write mode.
1116988ddb71SKirill A. Shutemov 	 */
1117d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
1118b46e756fSKirill A. Shutemov 
1119d5ab50b9SMatthew Wilcox (Oracle) 	result = alloc_charge_folio(&folio, mm, cc);
11209710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1121b46e756fSKirill A. Shutemov 		goto out_nolock;
1122b46e756fSKirill A. Shutemov 
1123d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
112434488399SZach O'Keefe 	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
112550ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED) {
1126d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
1127b46e756fSKirill A. Shutemov 		goto out_nolock;
1128b46e756fSKirill A. Shutemov 	}
1129b46e756fSKirill A. Shutemov 
113050722804SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, address, &pmd);
113150722804SZach O'Keefe 	if (result != SCAN_SUCCEED) {
1132d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
1133b46e756fSKirill A. Shutemov 		goto out_nolock;
1134b46e756fSKirill A. Shutemov 	}
1135b46e756fSKirill A. Shutemov 
113650ad2f24SZach O'Keefe 	if (unmapped) {
1137b46e756fSKirill A. Shutemov 		/*
113850ad2f24SZach O'Keefe 		 * __collapse_huge_page_swapin will return with mmap_lock
113950ad2f24SZach O'Keefe 		 * released when it fails. So we jump out_nolock directly in
114050ad2f24SZach O'Keefe 		 * that case.  Continuing to collapse causes inconsistency.
1141b46e756fSKirill A. Shutemov 		 */
114250ad2f24SZach O'Keefe 		result = __collapse_huge_page_swapin(mm, vma, address, pmd,
114350ad2f24SZach O'Keefe 						     referenced);
114450ad2f24SZach O'Keefe 		if (result != SCAN_SUCCEED)
1145b46e756fSKirill A. Shutemov 			goto out_nolock;
1146b46e756fSKirill A. Shutemov 	}
1147b46e756fSKirill A. Shutemov 
1148d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
1149b46e756fSKirill A. Shutemov 	/*
1150b46e756fSKirill A. Shutemov 	 * Prevent all access to pagetables with the exception of
1151b46e756fSKirill A. Shutemov 	 * gup_fast later handled by the ptep_clear_flush and the VM
1152b46e756fSKirill A. Shutemov 	 * handled by the anon_vma lock + PG_lock.
1153adef4406SAndrea Arcangeli 	 *
1154adef4406SAndrea Arcangeli 	 * UFFDIO_MOVE is prevented to race as well thanks to the
1155adef4406SAndrea Arcangeli 	 * mmap_lock.
1156b46e756fSKirill A. Shutemov 	 */
1157d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
115834488399SZach O'Keefe 	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
115950ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED)
116018d24a7cSMiaohe Lin 		goto out_up_write;
1161b46e756fSKirill A. Shutemov 	/* check if the pmd is still valid */
1162366a4532SBarry Song 	vma_start_write(vma);
116350722804SZach O'Keefe 	result = check_pmd_still_valid(mm, address, pmd);
116450722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
116518d24a7cSMiaohe Lin 		goto out_up_write;
1166b46e756fSKirill A. Shutemov 
1167b46e756fSKirill A. Shutemov 	anon_vma_lock_write(vma->anon_vma);
1168b46e756fSKirill A. Shutemov 
11697d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
11707d4a8be0SAlistair Popple 				address + HPAGE_PMD_SIZE);
1171ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1172ec649c9dSVille Syrjälä 
1173b46e756fSKirill A. Shutemov 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1174b46e756fSKirill A. Shutemov 	/*
117570cbc3ccSYang Shi 	 * This removes any huge TLB entry from the CPU so we won't allow
117670cbc3ccSYang Shi 	 * huge and small TLB entries for the same virtual address to
117770cbc3ccSYang Shi 	 * avoid the risk of CPU bugs in that area.
117870cbc3ccSYang Shi 	 *
11790ae0b2b3SDavid Hildenbrand 	 * Parallel GUP-fast is fine since GUP-fast will back off when
118070cbc3ccSYang Shi 	 * it detects PMD is changed.
1181b46e756fSKirill A. Shutemov 	 */
1182b46e756fSKirill A. Shutemov 	_pmd = pmdp_collapse_flush(vma, address, pmd);
1183b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1184ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
11852ba99c5eSJann Horn 	tlb_remove_table_sync_one();
1186b46e756fSKirill A. Shutemov 
1187895f5ee4SHugh Dickins 	pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl);
1188895f5ee4SHugh Dickins 	if (pte) {
1189d8ea7cc8SZach O'Keefe 		result = __collapse_huge_page_isolate(vma, address, pte, cc,
11905503fbf2SKirill A. Shutemov 						      &compound_pagelist);
1191b46e756fSKirill A. Shutemov 		spin_unlock(pte_ptl);
1192895f5ee4SHugh Dickins 	} else {
11939e014077SWei Yang 		result = SCAN_NO_PTE_TABLE;
1194895f5ee4SHugh Dickins 	}
1195b46e756fSKirill A. Shutemov 
119650ad2f24SZach O'Keefe 	if (unlikely(result != SCAN_SUCCEED)) {
1197895f5ee4SHugh Dickins 		if (pte)
1198b46e756fSKirill A. Shutemov 			pte_unmap(pte);
1199b46e756fSKirill A. Shutemov 		spin_lock(pmd_ptl);
1200b46e756fSKirill A. Shutemov 		BUG_ON(!pmd_none(*pmd));
1201b46e756fSKirill A. Shutemov 		/*
1202b46e756fSKirill A. Shutemov 		 * We can only use set_pmd_at when establishing
1203b46e756fSKirill A. Shutemov 		 * hugepmds and never for establishing regular pmds that
1204b46e756fSKirill A. Shutemov 		 * points to regular pagetables. Use pmd_populate for that
1205b46e756fSKirill A. Shutemov 		 */
1206b46e756fSKirill A. Shutemov 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1207b46e756fSKirill A. Shutemov 		spin_unlock(pmd_ptl);
1208b46e756fSKirill A. Shutemov 		anon_vma_unlock_write(vma->anon_vma);
120918d24a7cSMiaohe Lin 		goto out_up_write;
1210b46e756fSKirill A. Shutemov 	}
1211b46e756fSKirill A. Shutemov 
1212b46e756fSKirill A. Shutemov 	/*
1213b46e756fSKirill A. Shutemov 	 * All pages are isolated and locked so anon_vma rmap
1214b46e756fSKirill A. Shutemov 	 * can't run anymore.
1215b46e756fSKirill A. Shutemov 	 */
1216b46e756fSKirill A. Shutemov 	anon_vma_unlock_write(vma->anon_vma);
1217b46e756fSKirill A. Shutemov 
12188eca68e2SMatthew Wilcox (Oracle) 	result = __collapse_huge_page_copy(pte, folio, pmd, _pmd,
121998c76c9fSJiaqi Yan 					   vma, address, pte_ptl,
12205503fbf2SKirill A. Shutemov 					   &compound_pagelist);
1221b46e756fSKirill A. Shutemov 	pte_unmap(pte);
122298c76c9fSJiaqi Yan 	if (unlikely(result != SCAN_SUCCEED))
122398c76c9fSJiaqi Yan 		goto out_up_write;
122498c76c9fSJiaqi Yan 
1225588d01f9SMiaohe Lin 	/*
122654327268SMatthew Wilcox (Oracle) 	 * The smp_wmb() inside __folio_mark_uptodate() ensures the
122754327268SMatthew Wilcox (Oracle) 	 * copy_huge_page writes become visible before the set_pmd_at()
122854327268SMatthew Wilcox (Oracle) 	 * write.
1229588d01f9SMiaohe Lin 	 */
123054327268SMatthew Wilcox (Oracle) 	__folio_mark_uptodate(folio);
1231b46e756fSKirill A. Shutemov 	pgtable = pmd_pgtable(_pmd);
1232b46e756fSKirill A. Shutemov 
1233b46e756fSKirill A. Shutemov 	spin_lock(pmd_ptl);
1234b46e756fSKirill A. Shutemov 	BUG_ON(!pmd_none(*pmd));
1235b46e756fSKirill A. Shutemov 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1236ac775677SWei Yang 	map_anon_folio_pmd_nopf(folio, pmd, vma, address);
1237b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1238b46e756fSKirill A. Shutemov 
123902347792SMatthew Wilcox (Oracle) 	folio = NULL;
1240b46e756fSKirill A. Shutemov 
1241b46e756fSKirill A. Shutemov 	result = SCAN_SUCCEED;
1242b46e756fSKirill A. Shutemov out_up_write:
1243d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1244b46e756fSKirill A. Shutemov out_nolock:
124502347792SMatthew Wilcox (Oracle) 	if (folio)
124602347792SMatthew Wilcox (Oracle) 		folio_put(folio);
124750ad2f24SZach O'Keefe 	trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
124850ad2f24SZach O'Keefe 	return result;
1249b46e756fSKirill A. Shutemov }
1250b46e756fSKirill A. Shutemov 
collapse_scan_pmd(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long start_addr,bool * lock_dropped,struct collapse_control * cc)1251ff7e03a8SNico Pache static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
1252eeeb79d5SVernon Yang 		struct vm_area_struct *vma, unsigned long start_addr,
1253a155d945SNico Pache 		bool *lock_dropped, struct collapse_control *cc)
1254b46e756fSKirill A. Shutemov {
1255b46e756fSKirill A. Shutemov 	pmd_t *pmd;
1256b46e756fSKirill A. Shutemov 	pte_t *pte, *_pte;
125740bd4ff0SShivank Garg 	int none_or_zero = 0, shared = 0, referenced = 0;
125840bd4ff0SShivank Garg 	enum scan_result result = SCAN_FAIL;
1259b46e756fSKirill A. Shutemov 	struct page *page = NULL;
12605c07ebb3SVishal Moola (Oracle) 	struct folio *folio = NULL;
12611acc3693SWei Yang 	unsigned long addr;
1262b46e756fSKirill A. Shutemov 	spinlock_t *ptl;
1263b46e756fSKirill A. Shutemov 	int node = NUMA_NO_NODE, unmapped = 0;
1264b46e756fSKirill A. Shutemov 
12651acc3693SWei Yang 	VM_BUG_ON(start_addr & ~HPAGE_PMD_MASK);
1266b46e756fSKirill A. Shutemov 
12671acc3693SWei Yang 	result = find_pmd_or_thp_or_none(mm, start_addr, &pmd);
1268eeeb79d5SVernon Yang 	if (result != SCAN_SUCCEED) {
126934c1f77eSVernon Yang 		cc->progress++;
1270b46e756fSKirill A. Shutemov 		goto out;
1271eeeb79d5SVernon Yang 	}
1272b46e756fSKirill A. Shutemov 
127334d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1274e031ff96SYang Shi 	nodes_clear(cc->alloc_nmask);
12751acc3693SWei Yang 	pte = pte_offset_map_lock(mm, pmd, start_addr, &ptl);
1276895f5ee4SHugh Dickins 	if (!pte) {
127734c1f77eSVernon Yang 		cc->progress++;
12789e014077SWei Yang 		result = SCAN_NO_PTE_TABLE;
1279895f5ee4SHugh Dickins 		goto out;
1280895f5ee4SHugh Dickins 	}
1281895f5ee4SHugh Dickins 
12821acc3693SWei Yang 	for (addr = start_addr, _pte = pte; _pte < pte + HPAGE_PMD_NR;
12831acc3693SWei Yang 	     _pte++, addr += PAGE_SIZE) {
128434c1f77eSVernon Yang 		cc->progress++;
1285eeeb79d5SVernon Yang 
1286c33c7948SRyan Roberts 		pte_t pteval = ptep_get(_pte);
1287fb888710SLorenzo Stoakes 		if (pte_none_or_zero(pteval)) {
1288fb888710SLorenzo Stoakes 			++none_or_zero;
1289fb888710SLorenzo Stoakes 			if (!userfaultfd_armed(vma) &&
1290fb888710SLorenzo Stoakes 			    (!cc->is_khugepaged ||
1291fb888710SLorenzo Stoakes 			     none_or_zero <= khugepaged_max_ptes_none)) {
1292fb888710SLorenzo Stoakes 				continue;
1293fb888710SLorenzo Stoakes 			} else {
1294fb888710SLorenzo Stoakes 				result = SCAN_EXCEED_NONE_PTE;
1295fb888710SLorenzo Stoakes 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1296fb888710SLorenzo Stoakes 				goto out_unmap;
1297fb888710SLorenzo Stoakes 			}
1298fb888710SLorenzo Stoakes 		}
1299fb888710SLorenzo Stoakes 		if (!pte_present(pteval)) {
1300d8ea7cc8SZach O'Keefe 			++unmapped;
1301d8ea7cc8SZach O'Keefe 			if (!cc->is_khugepaged ||
1302d8ea7cc8SZach O'Keefe 			    unmapped <= khugepaged_max_ptes_swap) {
1303e1e267c7SPeter Xu 				/*
1304e1e267c7SPeter Xu 				 * Always be strict with uffd-wp
1305e1e267c7SPeter Xu 				 * enabled swap entries.  Please see
1306e1e267c7SPeter Xu 				 * comment below for pte_uffd_wp().
1307e1e267c7SPeter Xu 				 */
13082bad466cSPeter Xu 				if (pte_swp_uffd_wp_any(pteval)) {
1309e1e267c7SPeter Xu 					result = SCAN_PTE_UFFD_WP;
1310e1e267c7SPeter Xu 					goto out_unmap;
1311e1e267c7SPeter Xu 				}
1312b46e756fSKirill A. Shutemov 				continue;
1313b46e756fSKirill A. Shutemov 			} else {
1314b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1315e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1316b46e756fSKirill A. Shutemov 				goto out_unmap;
1317b46e756fSKirill A. Shutemov 			}
1318b46e756fSKirill A. Shutemov 		}
1319e1e267c7SPeter Xu 		if (pte_uffd_wp(pteval)) {
1320e1e267c7SPeter Xu 			/*
1321e1e267c7SPeter Xu 			 * Don't collapse the page if any of the small
1322e1e267c7SPeter Xu 			 * PTEs are armed with uffd write protection.
1323e1e267c7SPeter Xu 			 * Here we can also mark the new huge pmd as
1324e1e267c7SPeter Xu 			 * write protected if any of the small ones is
13258958b249SHaitao Shi 			 * marked but that could bring unknown
1326e1e267c7SPeter Xu 			 * userfault messages that falls outside of
1327e1e267c7SPeter Xu 			 * the registered range.  So, just be simple.
1328e1e267c7SPeter Xu 			 */
1329e1e267c7SPeter Xu 			result = SCAN_PTE_UFFD_WP;
1330e1e267c7SPeter Xu 			goto out_unmap;
1331e1e267c7SPeter Xu 		}
1332b46e756fSKirill A. Shutemov 
13331acc3693SWei Yang 		page = vm_normal_page(vma, addr, pteval);
13343218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1335b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
1336b46e756fSKirill A. Shutemov 			goto out_unmap;
1337b46e756fSKirill A. Shutemov 		}
13381bafe96eSDavid Hildenbrand 		folio = page_folio(page);
1339b46e756fSKirill A. Shutemov 
134005620419SVernon Yang 		/*
134105620419SVernon Yang 		 * If the vma has the VM_DROPPABLE flag, the collapse will
134205620419SVernon Yang 		 * preserve the lazyfree property without needing to skip.
134305620419SVernon Yang 		 */
134405620419SVernon Yang 		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
134505620419SVernon Yang 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
134605620419SVernon Yang 			result = SCAN_PAGE_LAZYFREE;
134705620419SVernon Yang 			goto out_unmap;
134805620419SVernon Yang 		}
134905620419SVernon Yang 
13501bafe96eSDavid Hildenbrand 		if (!folio_test_anon(folio)) {
13511bafe96eSDavid Hildenbrand 			result = SCAN_PAGE_ANON;
13521bafe96eSDavid Hildenbrand 			goto out_unmap;
13531bafe96eSDavid Hildenbrand 		}
13541bafe96eSDavid Hildenbrand 
13551bafe96eSDavid Hildenbrand 		/*
13561bafe96eSDavid Hildenbrand 		 * We treat a single page as shared if any part of the THP
1357003fde44SDavid Hildenbrand 		 * is shared.
13581bafe96eSDavid Hildenbrand 		 */
1359003fde44SDavid Hildenbrand 		if (folio_maybe_mapped_shared(folio)) {
1360d8ea7cc8SZach O'Keefe 			++shared;
1361d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
1362d8ea7cc8SZach O'Keefe 			    shared > khugepaged_max_ptes_shared) {
136371a2c112SKirill A. Shutemov 				result = SCAN_EXCEED_SHARED_PTE;
1364e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
136571a2c112SKirill A. Shutemov 				goto out_unmap;
136671a2c112SKirill A. Shutemov 			}
1367d8ea7cc8SZach O'Keefe 		}
136871a2c112SKirill A. Shutemov 
1369b46e756fSKirill A. Shutemov 		/*
1370b46e756fSKirill A. Shutemov 		 * Record which node the original page is from and save this
137134d6b470SZach O'Keefe 		 * information to cc->node_load[].
13720b8f0d87SQuanfa Fu 		 * Khugepaged will allocate hugepage from the node has the max
1373b46e756fSKirill A. Shutemov 		 * hit record.
1374b46e756fSKirill A. Shutemov 		 */
13755c07ebb3SVishal Moola (Oracle) 		node = folio_nid(folio);
1376ff7e03a8SNico Pache 		if (collapse_scan_abort(node, cc)) {
1377b46e756fSKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1378b46e756fSKirill A. Shutemov 			goto out_unmap;
1379b46e756fSKirill A. Shutemov 		}
138034d6b470SZach O'Keefe 		cc->node_load[node]++;
13815c07ebb3SVishal Moola (Oracle) 		if (!folio_test_lru(folio)) {
1382b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1383b46e756fSKirill A. Shutemov 			goto out_unmap;
1384b46e756fSKirill A. Shutemov 		}
13855c07ebb3SVishal Moola (Oracle) 		if (folio_test_locked(folio)) {
1386b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
1387b46e756fSKirill A. Shutemov 			goto out_unmap;
1388b46e756fSKirill A. Shutemov 		}
1389b46e756fSKirill A. Shutemov 
1390b46e756fSKirill A. Shutemov 		/*
13919445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
13929445689fSKirill A. Shutemov 		 *
1393cb67f428SHugh Dickins 		 * Here the check may be racy:
139405c5323bSDavid Hildenbrand 		 * it may see folio_mapcount() > folio_ref_count().
13959445689fSKirill A. Shutemov 		 * But such case is ephemeral we could always retry collapse
13969445689fSKirill A. Shutemov 		 * later.  However it may report false positive if the page
13979445689fSKirill A. Shutemov 		 * has excessive GUP pins (i.e. 512).  Anyway the same check
13989445689fSKirill A. Shutemov 		 * will be done again later the risk seems low.
1399b46e756fSKirill A. Shutemov 		 */
14000b43b8bcSShivank Garg 		if (folio_expected_ref_count(folio) != folio_ref_count(folio)) {
1401b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1402b46e756fSKirill A. Shutemov 			goto out_unmap;
1403b46e756fSKirill A. Shutemov 		}
1404d8ea7cc8SZach O'Keefe 
1405d8ea7cc8SZach O'Keefe 		/*
1406d8ea7cc8SZach O'Keefe 		 * If collapse was initiated by khugepaged, check that there is
1407d8ea7cc8SZach O'Keefe 		 * enough young pte to justify collapsing the page
1408d8ea7cc8SZach O'Keefe 		 */
1409d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
14105c07ebb3SVishal Moola (Oracle) 		    (pte_young(pteval) || folio_test_young(folio) ||
1411394bfac1SWei Yang 		     folio_test_referenced(folio) ||
14121acc3693SWei Yang 		     mmu_notifier_test_young(vma->vm_mm, addr)))
14130db501f7SEbru Akagunduz 			referenced++;
1414b46e756fSKirill A. Shutemov 	}
141562b98015SDev Jain 	if (cc->is_khugepaged &&
1416d8ea7cc8SZach O'Keefe 		   (!referenced ||
1417d8ea7cc8SZach O'Keefe 		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1418ffe945e6SKirill A. Shutemov 		result = SCAN_LACK_REFERENCED_PAGE;
1419ffe945e6SKirill A. Shutemov 	} else {
1420b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
1421b46e756fSKirill A. Shutemov 	}
1422b46e756fSKirill A. Shutemov out_unmap:
1423b46e756fSKirill A. Shutemov 	pte_unmap_unlock(pte, ptl);
142450ad2f24SZach O'Keefe 	if (result == SCAN_SUCCEED) {
14251acc3693SWei Yang 		result = collapse_huge_page(mm, start_addr, referenced,
142650ad2f24SZach O'Keefe 					    unmapped, cc);
1427c1e8d7c6SMichel Lespinasse 		/* collapse_huge_page will return with the mmap_lock released */
1428a155d945SNico Pache 		*lock_dropped = true;
1429b46e756fSKirill A. Shutemov 	}
1430b46e756fSKirill A. Shutemov out:
1431473b7322SDev Jain 	trace_mm_khugepaged_scan_pmd(mm, folio, referenced,
1432b46e756fSKirill A. Shutemov 				     none_or_zero, result, unmapped);
143350ad2f24SZach O'Keefe 	return result;
1434b46e756fSKirill A. Shutemov }
1435b46e756fSKirill A. Shutemov 
collect_mm_slot(struct mm_slot * slot)1436b4c9ffb5SWei Yang static void collect_mm_slot(struct mm_slot *slot)
1437b46e756fSKirill A. Shutemov {
1438b26e2701SQi Zheng 	struct mm_struct *mm = slot->mm;
1439b46e756fSKirill A. Shutemov 
144035f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1441b46e756fSKirill A. Shutemov 
1442ff7e03a8SNico Pache 	if (collapse_test_exit(mm)) {
1443b46e756fSKirill A. Shutemov 		/* free mm_slot */
1444b26e2701SQi Zheng 		hash_del(&slot->hash);
1445b26e2701SQi Zheng 		list_del(&slot->mm_node);
1446b46e756fSKirill A. Shutemov 
1447b46e756fSKirill A. Shutemov 		/*
1448b46e756fSKirill A. Shutemov 		 * Not strictly needed because the mm exited already.
1449b46e756fSKirill A. Shutemov 		 *
145012e423baSLorenzo Stoakes 		 * mm_flags_clear(MMF_VM_HUGEPAGE, mm);
1451b46e756fSKirill A. Shutemov 		 */
1452b46e756fSKirill A. Shutemov 
1453b46e756fSKirill A. Shutemov 		/* khugepaged_mm_lock actually not necessary for the below */
1454b4c9ffb5SWei Yang 		mm_slot_free(mm_slot_cache, slot);
1455b46e756fSKirill A. Shutemov 		mmdrop(mm);
1456b46e756fSKirill A. Shutemov 	}
1457b46e756fSKirill A. Shutemov }
1458b46e756fSKirill A. Shutemov 
145950533838SBaolin Wang /* folio must be locked, and mmap_lock must be held */
set_huge_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t * pmdp,struct folio * folio,struct page * page)146040bd4ff0SShivank Garg static enum scan_result set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
146150533838SBaolin Wang 		pmd_t *pmdp, struct folio *folio, struct page *page)
146234488399SZach O'Keefe {
1463f8a01513SKiryl Shutsemau 	struct mm_struct *mm = vma->vm_mm;
146434488399SZach O'Keefe 	struct vm_fault vmf = {
146534488399SZach O'Keefe 		.vma = vma,
146634488399SZach O'Keefe 		.address = addr,
146734488399SZach O'Keefe 		.flags = 0,
146834488399SZach O'Keefe 	};
1469f8a01513SKiryl Shutsemau 	pgd_t *pgdp;
1470f8a01513SKiryl Shutsemau 	p4d_t *p4dp;
1471f8a01513SKiryl Shutsemau 	pud_t *pudp;
147234488399SZach O'Keefe 
14731043173eSHugh Dickins 	mmap_assert_locked(vma->vm_mm);
147434488399SZach O'Keefe 
1475f8a01513SKiryl Shutsemau 	if (!pmdp) {
1476f8a01513SKiryl Shutsemau 		pgdp = pgd_offset(mm, addr);
1477f8a01513SKiryl Shutsemau 		p4dp = p4d_alloc(mm, pgdp, addr);
1478f8a01513SKiryl Shutsemau 		if (!p4dp)
1479f8a01513SKiryl Shutsemau 			return SCAN_FAIL;
1480f8a01513SKiryl Shutsemau 		pudp = pud_alloc(mm, p4dp, addr);
1481f8a01513SKiryl Shutsemau 		if (!pudp)
1482f8a01513SKiryl Shutsemau 			return SCAN_FAIL;
1483f8a01513SKiryl Shutsemau 		pmdp = pmd_alloc(mm, pudp, addr);
1484f8a01513SKiryl Shutsemau 		if (!pmdp)
1485f8a01513SKiryl Shutsemau 			return SCAN_FAIL;
1486f8a01513SKiryl Shutsemau 	}
1487f8a01513SKiryl Shutsemau 
1488f8a01513SKiryl Shutsemau 	vmf.pmd = pmdp;
1489698c0089SBaolin Wang 	if (do_set_pmd(&vmf, folio, page))
149034488399SZach O'Keefe 		return SCAN_FAIL;
149134488399SZach O'Keefe 
149250533838SBaolin Wang 	folio_get(folio);
149334488399SZach O'Keefe 	return SCAN_SUCCEED;
149427e1f827SSong Liu }
149527e1f827SSong Liu 
try_collapse_pte_mapped_thp(struct mm_struct * mm,unsigned long addr,bool install_pmd)149640bd4ff0SShivank Garg static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
149734488399SZach O'Keefe 		bool install_pmd)
149827e1f827SSong Liu {
149940bd4ff0SShivank Garg 	enum scan_result result = SCAN_FAIL;
150040bd4ff0SShivank Garg 	int nr_mapped_ptes = 0;
150122d02290SDev Jain 	unsigned int nr_batch_ptes;
15021043173eSHugh Dickins 	struct mmu_notifier_range range;
15031043173eSHugh Dickins 	bool notified = false;
150427e1f827SSong Liu 	unsigned long haddr = addr & HPAGE_PMD_MASK;
150522d02290SDev Jain 	unsigned long end = haddr + HPAGE_PMD_SIZE;
150694d815b2SLiam R. Howlett 	struct vm_area_struct *vma = vma_lookup(mm, haddr);
150798b32d29SVishal Moola (Oracle) 	struct folio *folio;
150827e1f827SSong Liu 	pte_t *start_pte, *pte;
15091043173eSHugh Dickins 	pmd_t *pmd, pgt_pmd;
1510a9846049SHugh Dickins 	spinlock_t *pml = NULL, *ptl;
151127e1f827SSong Liu 	int i;
151227e1f827SSong Liu 
15131043173eSHugh Dickins 	mmap_assert_locked(mm);
15141043173eSHugh Dickins 
15151043173eSHugh Dickins 	/* First check VMA found, in case page tables are being torn down */
15161043173eSHugh Dickins 	if (!vma || !vma->vm_file ||
15171043173eSHugh Dickins 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
15181043173eSHugh Dickins 		return SCAN_VMA_CHECK;
151958ac9a89SZach O'Keefe 
152034488399SZach O'Keefe 	/* Fast check before locking page if already PMD-mapped */
152158ac9a89SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
152234488399SZach O'Keefe 	if (result == SCAN_PMD_MAPPED)
152334488399SZach O'Keefe 		return result;
152458ac9a89SZach O'Keefe 
152527e1f827SSong Liu 	/*
1526a7f4e6e4SZach O'Keefe 	 * If we are here, we've succeeded in replacing all the native pages
1527a7f4e6e4SZach O'Keefe 	 * in the page cache with a single hugepage. If a mm were to fault-in
1528a7f4e6e4SZach O'Keefe 	 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1529a7f4e6e4SZach O'Keefe 	 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
15301f1c0610SDavid Hildenbrand 	 * analogously elide sysfs THP settings here and force collapse.
153127e1f827SSong Liu 	 */
15321f1c0610SDavid Hildenbrand 	if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER))
153334488399SZach O'Keefe 		return SCAN_VMA_CHECK;
153427e1f827SSong Liu 
1535deb4c93aSPeter Xu 	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1536deb4c93aSPeter Xu 	if (userfaultfd_wp(vma))
153734488399SZach O'Keefe 		return SCAN_PTE_UFFD_WP;
1538deb4c93aSPeter Xu 
153998b32d29SVishal Moola (Oracle) 	folio = filemap_lock_folio(vma->vm_file->f_mapping,
1540119a5fc1SHugh Dickins 			       linear_page_index(vma, haddr));
154198b32d29SVishal Moola (Oracle) 	if (IS_ERR(folio))
154234488399SZach O'Keefe 		return SCAN_PAGE_NULL;
1543119a5fc1SHugh Dickins 
1544b90c453dSNico Pache 	if (!is_pmd_order(folio_order(folio))) {
154534488399SZach O'Keefe 		result = SCAN_PAGE_COMPOUND;
154698b32d29SVishal Moola (Oracle) 		goto drop_folio;
154734488399SZach O'Keefe 	}
1548780a4b6fSZach O'Keefe 
15491043173eSHugh Dickins 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
155034488399SZach O'Keefe 	switch (result) {
155134488399SZach O'Keefe 	case SCAN_SUCCEED:
155234488399SZach O'Keefe 		break;
15539e014077SWei Yang 	case SCAN_NO_PTE_TABLE:
155434488399SZach O'Keefe 		/*
15551d65b771SHugh Dickins 		 * All pte entries have been removed and pmd cleared.
15561d65b771SHugh Dickins 		 * Skip all the pte checks and just update the pmd mapping.
155734488399SZach O'Keefe 		 */
155834488399SZach O'Keefe 		goto maybe_install_pmd;
155934488399SZach O'Keefe 	default:
156098b32d29SVishal Moola (Oracle) 		goto drop_folio;
156134488399SZach O'Keefe 	}
156227e1f827SSong Liu 
156334488399SZach O'Keefe 	result = SCAN_FAIL;
1564895f5ee4SHugh Dickins 	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
15651043173eSHugh Dickins 	if (!start_pte)		/* mmap_lock + page lock should prevent this */
156698b32d29SVishal Moola (Oracle) 		goto drop_folio;
156727e1f827SSong Liu 
156827e1f827SSong Liu 	/* step 1: check all mapped PTEs are to the right huge page */
156927e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
157027e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
157127e1f827SSong Liu 		struct page *page;
1572c33c7948SRyan Roberts 		pte_t ptent = ptep_get(pte);
157327e1f827SSong Liu 
157427e1f827SSong Liu 		/* empty pte, skip */
1575c33c7948SRyan Roberts 		if (pte_none(ptent))
157627e1f827SSong Liu 			continue;
157727e1f827SSong Liu 
157827e1f827SSong Liu 		/* page swapped out, abort */
1579c33c7948SRyan Roberts 		if (!pte_present(ptent)) {
158034488399SZach O'Keefe 			result = SCAN_PTE_NON_PRESENT;
158127e1f827SSong Liu 			goto abort;
158234488399SZach O'Keefe 		}
158327e1f827SSong Liu 
1584c33c7948SRyan Roberts 		page = vm_normal_page(vma, addr, ptent);
15853218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
15863218f871SAlex Sierra 			page = NULL;
158727e1f827SSong Liu 		/*
1588119a5fc1SHugh Dickins 		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1589119a5fc1SHugh Dickins 		 * page table, but the new page will not be a subpage of hpage.
159027e1f827SSong Liu 		 */
159198b32d29SVishal Moola (Oracle) 		if (folio_page(folio, i) != page)
159227e1f827SSong Liu 			goto abort;
159327e1f827SSong Liu 	}
159427e1f827SSong Liu 
15951043173eSHugh Dickins 	pte_unmap_unlock(start_pte, ptl);
15961043173eSHugh Dickins 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
15971043173eSHugh Dickins 				haddr, haddr + HPAGE_PMD_SIZE);
15981043173eSHugh Dickins 	mmu_notifier_invalidate_range_start(&range);
15991043173eSHugh Dickins 	notified = true;
1600a9846049SHugh Dickins 
1601a9846049SHugh Dickins 	/*
1602a9846049SHugh Dickins 	 * pmd_lock covers a wider range than ptl, and (if split from mm's
1603a9846049SHugh Dickins 	 * page_table_lock) ptl nests inside pml. The less time we hold pml,
1604a9846049SHugh Dickins 	 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA
1605a9846049SHugh Dickins 	 * inserts a valid as-if-COWed PTE without even looking up page cache.
160698b32d29SVishal Moola (Oracle) 	 * So page lock of folio does not protect from it, so we must not drop
1607a9846049SHugh Dickins 	 * ptl before pgt_pmd is removed, so uffd private needs pml taken now.
1608a9846049SHugh Dickins 	 */
1609a9846049SHugh Dickins 	if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED))
1610a9846049SHugh Dickins 		pml = pmd_lock(mm, pmd);
1611a9846049SHugh Dickins 
16126dfd0d2cSQi Zheng 	start_pte = pte_offset_map_rw_nolock(mm, pmd, haddr, &pgt_pmd, &ptl);
16131043173eSHugh Dickins 	if (!start_pte)		/* mmap_lock + page lock should prevent this */
16141043173eSHugh Dickins 		goto abort;
1615a9846049SHugh Dickins 	if (!pml)
1616a9846049SHugh Dickins 		spin_lock(ptl);
1617a9846049SHugh Dickins 	else if (ptl != pml)
1618a9846049SHugh Dickins 		spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
16191043173eSHugh Dickins 
16206dfd0d2cSQi Zheng 	if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd))))
16216dfd0d2cSQi Zheng 		goto abort;
16226dfd0d2cSQi Zheng 
16231043173eSHugh Dickins 	/* step 2: clear page table and adjust rmap */
162422d02290SDev Jain 	for (i = 0, addr = haddr, pte = start_pte; i < HPAGE_PMD_NR;
162522d02290SDev Jain 	     i += nr_batch_ptes, addr += nr_batch_ptes * PAGE_SIZE,
162622d02290SDev Jain 	     pte += nr_batch_ptes) {
162722d02290SDev Jain 		unsigned int max_nr_batch_ptes = (end - addr) >> PAGE_SHIFT;
162827e1f827SSong Liu 		struct page *page;
1629c33c7948SRyan Roberts 		pte_t ptent = ptep_get(pte);
163027e1f827SSong Liu 
163122d02290SDev Jain 		nr_batch_ptes = 1;
163222d02290SDev Jain 
1633c33c7948SRyan Roberts 		if (pte_none(ptent))
163427e1f827SSong Liu 			continue;
16351043173eSHugh Dickins 		/*
16361043173eSHugh Dickins 		 * We dropped ptl after the first scan, to do the mmu_notifier:
163798b32d29SVishal Moola (Oracle) 		 * page lock stops more PTEs of the folio being faulted in, but
16381043173eSHugh Dickins 		 * does not stop write faults COWing anon copies from existing
16391043173eSHugh Dickins 		 * PTEs; and does not stop those being swapped out or migrated.
16401043173eSHugh Dickins 		 */
16411043173eSHugh Dickins 		if (!pte_present(ptent)) {
16421043173eSHugh Dickins 			result = SCAN_PTE_NON_PRESENT;
16433218f871SAlex Sierra 			goto abort;
16441043173eSHugh Dickins 		}
16451043173eSHugh Dickins 		page = vm_normal_page(vma, addr, ptent);
164622d02290SDev Jain 
164798b32d29SVishal Moola (Oracle) 		if (folio_page(folio, i) != page)
16481043173eSHugh Dickins 			goto abort;
16491043173eSHugh Dickins 
165022d02290SDev Jain 		nr_batch_ptes = folio_pte_batch(folio, pte, ptent, max_nr_batch_ptes);
165122d02290SDev Jain 
16521043173eSHugh Dickins 		/*
16531043173eSHugh Dickins 		 * Must clear entry, or a racing truncate may re-remove it.
16541043173eSHugh Dickins 		 * TLB flush can be left until pmdp_collapse_flush() does it.
16551043173eSHugh Dickins 		 * PTE dirty? Shmem page is already dirty; file is read-only.
16561043173eSHugh Dickins 		 */
165722d02290SDev Jain 		clear_ptes(mm, addr, pte, nr_batch_ptes);
165822d02290SDev Jain 		folio_remove_rmap_ptes(folio, page, nr_batch_ptes, vma);
165922d02290SDev Jain 		nr_mapped_ptes += nr_batch_ptes;
166027e1f827SSong Liu 	}
166127e1f827SSong Liu 
1662a9846049SHugh Dickins 	if (!pml)
1663a9846049SHugh Dickins 		spin_unlock(ptl);
166427e1f827SSong Liu 
166527e1f827SSong Liu 	/* step 3: set proper refcount and mm_counters. */
166622d02290SDev Jain 	if (nr_mapped_ptes) {
166722d02290SDev Jain 		folio_ref_sub(folio, nr_mapped_ptes);
166822d02290SDev Jain 		add_mm_counter(mm, mm_counter_file(folio), -nr_mapped_ptes);
166927e1f827SSong Liu 	}
167027e1f827SSong Liu 
1671a9846049SHugh Dickins 	/* step 4: remove empty page table */
1672a9846049SHugh Dickins 	if (!pml) {
16731043173eSHugh Dickins 		pml = pmd_lock(mm, pmd);
16746dfd0d2cSQi Zheng 		if (ptl != pml) {
16751043173eSHugh Dickins 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
16766dfd0d2cSQi Zheng 			if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) {
16776dfd0d2cSQi Zheng 				flush_tlb_mm(mm);
16786dfd0d2cSQi Zheng 				goto unlock;
16796dfd0d2cSQi Zheng 			}
16806dfd0d2cSQi Zheng 		}
1681a9846049SHugh Dickins 	}
16821043173eSHugh Dickins 	pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd);
16831043173eSHugh Dickins 	pmdp_get_lockless_sync();
16846dfd0d2cSQi Zheng 	pte_unmap_unlock(start_pte, ptl);
16851043173eSHugh Dickins 	if (ptl != pml)
16861043173eSHugh Dickins 		spin_unlock(pml);
1687ab0c3f12SHugh Dickins 
16881043173eSHugh Dickins 	mmu_notifier_invalidate_range_end(&range);
168934488399SZach O'Keefe 
16901043173eSHugh Dickins 	mm_dec_nr_ptes(mm);
16911043173eSHugh Dickins 	page_table_check_pte_clear_range(mm, haddr, pgt_pmd);
16921043173eSHugh Dickins 	pte_free_defer(mm, pmd_pgtable(pgt_pmd));
16938d3c106eSJann Horn 
169434488399SZach O'Keefe maybe_install_pmd:
169534488399SZach O'Keefe 	/* step 5: install pmd entry */
169634488399SZach O'Keefe 	result = install_pmd
169750533838SBaolin Wang 			? set_huge_pmd(vma, haddr, pmd, folio, &folio->page)
169834488399SZach O'Keefe 			: SCAN_SUCCEED;
169998b32d29SVishal Moola (Oracle) 	goto drop_folio;
17001043173eSHugh Dickins abort:
170122d02290SDev Jain 	if (nr_mapped_ptes) {
17021043173eSHugh Dickins 		flush_tlb_mm(mm);
170322d02290SDev Jain 		folio_ref_sub(folio, nr_mapped_ptes);
170422d02290SDev Jain 		add_mm_counter(mm, mm_counter_file(folio), -nr_mapped_ptes);
17051043173eSHugh Dickins 	}
17066dfd0d2cSQi Zheng unlock:
17071043173eSHugh Dickins 	if (start_pte)
17081043173eSHugh Dickins 		pte_unmap_unlock(start_pte, ptl);
1709a9846049SHugh Dickins 	if (pml && pml != ptl)
1710a9846049SHugh Dickins 		spin_unlock(pml);
17111043173eSHugh Dickins 	if (notified)
17121043173eSHugh Dickins 		mmu_notifier_invalidate_range_end(&range);
171398b32d29SVishal Moola (Oracle) drop_folio:
171498b32d29SVishal Moola (Oracle) 	folio_unlock(folio);
171598b32d29SVishal Moola (Oracle) 	folio_put(folio);
171634488399SZach O'Keefe 	return result;
171727e1f827SSong Liu }
171827e1f827SSong Liu 
17193ab981c1SShivank Garg /**
17203ab981c1SShivank Garg  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
17213ab981c1SShivank Garg  * address haddr.
17223ab981c1SShivank Garg  *
17233ab981c1SShivank Garg  * @mm: process address space where collapse happens
17243ab981c1SShivank Garg  * @addr: THP collapse address
17253ab981c1SShivank Garg  * @install_pmd: If a huge PMD should be installed
17263ab981c1SShivank Garg  *
17273ab981c1SShivank Garg  * This function checks whether all the PTEs in the PMD are pointing to the
17283ab981c1SShivank Garg  * right THP. If so, retract the page table so the THP can refault in with
17293ab981c1SShivank Garg  * as pmd-mapped. Possibly install a huge PMD mapping the THP.
17303ab981c1SShivank Garg  */
collapse_pte_mapped_thp(struct mm_struct * mm,unsigned long addr,bool install_pmd)17313ab981c1SShivank Garg void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
17323ab981c1SShivank Garg 		bool install_pmd)
17333ab981c1SShivank Garg {
17343ab981c1SShivank Garg 	try_collapse_pte_mapped_thp(mm, addr, install_pmd);
17353ab981c1SShivank Garg }
17363ab981c1SShivank Garg 
173749e14dabSLorenzo Stoakes /* Can we retract page tables for this file-backed VMA? */
file_backed_vma_is_retractable(struct vm_area_struct * vma)173849e14dabSLorenzo Stoakes static bool file_backed_vma_is_retractable(struct vm_area_struct *vma)
173949e14dabSLorenzo Stoakes {
174049e14dabSLorenzo Stoakes 	/*
174149e14dabSLorenzo Stoakes 	 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
174249e14dabSLorenzo Stoakes 	 * got written to. These VMAs are likely not worth removing
174349e14dabSLorenzo Stoakes 	 * page tables from, as PMD-mapping is likely to be split later.
174449e14dabSLorenzo Stoakes 	 */
174549e14dabSLorenzo Stoakes 	if (READ_ONCE(vma->anon_vma))
174649e14dabSLorenzo Stoakes 		return false;
174749e14dabSLorenzo Stoakes 
174849e14dabSLorenzo Stoakes 	/*
174949e14dabSLorenzo Stoakes 	 * When a vma is registered with uffd-wp, we cannot recycle
175049e14dabSLorenzo Stoakes 	 * the page table because there may be pte markers installed.
175149e14dabSLorenzo Stoakes 	 * Other vmas can still have the same file mapped hugely, but
175249e14dabSLorenzo Stoakes 	 * skip this one: it will always be mapped in small page size
175349e14dabSLorenzo Stoakes 	 * for uffd-wp registered ranges.
175449e14dabSLorenzo Stoakes 	 */
175549e14dabSLorenzo Stoakes 	if (userfaultfd_wp(vma))
175649e14dabSLorenzo Stoakes 		return false;
175749e14dabSLorenzo Stoakes 
175849e14dabSLorenzo Stoakes 	/*
175949e14dabSLorenzo Stoakes 	 * If the VMA contains guard regions then we can't collapse it.
176049e14dabSLorenzo Stoakes 	 *
176149e14dabSLorenzo Stoakes 	 * This is set atomically on guard marker installation under mmap/VMA
176249e14dabSLorenzo Stoakes 	 * read lock, and here we may not hold any VMA or mmap lock at all.
176349e14dabSLorenzo Stoakes 	 *
176449e14dabSLorenzo Stoakes 	 * This is therefore serialised on the PTE page table lock, which is
176549e14dabSLorenzo Stoakes 	 * obtained on guard region installation after the flag is set, so this
176649e14dabSLorenzo Stoakes 	 * check being performed under this lock excludes races.
176749e14dabSLorenzo Stoakes 	 */
1768e388d312SLorenzo Stoakes 	if (vma_test_atomic_flag(vma, VMA_MAYBE_GUARD_BIT))
176949e14dabSLorenzo Stoakes 		return false;
177049e14dabSLorenzo Stoakes 
177149e14dabSLorenzo Stoakes 	return true;
177249e14dabSLorenzo Stoakes }
177349e14dabSLorenzo Stoakes 
retract_page_tables(struct address_space * mapping,pgoff_t pgoff)17741d65b771SHugh Dickins static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1775f3f0e1d2SKirill A. Shutemov {
1776f3f0e1d2SKirill A. Shutemov 	struct vm_area_struct *vma;
1777f3f0e1d2SKirill A. Shutemov 
17781d65b771SHugh Dickins 	i_mmap_lock_read(mapping);
1779f3f0e1d2SKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
17801d65b771SHugh Dickins 		struct mmu_notifier_range range;
17811d65b771SHugh Dickins 		struct mm_struct *mm;
17821d65b771SHugh Dickins 		unsigned long addr;
17831d65b771SHugh Dickins 		pmd_t *pmd, pgt_pmd;
17841d65b771SHugh Dickins 		spinlock_t *pml;
17851d65b771SHugh Dickins 		spinlock_t *ptl;
17866c18ec9aSQi Zheng 		bool success = false;
178734488399SZach O'Keefe 
1788f3f0e1d2SKirill A. Shutemov 		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
178934488399SZach O'Keefe 		if (addr & ~HPAGE_PMD_MASK ||
17901d65b771SHugh Dickins 		    vma->vm_end < addr + HPAGE_PMD_SIZE)
179134488399SZach O'Keefe 			continue;
17921d65b771SHugh Dickins 
17931d65b771SHugh Dickins 		mm = vma->vm_mm;
17941d65b771SHugh Dickins 		if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED)
17951d65b771SHugh Dickins 			continue;
17961d65b771SHugh Dickins 
1797ff7e03a8SNico Pache 		if (collapse_test_exit(mm))
17981d65b771SHugh Dickins 			continue;
179949e14dabSLorenzo Stoakes 
180049e14dabSLorenzo Stoakes 		if (!file_backed_vma_is_retractable(vma))
18011d65b771SHugh Dickins 			continue;
18021d65b771SHugh Dickins 
18031d65b771SHugh Dickins 		/* PTEs were notified when unmapped; but now for the PMD? */
18041d65b771SHugh Dickins 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
18051d65b771SHugh Dickins 					addr, addr + HPAGE_PMD_SIZE);
18061d65b771SHugh Dickins 		mmu_notifier_invalidate_range_start(&range);
18071d65b771SHugh Dickins 
18081d65b771SHugh Dickins 		pml = pmd_lock(mm, pmd);
18096c18ec9aSQi Zheng 		/*
18106c18ec9aSQi Zheng 		 * The lock of new_folio is still held, we will be blocked in
18116c18ec9aSQi Zheng 		 * the page fault path, which prevents the pte entries from
18126c18ec9aSQi Zheng 		 * being set again. So even though the old empty PTE page may be
18136c18ec9aSQi Zheng 		 * concurrently freed and a new PTE page is filled into the pmd
18146c18ec9aSQi Zheng 		 * entry, it is still empty and can be removed.
18156c18ec9aSQi Zheng 		 *
18166c18ec9aSQi Zheng 		 * So here we only need to recheck if the state of pmd entry
18176c18ec9aSQi Zheng 		 * still meets our requirements, rather than checking pmd_same()
18186c18ec9aSQi Zheng 		 * like elsewhere.
18196c18ec9aSQi Zheng 		 */
18206c18ec9aSQi Zheng 		if (check_pmd_state(pmd) != SCAN_SUCCEED)
18216c18ec9aSQi Zheng 			goto drop_pml;
18221d65b771SHugh Dickins 		ptl = pte_lockptr(mm, pmd);
18231d65b771SHugh Dickins 		if (ptl != pml)
18241d65b771SHugh Dickins 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
18251d65b771SHugh Dickins 
18261d65b771SHugh Dickins 		/*
182749e14dabSLorenzo Stoakes 		 * Huge page lock is still held, so normally the page table must
182849e14dabSLorenzo Stoakes 		 * remain empty; and we have already skipped anon_vma and
182949e14dabSLorenzo Stoakes 		 * userfaultfd_wp() vmas.  But since the mmap_lock is not held,
183049e14dabSLorenzo Stoakes 		 * it is still possible for a racing userfaultfd_ioctl() or
183149e14dabSLorenzo Stoakes 		 * madvise() to have inserted ptes or markers.  Now that we hold
183249e14dabSLorenzo Stoakes 		 * ptlock, repeating the retractable checks protects us from
183349e14dabSLorenzo Stoakes 		 * races against the prior checks.
18341d65b771SHugh Dickins 		 */
183549e14dabSLorenzo Stoakes 		if (likely(file_backed_vma_is_retractable(vma))) {
18361d65b771SHugh Dickins 			pgt_pmd = pmdp_collapse_flush(vma, addr, pmd);
18371d65b771SHugh Dickins 			pmdp_get_lockless_sync();
18386c18ec9aSQi Zheng 			success = true;
183934488399SZach O'Keefe 		}
18401d65b771SHugh Dickins 
18411d65b771SHugh Dickins 		if (ptl != pml)
18421d65b771SHugh Dickins 			spin_unlock(ptl);
18436c18ec9aSQi Zheng drop_pml:
18441d65b771SHugh Dickins 		spin_unlock(pml);
18451d65b771SHugh Dickins 
18461d65b771SHugh Dickins 		mmu_notifier_invalidate_range_end(&range);
18471d65b771SHugh Dickins 
18486c18ec9aSQi Zheng 		if (success) {
18491d65b771SHugh Dickins 			mm_dec_nr_ptes(mm);
18501d65b771SHugh Dickins 			page_table_check_pte_clear_range(mm, addr, pgt_pmd);
18511d65b771SHugh Dickins 			pte_free_defer(mm, pmd_pgtable(pgt_pmd));
1852f3f0e1d2SKirill A. Shutemov 		}
18531d65b771SHugh Dickins 	}
18541d65b771SHugh Dickins 	i_mmap_unlock_read(mapping);
1855f3f0e1d2SKirill A. Shutemov }
1856f3f0e1d2SKirill A. Shutemov 
1857f3f0e1d2SKirill A. Shutemov /**
185899cb0dbdSSong Liu  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1859f3f0e1d2SKirill A. Shutemov  *
1860336e6b53SAlex Shi  * @mm: process address space where collapse happens
186134488399SZach O'Keefe  * @addr: virtual collapse start address
1862336e6b53SAlex Shi  * @file: file that collapse on
1863336e6b53SAlex Shi  * @start: collapse start address
18649710a78aSZach O'Keefe  * @cc: collapse context and scratchpad
1865336e6b53SAlex Shi  *
1866f3f0e1d2SKirill A. Shutemov  * Basic scheme is simple, details are more complex:
186787c460a0SHugh Dickins  *  - allocate and lock a new huge page;
1868a2e17cc2SDavid Stevens  *  - scan page cache, locking old pages
186999cb0dbdSSong Liu  *    + swap/gup in pages if necessary;
1870a2e17cc2SDavid Stevens  *  - copy data to new page
1871a2e17cc2SDavid Stevens  *  - handle shmem holes
1872a2e17cc2SDavid Stevens  *    + re-validate that holes weren't filled by someone else
1873a2e17cc2SDavid Stevens  *    + check for userfaultfd
1874ac492b9cSDavid Stevens  *  - finalize updates to the page cache;
187577da9389SMatthew Wilcox  *  - if replacing succeeds:
187687c460a0SHugh Dickins  *    + unlock huge page;
1877a2e17cc2SDavid Stevens  *    + free old pages;
1878f3f0e1d2SKirill A. Shutemov  *  - if replacing failed;
1879a2e17cc2SDavid Stevens  *    + unlock old pages
188087c460a0SHugh Dickins  *    + unlock and free huge page;
1881f3f0e1d2SKirill A. Shutemov  */
collapse_file(struct mm_struct * mm,unsigned long addr,struct file * file,pgoff_t start,struct collapse_control * cc)188240bd4ff0SShivank Garg static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
188340bd4ff0SShivank Garg 		struct file *file, pgoff_t start, struct collapse_control *cc)
1884f3f0e1d2SKirill A. Shutemov {
1885579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
18868d1e24c0SMatthew Wilcox (Oracle) 	struct page *dst;
18878d1e24c0SMatthew Wilcox (Oracle) 	struct folio *folio, *tmp, *new_folio;
18884c9473e8SGautam Menghani 	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1889f3f0e1d2SKirill A. Shutemov 	LIST_HEAD(pagelist);
189077da9389SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
189140bd4ff0SShivank Garg 	enum scan_result result = SCAN_SUCCEED;
189240bd4ff0SShivank Garg 	int nr_none = 0;
189399cb0dbdSSong Liu 	bool is_shmem = shmem_file(file);
1894f3f0e1d2SKirill A. Shutemov 
189599cb0dbdSSong Liu 	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1896f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1897f3f0e1d2SKirill A. Shutemov 
1898d5ab50b9SMatthew Wilcox (Oracle) 	result = alloc_charge_folio(&new_folio, mm, cc);
18999710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1900f3f0e1d2SKirill A. Shutemov 		goto out;
1901f3f0e1d2SKirill A. Shutemov 
190262e72d2cSKairui Song 	mapping_set_update(&xas, mapping);
190362e72d2cSKairui Song 
1904610ff817SMatthew Wilcox (Oracle) 	__folio_set_locked(new_folio);
1905cae106ddSDavid Stevens 	if (is_shmem)
1906610ff817SMatthew Wilcox (Oracle) 		__folio_set_swapbacked(new_folio);
1907610ff817SMatthew Wilcox (Oracle) 	new_folio->index = start;
1908610ff817SMatthew Wilcox (Oracle) 	new_folio->mapping = mapping;
1909cae106ddSDavid Stevens 
19106b24ca4aSMatthew Wilcox (Oracle) 	/*
19116b24ca4aSMatthew Wilcox (Oracle) 	 * Ensure we have slots for all the pages in the range.  This is
19126b24ca4aSMatthew Wilcox (Oracle) 	 * almost certainly a no-op because most of the pages must be present
19136b24ca4aSMatthew Wilcox (Oracle) 	 */
191495feeabbSHugh Dickins 	do {
191595feeabbSHugh Dickins 		xas_lock_irq(&xas);
191695feeabbSHugh Dickins 		xas_create_range(&xas);
191795feeabbSHugh Dickins 		if (!xas_error(&xas))
191895feeabbSHugh Dickins 			break;
191995feeabbSHugh Dickins 		xas_unlock_irq(&xas);
192095feeabbSHugh Dickins 		if (!xas_nomem(&xas, GFP_KERNEL)) {
192195feeabbSHugh Dickins 			result = SCAN_FAIL;
1922cae106ddSDavid Stevens 			goto rollback;
192395feeabbSHugh Dickins 		}
192495feeabbSHugh Dickins 	} while (1);
192595feeabbSHugh Dickins 
19267de856ffSBaolin Wang 	for (index = start; index < end;) {
1927e8c716bcSHugh Dickins 		xas_set(&xas, index);
19288d1e24c0SMatthew Wilcox (Oracle) 		folio = xas_load(&xas);
192977da9389SMatthew Wilcox 
193077da9389SMatthew Wilcox 		VM_BUG_ON(index != xas.xa_index);
193199cb0dbdSSong Liu 		if (is_shmem) {
19328d1e24c0SMatthew Wilcox (Oracle) 			if (!folio) {
1933701270faSHugh Dickins 				/*
193499cb0dbdSSong Liu 				 * Stop if extent has been truncated or
193599cb0dbdSSong Liu 				 * hole-punched, and is now completely
193699cb0dbdSSong Liu 				 * empty.
1937701270faSHugh Dickins 				 */
1938701270faSHugh Dickins 				if (index == start) {
1939701270faSHugh Dickins 					if (!xas_next_entry(&xas, end - 1)) {
1940701270faSHugh Dickins 						result = SCAN_TRUNCATED;
1941042a3082SHugh Dickins 						goto xa_locked;
1942701270faSHugh Dickins 					}
1943701270faSHugh Dickins 				}
194477da9389SMatthew Wilcox 				nr_none++;
19457de856ffSBaolin Wang 				index++;
194677da9389SMatthew Wilcox 				continue;
1947f3f0e1d2SKirill A. Shutemov 			}
1948f3f0e1d2SKirill A. Shutemov 
19498d1e24c0SMatthew Wilcox (Oracle) 			if (xa_is_value(folio) || !folio_test_uptodate(folio)) {
195077da9389SMatthew Wilcox 				xas_unlock_irq(&xas);
1951f3f0e1d2SKirill A. Shutemov 				/* swap in or instantiate fallocated page */
1952e1e4cfd0SRik van Riel 				if (shmem_get_folio(mapping->host, index, 0,
19537459c149SMatthew Wilcox (Oracle) 						&folio, SGP_NOALLOC)) {
1954f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
195577da9389SMatthew Wilcox 					goto xa_unlocked;
1956f3f0e1d2SKirill A. Shutemov 				}
1957775d28fdSKefeng Wang 				/* drain lru cache to help folio_isolate_lru() */
1958efa3d814SDavid Stevens 				lru_add_drain();
19598d1e24c0SMatthew Wilcox (Oracle) 			} else if (folio_trylock(folio)) {
19608d1e24c0SMatthew Wilcox (Oracle) 				folio_get(folio);
1961042a3082SHugh Dickins 				xas_unlock_irq(&xas);
1962f3f0e1d2SKirill A. Shutemov 			} else {
1963f3f0e1d2SKirill A. Shutemov 				result = SCAN_PAGE_LOCK;
1964042a3082SHugh Dickins 				goto xa_locked;
1965f3f0e1d2SKirill A. Shutemov 			}
196699cb0dbdSSong Liu 		} else {	/* !is_shmem */
19678d1e24c0SMatthew Wilcox (Oracle) 			if (!folio || xa_is_value(folio)) {
196899cb0dbdSSong Liu 				xas_unlock_irq(&xas);
196999cb0dbdSSong Liu 				page_cache_sync_readahead(mapping, &file->f_ra,
197099cb0dbdSSong Liu 							  file, index,
1971e5a59d30SDavid Howells 							  end - index);
1972775d28fdSKefeng Wang 				/* drain lru cache to help folio_isolate_lru() */
197399cb0dbdSSong Liu 				lru_add_drain();
19748d1e24c0SMatthew Wilcox (Oracle) 				folio = filemap_lock_folio(mapping, index);
19758d1e24c0SMatthew Wilcox (Oracle) 				if (IS_ERR(folio)) {
197699cb0dbdSSong Liu 					result = SCAN_FAIL;
197799cb0dbdSSong Liu 					goto xa_unlocked;
197899cb0dbdSSong Liu 				}
19798d1e24c0SMatthew Wilcox (Oracle) 			} else if (folio_test_dirty(folio)) {
198075f36069SSong Liu 				/*
198175f36069SSong Liu 				 * khugepaged only works on read-only fd,
198275f36069SSong Liu 				 * so this page is dirty because it hasn't
198375f36069SSong Liu 				 * been flushed since first write. There
198475f36069SSong Liu 				 * won't be new dirty pages.
198575f36069SSong Liu 				 *
198675f36069SSong Liu 				 * Trigger async flush here and hope the
198775f36069SSong Liu 				 * writeback is done when khugepaged
198875f36069SSong Liu 				 * revisits this page.
198975f36069SSong Liu 				 *
199075f36069SSong Liu 				 * This is a one-off situation. We are not
199175f36069SSong Liu 				 * forcing writeback in loop.
199275f36069SSong Liu 				 */
199375f36069SSong Liu 				xas_unlock_irq(&xas);
199475f36069SSong Liu 				filemap_flush(mapping);
19955173ae0aSShivank Garg 				result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
199675f36069SSong Liu 				goto xa_unlocked;
19978d1e24c0SMatthew Wilcox (Oracle) 			} else if (folio_test_writeback(folio)) {
199874c42e1bSRongwei Wang 				xas_unlock_irq(&xas);
19995173ae0aSShivank Garg 				result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
200074c42e1bSRongwei Wang 				goto xa_unlocked;
20018d1e24c0SMatthew Wilcox (Oracle) 			} else if (folio_trylock(folio)) {
20028d1e24c0SMatthew Wilcox (Oracle) 				folio_get(folio);
200399cb0dbdSSong Liu 				xas_unlock_irq(&xas);
200499cb0dbdSSong Liu 			} else {
200599cb0dbdSSong Liu 				result = SCAN_PAGE_LOCK;
200699cb0dbdSSong Liu 				goto xa_locked;
200799cb0dbdSSong Liu 			}
200899cb0dbdSSong Liu 		}
2009f3f0e1d2SKirill A. Shutemov 
2010f3f0e1d2SKirill A. Shutemov 		/*
20118d1e24c0SMatthew Wilcox (Oracle) 		 * The folio must be locked, so we can drop the i_pages lock
2012f3f0e1d2SKirill A. Shutemov 		 * without racing with truncate.
2013f3f0e1d2SKirill A. Shutemov 		 */
20148d1e24c0SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
20154655e5e5SSong Liu 
20168d1e24c0SMatthew Wilcox (Oracle) 		/* make sure the folio is up to date */
20178d1e24c0SMatthew Wilcox (Oracle) 		if (unlikely(!folio_test_uptodate(folio))) {
20184655e5e5SSong Liu 			result = SCAN_FAIL;
20194655e5e5SSong Liu 			goto out_unlock;
20204655e5e5SSong Liu 		}
202106a5e126SHugh Dickins 
202206a5e126SHugh Dickins 		/*
202306a5e126SHugh Dickins 		 * If file was truncated then extended, or hole-punched, before
20248d1e24c0SMatthew Wilcox (Oracle) 		 * we locked the first folio, then a THP might be there already.
202558ac9a89SZach O'Keefe 		 * This will be discovered on the first iteration.
202606a5e126SHugh Dickins 		 */
2027b90c453dSNico Pache 		if (is_pmd_order(folio_order(folio))) {
20287de856ffSBaolin Wang 			result = SCAN_PTE_MAPPED_HUGEPAGE;
202906a5e126SHugh Dickins 			goto out_unlock;
203006a5e126SHugh Dickins 		}
2031f3f0e1d2SKirill A. Shutemov 
203264ab3195SVishal Moola (Oracle) 		if (folio_mapping(folio) != mapping) {
2033f3f0e1d2SKirill A. Shutemov 			result = SCAN_TRUNCATED;
2034f3f0e1d2SKirill A. Shutemov 			goto out_unlock;
2035f3f0e1d2SKirill A. Shutemov 		}
2036f3f0e1d2SKirill A. Shutemov 
203764ab3195SVishal Moola (Oracle) 		if (!is_shmem && (folio_test_dirty(folio) ||
203864ab3195SVishal Moola (Oracle) 				  folio_test_writeback(folio))) {
20394655e5e5SSong Liu 			/*
20404655e5e5SSong Liu 			 * khugepaged only works on read-only fd, so this
20418d1e24c0SMatthew Wilcox (Oracle) 			 * folio is dirty because it hasn't been flushed
20424655e5e5SSong Liu 			 * since first write.
20434655e5e5SSong Liu 			 */
20445173ae0aSShivank Garg 			result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
20454655e5e5SSong Liu 			goto out_unlock;
20464655e5e5SSong Liu 		}
20474655e5e5SSong Liu 
2048be2d5756SBaolin Wang 		if (!folio_isolate_lru(folio)) {
2049f3f0e1d2SKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
2050042a3082SHugh Dickins 			goto out_unlock;
2051f3f0e1d2SKirill A. Shutemov 		}
2052f3f0e1d2SKirill A. Shutemov 
20530201ebf2SDavid Howells 		if (!filemap_release_folio(folio, GFP_KERNEL)) {
205499cb0dbdSSong Liu 			result = SCAN_PAGE_HAS_PRIVATE;
205564ab3195SVishal Moola (Oracle) 			folio_putback_lru(folio);
205699cb0dbdSSong Liu 			goto out_unlock;
205799cb0dbdSSong Liu 		}
205899cb0dbdSSong Liu 
205964ab3195SVishal Moola (Oracle) 		if (folio_mapped(folio))
206064ab3195SVishal Moola (Oracle) 			try_to_unmap(folio,
2061869f7ee6SMatthew Wilcox (Oracle) 					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
2062f3f0e1d2SKirill A. Shutemov 
206377da9389SMatthew Wilcox 		xas_lock_irq(&xas);
2064f3f0e1d2SKirill A. Shutemov 
20658d1e24c0SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio);
2066f3f0e1d2SKirill A. Shutemov 
2067f3f0e1d2SKirill A. Shutemov 		/*
2068d6b8f296SBaolin Wang 		 * We control 2 + nr_pages references to the folio:
2069f3f0e1d2SKirill A. Shutemov 		 *  - we hold a pin on it;
2070d6b8f296SBaolin Wang 		 *  - nr_pages reference from page cache;
20718d1e24c0SMatthew Wilcox (Oracle) 		 *  - one from lru_isolate_folio;
20728d1e24c0SMatthew Wilcox (Oracle) 		 * If those are the only references, then any new usage
20738d1e24c0SMatthew Wilcox (Oracle) 		 * of the folio will have to fetch it from the page
20748d1e24c0SMatthew Wilcox (Oracle) 		 * cache. That requires locking the folio to handle
20758d1e24c0SMatthew Wilcox (Oracle) 		 * truncate, so any new usage will be blocked until we
20768d1e24c0SMatthew Wilcox (Oracle) 		 * unlock folio after collapse/during rollback.
2077f3f0e1d2SKirill A. Shutemov 		 */
2078d6b8f296SBaolin Wang 		if (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) {
2079f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
2080042a3082SHugh Dickins 			xas_unlock_irq(&xas);
20818d1e24c0SMatthew Wilcox (Oracle) 			folio_putback_lru(folio);
2082042a3082SHugh Dickins 			goto out_unlock;
2083f3f0e1d2SKirill A. Shutemov 		}
2084f3f0e1d2SKirill A. Shutemov 
2085f3f0e1d2SKirill A. Shutemov 		/*
20868d1e24c0SMatthew Wilcox (Oracle) 		 * Accumulate the folios that are being collapsed.
2087f3f0e1d2SKirill A. Shutemov 		 */
20888d1e24c0SMatthew Wilcox (Oracle) 		list_add_tail(&folio->lru, &pagelist);
20897de856ffSBaolin Wang 		index += folio_nr_pages(folio);
2090f3f0e1d2SKirill A. Shutemov 		continue;
2091f3f0e1d2SKirill A. Shutemov out_unlock:
20928d1e24c0SMatthew Wilcox (Oracle) 		folio_unlock(folio);
20938d1e24c0SMatthew Wilcox (Oracle) 		folio_put(folio);
2094042a3082SHugh Dickins 		goto xa_unlocked;
2095f3f0e1d2SKirill A. Shutemov 	}
2096f3f0e1d2SKirill A. Shutemov 
209712904d95SJiaqi Yan 	if (!is_shmem) {
209809d91cdaSSong Liu 		filemap_nr_thps_inc(mapping);
2099eb6ecbedSCollin Fijalkovich 		/*
21008e344782SMateusz Guzik 		 * Paired with the fence in do_dentry_open() -> get_write_access()
21018e344782SMateusz Guzik 		 * to ensure i_writecount is up to date and the update to nr_thps
21028e344782SMateusz Guzik 		 * is visible. Ensures the page cache will be truncated if the
2103eb6ecbedSCollin Fijalkovich 		 * file is opened writable.
2104eb6ecbedSCollin Fijalkovich 		 */
2105eb6ecbedSCollin Fijalkovich 		smp_mb();
2106eb6ecbedSCollin Fijalkovich 		if (inode_is_open_for_write(mapping->host)) {
2107eb6ecbedSCollin Fijalkovich 			result = SCAN_FAIL;
2108eb6ecbedSCollin Fijalkovich 			filemap_nr_thps_dec(mapping);
2109eb6ecbedSCollin Fijalkovich 		}
211009d91cdaSSong Liu 	}
211199cb0dbdSSong Liu 
2112042a3082SHugh Dickins xa_locked:
2113042a3082SHugh Dickins 	xas_unlock_irq(&xas);
211477da9389SMatthew Wilcox xa_unlocked:
2115042a3082SHugh Dickins 
21166d9df8a5SHugh Dickins 	/*
21176d9df8a5SHugh Dickins 	 * If collapse is successful, flush must be done now before copying.
21186d9df8a5SHugh Dickins 	 * If collapse is unsuccessful, does flush actually need to be done?
21196d9df8a5SHugh Dickins 	 * Do it anyway, to clear the state.
21206d9df8a5SHugh Dickins 	 */
21216d9df8a5SHugh Dickins 	try_to_unmap_flush();
21226d9df8a5SHugh Dickins 
2123509f0069SHugh Dickins 	if (result == SCAN_SUCCEED && nr_none &&
2124509f0069SHugh Dickins 	    !shmem_charge(mapping->host, nr_none))
2125509f0069SHugh Dickins 		result = SCAN_FAIL;
2126509f0069SHugh Dickins 	if (result != SCAN_SUCCEED) {
2127509f0069SHugh Dickins 		nr_none = 0;
2128cae106ddSDavid Stevens 		goto rollback;
2129509f0069SHugh Dickins 	}
2130cae106ddSDavid Stevens 
2131f3f0e1d2SKirill A. Shutemov 	/*
21328d1e24c0SMatthew Wilcox (Oracle) 	 * The old folios are locked, so they won't change anymore.
2133f3f0e1d2SKirill A. Shutemov 	 */
21342af8ff29SHugh Dickins 	index = start;
2135610ff817SMatthew Wilcox (Oracle) 	dst = folio_page(new_folio, 0);
21368d1e24c0SMatthew Wilcox (Oracle) 	list_for_each_entry(folio, &pagelist, lru) {
2137dfa98f56SBaolin Wang 		int i, nr_pages = folio_nr_pages(folio);
2138dfa98f56SBaolin Wang 
21398d1e24c0SMatthew Wilcox (Oracle) 		while (index < folio->index) {
2140610ff817SMatthew Wilcox (Oracle) 			clear_highpage(dst);
21412af8ff29SHugh Dickins 			index++;
2142610ff817SMatthew Wilcox (Oracle) 			dst++;
21432af8ff29SHugh Dickins 		}
2144dfa98f56SBaolin Wang 
2145dfa98f56SBaolin Wang 		for (i = 0; i < nr_pages; i++) {
2146dfa98f56SBaolin Wang 			if (copy_mc_highpage(dst, folio_page(folio, i)) > 0) {
214712904d95SJiaqi Yan 				result = SCAN_COPY_MC;
2148cae106ddSDavid Stevens 				goto rollback;
214912904d95SJiaqi Yan 			}
215012904d95SJiaqi Yan 			index++;
2151610ff817SMatthew Wilcox (Oracle) 			dst++;
215212904d95SJiaqi Yan 		}
2153dfa98f56SBaolin Wang 	}
2154cae106ddSDavid Stevens 	while (index < end) {
2155610ff817SMatthew Wilcox (Oracle) 		clear_highpage(dst);
215612904d95SJiaqi Yan 		index++;
2157610ff817SMatthew Wilcox (Oracle) 		dst++;
215812904d95SJiaqi Yan 	}
215912904d95SJiaqi Yan 
2160ac492b9cSDavid Stevens 	if (nr_none) {
2161ac492b9cSDavid Stevens 		struct vm_area_struct *vma;
2162ac492b9cSDavid Stevens 		int nr_none_check = 0;
2163ac492b9cSDavid Stevens 
2164ac492b9cSDavid Stevens 		i_mmap_lock_read(mapping);
2165ac492b9cSDavid Stevens 		xas_lock_irq(&xas);
2166ac492b9cSDavid Stevens 
2167ac492b9cSDavid Stevens 		xas_set(&xas, start);
2168ac492b9cSDavid Stevens 		for (index = start; index < end; index++) {
2169ac492b9cSDavid Stevens 			if (!xas_next(&xas)) {
2170ac492b9cSDavid Stevens 				xas_store(&xas, XA_RETRY_ENTRY);
2171ac492b9cSDavid Stevens 				if (xas_error(&xas)) {
2172ac492b9cSDavid Stevens 					result = SCAN_STORE_FAILED;
2173ac492b9cSDavid Stevens 					goto immap_locked;
2174ac492b9cSDavid Stevens 				}
2175ac492b9cSDavid Stevens 				nr_none_check++;
2176ac492b9cSDavid Stevens 			}
2177ac492b9cSDavid Stevens 		}
2178ac492b9cSDavid Stevens 
2179ac492b9cSDavid Stevens 		if (nr_none != nr_none_check) {
2180ac492b9cSDavid Stevens 			result = SCAN_PAGE_FILLED;
2181ac492b9cSDavid Stevens 			goto immap_locked;
2182ac492b9cSDavid Stevens 		}
2183ac492b9cSDavid Stevens 
218412904d95SJiaqi Yan 		/*
2185610ff817SMatthew Wilcox (Oracle) 		 * If userspace observed a missing page in a VMA with
2186610ff817SMatthew Wilcox (Oracle) 		 * a MODE_MISSING userfaultfd, then it might expect a
2187610ff817SMatthew Wilcox (Oracle) 		 * UFFD_EVENT_PAGEFAULT for that page. If so, we need to
2188610ff817SMatthew Wilcox (Oracle) 		 * roll back to avoid suppressing such an event. Since
2189610ff817SMatthew Wilcox (Oracle) 		 * wp/minor userfaultfds don't give userspace any
2190610ff817SMatthew Wilcox (Oracle) 		 * guarantees that the kernel doesn't fill a missing
2191610ff817SMatthew Wilcox (Oracle) 		 * page with a zero page, so they don't matter here.
2192ac492b9cSDavid Stevens 		 *
2193610ff817SMatthew Wilcox (Oracle) 		 * Any userfaultfds registered after this point will
2194610ff817SMatthew Wilcox (Oracle) 		 * not be able to observe any missing pages due to the
2195610ff817SMatthew Wilcox (Oracle) 		 * previously inserted retry entries.
219612904d95SJiaqi Yan 		 */
2197ac492b9cSDavid Stevens 		vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2198ac492b9cSDavid Stevens 			if (userfaultfd_missing(vma)) {
2199ac492b9cSDavid Stevens 				result = SCAN_EXCEED_NONE_PTE;
2200ac492b9cSDavid Stevens 				goto immap_locked;
2201ac492b9cSDavid Stevens 			}
2202ac492b9cSDavid Stevens 		}
2203ac492b9cSDavid Stevens 
2204ac492b9cSDavid Stevens immap_locked:
2205ac492b9cSDavid Stevens 		i_mmap_unlock_read(mapping);
2206ac492b9cSDavid Stevens 		if (result != SCAN_SUCCEED) {
2207ac492b9cSDavid Stevens 			xas_set(&xas, start);
2208ac492b9cSDavid Stevens 			for (index = start; index < end; index++) {
2209ac492b9cSDavid Stevens 				if (xas_next(&xas) == XA_RETRY_ENTRY)
2210ac492b9cSDavid Stevens 					xas_store(&xas, NULL);
2211ac492b9cSDavid Stevens 			}
2212ac492b9cSDavid Stevens 
2213ac492b9cSDavid Stevens 			xas_unlock_irq(&xas);
2214ac492b9cSDavid Stevens 			goto rollback;
2215ac492b9cSDavid Stevens 		}
2216ac492b9cSDavid Stevens 	} else {
2217ac492b9cSDavid Stevens 		xas_lock_irq(&xas);
22182af8ff29SHugh Dickins 	}
221912904d95SJiaqi Yan 
22204188b259SShakeel Butt 	if (is_shmem) {
22214188b259SShakeel Butt 		lruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR);
2222c1bd0999SShakeel Butt 		lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
22234188b259SShakeel Butt 	} else {
2224c1bd0999SShakeel Butt 		lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);
2225f3f0e1d2SKirill A. Shutemov 	}
22264188b259SShakeel Butt 	lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR);
2227f3f0e1d2SKirill A. Shutemov 
2228a2e17cc2SDavid Stevens 	/*
2229610ff817SMatthew Wilcox (Oracle) 	 * Mark new_folio as uptodate before inserting it into the
2230610ff817SMatthew Wilcox (Oracle) 	 * page cache so that it isn't mistaken for an fallocated but
2231610ff817SMatthew Wilcox (Oracle) 	 * unwritten page.
2232a2e17cc2SDavid Stevens 	 */
2233610ff817SMatthew Wilcox (Oracle) 	folio_mark_uptodate(new_folio);
2234610ff817SMatthew Wilcox (Oracle) 	folio_ref_add(new_folio, HPAGE_PMD_NR - 1);
2235284a344eSVishal Moola (Oracle) 
22366058eaecSJohannes Weiner 	if (is_shmem)
2237610ff817SMatthew Wilcox (Oracle) 		folio_mark_dirty(new_folio);
2238610ff817SMatthew Wilcox (Oracle) 	folio_add_lru(new_folio);
2239f3f0e1d2SKirill A. Shutemov 
2240a2e17cc2SDavid Stevens 	/* Join all the small entries into a single multi-index entry. */
2241a2e17cc2SDavid Stevens 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2242610ff817SMatthew Wilcox (Oracle) 	xas_store(&xas, new_folio);
22430175ab61SHugh Dickins 	WARN_ON_ONCE(xas_error(&xas));
2244a2e17cc2SDavid Stevens 	xas_unlock_irq(&xas);
2245a2e17cc2SDavid Stevens 
2246042a3082SHugh Dickins 	/*
2247042a3082SHugh Dickins 	 * Remove pte page tables, so we can re-fault the page as huge.
22483ab981c1SShivank Garg 	 * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp().
2249042a3082SHugh Dickins 	 */
22501d65b771SHugh Dickins 	retract_page_tables(mapping, start);
22511d65b771SHugh Dickins 	if (cc && !cc->is_khugepaged)
22521d65b771SHugh Dickins 		result = SCAN_PTE_MAPPED_HUGEPAGE;
2253610ff817SMatthew Wilcox (Oracle) 	folio_unlock(new_folio);
2254ac492b9cSDavid Stevens 
2255ac492b9cSDavid Stevens 	/*
22568d1e24c0SMatthew Wilcox (Oracle) 	 * The collapse has succeeded, so free the old folios.
2257ac492b9cSDavid Stevens 	 */
22588d1e24c0SMatthew Wilcox (Oracle) 	list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
22598d1e24c0SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
22604188b259SShakeel Butt 		lruvec_stat_mod_folio(folio, NR_FILE_PAGES,
22614188b259SShakeel Butt 				      -folio_nr_pages(folio));
22624188b259SShakeel Butt 		if (is_shmem)
22634188b259SShakeel Butt 			lruvec_stat_mod_folio(folio, NR_SHMEM,
22644188b259SShakeel Butt 					      -folio_nr_pages(folio));
22658d1e24c0SMatthew Wilcox (Oracle) 		folio->mapping = NULL;
22668d1e24c0SMatthew Wilcox (Oracle) 		folio_clear_active(folio);
22678d1e24c0SMatthew Wilcox (Oracle) 		folio_clear_unevictable(folio);
22688d1e24c0SMatthew Wilcox (Oracle) 		folio_unlock(folio);
2269d6b8f296SBaolin Wang 		folio_put_refs(folio, 2 + folio_nr_pages(folio));
2270ac492b9cSDavid Stevens 	}
2271ac492b9cSDavid Stevens 
2272cae106ddSDavid Stevens 	goto out;
2273cae106ddSDavid Stevens 
2274cae106ddSDavid Stevens rollback:
227577da9389SMatthew Wilcox 	/* Something went wrong: roll back page cache changes */
22762f55f070SMiaohe Lin 	if (nr_none) {
2277a2e17cc2SDavid Stevens 		xas_lock_irq(&xas);
2278aaa52e34SHugh Dickins 		mapping->nrpages -= nr_none;
227977da9389SMatthew Wilcox 		xas_unlock_irq(&xas);
2280509f0069SHugh Dickins 		shmem_uncharge(mapping->host, nr_none);
2281a2e17cc2SDavid Stevens 	}
2282a2e17cc2SDavid Stevens 
22838d1e24c0SMatthew Wilcox (Oracle) 	list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
22848d1e24c0SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
22858d1e24c0SMatthew Wilcox (Oracle) 		folio_unlock(folio);
22868d1e24c0SMatthew Wilcox (Oracle) 		folio_putback_lru(folio);
22878d1e24c0SMatthew Wilcox (Oracle) 		folio_put(folio);
2288f3f0e1d2SKirill A. Shutemov 	}
228912904d95SJiaqi Yan 	/*
229012904d95SJiaqi Yan 	 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
229112904d95SJiaqi Yan 	 * file only. This undo is not needed unless failure is
229212904d95SJiaqi Yan 	 * due to SCAN_COPY_MC.
229312904d95SJiaqi Yan 	 */
229412904d95SJiaqi Yan 	if (!is_shmem && result == SCAN_COPY_MC) {
229512904d95SJiaqi Yan 		filemap_nr_thps_dec(mapping);
229612904d95SJiaqi Yan 		/*
22978e344782SMateusz Guzik 		 * Paired with the fence in do_dentry_open() -> get_write_access()
22988e344782SMateusz Guzik 		 * to ensure the update to nr_thps is visible.
229912904d95SJiaqi Yan 		 */
230012904d95SJiaqi Yan 		smp_mb();
230112904d95SJiaqi Yan 	}
230212904d95SJiaqi Yan 
2303610ff817SMatthew Wilcox (Oracle) 	new_folio->mapping = NULL;
2304042a3082SHugh Dickins 
2305610ff817SMatthew Wilcox (Oracle) 	folio_unlock(new_folio);
2306610ff817SMatthew Wilcox (Oracle) 	folio_put(new_folio);
2307f3f0e1d2SKirill A. Shutemov out:
2308f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(!list_empty(&pagelist));
230937f0b47cSYang Shi 	trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
231050ad2f24SZach O'Keefe 	return result;
2311f3f0e1d2SKirill A. Shutemov }
2312f3f0e1d2SKirill A. Shutemov 
collapse_scan_file(struct mm_struct * mm,unsigned long addr,struct file * file,pgoff_t start,struct collapse_control * cc)2313ff7e03a8SNico Pache static enum scan_result collapse_scan_file(struct mm_struct *mm,
2314eeeb79d5SVernon Yang 		unsigned long addr, struct file *file, pgoff_t start,
231534c1f77eSVernon Yang 		struct collapse_control *cc)
2316f3f0e1d2SKirill A. Shutemov {
231743849758SMatthew Wilcox (Oracle) 	struct folio *folio = NULL;
2318579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
231985b392dbSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
2320f3f0e1d2SKirill A. Shutemov 	int present, swap;
2321f3f0e1d2SKirill A. Shutemov 	int node = NUMA_NO_NODE;
232240bd4ff0SShivank Garg 	enum scan_result result = SCAN_SUCCEED;
2323f3f0e1d2SKirill A. Shutemov 
2324f3f0e1d2SKirill A. Shutemov 	present = 0;
2325f3f0e1d2SKirill A. Shutemov 	swap = 0;
232634d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
2327e031ff96SYang Shi 	nodes_clear(cc->alloc_nmask);
2328f3f0e1d2SKirill A. Shutemov 	rcu_read_lock();
232943849758SMatthew Wilcox (Oracle) 	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
233043849758SMatthew Wilcox (Oracle) 		if (xas_retry(&xas, folio))
2331f3f0e1d2SKirill A. Shutemov 			continue;
2332f3f0e1d2SKirill A. Shutemov 
233343849758SMatthew Wilcox (Oracle) 		if (xa_is_value(folio)) {
2334d60fcaf0SBaolin Wang 			swap += 1 << xas_get_order(&xas);
2335d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
2336d8ea7cc8SZach O'Keefe 			    swap > khugepaged_max_ptes_swap) {
2337f3f0e1d2SKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
2338e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2339f3f0e1d2SKirill A. Shutemov 				break;
2340f3f0e1d2SKirill A. Shutemov 			}
2341f3f0e1d2SKirill A. Shutemov 			continue;
2342f3f0e1d2SKirill A. Shutemov 		}
2343f3f0e1d2SKirill A. Shutemov 
2344595cf683SShivank Garg 		if (!folio_try_get(folio)) {
2345595cf683SShivank Garg 			xas_reset(&xas);
2346595cf683SShivank Garg 			continue;
2347595cf683SShivank Garg 		}
2348595cf683SShivank Garg 
2349595cf683SShivank Garg 		if (unlikely(folio != xas_reload(&xas))) {
2350595cf683SShivank Garg 			folio_put(folio);
2351595cf683SShivank Garg 			xas_reset(&xas);
2352595cf683SShivank Garg 			continue;
2353595cf683SShivank Garg 		}
2354595cf683SShivank Garg 
2355b90c453dSNico Pache 		if (is_pmd_order(folio_order(folio))) {
23567de856ffSBaolin Wang 			result = SCAN_PTE_MAPPED_HUGEPAGE;
235758ac9a89SZach O'Keefe 			/*
235822aa3321SDev Jain 			 * PMD-sized THP implies that we can only try
235922aa3321SDev Jain 			 * retracting the PTE table.
236058ac9a89SZach O'Keefe 			 */
2361595cf683SShivank Garg 			folio_put(folio);
2362f3f0e1d2SKirill A. Shutemov 			break;
2363f3f0e1d2SKirill A. Shutemov 		}
2364f3f0e1d2SKirill A. Shutemov 
236543849758SMatthew Wilcox (Oracle) 		node = folio_nid(folio);
2366ff7e03a8SNico Pache 		if (collapse_scan_abort(node, cc)) {
2367f3f0e1d2SKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
2368595cf683SShivank Garg 			folio_put(folio);
2369f3f0e1d2SKirill A. Shutemov 			break;
2370f3f0e1d2SKirill A. Shutemov 		}
237134d6b470SZach O'Keefe 		cc->node_load[node]++;
2372f3f0e1d2SKirill A. Shutemov 
237343849758SMatthew Wilcox (Oracle) 		if (!folio_test_lru(folio)) {
2374f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_LRU;
2375595cf683SShivank Garg 			folio_put(folio);
2376f3f0e1d2SKirill A. Shutemov 			break;
2377f3f0e1d2SKirill A. Shutemov 		}
2378f3f0e1d2SKirill A. Shutemov 
2379595cf683SShivank Garg 		if (folio_expected_ref_count(folio) + 1 != folio_ref_count(folio)) {
2380f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
2381595cf683SShivank Garg 			folio_put(folio);
2382f3f0e1d2SKirill A. Shutemov 			break;
2383f3f0e1d2SKirill A. Shutemov 		}
2384f3f0e1d2SKirill A. Shutemov 
2385f3f0e1d2SKirill A. Shutemov 		/*
238643849758SMatthew Wilcox (Oracle) 		 * We probably should check if the folio is referenced
238743849758SMatthew Wilcox (Oracle) 		 * here, but nobody would transfer pte_young() to
238843849758SMatthew Wilcox (Oracle) 		 * folio_test_referenced() for us.  And rmap walk here
238943849758SMatthew Wilcox (Oracle) 		 * is just too costly...
2390f3f0e1d2SKirill A. Shutemov 		 */
2391f3f0e1d2SKirill A. Shutemov 
2392d60fcaf0SBaolin Wang 		present += folio_nr_pages(folio);
2393595cf683SShivank Garg 		folio_put(folio);
2394f3f0e1d2SKirill A. Shutemov 
2395f3f0e1d2SKirill A. Shutemov 		if (need_resched()) {
239685b392dbSMatthew Wilcox 			xas_pause(&xas);
2397f3f0e1d2SKirill A. Shutemov 			cond_resched_rcu();
2398f3f0e1d2SKirill A. Shutemov 		}
2399f3f0e1d2SKirill A. Shutemov 	}
2400f3f0e1d2SKirill A. Shutemov 	rcu_read_unlock();
2401eeeb79d5SVernon Yang 	if (result == SCAN_PTE_MAPPED_HUGEPAGE)
240234c1f77eSVernon Yang 		cc->progress++;
2403eeeb79d5SVernon Yang 	else
240434c1f77eSVernon Yang 		cc->progress += HPAGE_PMD_NR;
2405f3f0e1d2SKirill A. Shutemov 
2406f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
2407d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
2408d8ea7cc8SZach O'Keefe 		    present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2409f3f0e1d2SKirill A. Shutemov 			result = SCAN_EXCEED_NONE_PTE;
2410e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2411f3f0e1d2SKirill A. Shutemov 		} else {
241234488399SZach O'Keefe 			result = collapse_file(mm, addr, file, start, cc);
2413f3f0e1d2SKirill A. Shutemov 		}
2414f3f0e1d2SKirill A. Shutemov 	}
2415f3f0e1d2SKirill A. Shutemov 
241643849758SMatthew Wilcox (Oracle) 	trace_mm_khugepaged_scan_file(mm, folio, file, present, swap, result);
241750ad2f24SZach O'Keefe 	return result;
2418f3f0e1d2SKirill A. Shutemov }
2419f3f0e1d2SKirill A. Shutemov 
2420a155d945SNico Pache /*
2421a155d945SNico Pache  * Try to collapse a single PMD starting at a PMD aligned addr, and return
2422a155d945SNico Pache  * the results.
2423a155d945SNico Pache  */
collapse_single_pmd(unsigned long addr,struct vm_area_struct * vma,bool * lock_dropped,struct collapse_control * cc)2424a155d945SNico Pache static enum scan_result collapse_single_pmd(unsigned long addr,
2425a155d945SNico Pache 		struct vm_area_struct *vma, bool *lock_dropped,
2426a155d945SNico Pache 		struct collapse_control *cc)
2427a155d945SNico Pache {
2428a155d945SNico Pache 	struct mm_struct *mm = vma->vm_mm;
2429a155d945SNico Pache 	bool triggered_wb = false;
2430a155d945SNico Pache 	enum scan_result result;
2431a155d945SNico Pache 	struct file *file;
2432a155d945SNico Pache 	pgoff_t pgoff;
2433a155d945SNico Pache 
2434a155d945SNico Pache 	mmap_assert_locked(mm);
2435a155d945SNico Pache 
2436a155d945SNico Pache 	if (vma_is_anonymous(vma)) {
2437a155d945SNico Pache 		result = collapse_scan_pmd(mm, vma, addr, lock_dropped, cc);
2438a155d945SNico Pache 		goto end;
2439a155d945SNico Pache 	}
2440a155d945SNico Pache 
2441a155d945SNico Pache 	file = get_file(vma->vm_file);
2442a155d945SNico Pache 	pgoff = linear_page_index(vma, addr);
2443a155d945SNico Pache 
2444a155d945SNico Pache 	mmap_read_unlock(mm);
2445a155d945SNico Pache 	*lock_dropped = true;
2446a155d945SNico Pache retry:
2447a155d945SNico Pache 	result = collapse_scan_file(mm, addr, file, pgoff, cc);
2448a155d945SNico Pache 
2449a155d945SNico Pache 	/*
2450a155d945SNico Pache 	 * For MADV_COLLAPSE, when encountering dirty pages, try to writeback,
2451a155d945SNico Pache 	 * then retry the collapse one time.
2452a155d945SNico Pache 	 */
2453a155d945SNico Pache 	if (!cc->is_khugepaged && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
2454a155d945SNico Pache 	    !triggered_wb && mapping_can_writeback(file->f_mapping)) {
2455a155d945SNico Pache 		const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT;
2456a155d945SNico Pache 		const loff_t lend = lstart + HPAGE_PMD_SIZE - 1;
2457a155d945SNico Pache 
2458a155d945SNico Pache 		filemap_write_and_wait_range(file->f_mapping, lstart, lend);
2459a155d945SNico Pache 		triggered_wb = true;
2460a155d945SNico Pache 		goto retry;
2461a155d945SNico Pache 	}
2462a155d945SNico Pache 	fput(file);
2463a155d945SNico Pache 
2464a155d945SNico Pache 	if (result == SCAN_PTE_MAPPED_HUGEPAGE) {
2465a155d945SNico Pache 		mmap_read_lock(mm);
2466a155d945SNico Pache 		if (collapse_test_exit_or_disable(mm))
2467a155d945SNico Pache 			result = SCAN_ANY_PROCESS;
2468a155d945SNico Pache 		else
2469a155d945SNico Pache 			result = try_collapse_pte_mapped_thp(mm, addr,
2470a155d945SNico Pache 							     !cc->is_khugepaged);
2471a155d945SNico Pache 		if (result == SCAN_PMD_MAPPED)
2472a155d945SNico Pache 			result = SCAN_SUCCEED;
2473a155d945SNico Pache 		mmap_read_unlock(mm);
2474a155d945SNico Pache 	}
2475a155d945SNico Pache end:
2476a155d945SNico Pache 	if (cc->is_khugepaged && result == SCAN_SUCCEED)
2477a155d945SNico Pache 		++khugepaged_pages_collapsed;
2478a155d945SNico Pache 	return result;
2479a155d945SNico Pache }
2480a155d945SNico Pache 
collapse_scan_mm_slot(unsigned int progress_max,enum scan_result * result,struct collapse_control * cc)2481ff7e03a8SNico Pache static void collapse_scan_mm_slot(unsigned int progress_max,
248234c1f77eSVernon Yang 		enum scan_result *result, struct collapse_control *cc)
2483b46e756fSKirill A. Shutemov 	__releases(&khugepaged_mm_lock)
2484b46e756fSKirill A. Shutemov 	__acquires(&khugepaged_mm_lock)
2485b46e756fSKirill A. Shutemov {
248668540502SMatthew Wilcox (Oracle) 	struct vma_iterator vmi;
2487b26e2701SQi Zheng 	struct mm_slot *slot;
2488b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
2489b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
249034c1f77eSVernon Yang 	unsigned int progress_prev = cc->progress;
2491b46e756fSKirill A. Shutemov 
249235f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
249350ad2f24SZach O'Keefe 	*result = SCAN_FAIL;
2494b46e756fSKirill A. Shutemov 
2495b26e2701SQi Zheng 	if (khugepaged_scan.mm_slot) {
2496b4c9ffb5SWei Yang 		slot = khugepaged_scan.mm_slot;
2497b26e2701SQi Zheng 	} else {
24983615e106SWei Yang 		slot = list_first_entry(&khugepaged_scan.mm_head,
2499b46e756fSKirill A. Shutemov 				     struct mm_slot, mm_node);
2500b46e756fSKirill A. Shutemov 		khugepaged_scan.address = 0;
2501b4c9ffb5SWei Yang 		khugepaged_scan.mm_slot = slot;
2502b46e756fSKirill A. Shutemov 	}
2503b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2504b46e756fSKirill A. Shutemov 
2505b26e2701SQi Zheng 	mm = slot->mm;
25063b454ad3SYang Shi 	/*
25073b454ad3SYang Shi 	 * Don't wait for semaphore (to avoid long wait times).  Just move to
25083b454ad3SYang Shi 	 * the next mm on the list.
25093b454ad3SYang Shi 	 */
2510b46e756fSKirill A. Shutemov 	vma = NULL;
2511d8ed45c5SMichel Lespinasse 	if (unlikely(!mmap_read_trylock(mm)))
2512c1e8d7c6SMichel Lespinasse 		goto breakouterloop_mmap_lock;
2513b46e756fSKirill A. Shutemov 
251434c1f77eSVernon Yang 	cc->progress++;
2515ff7e03a8SNico Pache 	if (unlikely(collapse_test_exit_or_disable(mm)))
251668540502SMatthew Wilcox (Oracle) 		goto breakouterloop;
251768540502SMatthew Wilcox (Oracle) 
251868540502SMatthew Wilcox (Oracle) 	vma_iter_init(&vmi, mm, khugepaged_scan.address);
251968540502SMatthew Wilcox (Oracle) 	for_each_vma(vmi, vma) {
2520b46e756fSKirill A. Shutemov 		unsigned long hstart, hend;
2521b46e756fSKirill A. Shutemov 
2522b46e756fSKirill A. Shutemov 		cond_resched();
2523ff7e03a8SNico Pache 		if (unlikely(collapse_test_exit_or_disable(mm))) {
252434c1f77eSVernon Yang 			cc->progress++;
2525b46e756fSKirill A. Shutemov 			break;
2526b46e756fSKirill A. Shutemov 		}
25271f1c0610SDavid Hildenbrand 		if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_KHUGEPAGED, PMD_ORDER)) {
252834c1f77eSVernon Yang 			cc->progress++;
2529b46e756fSKirill A. Shutemov 			continue;
2530b46e756fSKirill A. Shutemov 		}
25314fa6893fSYang Shi 		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
25324fa6893fSYang Shi 		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
25337832e4d5SShivank Garg 		if (khugepaged_scan.address > hend) {
253434c1f77eSVernon Yang 			cc->progress++;
25357832e4d5SShivank Garg 			continue;
25367832e4d5SShivank Garg 		}
2537b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address < hstart)
2538b46e756fSKirill A. Shutemov 			khugepaged_scan.address = hstart;
2539b46e756fSKirill A. Shutemov 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2540b46e756fSKirill A. Shutemov 
2541b46e756fSKirill A. Shutemov 		while (khugepaged_scan.address < hend) {
2542a155d945SNico Pache 			bool lock_dropped = false;
254350ad2f24SZach O'Keefe 
2544b46e756fSKirill A. Shutemov 			cond_resched();
2545ff7e03a8SNico Pache 			if (unlikely(collapse_test_exit_or_disable(mm)))
2546b46e756fSKirill A. Shutemov 				goto breakouterloop;
2547b46e756fSKirill A. Shutemov 
2548a155d945SNico Pache 			VM_WARN_ON_ONCE(khugepaged_scan.address < hstart ||
2549b46e756fSKirill A. Shutemov 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2550b46e756fSKirill A. Shutemov 				  hend);
255199cb0dbdSSong Liu 
2552a155d945SNico Pache 			*result = collapse_single_pmd(khugepaged_scan.address,
2553a155d945SNico Pache 						      vma, &lock_dropped, cc);
2554b46e756fSKirill A. Shutemov 			/* move to next address */
2555b46e756fSKirill A. Shutemov 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2556a155d945SNico Pache 			if (lock_dropped)
255750ad2f24SZach O'Keefe 				/*
255850ad2f24SZach O'Keefe 				 * We released mmap_lock so break loop.  Note
255950ad2f24SZach O'Keefe 				 * that we drop mmap_lock before all hugepage
256050ad2f24SZach O'Keefe 				 * allocations, so if allocation fails, we are
256150ad2f24SZach O'Keefe 				 * guaranteed to break here and report the
256250ad2f24SZach O'Keefe 				 * correct result back to caller.
256350ad2f24SZach O'Keefe 				 */
2564c1e8d7c6SMichel Lespinasse 				goto breakouterloop_mmap_lock;
256534c1f77eSVernon Yang 			if (cc->progress >= progress_max)
2566b46e756fSKirill A. Shutemov 				goto breakouterloop;
2567b46e756fSKirill A. Shutemov 		}
2568b46e756fSKirill A. Shutemov 	}
2569b46e756fSKirill A. Shutemov breakouterloop:
2570d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2571c1e8d7c6SMichel Lespinasse breakouterloop_mmap_lock:
2572b46e756fSKirill A. Shutemov 
2573b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2574b4c9ffb5SWei Yang 	VM_BUG_ON(khugepaged_scan.mm_slot != slot);
2575b46e756fSKirill A. Shutemov 	/*
2576b46e756fSKirill A. Shutemov 	 * Release the current mm_slot if this mm is about to die, or
257780a4bcacSVernon Yang 	 * if we scanned all vmas of this mm, or THP got disabled.
2578b46e756fSKirill A. Shutemov 	 */
2579ff7e03a8SNico Pache 	if (collapse_test_exit_or_disable(mm) || !vma) {
2580b46e756fSKirill A. Shutemov 		/*
2581b46e756fSKirill A. Shutemov 		 * Make sure that if mm_users is reaching zero while
2582b46e756fSKirill A. Shutemov 		 * khugepaged runs here, khugepaged_exit will find
2583b46e756fSKirill A. Shutemov 		 * mm_slot not pointing to the exiting mm.
2584b46e756fSKirill A. Shutemov 		 */
25853615e106SWei Yang 		if (!list_is_last(&slot->mm_node, &khugepaged_scan.mm_head)) {
2586b4c9ffb5SWei Yang 			khugepaged_scan.mm_slot = list_next_entry(slot, mm_node);
2587b46e756fSKirill A. Shutemov 			khugepaged_scan.address = 0;
2588b46e756fSKirill A. Shutemov 		} else {
2589b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = NULL;
2590b46e756fSKirill A. Shutemov 			khugepaged_full_scans++;
2591b46e756fSKirill A. Shutemov 		}
2592b46e756fSKirill A. Shutemov 
2593b4c9ffb5SWei Yang 		collect_mm_slot(slot);
2594b46e756fSKirill A. Shutemov 	}
2595b46e756fSKirill A. Shutemov 
259634c1f77eSVernon Yang 	trace_mm_khugepaged_scan(mm, cc->progress - progress_prev,
259734c1f77eSVernon Yang 				 khugepaged_scan.mm_slot == NULL);
2598b46e756fSKirill A. Shutemov }
2599b46e756fSKirill A. Shutemov 
khugepaged_has_work(void)2600b46e756fSKirill A. Shutemov static int khugepaged_has_work(void)
2601b46e756fSKirill A. Shutemov {
260200f58104SRyan Roberts 	return !list_empty(&khugepaged_scan.mm_head) && hugepage_pmd_enabled();
2603b46e756fSKirill A. Shutemov }
2604b46e756fSKirill A. Shutemov 
khugepaged_wait_event(void)2605b46e756fSKirill A. Shutemov static int khugepaged_wait_event(void)
2606b46e756fSKirill A. Shutemov {
2607b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) ||
2608b46e756fSKirill A. Shutemov 		kthread_should_stop();
2609b46e756fSKirill A. Shutemov }
2610b46e756fSKirill A. Shutemov 
khugepaged_do_scan(struct collapse_control * cc)261134d6b470SZach O'Keefe static void khugepaged_do_scan(struct collapse_control *cc)
2612b46e756fSKirill A. Shutemov {
261334c1f77eSVernon Yang 	const unsigned int progress_max = READ_ONCE(khugepaged_pages_to_scan);
261434c1f77eSVernon Yang 	unsigned int pass_through_head = 0;
2615b46e756fSKirill A. Shutemov 	bool wait = true;
261640bd4ff0SShivank Garg 	enum scan_result result = SCAN_SUCCEED;
2617b46e756fSKirill A. Shutemov 
2618a980df33SKirill A. Shutemov 	lru_add_drain_all();
2619a980df33SKirill A. Shutemov 
262034c1f77eSVernon Yang 	cc->progress = 0;
2621c6a7f445SYang Shi 	while (true) {
2622b46e756fSKirill A. Shutemov 		cond_resched();
2623b46e756fSKirill A. Shutemov 
2624b39ca208SKevin Hao 		if (unlikely(kthread_should_stop()))
2625b46e756fSKirill A. Shutemov 			break;
2626b46e756fSKirill A. Shutemov 
2627b46e756fSKirill A. Shutemov 		spin_lock(&khugepaged_mm_lock);
2628b46e756fSKirill A. Shutemov 		if (!khugepaged_scan.mm_slot)
2629b46e756fSKirill A. Shutemov 			pass_through_head++;
2630b46e756fSKirill A. Shutemov 		if (khugepaged_has_work() &&
2631b46e756fSKirill A. Shutemov 		    pass_through_head < 2)
2632ff7e03a8SNico Pache 			collapse_scan_mm_slot(progress_max, &result, cc);
2633b46e756fSKirill A. Shutemov 		else
263434c1f77eSVernon Yang 			cc->progress = progress_max;
2635b46e756fSKirill A. Shutemov 		spin_unlock(&khugepaged_mm_lock);
2636b46e756fSKirill A. Shutemov 
263734c1f77eSVernon Yang 		if (cc->progress >= progress_max)
2638c6a7f445SYang Shi 			break;
2639c6a7f445SYang Shi 
264050ad2f24SZach O'Keefe 		if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2641c6a7f445SYang Shi 			/*
2642c6a7f445SYang Shi 			 * If fail to allocate the first time, try to sleep for
2643c6a7f445SYang Shi 			 * a while.  When hit again, cancel the scan.
2644c6a7f445SYang Shi 			 */
2645c6a7f445SYang Shi 			if (!wait)
2646c6a7f445SYang Shi 				break;
2647c6a7f445SYang Shi 			wait = false;
2648c6a7f445SYang Shi 			khugepaged_alloc_sleep();
2649c6a7f445SYang Shi 		}
2650c6a7f445SYang Shi 	}
2651b46e756fSKirill A. Shutemov }
2652b46e756fSKirill A. Shutemov 
khugepaged_should_wakeup(void)2653b46e756fSKirill A. Shutemov static bool khugepaged_should_wakeup(void)
2654b46e756fSKirill A. Shutemov {
2655b46e756fSKirill A. Shutemov 	return kthread_should_stop() ||
2656b46e756fSKirill A. Shutemov 	       time_after_eq(jiffies, khugepaged_sleep_expire);
2657b46e756fSKirill A. Shutemov }
2658b46e756fSKirill A. Shutemov 
khugepaged_wait_work(void)2659b46e756fSKirill A. Shutemov static void khugepaged_wait_work(void)
2660b46e756fSKirill A. Shutemov {
2661b46e756fSKirill A. Shutemov 	if (khugepaged_has_work()) {
2662b46e756fSKirill A. Shutemov 		const unsigned long scan_sleep_jiffies =
2663b46e756fSKirill A. Shutemov 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2664b46e756fSKirill A. Shutemov 
2665b46e756fSKirill A. Shutemov 		if (!scan_sleep_jiffies)
2666b46e756fSKirill A. Shutemov 			return;
2667b46e756fSKirill A. Shutemov 
2668b46e756fSKirill A. Shutemov 		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2669b46e756fSKirill A. Shutemov 		wait_event_freezable_timeout(khugepaged_wait,
2670b46e756fSKirill A. Shutemov 					     khugepaged_should_wakeup(),
2671b46e756fSKirill A. Shutemov 					     scan_sleep_jiffies);
2672b46e756fSKirill A. Shutemov 		return;
2673b46e756fSKirill A. Shutemov 	}
2674b46e756fSKirill A. Shutemov 
267500f58104SRyan Roberts 	if (hugepage_pmd_enabled())
2676b46e756fSKirill A. Shutemov 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2677b46e756fSKirill A. Shutemov }
2678b46e756fSKirill A. Shutemov 
khugepaged(void * none)2679b46e756fSKirill A. Shutemov static int khugepaged(void *none)
2680b46e756fSKirill A. Shutemov {
2681b4c9ffb5SWei Yang 	struct mm_slot *slot;
2682b46e756fSKirill A. Shutemov 
2683b46e756fSKirill A. Shutemov 	set_freezable();
2684b46e756fSKirill A. Shutemov 	set_user_nice(current, MAX_NICE);
2685b46e756fSKirill A. Shutemov 
2686b46e756fSKirill A. Shutemov 	while (!kthread_should_stop()) {
268734d6b470SZach O'Keefe 		khugepaged_do_scan(&khugepaged_collapse_control);
2688b46e756fSKirill A. Shutemov 		khugepaged_wait_work();
2689b46e756fSKirill A. Shutemov 	}
2690b46e756fSKirill A. Shutemov 
2691b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2692b4c9ffb5SWei Yang 	slot = khugepaged_scan.mm_slot;
2693b46e756fSKirill A. Shutemov 	khugepaged_scan.mm_slot = NULL;
2694b4c9ffb5SWei Yang 	if (slot)
2695b4c9ffb5SWei Yang 		collect_mm_slot(slot);
2696b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2697b46e756fSKirill A. Shutemov 	return 0;
2698b46e756fSKirill A. Shutemov }
2699b46e756fSKirill A. Shutemov 
set_recommended_min_free_kbytes(void)2700c82aade0SBreno Leitao void set_recommended_min_free_kbytes(void)
2701b46e756fSKirill A. Shutemov {
2702b46e756fSKirill A. Shutemov 	struct zone *zone;
2703b46e756fSKirill A. Shutemov 	int nr_zones = 0;
2704b46e756fSKirill A. Shutemov 	unsigned long recommended_min;
2705b46e756fSKirill A. Shutemov 
270600f58104SRyan Roberts 	if (!hugepage_pmd_enabled()) {
2707bd3400eaSLiangcai Fan 		calculate_min_free_kbytes();
2708bd3400eaSLiangcai Fan 		goto update_wmarks;
2709bd3400eaSLiangcai Fan 	}
2710bd3400eaSLiangcai Fan 
2711b7d349c7SJoonsoo Kim 	for_each_populated_zone(zone) {
2712b7d349c7SJoonsoo Kim 		/*
2713b7d349c7SJoonsoo Kim 		 * We don't need to worry about fragmentation of
2714b7d349c7SJoonsoo Kim 		 * ZONE_MOVABLE since it only has movable pages.
2715b7d349c7SJoonsoo Kim 		 */
2716b7d349c7SJoonsoo Kim 		if (zone_idx(zone) > gfp_zone(GFP_USER))
2717b7d349c7SJoonsoo Kim 			continue;
2718b7d349c7SJoonsoo Kim 
2719b46e756fSKirill A. Shutemov 		nr_zones++;
2720b7d349c7SJoonsoo Kim 	}
2721b46e756fSKirill A. Shutemov 
2722b46e756fSKirill A. Shutemov 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2723b46e756fSKirill A. Shutemov 	recommended_min = pageblock_nr_pages * nr_zones * 2;
2724b46e756fSKirill A. Shutemov 
2725b46e756fSKirill A. Shutemov 	/*
2726b46e756fSKirill A. Shutemov 	 * Make sure that on average at least two pageblocks are almost free
2727b46e756fSKirill A. Shutemov 	 * of another type, one for a migratetype to fall back to and a
2728b46e756fSKirill A. Shutemov 	 * second to avoid subsequent fallbacks of other types There are 3
2729b46e756fSKirill A. Shutemov 	 * MIGRATE_TYPES we care about.
2730b46e756fSKirill A. Shutemov 	 */
2731b46e756fSKirill A. Shutemov 	recommended_min += pageblock_nr_pages * nr_zones *
2732b46e756fSKirill A. Shutemov 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2733b46e756fSKirill A. Shutemov 
2734b46e756fSKirill A. Shutemov 	/* don't ever allow to reserve more than 5% of the lowmem */
2735b46e756fSKirill A. Shutemov 	recommended_min = min(recommended_min,
2736b46e756fSKirill A. Shutemov 			      (unsigned long) nr_free_buffer_pages() / 20);
2737b46e756fSKirill A. Shutemov 	recommended_min <<= (PAGE_SHIFT-10);
2738b46e756fSKirill A. Shutemov 
2739b46e756fSKirill A. Shutemov 	if (recommended_min > min_free_kbytes) {
2740b46e756fSKirill A. Shutemov 		if (user_min_free_kbytes >= 0)
27413203a870SBreno Leitao 			pr_info_ratelimited("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2742b46e756fSKirill A. Shutemov 					    min_free_kbytes, recommended_min);
2743b46e756fSKirill A. Shutemov 
2744b46e756fSKirill A. Shutemov 		min_free_kbytes = recommended_min;
2745b46e756fSKirill A. Shutemov 	}
2746bd3400eaSLiangcai Fan 
2747bd3400eaSLiangcai Fan update_wmarks:
2748b46e756fSKirill A. Shutemov 	setup_per_zone_wmarks();
2749b46e756fSKirill A. Shutemov }
2750b46e756fSKirill A. Shutemov 
start_stop_khugepaged(void)2751b46e756fSKirill A. Shutemov int start_stop_khugepaged(void)
2752b46e756fSKirill A. Shutemov {
2753b46e756fSKirill A. Shutemov 	int err = 0;
2754b46e756fSKirill A. Shutemov 
2755b46e756fSKirill A. Shutemov 	mutex_lock(&khugepaged_mutex);
275600f58104SRyan Roberts 	if (hugepage_pmd_enabled()) {
2757b46e756fSKirill A. Shutemov 		if (!khugepaged_thread)
2758b46e756fSKirill A. Shutemov 			khugepaged_thread = kthread_run(khugepaged, NULL,
2759b46e756fSKirill A. Shutemov 							"khugepaged");
2760b46e756fSKirill A. Shutemov 		if (IS_ERR(khugepaged_thread)) {
2761b46e756fSKirill A. Shutemov 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2762b46e756fSKirill A. Shutemov 			err = PTR_ERR(khugepaged_thread);
2763b46e756fSKirill A. Shutemov 			khugepaged_thread = NULL;
2764b46e756fSKirill A. Shutemov 			goto fail;
2765b46e756fSKirill A. Shutemov 		}
2766b46e756fSKirill A. Shutemov 
2767b46e756fSKirill A. Shutemov 		if (!list_empty(&khugepaged_scan.mm_head))
2768b46e756fSKirill A. Shutemov 			wake_up_interruptible(&khugepaged_wait);
2769b46e756fSKirill A. Shutemov 	} else if (khugepaged_thread) {
2770b46e756fSKirill A. Shutemov 		kthread_stop(khugepaged_thread);
2771b46e756fSKirill A. Shutemov 		khugepaged_thread = NULL;
2772b46e756fSKirill A. Shutemov 	}
2773bd3400eaSLiangcai Fan 	set_recommended_min_free_kbytes();
2774b46e756fSKirill A. Shutemov fail:
2775b46e756fSKirill A. Shutemov 	mutex_unlock(&khugepaged_mutex);
2776b46e756fSKirill A. Shutemov 	return err;
2777b46e756fSKirill A. Shutemov }
27784aab2be0SVijay Balakrishna 
khugepaged_min_free_kbytes_update(void)27794aab2be0SVijay Balakrishna void khugepaged_min_free_kbytes_update(void)
27804aab2be0SVijay Balakrishna {
27814aab2be0SVijay Balakrishna 	mutex_lock(&khugepaged_mutex);
278200f58104SRyan Roberts 	if (hugepage_pmd_enabled() && khugepaged_thread)
27834aab2be0SVijay Balakrishna 		set_recommended_min_free_kbytes();
27844aab2be0SVijay Balakrishna 	mutex_unlock(&khugepaged_mutex);
27854aab2be0SVijay Balakrishna }
27867d8faaf1SZach O'Keefe 
current_is_khugepaged(void)278757e9cc50SJohannes Weiner bool current_is_khugepaged(void)
278857e9cc50SJohannes Weiner {
278957e9cc50SJohannes Weiner 	return kthread_func(current) == khugepaged;
279057e9cc50SJohannes Weiner }
279157e9cc50SJohannes Weiner 
madvise_collapse_errno(enum scan_result r)27927d8faaf1SZach O'Keefe static int madvise_collapse_errno(enum scan_result r)
27937d8faaf1SZach O'Keefe {
27947d8faaf1SZach O'Keefe 	/*
27957d8faaf1SZach O'Keefe 	 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
27967d8faaf1SZach O'Keefe 	 * actionable feedback to caller, so they may take an appropriate
27977d8faaf1SZach O'Keefe 	 * fallback measure depending on the nature of the failure.
27987d8faaf1SZach O'Keefe 	 */
27997d8faaf1SZach O'Keefe 	switch (r) {
28007d8faaf1SZach O'Keefe 	case SCAN_ALLOC_HUGE_PAGE_FAIL:
28017d8faaf1SZach O'Keefe 		return -ENOMEM;
28027d8faaf1SZach O'Keefe 	case SCAN_CGROUP_CHARGE_FAIL:
2803ac492b9cSDavid Stevens 	case SCAN_EXCEED_NONE_PTE:
28047d8faaf1SZach O'Keefe 		return -EBUSY;
28057d8faaf1SZach O'Keefe 	/* Resource temporary unavailable - trying again might succeed */
2806ae63c898SZach O'Keefe 	case SCAN_PAGE_COUNT:
28077d8faaf1SZach O'Keefe 	case SCAN_PAGE_LOCK:
28087d8faaf1SZach O'Keefe 	case SCAN_PAGE_LRU:
28090f3e2a2cSZach O'Keefe 	case SCAN_DEL_PAGE_LRU:
2810ac492b9cSDavid Stevens 	case SCAN_PAGE_FILLED:
28115173ae0aSShivank Garg 	case SCAN_PAGE_DIRTY_OR_WRITEBACK:
28127d8faaf1SZach O'Keefe 		return -EAGAIN;
28137d8faaf1SZach O'Keefe 	/*
28147d8faaf1SZach O'Keefe 	 * Other: Trying again likely not to succeed / error intrinsic to
28157d8faaf1SZach O'Keefe 	 * specified memory range. khugepaged likely won't be able to collapse
28167d8faaf1SZach O'Keefe 	 * either.
28177d8faaf1SZach O'Keefe 	 */
28187d8faaf1SZach O'Keefe 	default:
28197d8faaf1SZach O'Keefe 		return -EINVAL;
28207d8faaf1SZach O'Keefe 	}
28217d8faaf1SZach O'Keefe }
28227d8faaf1SZach O'Keefe 
madvise_collapse(struct vm_area_struct * vma,unsigned long start,unsigned long end,bool * lock_dropped)2823e24d552aSLorenzo Stoakes int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
2824e24d552aSLorenzo Stoakes 		     unsigned long end, bool *lock_dropped)
28257d8faaf1SZach O'Keefe {
28267d8faaf1SZach O'Keefe 	struct collapse_control *cc;
28277d8faaf1SZach O'Keefe 	struct mm_struct *mm = vma->vm_mm;
28287d8faaf1SZach O'Keefe 	unsigned long hstart, hend, addr;
282940bd4ff0SShivank Garg 	enum scan_result last_fail = SCAN_FAIL;
283040bd4ff0SShivank Garg 	int thps = 0;
2831*5a620198SLorenzo Stoakes (Oracle) 	bool mmap_unlocked = false;
28327d8faaf1SZach O'Keefe 
28337d8faaf1SZach O'Keefe 	BUG_ON(vma->vm_start > start);
28347d8faaf1SZach O'Keefe 	BUG_ON(vma->vm_end < end);
28357d8faaf1SZach O'Keefe 
28361f1c0610SDavid Hildenbrand 	if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER))
28377d8faaf1SZach O'Keefe 		return -EINVAL;
28387d8faaf1SZach O'Keefe 
2839bf4afc53SLinus Torvalds 	cc = kmalloc_obj(*cc);
28407d8faaf1SZach O'Keefe 	if (!cc)
28417d8faaf1SZach O'Keefe 		return -ENOMEM;
28427d8faaf1SZach O'Keefe 	cc->is_khugepaged = false;
284334c1f77eSVernon Yang 	cc->progress = 0;
28447d8faaf1SZach O'Keefe 
28457d8faaf1SZach O'Keefe 	mmgrab(mm);
28467d8faaf1SZach O'Keefe 	lru_add_drain_all();
28477d8faaf1SZach O'Keefe 
28487d8faaf1SZach O'Keefe 	hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
28497d8faaf1SZach O'Keefe 	hend = end & HPAGE_PMD_MASK;
28507d8faaf1SZach O'Keefe 
28517d8faaf1SZach O'Keefe 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
285240bd4ff0SShivank Garg 		enum scan_result result = SCAN_FAIL;
28537d8faaf1SZach O'Keefe 
2854*5a620198SLorenzo Stoakes (Oracle) 		if (mmap_unlocked) {
28557d8faaf1SZach O'Keefe 			cond_resched();
28567d8faaf1SZach O'Keefe 			mmap_read_lock(mm);
2857*5a620198SLorenzo Stoakes (Oracle) 			mmap_unlocked = false;
2858*5a620198SLorenzo Stoakes (Oracle) 			*lock_dropped = true;
285934488399SZach O'Keefe 			result = hugepage_vma_revalidate(mm, addr, false, &vma,
286034488399SZach O'Keefe 							 cc);
28617d8faaf1SZach O'Keefe 			if (result  != SCAN_SUCCEED) {
28627d8faaf1SZach O'Keefe 				last_fail = result;
28637d8faaf1SZach O'Keefe 				goto out_nolock;
28647d8faaf1SZach O'Keefe 			}
28654d24de94SYang Shi 
286652dc0310SZach O'Keefe 			hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
28677d8faaf1SZach O'Keefe 		}
286834488399SZach O'Keefe 
2869*5a620198SLorenzo Stoakes (Oracle) 		result = collapse_single_pmd(addr, vma, &mmap_unlocked, cc);
287039855657SShivank Garg 
28717d8faaf1SZach O'Keefe 		switch (result) {
28727d8faaf1SZach O'Keefe 		case SCAN_SUCCEED:
28737d8faaf1SZach O'Keefe 		case SCAN_PMD_MAPPED:
28747d8faaf1SZach O'Keefe 			++thps;
28757d8faaf1SZach O'Keefe 			break;
28767d8faaf1SZach O'Keefe 		/* Whitelisted set of results where continuing OK */
28779e014077SWei Yang 		case SCAN_NO_PTE_TABLE:
28787d8faaf1SZach O'Keefe 		case SCAN_PTE_NON_PRESENT:
28797d8faaf1SZach O'Keefe 		case SCAN_PTE_UFFD_WP:
28807d8faaf1SZach O'Keefe 		case SCAN_LACK_REFERENCED_PAGE:
28817d8faaf1SZach O'Keefe 		case SCAN_PAGE_NULL:
28827d8faaf1SZach O'Keefe 		case SCAN_PAGE_COUNT:
28837d8faaf1SZach O'Keefe 		case SCAN_PAGE_LOCK:
28847d8faaf1SZach O'Keefe 		case SCAN_PAGE_COMPOUND:
28857d8faaf1SZach O'Keefe 		case SCAN_PAGE_LRU:
28860f3e2a2cSZach O'Keefe 		case SCAN_DEL_PAGE_LRU:
28877d8faaf1SZach O'Keefe 			last_fail = result;
28887d8faaf1SZach O'Keefe 			break;
28897d8faaf1SZach O'Keefe 		default:
28907d8faaf1SZach O'Keefe 			last_fail = result;
28917d8faaf1SZach O'Keefe 			/* Other error, exit */
28927d8faaf1SZach O'Keefe 			goto out_maybelock;
28937d8faaf1SZach O'Keefe 		}
28947d8faaf1SZach O'Keefe 	}
28957d8faaf1SZach O'Keefe 
28967d8faaf1SZach O'Keefe out_maybelock:
28977d8faaf1SZach O'Keefe 	/* Caller expects us to hold mmap_lock on return */
2898*5a620198SLorenzo Stoakes (Oracle) 	if (mmap_unlocked) {
2899*5a620198SLorenzo Stoakes (Oracle) 		*lock_dropped = true;
29007d8faaf1SZach O'Keefe 		mmap_read_lock(mm);
2901*5a620198SLorenzo Stoakes (Oracle) 	}
29027d8faaf1SZach O'Keefe out_nolock:
29037d8faaf1SZach O'Keefe 	mmap_assert_locked(mm);
29047d8faaf1SZach O'Keefe 	mmdrop(mm);
29057d8faaf1SZach O'Keefe 	kfree(cc);
29067d8faaf1SZach O'Keefe 
29077d8faaf1SZach O'Keefe 	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
29087d8faaf1SZach O'Keefe 			: madvise_collapse_errno(last_fail);
29097d8faaf1SZach O'Keefe }
2910