xref: /linux/mm/khugepaged.c (revision 98b32d296d95d7aa0516c36b72406277412268cd)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2b46e756fSKirill A. Shutemov #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3b46e756fSKirill A. Shutemov 
4b46e756fSKirill A. Shutemov #include <linux/mm.h>
5b46e756fSKirill A. Shutemov #include <linux/sched.h>
66e84f315SIngo Molnar #include <linux/sched/mm.h>
7f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
8b46e756fSKirill A. Shutemov #include <linux/mmu_notifier.h>
9b46e756fSKirill A. Shutemov #include <linux/rmap.h>
10b46e756fSKirill A. Shutemov #include <linux/swap.h>
11b46e756fSKirill A. Shutemov #include <linux/mm_inline.h>
12b46e756fSKirill A. Shutemov #include <linux/kthread.h>
13b46e756fSKirill A. Shutemov #include <linux/khugepaged.h>
14b46e756fSKirill A. Shutemov #include <linux/freezer.h>
15b46e756fSKirill A. Shutemov #include <linux/mman.h>
16b46e756fSKirill A. Shutemov #include <linux/hashtable.h>
17b46e756fSKirill A. Shutemov #include <linux/userfaultfd_k.h>
18b46e756fSKirill A. Shutemov #include <linux/page_idle.h>
1980110bbfSPasha Tatashin #include <linux/page_table_check.h>
20b46e756fSKirill A. Shutemov #include <linux/swapops.h>
21f3f0e1d2SKirill A. Shutemov #include <linux/shmem_fs.h>
22e2942062Sxu xin #include <linux/ksm.h>
23b46e756fSKirill A. Shutemov 
24b46e756fSKirill A. Shutemov #include <asm/tlb.h>
25b46e756fSKirill A. Shutemov #include <asm/pgalloc.h>
26b46e756fSKirill A. Shutemov #include "internal.h"
27b26e2701SQi Zheng #include "mm_slot.h"
28b46e756fSKirill A. Shutemov 
29b46e756fSKirill A. Shutemov enum scan_result {
30b46e756fSKirill A. Shutemov 	SCAN_FAIL,
31b46e756fSKirill A. Shutemov 	SCAN_SUCCEED,
32b46e756fSKirill A. Shutemov 	SCAN_PMD_NULL,
3334488399SZach O'Keefe 	SCAN_PMD_NONE,
3450722804SZach O'Keefe 	SCAN_PMD_MAPPED,
35b46e756fSKirill A. Shutemov 	SCAN_EXCEED_NONE_PTE,
3671a2c112SKirill A. Shutemov 	SCAN_EXCEED_SWAP_PTE,
3771a2c112SKirill A. Shutemov 	SCAN_EXCEED_SHARED_PTE,
38b46e756fSKirill A. Shutemov 	SCAN_PTE_NON_PRESENT,
39e1e267c7SPeter Xu 	SCAN_PTE_UFFD_WP,
4058ac9a89SZach O'Keefe 	SCAN_PTE_MAPPED_HUGEPAGE,
41b46e756fSKirill A. Shutemov 	SCAN_PAGE_RO,
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,
49b46e756fSKirill A. Shutemov 	SCAN_PAGE_COMPOUND,
50b46e756fSKirill A. Shutemov 	SCAN_ANY_PROCESS,
51b46e756fSKirill A. Shutemov 	SCAN_VMA_NULL,
52b46e756fSKirill A. Shutemov 	SCAN_VMA_CHECK,
53b46e756fSKirill A. Shutemov 	SCAN_ADDRESS_RANGE,
54b46e756fSKirill A. Shutemov 	SCAN_DEL_PAGE_LRU,
55b46e756fSKirill A. Shutemov 	SCAN_ALLOC_HUGE_PAGE_FAIL,
56b46e756fSKirill A. Shutemov 	SCAN_CGROUP_CHARGE_FAIL,
57f3f0e1d2SKirill A. Shutemov 	SCAN_TRUNCATED,
5899cb0dbdSSong Liu 	SCAN_PAGE_HAS_PRIVATE,
592ce0bdfeSIvan Orlov 	SCAN_STORE_FAILED,
6098c76c9fSJiaqi Yan 	SCAN_COPY_MC,
61ac492b9cSDavid Stevens 	SCAN_PAGE_FILLED,
62b46e756fSKirill A. Shutemov };
63b46e756fSKirill A. Shutemov 
64b46e756fSKirill A. Shutemov #define CREATE_TRACE_POINTS
65b46e756fSKirill A. Shutemov #include <trace/events/huge_memory.h>
66b46e756fSKirill A. Shutemov 
674aab2be0SVijay Balakrishna static struct task_struct *khugepaged_thread __read_mostly;
684aab2be0SVijay Balakrishna static DEFINE_MUTEX(khugepaged_mutex);
694aab2be0SVijay Balakrishna 
70b46e756fSKirill A. Shutemov /* default scan 8*512 pte (or vmas) every 30 second */
71b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_to_scan __read_mostly;
72b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_collapsed;
73b46e756fSKirill A. Shutemov static unsigned int khugepaged_full_scans;
74b46e756fSKirill A. Shutemov static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
75b46e756fSKirill A. Shutemov /* during fragmentation poll the hugepage allocator once every minute */
76b46e756fSKirill A. Shutemov static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
77b46e756fSKirill A. Shutemov static unsigned long khugepaged_sleep_expire;
78b46e756fSKirill A. Shutemov static DEFINE_SPINLOCK(khugepaged_mm_lock);
79b46e756fSKirill A. Shutemov static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
80b46e756fSKirill A. Shutemov /*
81b46e756fSKirill A. Shutemov  * default collapse hugepages if there is at least one pte mapped like
82b46e756fSKirill A. Shutemov  * it would have happened if the vma was large enough during page
83b46e756fSKirill A. Shutemov  * fault.
84d8ea7cc8SZach O'Keefe  *
85d8ea7cc8SZach O'Keefe  * Note that these are only respected if collapse was initiated by khugepaged.
86b46e756fSKirill A. Shutemov  */
87b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_none __read_mostly;
88b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_swap __read_mostly;
8971a2c112SKirill A. Shutemov static unsigned int khugepaged_max_ptes_shared __read_mostly;
90b46e756fSKirill A. Shutemov 
91b46e756fSKirill A. Shutemov #define MM_SLOTS_HASH_BITS 10
92e1ad3e66SNick Desaulniers static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
93b46e756fSKirill A. Shutemov 
94b46e756fSKirill A. Shutemov static struct kmem_cache *mm_slot_cache __read_mostly;
95b46e756fSKirill A. Shutemov 
9634d6b470SZach O'Keefe struct collapse_control {
97d8ea7cc8SZach O'Keefe 	bool is_khugepaged;
98d8ea7cc8SZach O'Keefe 
9934d6b470SZach O'Keefe 	/* Num pages scanned per node */
10034d6b470SZach O'Keefe 	u32 node_load[MAX_NUMNODES];
10134d6b470SZach O'Keefe 
102e031ff96SYang Shi 	/* nodemask for allocation fallback */
103e031ff96SYang Shi 	nodemask_t alloc_nmask;
10434d6b470SZach O'Keefe };
10534d6b470SZach O'Keefe 
106b46e756fSKirill A. Shutemov /**
107b26e2701SQi Zheng  * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
108b26e2701SQi Zheng  * @slot: hash lookup from mm to mm_slot
109b46e756fSKirill A. Shutemov  */
110b26e2701SQi Zheng struct khugepaged_mm_slot {
111b26e2701SQi Zheng 	struct mm_slot slot;
112b46e756fSKirill A. Shutemov };
113b46e756fSKirill A. Shutemov 
114b46e756fSKirill A. Shutemov /**
115b46e756fSKirill A. Shutemov  * struct khugepaged_scan - cursor for scanning
116b46e756fSKirill A. Shutemov  * @mm_head: the head of the mm list to scan
117b46e756fSKirill A. Shutemov  * @mm_slot: the current mm_slot we are scanning
118b46e756fSKirill A. Shutemov  * @address: the next address inside that to be scanned
119b46e756fSKirill A. Shutemov  *
120b46e756fSKirill A. Shutemov  * There is only the one khugepaged_scan instance of this cursor structure.
121b46e756fSKirill A. Shutemov  */
122b46e756fSKirill A. Shutemov struct khugepaged_scan {
123b46e756fSKirill A. Shutemov 	struct list_head mm_head;
124b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
125b46e756fSKirill A. Shutemov 	unsigned long address;
126b46e756fSKirill A. Shutemov };
127b46e756fSKirill A. Shutemov 
128b46e756fSKirill A. Shutemov static struct khugepaged_scan khugepaged_scan = {
129b46e756fSKirill A. Shutemov 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
130b46e756fSKirill A. Shutemov };
131b46e756fSKirill A. Shutemov 
132e1465d12SJérémy Lefaure #ifdef CONFIG_SYSFS
133b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
134b46e756fSKirill A. Shutemov 					 struct kobj_attribute *attr,
135b46e756fSKirill A. Shutemov 					 char *buf)
136b46e756fSKirill A. Shutemov {
137ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
138b46e756fSKirill A. Shutemov }
139b46e756fSKirill A. Shutemov 
140b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
141b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
142b46e756fSKirill A. Shutemov 					  const char *buf, size_t count)
143b46e756fSKirill A. Shutemov {
144dfefd226SAlexey Dobriyan 	unsigned int msecs;
145b46e756fSKirill A. Shutemov 	int err;
146b46e756fSKirill A. Shutemov 
147dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
148dfefd226SAlexey Dobriyan 	if (err)
149b46e756fSKirill A. Shutemov 		return -EINVAL;
150b46e756fSKirill A. Shutemov 
151b46e756fSKirill A. Shutemov 	khugepaged_scan_sleep_millisecs = msecs;
152b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
153b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
154b46e756fSKirill A. Shutemov 
155b46e756fSKirill A. Shutemov 	return count;
156b46e756fSKirill A. Shutemov }
157b46e756fSKirill A. Shutemov static struct kobj_attribute scan_sleep_millisecs_attr =
1586dcdc94dSMiaohe Lin 	__ATTR_RW(scan_sleep_millisecs);
159b46e756fSKirill A. Shutemov 
160b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
161b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
162b46e756fSKirill A. Shutemov 					  char *buf)
163b46e756fSKirill A. Shutemov {
164ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
165b46e756fSKirill A. Shutemov }
166b46e756fSKirill A. Shutemov 
167b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
168b46e756fSKirill A. Shutemov 					   struct kobj_attribute *attr,
169b46e756fSKirill A. Shutemov 					   const char *buf, size_t count)
170b46e756fSKirill A. Shutemov {
171dfefd226SAlexey Dobriyan 	unsigned int msecs;
172b46e756fSKirill A. Shutemov 	int err;
173b46e756fSKirill A. Shutemov 
174dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
175dfefd226SAlexey Dobriyan 	if (err)
176b46e756fSKirill A. Shutemov 		return -EINVAL;
177b46e756fSKirill A. Shutemov 
178b46e756fSKirill A. Shutemov 	khugepaged_alloc_sleep_millisecs = msecs;
179b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
180b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
181b46e756fSKirill A. Shutemov 
182b46e756fSKirill A. Shutemov 	return count;
183b46e756fSKirill A. Shutemov }
184b46e756fSKirill A. Shutemov static struct kobj_attribute alloc_sleep_millisecs_attr =
1856dcdc94dSMiaohe Lin 	__ATTR_RW(alloc_sleep_millisecs);
186b46e756fSKirill A. Shutemov 
187b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_show(struct kobject *kobj,
188b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
189b46e756fSKirill A. Shutemov 				  char *buf)
190b46e756fSKirill A. Shutemov {
191ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
192b46e756fSKirill A. Shutemov }
193b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_store(struct kobject *kobj,
194b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
195b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
196b46e756fSKirill A. Shutemov {
197dfefd226SAlexey Dobriyan 	unsigned int pages;
198b46e756fSKirill A. Shutemov 	int err;
199b46e756fSKirill A. Shutemov 
200dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &pages);
201dfefd226SAlexey Dobriyan 	if (err || !pages)
202b46e756fSKirill A. Shutemov 		return -EINVAL;
203b46e756fSKirill A. Shutemov 
204b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = pages;
205b46e756fSKirill A. Shutemov 
206b46e756fSKirill A. Shutemov 	return count;
207b46e756fSKirill A. Shutemov }
208b46e756fSKirill A. Shutemov static struct kobj_attribute pages_to_scan_attr =
2096dcdc94dSMiaohe Lin 	__ATTR_RW(pages_to_scan);
210b46e756fSKirill A. Shutemov 
211b46e756fSKirill A. Shutemov static ssize_t pages_collapsed_show(struct kobject *kobj,
212b46e756fSKirill A. Shutemov 				    struct kobj_attribute *attr,
213b46e756fSKirill A. Shutemov 				    char *buf)
214b46e756fSKirill A. Shutemov {
215ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
216b46e756fSKirill A. Shutemov }
217b46e756fSKirill A. Shutemov static struct kobj_attribute pages_collapsed_attr =
218b46e756fSKirill A. Shutemov 	__ATTR_RO(pages_collapsed);
219b46e756fSKirill A. Shutemov 
220b46e756fSKirill A. Shutemov static ssize_t full_scans_show(struct kobject *kobj,
221b46e756fSKirill A. Shutemov 			       struct kobj_attribute *attr,
222b46e756fSKirill A. Shutemov 			       char *buf)
223b46e756fSKirill A. Shutemov {
224ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
225b46e756fSKirill A. Shutemov }
226b46e756fSKirill A. Shutemov static struct kobj_attribute full_scans_attr =
227b46e756fSKirill A. Shutemov 	__ATTR_RO(full_scans);
228b46e756fSKirill A. Shutemov 
2296dcdc94dSMiaohe Lin static ssize_t defrag_show(struct kobject *kobj,
230b46e756fSKirill A. Shutemov 			   struct kobj_attribute *attr, char *buf)
231b46e756fSKirill A. Shutemov {
232b46e756fSKirill A. Shutemov 	return single_hugepage_flag_show(kobj, attr, buf,
233b46e756fSKirill A. Shutemov 					 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
234b46e756fSKirill A. Shutemov }
2356dcdc94dSMiaohe Lin static ssize_t defrag_store(struct kobject *kobj,
236b46e756fSKirill A. Shutemov 			    struct kobj_attribute *attr,
237b46e756fSKirill A. Shutemov 			    const char *buf, size_t count)
238b46e756fSKirill A. Shutemov {
239b46e756fSKirill A. Shutemov 	return single_hugepage_flag_store(kobj, attr, buf, count,
240b46e756fSKirill A. Shutemov 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
241b46e756fSKirill A. Shutemov }
242b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_defrag_attr =
2436dcdc94dSMiaohe Lin 	__ATTR_RW(defrag);
244b46e756fSKirill A. Shutemov 
245b46e756fSKirill A. Shutemov /*
246b46e756fSKirill A. Shutemov  * max_ptes_none controls if khugepaged should collapse hugepages over
247b46e756fSKirill A. Shutemov  * any unmapped ptes in turn potentially increasing the memory
248b46e756fSKirill A. Shutemov  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
249b46e756fSKirill A. Shutemov  * reduce the available free memory in the system as it
250b46e756fSKirill A. Shutemov  * runs. Increasing max_ptes_none will instead potentially reduce the
251b46e756fSKirill A. Shutemov  * free memory in the system during the khugepaged scan.
252b46e756fSKirill A. Shutemov  */
2536dcdc94dSMiaohe Lin static ssize_t max_ptes_none_show(struct kobject *kobj,
254b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
255b46e756fSKirill A. Shutemov 				  char *buf)
256b46e756fSKirill A. Shutemov {
257ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
258b46e756fSKirill A. Shutemov }
2596dcdc94dSMiaohe Lin static ssize_t max_ptes_none_store(struct kobject *kobj,
260b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
261b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
262b46e756fSKirill A. Shutemov {
263b46e756fSKirill A. Shutemov 	int err;
264b46e756fSKirill A. Shutemov 	unsigned long max_ptes_none;
265b46e756fSKirill A. Shutemov 
266b46e756fSKirill A. Shutemov 	err = kstrtoul(buf, 10, &max_ptes_none);
267b46e756fSKirill A. Shutemov 	if (err || max_ptes_none > HPAGE_PMD_NR - 1)
268b46e756fSKirill A. Shutemov 		return -EINVAL;
269b46e756fSKirill A. Shutemov 
270b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = max_ptes_none;
271b46e756fSKirill A. Shutemov 
272b46e756fSKirill A. Shutemov 	return count;
273b46e756fSKirill A. Shutemov }
274b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_none_attr =
2756dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_none);
276b46e756fSKirill A. Shutemov 
2776dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_show(struct kobject *kobj,
278b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
279b46e756fSKirill A. Shutemov 				  char *buf)
280b46e756fSKirill A. Shutemov {
281ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
282b46e756fSKirill A. Shutemov }
283b46e756fSKirill A. Shutemov 
2846dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_store(struct kobject *kobj,
285b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
286b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
287b46e756fSKirill A. Shutemov {
288b46e756fSKirill A. Shutemov 	int err;
289b46e756fSKirill A. Shutemov 	unsigned long max_ptes_swap;
290b46e756fSKirill A. Shutemov 
291b46e756fSKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_swap);
292b46e756fSKirill A. Shutemov 	if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
293b46e756fSKirill A. Shutemov 		return -EINVAL;
294b46e756fSKirill A. Shutemov 
295b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = max_ptes_swap;
296b46e756fSKirill A. Shutemov 
297b46e756fSKirill A. Shutemov 	return count;
298b46e756fSKirill A. Shutemov }
299b46e756fSKirill A. Shutemov 
300b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_swap_attr =
3016dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_swap);
302b46e756fSKirill A. Shutemov 
3036dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_show(struct kobject *kobj,
30471a2c112SKirill A. Shutemov 				    struct kobj_attribute *attr,
30571a2c112SKirill A. Shutemov 				    char *buf)
30671a2c112SKirill A. Shutemov {
307ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
30871a2c112SKirill A. Shutemov }
30971a2c112SKirill A. Shutemov 
3106dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_store(struct kobject *kobj,
31171a2c112SKirill A. Shutemov 				     struct kobj_attribute *attr,
31271a2c112SKirill A. Shutemov 				     const char *buf, size_t count)
31371a2c112SKirill A. Shutemov {
31471a2c112SKirill A. Shutemov 	int err;
31571a2c112SKirill A. Shutemov 	unsigned long max_ptes_shared;
31671a2c112SKirill A. Shutemov 
31771a2c112SKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_shared);
31871a2c112SKirill A. Shutemov 	if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
31971a2c112SKirill A. Shutemov 		return -EINVAL;
32071a2c112SKirill A. Shutemov 
32171a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = max_ptes_shared;
32271a2c112SKirill A. Shutemov 
32371a2c112SKirill A. Shutemov 	return count;
32471a2c112SKirill A. Shutemov }
32571a2c112SKirill A. Shutemov 
32671a2c112SKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_shared_attr =
3276dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_shared);
32871a2c112SKirill A. Shutemov 
329b46e756fSKirill A. Shutemov static struct attribute *khugepaged_attr[] = {
330b46e756fSKirill A. Shutemov 	&khugepaged_defrag_attr.attr,
331b46e756fSKirill A. Shutemov 	&khugepaged_max_ptes_none_attr.attr,
33271a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_swap_attr.attr,
33371a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_shared_attr.attr,
334b46e756fSKirill A. Shutemov 	&pages_to_scan_attr.attr,
335b46e756fSKirill A. Shutemov 	&pages_collapsed_attr.attr,
336b46e756fSKirill A. Shutemov 	&full_scans_attr.attr,
337b46e756fSKirill A. Shutemov 	&scan_sleep_millisecs_attr.attr,
338b46e756fSKirill A. Shutemov 	&alloc_sleep_millisecs_attr.attr,
339b46e756fSKirill A. Shutemov 	NULL,
340b46e756fSKirill A. Shutemov };
341b46e756fSKirill A. Shutemov 
342b46e756fSKirill A. Shutemov struct attribute_group khugepaged_attr_group = {
343b46e756fSKirill A. Shutemov 	.attrs = khugepaged_attr,
344b46e756fSKirill A. Shutemov 	.name = "khugepaged",
345b46e756fSKirill A. Shutemov };
346e1465d12SJérémy Lefaure #endif /* CONFIG_SYSFS */
347b46e756fSKirill A. Shutemov 
348b46e756fSKirill A. Shutemov int hugepage_madvise(struct vm_area_struct *vma,
349b46e756fSKirill A. Shutemov 		     unsigned long *vm_flags, int advice)
350b46e756fSKirill A. Shutemov {
351b46e756fSKirill A. Shutemov 	switch (advice) {
352b46e756fSKirill A. Shutemov 	case MADV_HUGEPAGE:
353b46e756fSKirill A. Shutemov #ifdef CONFIG_S390
354b46e756fSKirill A. Shutemov 		/*
355b46e756fSKirill A. Shutemov 		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
356b46e756fSKirill A. Shutemov 		 * can't handle this properly after s390_enable_sie, so we simply
357b46e756fSKirill A. Shutemov 		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
358b46e756fSKirill A. Shutemov 		 */
359b46e756fSKirill A. Shutemov 		if (mm_has_pgste(vma->vm_mm))
360b46e756fSKirill A. Shutemov 			return 0;
361b46e756fSKirill A. Shutemov #endif
362b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_NOHUGEPAGE;
363b46e756fSKirill A. Shutemov 		*vm_flags |= VM_HUGEPAGE;
364b46e756fSKirill A. Shutemov 		/*
365b46e756fSKirill A. Shutemov 		 * If the vma become good for khugepaged to scan,
366b46e756fSKirill A. Shutemov 		 * register it here without waiting a page fault that
367b46e756fSKirill A. Shutemov 		 * may not happen any time soon.
368b46e756fSKirill A. Shutemov 		 */
369c791576cSYang Shi 		khugepaged_enter_vma(vma, *vm_flags);
370b46e756fSKirill A. Shutemov 		break;
371b46e756fSKirill A. Shutemov 	case MADV_NOHUGEPAGE:
372b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_HUGEPAGE;
373b46e756fSKirill A. Shutemov 		*vm_flags |= VM_NOHUGEPAGE;
374b46e756fSKirill A. Shutemov 		/*
375b46e756fSKirill A. Shutemov 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
376b46e756fSKirill A. Shutemov 		 * this vma even if we leave the mm registered in khugepaged if
377b46e756fSKirill A. Shutemov 		 * it got registered before VM_NOHUGEPAGE was set.
378b46e756fSKirill A. Shutemov 		 */
379b46e756fSKirill A. Shutemov 		break;
380b46e756fSKirill A. Shutemov 	}
381b46e756fSKirill A. Shutemov 
382b46e756fSKirill A. Shutemov 	return 0;
383b46e756fSKirill A. Shutemov }
384b46e756fSKirill A. Shutemov 
385b46e756fSKirill A. Shutemov int __init khugepaged_init(void)
386b46e756fSKirill A. Shutemov {
387b46e756fSKirill A. Shutemov 	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
388b26e2701SQi Zheng 					  sizeof(struct khugepaged_mm_slot),
389b26e2701SQi Zheng 					  __alignof__(struct khugepaged_mm_slot),
390b26e2701SQi Zheng 					  0, NULL);
391b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)
392b46e756fSKirill A. Shutemov 		return -ENOMEM;
393b46e756fSKirill A. Shutemov 
394b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
395b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
396b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
39771a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
398b46e756fSKirill A. Shutemov 
399b46e756fSKirill A. Shutemov 	return 0;
400b46e756fSKirill A. Shutemov }
401b46e756fSKirill A. Shutemov 
402b46e756fSKirill A. Shutemov void __init khugepaged_destroy(void)
403b46e756fSKirill A. Shutemov {
404b46e756fSKirill A. Shutemov 	kmem_cache_destroy(mm_slot_cache);
405b46e756fSKirill A. Shutemov }
406b46e756fSKirill A. Shutemov 
4077d2c4385SZach O'Keefe static inline int hpage_collapse_test_exit(struct mm_struct *mm)
408b46e756fSKirill A. Shutemov {
4094d45e75aSJann Horn 	return atomic_read(&mm->mm_users) == 0;
410b46e756fSKirill A. Shutemov }
411b46e756fSKirill A. Shutemov 
412d2081b2bSYang Shi void __khugepaged_enter(struct mm_struct *mm)
413b46e756fSKirill A. Shutemov {
414b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
415b26e2701SQi Zheng 	struct mm_slot *slot;
416b46e756fSKirill A. Shutemov 	int wakeup;
417b46e756fSKirill A. Shutemov 
41816618670SXin Hao 	/* __khugepaged_exit() must not run from under us */
41916618670SXin Hao 	VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
42016618670SXin Hao 	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags)))
42116618670SXin Hao 		return;
42216618670SXin Hao 
423b26e2701SQi Zheng 	mm_slot = mm_slot_alloc(mm_slot_cache);
424b46e756fSKirill A. Shutemov 	if (!mm_slot)
425d2081b2bSYang Shi 		return;
426b46e756fSKirill A. Shutemov 
427b26e2701SQi Zheng 	slot = &mm_slot->slot;
428b26e2701SQi Zheng 
429b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
430b26e2701SQi Zheng 	mm_slot_insert(mm_slots_hash, mm, slot);
431b46e756fSKirill A. Shutemov 	/*
432b46e756fSKirill A. Shutemov 	 * Insert just behind the scanning cursor, to let the area settle
433b46e756fSKirill A. Shutemov 	 * down a little.
434b46e756fSKirill A. Shutemov 	 */
435b46e756fSKirill A. Shutemov 	wakeup = list_empty(&khugepaged_scan.mm_head);
436b26e2701SQi Zheng 	list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
437b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
438b46e756fSKirill A. Shutemov 
439f1f10076SVegard Nossum 	mmgrab(mm);
440b46e756fSKirill A. Shutemov 	if (wakeup)
441b46e756fSKirill A. Shutemov 		wake_up_interruptible(&khugepaged_wait);
442b46e756fSKirill A. Shutemov }
443b46e756fSKirill A. Shutemov 
444c791576cSYang Shi void khugepaged_enter_vma(struct vm_area_struct *vma,
445b46e756fSKirill A. Shutemov 			  unsigned long vm_flags)
446b46e756fSKirill A. Shutemov {
4472647d11bSYang Shi 	if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
4481064026bSYang Shi 	    hugepage_flags_enabled()) {
449a7f4e6e4SZach O'Keefe 		if (hugepage_vma_check(vma, vm_flags, false, false, true))
4502647d11bSYang Shi 			__khugepaged_enter(vma->vm_mm);
4512647d11bSYang Shi 	}
452b46e756fSKirill A. Shutemov }
453b46e756fSKirill A. Shutemov 
454b46e756fSKirill A. Shutemov void __khugepaged_exit(struct mm_struct *mm)
455b46e756fSKirill A. Shutemov {
456b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
457b26e2701SQi Zheng 	struct mm_slot *slot;
458b46e756fSKirill A. Shutemov 	int free = 0;
459b46e756fSKirill A. Shutemov 
460b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
461b26e2701SQi Zheng 	slot = mm_slot_lookup(mm_slots_hash, mm);
462b26e2701SQi Zheng 	mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
463b46e756fSKirill A. Shutemov 	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
464b26e2701SQi Zheng 		hash_del(&slot->hash);
465b26e2701SQi Zheng 		list_del(&slot->mm_node);
466b46e756fSKirill A. Shutemov 		free = 1;
467b46e756fSKirill A. Shutemov 	}
468b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
469b46e756fSKirill A. Shutemov 
470b46e756fSKirill A. Shutemov 	if (free) {
471b46e756fSKirill A. Shutemov 		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
472b26e2701SQi Zheng 		mm_slot_free(mm_slot_cache, mm_slot);
473b46e756fSKirill A. Shutemov 		mmdrop(mm);
474b46e756fSKirill A. Shutemov 	} else if (mm_slot) {
475b46e756fSKirill A. Shutemov 		/*
476b46e756fSKirill A. Shutemov 		 * This is required to serialize against
4777d2c4385SZach O'Keefe 		 * hpage_collapse_test_exit() (which is guaranteed to run
4787d2c4385SZach O'Keefe 		 * under mmap sem read mode). Stop here (after we return all
4797d2c4385SZach O'Keefe 		 * pagetables will be destroyed) until khugepaged has finished
4807d2c4385SZach O'Keefe 		 * working on the pagetables under the mmap_lock.
481b46e756fSKirill A. Shutemov 		 */
482d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
483d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
484b46e756fSKirill A. Shutemov 	}
485b46e756fSKirill A. Shutemov }
486b46e756fSKirill A. Shutemov 
48792644f58SVishal Moola (Oracle) static void release_pte_folio(struct folio *folio)
48892644f58SVishal Moola (Oracle) {
48992644f58SVishal Moola (Oracle) 	node_stat_mod_folio(folio,
49092644f58SVishal Moola (Oracle) 			NR_ISOLATED_ANON + folio_is_file_lru(folio),
49192644f58SVishal Moola (Oracle) 			-folio_nr_pages(folio));
49292644f58SVishal Moola (Oracle) 	folio_unlock(folio);
49392644f58SVishal Moola (Oracle) 	folio_putback_lru(folio);
49492644f58SVishal Moola (Oracle) }
49592644f58SVishal Moola (Oracle) 
496b46e756fSKirill A. Shutemov static void release_pte_page(struct page *page)
497b46e756fSKirill A. Shutemov {
49892644f58SVishal Moola (Oracle) 	release_pte_folio(page_folio(page));
499b46e756fSKirill A. Shutemov }
500b46e756fSKirill A. Shutemov 
5015503fbf2SKirill A. Shutemov static void release_pte_pages(pte_t *pte, pte_t *_pte,
5025503fbf2SKirill A. Shutemov 		struct list_head *compound_pagelist)
503b46e756fSKirill A. Shutemov {
5049bdfeea4SVishal Moola (Oracle) 	struct folio *folio, *tmp;
5055503fbf2SKirill A. Shutemov 
506b46e756fSKirill A. Shutemov 	while (--_pte >= pte) {
507c33c7948SRyan Roberts 		pte_t pteval = ptep_get(_pte);
508f528260bSVishal Moola (Oracle) 		unsigned long pfn;
5095503fbf2SKirill A. Shutemov 
510f528260bSVishal Moola (Oracle) 		if (pte_none(pteval))
511f528260bSVishal Moola (Oracle) 			continue;
512f528260bSVishal Moola (Oracle) 		pfn = pte_pfn(pteval);
513f528260bSVishal Moola (Oracle) 		if (is_zero_pfn(pfn))
514f528260bSVishal Moola (Oracle) 			continue;
515f528260bSVishal Moola (Oracle) 		folio = pfn_folio(pfn);
516f528260bSVishal Moola (Oracle) 		if (folio_test_large(folio))
517f528260bSVishal Moola (Oracle) 			continue;
5189bdfeea4SVishal Moola (Oracle) 		release_pte_folio(folio);
5195503fbf2SKirill A. Shutemov 	}
5205503fbf2SKirill A. Shutemov 
5219bdfeea4SVishal Moola (Oracle) 	list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
5229bdfeea4SVishal Moola (Oracle) 		list_del(&folio->lru);
5239bdfeea4SVishal Moola (Oracle) 		release_pte_folio(folio);
524b46e756fSKirill A. Shutemov 	}
525b46e756fSKirill A. Shutemov }
526b46e756fSKirill A. Shutemov 
527dbf85c21SVishal Moola (Oracle) static bool is_refcount_suitable(struct folio *folio)
5289445689fSKirill A. Shutemov {
5299445689fSKirill A. Shutemov 	int expected_refcount;
5309445689fSKirill A. Shutemov 
531dbf85c21SVishal Moola (Oracle) 	expected_refcount = folio_mapcount(folio);
532dbf85c21SVishal Moola (Oracle) 	if (folio_test_swapcache(folio))
533dbf85c21SVishal Moola (Oracle) 		expected_refcount += folio_nr_pages(folio);
5349445689fSKirill A. Shutemov 
535dbf85c21SVishal Moola (Oracle) 	return folio_ref_count(folio) == expected_refcount;
5369445689fSKirill A. Shutemov }
5379445689fSKirill A. Shutemov 
538b46e756fSKirill A. Shutemov static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
539b46e756fSKirill A. Shutemov 					unsigned long address,
5405503fbf2SKirill A. Shutemov 					pte_t *pte,
541d8ea7cc8SZach O'Keefe 					struct collapse_control *cc,
5425503fbf2SKirill A. Shutemov 					struct list_head *compound_pagelist)
543b46e756fSKirill A. Shutemov {
544b46e756fSKirill A. Shutemov 	struct page *page = NULL;
5458dd1e896SVishal Moola (Oracle) 	struct folio *folio = NULL;
546b46e756fSKirill A. Shutemov 	pte_t *_pte;
54750ad2f24SZach O'Keefe 	int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
5480db501f7SEbru Akagunduz 	bool writable = false;
549b46e756fSKirill A. Shutemov 
550b46e756fSKirill A. Shutemov 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
551b46e756fSKirill A. Shutemov 	     _pte++, address += PAGE_SIZE) {
552c33c7948SRyan Roberts 		pte_t pteval = ptep_get(_pte);
553b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || (pte_present(pteval) &&
554b46e756fSKirill A. Shutemov 				is_zero_pfn(pte_pfn(pteval)))) {
555d8ea7cc8SZach O'Keefe 			++none_or_zero;
556b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
557d8ea7cc8SZach O'Keefe 			    (!cc->is_khugepaged ||
558d8ea7cc8SZach O'Keefe 			     none_or_zero <= khugepaged_max_ptes_none)) {
559b46e756fSKirill A. Shutemov 				continue;
560b46e756fSKirill A. Shutemov 			} else {
561b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
562e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
563b46e756fSKirill A. Shutemov 				goto out;
564b46e756fSKirill A. Shutemov 			}
565b46e756fSKirill A. Shutemov 		}
566b46e756fSKirill A. Shutemov 		if (!pte_present(pteval)) {
567b46e756fSKirill A. Shutemov 			result = SCAN_PTE_NON_PRESENT;
568b46e756fSKirill A. Shutemov 			goto out;
569b46e756fSKirill A. Shutemov 		}
570dd47ac42SPeter Xu 		if (pte_uffd_wp(pteval)) {
571dd47ac42SPeter Xu 			result = SCAN_PTE_UFFD_WP;
572dd47ac42SPeter Xu 			goto out;
573dd47ac42SPeter Xu 		}
574b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, address, pteval);
5753218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
576b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
577b46e756fSKirill A. Shutemov 			goto out;
578b46e756fSKirill A. Shutemov 		}
579b46e756fSKirill A. Shutemov 
5808dd1e896SVishal Moola (Oracle) 		folio = page_folio(page);
5818dd1e896SVishal Moola (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_anon(folio), folio);
582b46e756fSKirill A. Shutemov 
583d8ea7cc8SZach O'Keefe 		if (page_mapcount(page) > 1) {
584d8ea7cc8SZach O'Keefe 			++shared;
585d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
586d8ea7cc8SZach O'Keefe 			    shared > khugepaged_max_ptes_shared) {
58771a2c112SKirill A. Shutemov 				result = SCAN_EXCEED_SHARED_PTE;
588e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
58971a2c112SKirill A. Shutemov 				goto out;
59071a2c112SKirill A. Shutemov 			}
591d8ea7cc8SZach O'Keefe 		}
59271a2c112SKirill A. Shutemov 
5938dd1e896SVishal Moola (Oracle) 		if (folio_test_large(folio)) {
5948dd1e896SVishal Moola (Oracle) 			struct folio *f;
5955503fbf2SKirill A. Shutemov 
5965503fbf2SKirill A. Shutemov 			/*
5975503fbf2SKirill A. Shutemov 			 * Check if we have dealt with the compound page
5985503fbf2SKirill A. Shutemov 			 * already
5995503fbf2SKirill A. Shutemov 			 */
6008dd1e896SVishal Moola (Oracle) 			list_for_each_entry(f, compound_pagelist, lru) {
6018dd1e896SVishal Moola (Oracle) 				if (folio == f)
6025503fbf2SKirill A. Shutemov 					goto next;
6035503fbf2SKirill A. Shutemov 			}
6045503fbf2SKirill A. Shutemov 		}
6055503fbf2SKirill A. Shutemov 
606b46e756fSKirill A. Shutemov 		/*
607b46e756fSKirill A. Shutemov 		 * We can do it before isolate_lru_page because the
608b46e756fSKirill A. Shutemov 		 * page can't be freed from under us. NOTE: PG_lock
609b46e756fSKirill A. Shutemov 		 * is needed to serialize against split_huge_page
610b46e756fSKirill A. Shutemov 		 * when invoked from the VM.
611b46e756fSKirill A. Shutemov 		 */
6128dd1e896SVishal Moola (Oracle) 		if (!folio_trylock(folio)) {
613b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
614b46e756fSKirill A. Shutemov 			goto out;
615b46e756fSKirill A. Shutemov 		}
616b46e756fSKirill A. Shutemov 
617b46e756fSKirill A. Shutemov 		/*
6189445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
6199445689fSKirill A. Shutemov 		 *
6209445689fSKirill A. Shutemov 		 * The page table that maps the page has been already unlinked
6219445689fSKirill A. Shutemov 		 * from the page table tree and this process cannot get
622f0953a1bSIngo Molnar 		 * an additional pin on the page.
6239445689fSKirill A. Shutemov 		 *
6249445689fSKirill A. Shutemov 		 * New pins can come later if the page is shared across fork,
6259445689fSKirill A. Shutemov 		 * but not from this process. The other process cannot write to
6269445689fSKirill A. Shutemov 		 * the page, only trigger CoW.
627b46e756fSKirill A. Shutemov 		 */
628dbf85c21SVishal Moola (Oracle) 		if (!is_refcount_suitable(folio)) {
6298dd1e896SVishal Moola (Oracle) 			folio_unlock(folio);
630b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
631b46e756fSKirill A. Shutemov 			goto out;
632b46e756fSKirill A. Shutemov 		}
633b46e756fSKirill A. Shutemov 
634b46e756fSKirill A. Shutemov 		/*
635b46e756fSKirill A. Shutemov 		 * Isolate the page to avoid collapsing an hugepage
636b46e756fSKirill A. Shutemov 		 * currently in use by the VM.
637b46e756fSKirill A. Shutemov 		 */
6388dd1e896SVishal Moola (Oracle) 		if (!folio_isolate_lru(folio)) {
6398dd1e896SVishal Moola (Oracle) 			folio_unlock(folio);
640b46e756fSKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
641b46e756fSKirill A. Shutemov 			goto out;
642b46e756fSKirill A. Shutemov 		}
6438dd1e896SVishal Moola (Oracle) 		node_stat_mod_folio(folio,
6448dd1e896SVishal Moola (Oracle) 				NR_ISOLATED_ANON + folio_is_file_lru(folio),
6458dd1e896SVishal Moola (Oracle) 				folio_nr_pages(folio));
6468dd1e896SVishal Moola (Oracle) 		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
6478dd1e896SVishal Moola (Oracle) 		VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
648b46e756fSKirill A. Shutemov 
6498dd1e896SVishal Moola (Oracle) 		if (folio_test_large(folio))
6508dd1e896SVishal Moola (Oracle) 			list_add_tail(&folio->lru, compound_pagelist);
6515503fbf2SKirill A. Shutemov next:
652d8ea7cc8SZach O'Keefe 		/*
653d8ea7cc8SZach O'Keefe 		 * If collapse was initiated by khugepaged, check that there is
654d8ea7cc8SZach O'Keefe 		 * enough young pte to justify collapsing the page
655d8ea7cc8SZach O'Keefe 		 */
656d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
6578dd1e896SVishal Moola (Oracle) 		    (pte_young(pteval) || folio_test_young(folio) ||
6588dd1e896SVishal Moola (Oracle) 		     folio_test_referenced(folio) || mmu_notifier_test_young(vma->vm_mm,
659d8ea7cc8SZach O'Keefe 								     address)))
6600db501f7SEbru Akagunduz 			referenced++;
6615503fbf2SKirill A. Shutemov 
6625503fbf2SKirill A. Shutemov 		if (pte_write(pteval))
6635503fbf2SKirill A. Shutemov 			writable = true;
664b46e756fSKirill A. Shutemov 	}
66574e579bfSMiaohe Lin 
66674e579bfSMiaohe Lin 	if (unlikely(!writable)) {
66774e579bfSMiaohe Lin 		result = SCAN_PAGE_RO;
668d8ea7cc8SZach O'Keefe 	} else if (unlikely(cc->is_khugepaged && !referenced)) {
66974e579bfSMiaohe Lin 		result = SCAN_LACK_REFERENCED_PAGE;
67074e579bfSMiaohe Lin 	} else {
671b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
6728dd1e896SVishal Moola (Oracle) 		trace_mm_collapse_huge_page_isolate(&folio->page, none_or_zero,
673b46e756fSKirill A. Shutemov 						    referenced, writable, result);
67450ad2f24SZach O'Keefe 		return result;
675b46e756fSKirill A. Shutemov 	}
676b46e756fSKirill A. Shutemov out:
6775503fbf2SKirill A. Shutemov 	release_pte_pages(pte, _pte, compound_pagelist);
6788dd1e896SVishal Moola (Oracle) 	trace_mm_collapse_huge_page_isolate(&folio->page, none_or_zero,
679b46e756fSKirill A. Shutemov 					    referenced, writable, result);
68050ad2f24SZach O'Keefe 	return result;
681b46e756fSKirill A. Shutemov }
682b46e756fSKirill A. Shutemov 
68398c76c9fSJiaqi Yan static void __collapse_huge_page_copy_succeeded(pte_t *pte,
684b46e756fSKirill A. Shutemov 						struct vm_area_struct *vma,
685b46e756fSKirill A. Shutemov 						unsigned long address,
6865503fbf2SKirill A. Shutemov 						spinlock_t *ptl,
6875503fbf2SKirill A. Shutemov 						struct list_head *compound_pagelist)
688b46e756fSKirill A. Shutemov {
68998c76c9fSJiaqi Yan 	struct page *src_page;
69098c76c9fSJiaqi Yan 	struct page *tmp;
691b46e756fSKirill A. Shutemov 	pte_t *_pte;
69298c76c9fSJiaqi Yan 	pte_t pteval;
693b46e756fSKirill A. Shutemov 
69498c76c9fSJiaqi Yan 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
69598c76c9fSJiaqi Yan 	     _pte++, address += PAGE_SIZE) {
696c33c7948SRyan Roberts 		pteval = ptep_get(_pte);
697b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
698b46e756fSKirill A. Shutemov 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
699b46e756fSKirill A. Shutemov 			if (is_zero_pfn(pte_pfn(pteval))) {
700b46e756fSKirill A. Shutemov 				/*
701b46e756fSKirill A. Shutemov 				 * ptl mostly unnecessary.
702b46e756fSKirill A. Shutemov 				 */
703b46e756fSKirill A. Shutemov 				spin_lock(ptl);
70408d5b29eSPasha Tatashin 				ptep_clear(vma->vm_mm, address, _pte);
705b46e756fSKirill A. Shutemov 				spin_unlock(ptl);
7066080d19fSxu xin 				ksm_might_unmap_zero_page(vma->vm_mm, pteval);
707b46e756fSKirill A. Shutemov 			}
708b46e756fSKirill A. Shutemov 		} else {
709b46e756fSKirill A. Shutemov 			src_page = pte_page(pteval);
7105503fbf2SKirill A. Shutemov 			if (!PageCompound(src_page))
711b46e756fSKirill A. Shutemov 				release_pte_page(src_page);
712b46e756fSKirill A. Shutemov 			/*
713b46e756fSKirill A. Shutemov 			 * ptl mostly unnecessary, but preempt has to
714b46e756fSKirill A. Shutemov 			 * be disabled to update the per-cpu stats
715b46e756fSKirill A. Shutemov 			 * inside page_remove_rmap().
716b46e756fSKirill A. Shutemov 			 */
717b46e756fSKirill A. Shutemov 			spin_lock(ptl);
71808d5b29eSPasha Tatashin 			ptep_clear(vma->vm_mm, address, _pte);
719cea86fe2SHugh Dickins 			page_remove_rmap(src_page, vma, false);
720b46e756fSKirill A. Shutemov 			spin_unlock(ptl);
721b46e756fSKirill A. Shutemov 			free_page_and_swap_cache(src_page);
722b46e756fSKirill A. Shutemov 		}
723b46e756fSKirill A. Shutemov 	}
7245503fbf2SKirill A. Shutemov 
7255503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
7265503fbf2SKirill A. Shutemov 		list_del(&src_page->lru);
7271baec203SMiaohe Lin 		mod_node_page_state(page_pgdat(src_page),
7281baec203SMiaohe Lin 				    NR_ISOLATED_ANON + page_is_file_lru(src_page),
7291baec203SMiaohe Lin 				    -compound_nr(src_page));
7301baec203SMiaohe Lin 		unlock_page(src_page);
7311baec203SMiaohe Lin 		free_swap_cache(src_page);
7321baec203SMiaohe Lin 		putback_lru_page(src_page);
7335503fbf2SKirill A. Shutemov 	}
734b46e756fSKirill A. Shutemov }
735b46e756fSKirill A. Shutemov 
73698c76c9fSJiaqi Yan static void __collapse_huge_page_copy_failed(pte_t *pte,
73798c76c9fSJiaqi Yan 					     pmd_t *pmd,
73898c76c9fSJiaqi Yan 					     pmd_t orig_pmd,
73998c76c9fSJiaqi Yan 					     struct vm_area_struct *vma,
74098c76c9fSJiaqi Yan 					     struct list_head *compound_pagelist)
74198c76c9fSJiaqi Yan {
74298c76c9fSJiaqi Yan 	spinlock_t *pmd_ptl;
74398c76c9fSJiaqi Yan 
74498c76c9fSJiaqi Yan 	/*
74598c76c9fSJiaqi Yan 	 * Re-establish the PMD to point to the original page table
74698c76c9fSJiaqi Yan 	 * entry. Restoring PMD needs to be done prior to releasing
74798c76c9fSJiaqi Yan 	 * pages. Since pages are still isolated and locked here,
74898c76c9fSJiaqi Yan 	 * acquiring anon_vma_lock_write is unnecessary.
74998c76c9fSJiaqi Yan 	 */
75098c76c9fSJiaqi Yan 	pmd_ptl = pmd_lock(vma->vm_mm, pmd);
75198c76c9fSJiaqi Yan 	pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd));
75298c76c9fSJiaqi Yan 	spin_unlock(pmd_ptl);
75398c76c9fSJiaqi Yan 	/*
75498c76c9fSJiaqi Yan 	 * Release both raw and compound pages isolated
75598c76c9fSJiaqi Yan 	 * in __collapse_huge_page_isolate.
75698c76c9fSJiaqi Yan 	 */
75798c76c9fSJiaqi Yan 	release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist);
75898c76c9fSJiaqi Yan }
75998c76c9fSJiaqi Yan 
76098c76c9fSJiaqi Yan /*
76198c76c9fSJiaqi Yan  * __collapse_huge_page_copy - attempts to copy memory contents from raw
76298c76c9fSJiaqi Yan  * pages to a hugepage. Cleans up the raw pages if copying succeeds;
76398c76c9fSJiaqi Yan  * otherwise restores the original page table and releases isolated raw pages.
76498c76c9fSJiaqi Yan  * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC.
76598c76c9fSJiaqi Yan  *
76698c76c9fSJiaqi Yan  * @pte: starting of the PTEs to copy from
76798c76c9fSJiaqi Yan  * @page: the new hugepage to copy contents to
76898c76c9fSJiaqi Yan  * @pmd: pointer to the new hugepage's PMD
76998c76c9fSJiaqi Yan  * @orig_pmd: the original raw pages' PMD
77098c76c9fSJiaqi Yan  * @vma: the original raw pages' virtual memory area
77198c76c9fSJiaqi Yan  * @address: starting address to copy
77298c76c9fSJiaqi Yan  * @ptl: lock on raw pages' PTEs
77398c76c9fSJiaqi Yan  * @compound_pagelist: list that stores compound pages
77498c76c9fSJiaqi Yan  */
77598c76c9fSJiaqi Yan static int __collapse_huge_page_copy(pte_t *pte,
77698c76c9fSJiaqi Yan 				     struct page *page,
77798c76c9fSJiaqi Yan 				     pmd_t *pmd,
77898c76c9fSJiaqi Yan 				     pmd_t orig_pmd,
77998c76c9fSJiaqi Yan 				     struct vm_area_struct *vma,
78098c76c9fSJiaqi Yan 				     unsigned long address,
78198c76c9fSJiaqi Yan 				     spinlock_t *ptl,
78298c76c9fSJiaqi Yan 				     struct list_head *compound_pagelist)
78398c76c9fSJiaqi Yan {
78498c76c9fSJiaqi Yan 	struct page *src_page;
78598c76c9fSJiaqi Yan 	pte_t *_pte;
78698c76c9fSJiaqi Yan 	pte_t pteval;
78798c76c9fSJiaqi Yan 	unsigned long _address;
78898c76c9fSJiaqi Yan 	int result = SCAN_SUCCEED;
78998c76c9fSJiaqi Yan 
79098c76c9fSJiaqi Yan 	/*
79198c76c9fSJiaqi Yan 	 * Copying pages' contents is subject to memory poison at any iteration.
79298c76c9fSJiaqi Yan 	 */
79398c76c9fSJiaqi Yan 	for (_pte = pte, _address = address; _pte < pte + HPAGE_PMD_NR;
79498c76c9fSJiaqi Yan 	     _pte++, page++, _address += PAGE_SIZE) {
795c33c7948SRyan Roberts 		pteval = ptep_get(_pte);
79698c76c9fSJiaqi Yan 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
79798c76c9fSJiaqi Yan 			clear_user_highpage(page, _address);
79898c76c9fSJiaqi Yan 			continue;
79998c76c9fSJiaqi Yan 		}
80098c76c9fSJiaqi Yan 		src_page = pte_page(pteval);
80198c76c9fSJiaqi Yan 		if (copy_mc_user_highpage(page, src_page, _address, vma) > 0) {
80298c76c9fSJiaqi Yan 			result = SCAN_COPY_MC;
80398c76c9fSJiaqi Yan 			break;
80498c76c9fSJiaqi Yan 		}
80598c76c9fSJiaqi Yan 	}
80698c76c9fSJiaqi Yan 
80798c76c9fSJiaqi Yan 	if (likely(result == SCAN_SUCCEED))
80898c76c9fSJiaqi Yan 		__collapse_huge_page_copy_succeeded(pte, vma, address, ptl,
80998c76c9fSJiaqi Yan 						    compound_pagelist);
81098c76c9fSJiaqi Yan 	else
81198c76c9fSJiaqi Yan 		__collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma,
81298c76c9fSJiaqi Yan 						 compound_pagelist);
81398c76c9fSJiaqi Yan 
81498c76c9fSJiaqi Yan 	return result;
81598c76c9fSJiaqi Yan }
81698c76c9fSJiaqi Yan 
817b46e756fSKirill A. Shutemov static void khugepaged_alloc_sleep(void)
818b46e756fSKirill A. Shutemov {
819b46e756fSKirill A. Shutemov 	DEFINE_WAIT(wait);
820b46e756fSKirill A. Shutemov 
821b46e756fSKirill A. Shutemov 	add_wait_queue(&khugepaged_wait, &wait);
822f5d39b02SPeter Zijlstra 	__set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
823f5d39b02SPeter Zijlstra 	schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
824b46e756fSKirill A. Shutemov 	remove_wait_queue(&khugepaged_wait, &wait);
825b46e756fSKirill A. Shutemov }
826b46e756fSKirill A. Shutemov 
82734d6b470SZach O'Keefe struct collapse_control khugepaged_collapse_control = {
828d8ea7cc8SZach O'Keefe 	.is_khugepaged = true,
82934d6b470SZach O'Keefe };
830b46e756fSKirill A. Shutemov 
8317d2c4385SZach O'Keefe static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
832b46e756fSKirill A. Shutemov {
833b46e756fSKirill A. Shutemov 	int i;
834b46e756fSKirill A. Shutemov 
835b46e756fSKirill A. Shutemov 	/*
836a5f5f91dSMel Gorman 	 * If node_reclaim_mode is disabled, then no extra effort is made to
837b46e756fSKirill A. Shutemov 	 * allocate memory locally.
838b46e756fSKirill A. Shutemov 	 */
839202e35dbSDave Hansen 	if (!node_reclaim_enabled())
840b46e756fSKirill A. Shutemov 		return false;
841b46e756fSKirill A. Shutemov 
842b46e756fSKirill A. Shutemov 	/* If there is a count for this node already, it must be acceptable */
84334d6b470SZach O'Keefe 	if (cc->node_load[nid])
844b46e756fSKirill A. Shutemov 		return false;
845b46e756fSKirill A. Shutemov 
846b46e756fSKirill A. Shutemov 	for (i = 0; i < MAX_NUMNODES; i++) {
84734d6b470SZach O'Keefe 		if (!cc->node_load[i])
848b46e756fSKirill A. Shutemov 			continue;
849a55c7454SMatt Fleming 		if (node_distance(nid, i) > node_reclaim_distance)
850b46e756fSKirill A. Shutemov 			return true;
851b46e756fSKirill A. Shutemov 	}
852b46e756fSKirill A. Shutemov 	return false;
853b46e756fSKirill A. Shutemov }
854b46e756fSKirill A. Shutemov 
8551064026bSYang Shi #define khugepaged_defrag()					\
8561064026bSYang Shi 	(transparent_hugepage_flags &				\
8571064026bSYang Shi 	 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
8581064026bSYang Shi 
859b46e756fSKirill A. Shutemov /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
860b46e756fSKirill A. Shutemov static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
861b46e756fSKirill A. Shutemov {
86225160354SVlastimil Babka 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
863b46e756fSKirill A. Shutemov }
864b46e756fSKirill A. Shutemov 
865b46e756fSKirill A. Shutemov #ifdef CONFIG_NUMA
8667d2c4385SZach O'Keefe static int hpage_collapse_find_target_node(struct collapse_control *cc)
867b46e756fSKirill A. Shutemov {
868b46e756fSKirill A. Shutemov 	int nid, target_node = 0, max_value = 0;
869b46e756fSKirill A. Shutemov 
870b46e756fSKirill A. Shutemov 	/* find first node with max normal pages hit */
871b46e756fSKirill A. Shutemov 	for (nid = 0; nid < MAX_NUMNODES; nid++)
87234d6b470SZach O'Keefe 		if (cc->node_load[nid] > max_value) {
87334d6b470SZach O'Keefe 			max_value = cc->node_load[nid];
874b46e756fSKirill A. Shutemov 			target_node = nid;
875b46e756fSKirill A. Shutemov 		}
876b46e756fSKirill A. Shutemov 
877e031ff96SYang Shi 	for_each_online_node(nid) {
878e031ff96SYang Shi 		if (max_value == cc->node_load[nid])
879e031ff96SYang Shi 			node_set(nid, cc->alloc_nmask);
880b46e756fSKirill A. Shutemov 	}
881b46e756fSKirill A. Shutemov 
882b46e756fSKirill A. Shutemov 	return target_node;
883b46e756fSKirill A. Shutemov }
884c6a7f445SYang Shi #else
8857d2c4385SZach O'Keefe static int hpage_collapse_find_target_node(struct collapse_control *cc)
886b46e756fSKirill A. Shutemov {
887c6a7f445SYang Shi 	return 0;
888b46e756fSKirill A. Shutemov }
889c6a7f445SYang Shi #endif
890b46e756fSKirill A. Shutemov 
891b455f39dSVishal Moola (Oracle) static bool hpage_collapse_alloc_folio(struct folio **folio, gfp_t gfp, int node,
892e031ff96SYang Shi 				      nodemask_t *nmask)
893b46e756fSKirill A. Shutemov {
894b455f39dSVishal Moola (Oracle) 	*folio = __folio_alloc(gfp, HPAGE_PMD_ORDER, node, nmask);
895b455f39dSVishal Moola (Oracle) 
896b455f39dSVishal Moola (Oracle) 	if (unlikely(!*folio)) {
897b46e756fSKirill A. Shutemov 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
8989710a78aSZach O'Keefe 		return false;
899b46e756fSKirill A. Shutemov 	}
900b46e756fSKirill A. Shutemov 
901b46e756fSKirill A. Shutemov 	count_vm_event(THP_COLLAPSE_ALLOC);
902b46e756fSKirill A. Shutemov 	return true;
903b46e756fSKirill A. Shutemov }
904b46e756fSKirill A. Shutemov 
905b46e756fSKirill A. Shutemov /*
906c1e8d7c6SMichel Lespinasse  * If mmap_lock temporarily dropped, revalidate vma
907c1e8d7c6SMichel Lespinasse  * before taking mmap_lock.
90850ad2f24SZach O'Keefe  * Returns enum scan_result value.
909b46e756fSKirill A. Shutemov  */
910b46e756fSKirill A. Shutemov 
911c131f751SKirill A. Shutemov static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
91234488399SZach O'Keefe 				   bool expect_anon,
913a7f4e6e4SZach O'Keefe 				   struct vm_area_struct **vmap,
914a7f4e6e4SZach O'Keefe 				   struct collapse_control *cc)
915b46e756fSKirill A. Shutemov {
916b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
917b46e756fSKirill A. Shutemov 
9187d2c4385SZach O'Keefe 	if (unlikely(hpage_collapse_test_exit(mm)))
919b46e756fSKirill A. Shutemov 		return SCAN_ANY_PROCESS;
920b46e756fSKirill A. Shutemov 
921c131f751SKirill A. Shutemov 	*vmap = vma = find_vma(mm, address);
922b46e756fSKirill A. Shutemov 	if (!vma)
923b46e756fSKirill A. Shutemov 		return SCAN_VMA_NULL;
924b46e756fSKirill A. Shutemov 
9254fa6893fSYang Shi 	if (!transhuge_vma_suitable(vma, address))
926b46e756fSKirill A. Shutemov 		return SCAN_ADDRESS_RANGE;
927a7f4e6e4SZach O'Keefe 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false,
928a7f4e6e4SZach O'Keefe 				cc->is_khugepaged))
929b46e756fSKirill A. Shutemov 		return SCAN_VMA_CHECK;
930f707fa49SYang Shi 	/*
931f707fa49SYang Shi 	 * Anon VMA expected, the address may be unmapped then
932f707fa49SYang Shi 	 * remapped to file after khugepaged reaquired the mmap_lock.
933f707fa49SYang Shi 	 *
934f707fa49SYang Shi 	 * hugepage_vma_check may return true for qualified file
935f707fa49SYang Shi 	 * vmas.
936f707fa49SYang Shi 	 */
93734488399SZach O'Keefe 	if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
93834488399SZach O'Keefe 		return SCAN_PAGE_ANON;
93950ad2f24SZach O'Keefe 	return SCAN_SUCCEED;
940b46e756fSKirill A. Shutemov }
941b46e756fSKirill A. Shutemov 
94250722804SZach O'Keefe static int find_pmd_or_thp_or_none(struct mm_struct *mm,
94350722804SZach O'Keefe 				   unsigned long address,
94450722804SZach O'Keefe 				   pmd_t **pmd)
94550722804SZach O'Keefe {
94650722804SZach O'Keefe 	pmd_t pmde;
94750722804SZach O'Keefe 
94850722804SZach O'Keefe 	*pmd = mm_find_pmd(mm, address);
94950722804SZach O'Keefe 	if (!*pmd)
95050722804SZach O'Keefe 		return SCAN_PMD_NULL;
95150722804SZach O'Keefe 
952dab6e717SPeter Zijlstra 	pmde = pmdp_get_lockless(*pmd);
95334488399SZach O'Keefe 	if (pmd_none(pmde))
95434488399SZach O'Keefe 		return SCAN_PMD_NONE;
955edb5d0cfSZach O'Keefe 	if (!pmd_present(pmde))
956edb5d0cfSZach O'Keefe 		return SCAN_PMD_NULL;
95750722804SZach O'Keefe 	if (pmd_trans_huge(pmde))
95850722804SZach O'Keefe 		return SCAN_PMD_MAPPED;
959edb5d0cfSZach O'Keefe 	if (pmd_devmap(pmde))
960edb5d0cfSZach O'Keefe 		return SCAN_PMD_NULL;
96150722804SZach O'Keefe 	if (pmd_bad(pmde))
96250722804SZach O'Keefe 		return SCAN_PMD_NULL;
96350722804SZach O'Keefe 	return SCAN_SUCCEED;
96450722804SZach O'Keefe }
96550722804SZach O'Keefe 
96650722804SZach O'Keefe static int check_pmd_still_valid(struct mm_struct *mm,
96750722804SZach O'Keefe 				 unsigned long address,
96850722804SZach O'Keefe 				 pmd_t *pmd)
96950722804SZach O'Keefe {
97050722804SZach O'Keefe 	pmd_t *new_pmd;
97150722804SZach O'Keefe 	int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
97250722804SZach O'Keefe 
97350722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
97450722804SZach O'Keefe 		return result;
97550722804SZach O'Keefe 	if (new_pmd != pmd)
97650722804SZach O'Keefe 		return SCAN_FAIL;
97750722804SZach O'Keefe 	return SCAN_SUCCEED;
978b46e756fSKirill A. Shutemov }
979b46e756fSKirill A. Shutemov 
980b46e756fSKirill A. Shutemov /*
981b46e756fSKirill A. Shutemov  * Bring missing pages in from swap, to complete THP collapse.
9827d2c4385SZach O'Keefe  * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
983b46e756fSKirill A. Shutemov  *
9844d928e20SMiaohe Lin  * Called and returns without pte mapped or spinlocks held.
985895f5ee4SHugh Dickins  * Returns result: if not SCAN_SUCCEED, mmap_lock has been released.
986b46e756fSKirill A. Shutemov  */
98750ad2f24SZach O'Keefe static int __collapse_huge_page_swapin(struct mm_struct *mm,
988b46e756fSKirill A. Shutemov 				       struct vm_area_struct *vma,
9892b635dd3SWill Deacon 				       unsigned long haddr, pmd_t *pmd,
9900db501f7SEbru Akagunduz 				       int referenced)
991b46e756fSKirill A. Shutemov {
9922b740303SSouptick Joarder 	int swapped_in = 0;
9932b740303SSouptick Joarder 	vm_fault_t ret = 0;
9942b635dd3SWill Deacon 	unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
995895f5ee4SHugh Dickins 	int result;
996895f5ee4SHugh Dickins 	pte_t *pte = NULL;
997c7ad0880SHugh Dickins 	spinlock_t *ptl;
9982b635dd3SWill Deacon 
9992b635dd3SWill Deacon 	for (address = haddr; address < end; address += PAGE_SIZE) {
100082b0f8c3SJan Kara 		struct vm_fault vmf = {
1001b46e756fSKirill A. Shutemov 			.vma = vma,
1002b46e756fSKirill A. Shutemov 			.address = address,
1003895f5ee4SHugh Dickins 			.pgoff = linear_page_index(vma, address),
1004b46e756fSKirill A. Shutemov 			.flags = FAULT_FLAG_ALLOW_RETRY,
1005b46e756fSKirill A. Shutemov 			.pmd = pmd,
1006b46e756fSKirill A. Shutemov 		};
1007b46e756fSKirill A. Shutemov 
1008895f5ee4SHugh Dickins 		if (!pte++) {
1009c7ad0880SHugh Dickins 			pte = pte_offset_map_nolock(mm, pmd, address, &ptl);
1010895f5ee4SHugh Dickins 			if (!pte) {
1011895f5ee4SHugh Dickins 				mmap_read_unlock(mm);
1012895f5ee4SHugh Dickins 				result = SCAN_PMD_NULL;
1013895f5ee4SHugh Dickins 				goto out;
10142b635dd3SWill Deacon 			}
1015895f5ee4SHugh Dickins 		}
1016895f5ee4SHugh Dickins 
1017c7ad0880SHugh Dickins 		vmf.orig_pte = ptep_get_lockless(pte);
1018895f5ee4SHugh Dickins 		if (!is_swap_pte(vmf.orig_pte))
1019895f5ee4SHugh Dickins 			continue;
1020895f5ee4SHugh Dickins 
1021895f5ee4SHugh Dickins 		vmf.pte = pte;
1022c7ad0880SHugh Dickins 		vmf.ptl = ptl;
10232994302bSJan Kara 		ret = do_swap_page(&vmf);
1024895f5ee4SHugh Dickins 		/* Which unmaps pte (after perhaps re-checking the entry) */
1025895f5ee4SHugh Dickins 		pte = NULL;
10260db501f7SEbru Akagunduz 
10274d928e20SMiaohe Lin 		/*
10284d928e20SMiaohe Lin 		 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
10294d928e20SMiaohe Lin 		 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
10304d928e20SMiaohe Lin 		 * we do not retry here and swap entry will remain in pagetable
10314d928e20SMiaohe Lin 		 * resulting in later failure.
10324d928e20SMiaohe Lin 		 */
1033b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_RETRY) {
103450ad2f24SZach O'Keefe 			/* Likely, but not guaranteed, that page lock failed */
1035895f5ee4SHugh Dickins 			result = SCAN_PAGE_LOCK;
1036895f5ee4SHugh Dickins 			goto out;
103747f863eaSEbru Akagunduz 		}
1038b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_ERROR) {
10394d928e20SMiaohe Lin 			mmap_read_unlock(mm);
1040895f5ee4SHugh Dickins 			result = SCAN_FAIL;
1041895f5ee4SHugh Dickins 			goto out;
1042b46e756fSKirill A. Shutemov 		}
10434d928e20SMiaohe Lin 		swapped_in++;
1044b46e756fSKirill A. Shutemov 	}
1045ae2c5d80SKirill A. Shutemov 
1046895f5ee4SHugh Dickins 	if (pte)
1047895f5ee4SHugh Dickins 		pte_unmap(pte);
1048895f5ee4SHugh Dickins 
10491fec6890SMatthew Wilcox (Oracle) 	/* Drain LRU cache to remove extra pin on the swapped in pages */
1050ae2c5d80SKirill A. Shutemov 	if (swapped_in)
1051ae2c5d80SKirill A. Shutemov 		lru_add_drain();
1052ae2c5d80SKirill A. Shutemov 
1053895f5ee4SHugh Dickins 	result = SCAN_SUCCEED;
1054895f5ee4SHugh Dickins out:
1055895f5ee4SHugh Dickins 	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, result);
1056895f5ee4SHugh Dickins 	return result;
1057b46e756fSKirill A. Shutemov }
1058b46e756fSKirill A. Shutemov 
10599710a78aSZach O'Keefe static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
10609710a78aSZach O'Keefe 			      struct collapse_control *cc)
10619710a78aSZach O'Keefe {
10627d8faaf1SZach O'Keefe 	gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
1063e031ff96SYang Shi 		     GFP_TRANSHUGE);
10647d2c4385SZach O'Keefe 	int node = hpage_collapse_find_target_node(cc);
106594c02ad7SPeter Xu 	struct folio *folio;
10669710a78aSZach O'Keefe 
1067b455f39dSVishal Moola (Oracle) 	if (!hpage_collapse_alloc_folio(&folio, gfp, node, &cc->alloc_nmask)) {
1068b455f39dSVishal Moola (Oracle) 		*hpage = NULL;
10699710a78aSZach O'Keefe 		return SCAN_ALLOC_HUGE_PAGE_FAIL;
1070b455f39dSVishal Moola (Oracle) 	}
107194c02ad7SPeter Xu 
107294c02ad7SPeter Xu 	if (unlikely(mem_cgroup_charge(folio, mm, gfp))) {
107394c02ad7SPeter Xu 		folio_put(folio);
107494c02ad7SPeter Xu 		*hpage = NULL;
10759710a78aSZach O'Keefe 		return SCAN_CGROUP_CHARGE_FAIL;
107694c02ad7SPeter Xu 	}
107794c02ad7SPeter Xu 
1078b455f39dSVishal Moola (Oracle) 	count_memcg_folio_events(folio, THP_COLLAPSE_ALLOC, 1);
1079b455f39dSVishal Moola (Oracle) 
1080b455f39dSVishal Moola (Oracle) 	*hpage = folio_page(folio, 0);
10819710a78aSZach O'Keefe 	return SCAN_SUCCEED;
10829710a78aSZach O'Keefe }
10839710a78aSZach O'Keefe 
108450ad2f24SZach O'Keefe static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
108550ad2f24SZach O'Keefe 			      int referenced, int unmapped,
108650ad2f24SZach O'Keefe 			      struct collapse_control *cc)
1087b46e756fSKirill A. Shutemov {
10885503fbf2SKirill A. Shutemov 	LIST_HEAD(compound_pagelist);
1089b46e756fSKirill A. Shutemov 	pmd_t *pmd, _pmd;
1090b46e756fSKirill A. Shutemov 	pte_t *pte;
1091b46e756fSKirill A. Shutemov 	pgtable_t pgtable;
109250ad2f24SZach O'Keefe 	struct page *hpage;
1093b46e756fSKirill A. Shutemov 	spinlock_t *pmd_ptl, *pte_ptl;
109450ad2f24SZach O'Keefe 	int result = SCAN_FAIL;
1095c131f751SKirill A. Shutemov 	struct vm_area_struct *vma;
1096ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
1097b46e756fSKirill A. Shutemov 
1098b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1099b46e756fSKirill A. Shutemov 
1100988ddb71SKirill A. Shutemov 	/*
1101c1e8d7c6SMichel Lespinasse 	 * Before allocating the hugepage, release the mmap_lock read lock.
1102988ddb71SKirill A. Shutemov 	 * The allocation can take potentially a long time if it involves
1103c1e8d7c6SMichel Lespinasse 	 * sync compaction, and we do not need to hold the mmap_lock during
1104988ddb71SKirill A. Shutemov 	 * that. We will recheck the vma after taking it again in write mode.
1105988ddb71SKirill A. Shutemov 	 */
1106d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
1107b46e756fSKirill A. Shutemov 
110850ad2f24SZach O'Keefe 	result = alloc_charge_hpage(&hpage, mm, cc);
11099710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1110b46e756fSKirill A. Shutemov 		goto out_nolock;
1111b46e756fSKirill A. Shutemov 
1112d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
111334488399SZach O'Keefe 	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
111450ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED) {
1115d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
1116b46e756fSKirill A. Shutemov 		goto out_nolock;
1117b46e756fSKirill A. Shutemov 	}
1118b46e756fSKirill A. Shutemov 
111950722804SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, address, &pmd);
112050722804SZach O'Keefe 	if (result != SCAN_SUCCEED) {
1121d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
1122b46e756fSKirill A. Shutemov 		goto out_nolock;
1123b46e756fSKirill A. Shutemov 	}
1124b46e756fSKirill A. Shutemov 
112550ad2f24SZach O'Keefe 	if (unmapped) {
1126b46e756fSKirill A. Shutemov 		/*
112750ad2f24SZach O'Keefe 		 * __collapse_huge_page_swapin will return with mmap_lock
112850ad2f24SZach O'Keefe 		 * released when it fails. So we jump out_nolock directly in
112950ad2f24SZach O'Keefe 		 * that case.  Continuing to collapse causes inconsistency.
1130b46e756fSKirill A. Shutemov 		 */
113150ad2f24SZach O'Keefe 		result = __collapse_huge_page_swapin(mm, vma, address, pmd,
113250ad2f24SZach O'Keefe 						     referenced);
113350ad2f24SZach O'Keefe 		if (result != SCAN_SUCCEED)
1134b46e756fSKirill A. Shutemov 			goto out_nolock;
1135b46e756fSKirill A. Shutemov 	}
1136b46e756fSKirill A. Shutemov 
1137d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
1138b46e756fSKirill A. Shutemov 	/*
1139b46e756fSKirill A. Shutemov 	 * Prevent all access to pagetables with the exception of
1140b46e756fSKirill A. Shutemov 	 * gup_fast later handled by the ptep_clear_flush and the VM
1141b46e756fSKirill A. Shutemov 	 * handled by the anon_vma lock + PG_lock.
1142b46e756fSKirill A. Shutemov 	 */
1143d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
114434488399SZach O'Keefe 	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
114550ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED)
114618d24a7cSMiaohe Lin 		goto out_up_write;
1147b46e756fSKirill A. Shutemov 	/* check if the pmd is still valid */
114850722804SZach O'Keefe 	result = check_pmd_still_valid(mm, address, pmd);
114950722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
115018d24a7cSMiaohe Lin 		goto out_up_write;
1151b46e756fSKirill A. Shutemov 
115255fd6fccSSuren Baghdasaryan 	vma_start_write(vma);
1153b46e756fSKirill A. Shutemov 	anon_vma_lock_write(vma->anon_vma);
1154b46e756fSKirill A. Shutemov 
11557d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
11567d4a8be0SAlistair Popple 				address + HPAGE_PMD_SIZE);
1157ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1158ec649c9dSVille Syrjälä 
1159b46e756fSKirill A. Shutemov 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1160b46e756fSKirill A. Shutemov 	/*
116170cbc3ccSYang Shi 	 * This removes any huge TLB entry from the CPU so we won't allow
116270cbc3ccSYang Shi 	 * huge and small TLB entries for the same virtual address to
116370cbc3ccSYang Shi 	 * avoid the risk of CPU bugs in that area.
116470cbc3ccSYang Shi 	 *
116570cbc3ccSYang Shi 	 * Parallel fast GUP is fine since fast GUP will back off when
116670cbc3ccSYang Shi 	 * it detects PMD is changed.
1167b46e756fSKirill A. Shutemov 	 */
1168b46e756fSKirill A. Shutemov 	_pmd = pmdp_collapse_flush(vma, address, pmd);
1169b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1170ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
11712ba99c5eSJann Horn 	tlb_remove_table_sync_one();
1172b46e756fSKirill A. Shutemov 
1173895f5ee4SHugh Dickins 	pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl);
1174895f5ee4SHugh Dickins 	if (pte) {
1175d8ea7cc8SZach O'Keefe 		result = __collapse_huge_page_isolate(vma, address, pte, cc,
11765503fbf2SKirill A. Shutemov 						      &compound_pagelist);
1177b46e756fSKirill A. Shutemov 		spin_unlock(pte_ptl);
1178895f5ee4SHugh Dickins 	} else {
1179895f5ee4SHugh Dickins 		result = SCAN_PMD_NULL;
1180895f5ee4SHugh Dickins 	}
1181b46e756fSKirill A. Shutemov 
118250ad2f24SZach O'Keefe 	if (unlikely(result != SCAN_SUCCEED)) {
1183895f5ee4SHugh Dickins 		if (pte)
1184b46e756fSKirill A. Shutemov 			pte_unmap(pte);
1185b46e756fSKirill A. Shutemov 		spin_lock(pmd_ptl);
1186b46e756fSKirill A. Shutemov 		BUG_ON(!pmd_none(*pmd));
1187b46e756fSKirill A. Shutemov 		/*
1188b46e756fSKirill A. Shutemov 		 * We can only use set_pmd_at when establishing
1189b46e756fSKirill A. Shutemov 		 * hugepmds and never for establishing regular pmds that
1190b46e756fSKirill A. Shutemov 		 * points to regular pagetables. Use pmd_populate for that
1191b46e756fSKirill A. Shutemov 		 */
1192b46e756fSKirill A. Shutemov 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1193b46e756fSKirill A. Shutemov 		spin_unlock(pmd_ptl);
1194b46e756fSKirill A. Shutemov 		anon_vma_unlock_write(vma->anon_vma);
119518d24a7cSMiaohe Lin 		goto out_up_write;
1196b46e756fSKirill A. Shutemov 	}
1197b46e756fSKirill A. Shutemov 
1198b46e756fSKirill A. Shutemov 	/*
1199b46e756fSKirill A. Shutemov 	 * All pages are isolated and locked so anon_vma rmap
1200b46e756fSKirill A. Shutemov 	 * can't run anymore.
1201b46e756fSKirill A. Shutemov 	 */
1202b46e756fSKirill A. Shutemov 	anon_vma_unlock_write(vma->anon_vma);
1203b46e756fSKirill A. Shutemov 
120498c76c9fSJiaqi Yan 	result = __collapse_huge_page_copy(pte, hpage, pmd, _pmd,
120598c76c9fSJiaqi Yan 					   vma, address, pte_ptl,
12065503fbf2SKirill A. Shutemov 					   &compound_pagelist);
1207b46e756fSKirill A. Shutemov 	pte_unmap(pte);
120898c76c9fSJiaqi Yan 	if (unlikely(result != SCAN_SUCCEED))
120998c76c9fSJiaqi Yan 		goto out_up_write;
121098c76c9fSJiaqi Yan 
1211588d01f9SMiaohe Lin 	/*
1212588d01f9SMiaohe Lin 	 * spin_lock() below is not the equivalent of smp_wmb(), but
1213588d01f9SMiaohe Lin 	 * the smp_wmb() inside __SetPageUptodate() can be reused to
1214588d01f9SMiaohe Lin 	 * avoid the copy_huge_page writes to become visible after
1215588d01f9SMiaohe Lin 	 * the set_pmd_at() write.
1216588d01f9SMiaohe Lin 	 */
121750ad2f24SZach O'Keefe 	__SetPageUptodate(hpage);
1218b46e756fSKirill A. Shutemov 	pgtable = pmd_pgtable(_pmd);
1219b46e756fSKirill A. Shutemov 
122050ad2f24SZach O'Keefe 	_pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1221f55e1014SLinus Torvalds 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1222b46e756fSKirill A. Shutemov 
1223b46e756fSKirill A. Shutemov 	spin_lock(pmd_ptl);
1224b46e756fSKirill A. Shutemov 	BUG_ON(!pmd_none(*pmd));
122550ad2f24SZach O'Keefe 	page_add_new_anon_rmap(hpage, vma, address);
122650ad2f24SZach O'Keefe 	lru_cache_add_inactive_or_unevictable(hpage, vma);
1227b46e756fSKirill A. Shutemov 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1228b46e756fSKirill A. Shutemov 	set_pmd_at(mm, address, pmd, _pmd);
1229b46e756fSKirill A. Shutemov 	update_mmu_cache_pmd(vma, address, pmd);
1230b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1231b46e756fSKirill A. Shutemov 
123250ad2f24SZach O'Keefe 	hpage = NULL;
1233b46e756fSKirill A. Shutemov 
1234b46e756fSKirill A. Shutemov 	result = SCAN_SUCCEED;
1235b46e756fSKirill A. Shutemov out_up_write:
1236d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1237b46e756fSKirill A. Shutemov out_nolock:
12387cb1d7efSPeter Xu 	if (hpage)
123950ad2f24SZach O'Keefe 		put_page(hpage);
124050ad2f24SZach O'Keefe 	trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
124150ad2f24SZach O'Keefe 	return result;
1242b46e756fSKirill A. Shutemov }
1243b46e756fSKirill A. Shutemov 
12447d2c4385SZach O'Keefe static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1245b46e756fSKirill A. Shutemov 				   struct vm_area_struct *vma,
124650ad2f24SZach O'Keefe 				   unsigned long address, bool *mmap_locked,
124734d6b470SZach O'Keefe 				   struct collapse_control *cc)
1248b46e756fSKirill A. Shutemov {
1249b46e756fSKirill A. Shutemov 	pmd_t *pmd;
1250b46e756fSKirill A. Shutemov 	pte_t *pte, *_pte;
125150ad2f24SZach O'Keefe 	int result = SCAN_FAIL, referenced = 0;
125271a2c112SKirill A. Shutemov 	int none_or_zero = 0, shared = 0;
1253b46e756fSKirill A. Shutemov 	struct page *page = NULL;
12545c07ebb3SVishal Moola (Oracle) 	struct folio *folio = NULL;
1255b46e756fSKirill A. Shutemov 	unsigned long _address;
1256b46e756fSKirill A. Shutemov 	spinlock_t *ptl;
1257b46e756fSKirill A. Shutemov 	int node = NUMA_NO_NODE, unmapped = 0;
12580db501f7SEbru Akagunduz 	bool writable = false;
1259b46e756fSKirill A. Shutemov 
1260b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1261b46e756fSKirill A. Shutemov 
126250722804SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, address, &pmd);
126350722804SZach O'Keefe 	if (result != SCAN_SUCCEED)
1264b46e756fSKirill A. Shutemov 		goto out;
1265b46e756fSKirill A. Shutemov 
126634d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1267e031ff96SYang Shi 	nodes_clear(cc->alloc_nmask);
1268b46e756fSKirill A. Shutemov 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1269895f5ee4SHugh Dickins 	if (!pte) {
1270895f5ee4SHugh Dickins 		result = SCAN_PMD_NULL;
1271895f5ee4SHugh Dickins 		goto out;
1272895f5ee4SHugh Dickins 	}
1273895f5ee4SHugh Dickins 
1274b46e756fSKirill A. Shutemov 	for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1275b46e756fSKirill A. Shutemov 	     _pte++, _address += PAGE_SIZE) {
1276c33c7948SRyan Roberts 		pte_t pteval = ptep_get(_pte);
1277b46e756fSKirill A. Shutemov 		if (is_swap_pte(pteval)) {
1278d8ea7cc8SZach O'Keefe 			++unmapped;
1279d8ea7cc8SZach O'Keefe 			if (!cc->is_khugepaged ||
1280d8ea7cc8SZach O'Keefe 			    unmapped <= khugepaged_max_ptes_swap) {
1281e1e267c7SPeter Xu 				/*
1282e1e267c7SPeter Xu 				 * Always be strict with uffd-wp
1283e1e267c7SPeter Xu 				 * enabled swap entries.  Please see
1284e1e267c7SPeter Xu 				 * comment below for pte_uffd_wp().
1285e1e267c7SPeter Xu 				 */
12862bad466cSPeter Xu 				if (pte_swp_uffd_wp_any(pteval)) {
1287e1e267c7SPeter Xu 					result = SCAN_PTE_UFFD_WP;
1288e1e267c7SPeter Xu 					goto out_unmap;
1289e1e267c7SPeter Xu 				}
1290b46e756fSKirill A. Shutemov 				continue;
1291b46e756fSKirill A. Shutemov 			} else {
1292b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1293e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1294b46e756fSKirill A. Shutemov 				goto out_unmap;
1295b46e756fSKirill A. Shutemov 			}
1296b46e756fSKirill A. Shutemov 		}
1297b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1298d8ea7cc8SZach O'Keefe 			++none_or_zero;
1299b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
1300d8ea7cc8SZach O'Keefe 			    (!cc->is_khugepaged ||
1301d8ea7cc8SZach O'Keefe 			     none_or_zero <= khugepaged_max_ptes_none)) {
1302b46e756fSKirill A. Shutemov 				continue;
1303b46e756fSKirill A. Shutemov 			} else {
1304b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
1305e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1306b46e756fSKirill A. Shutemov 				goto out_unmap;
1307b46e756fSKirill A. Shutemov 			}
1308b46e756fSKirill A. Shutemov 		}
1309e1e267c7SPeter Xu 		if (pte_uffd_wp(pteval)) {
1310e1e267c7SPeter Xu 			/*
1311e1e267c7SPeter Xu 			 * Don't collapse the page if any of the small
1312e1e267c7SPeter Xu 			 * PTEs are armed with uffd write protection.
1313e1e267c7SPeter Xu 			 * Here we can also mark the new huge pmd as
1314e1e267c7SPeter Xu 			 * write protected if any of the small ones is
13158958b249SHaitao Shi 			 * marked but that could bring unknown
1316e1e267c7SPeter Xu 			 * userfault messages that falls outside of
1317e1e267c7SPeter Xu 			 * the registered range.  So, just be simple.
1318e1e267c7SPeter Xu 			 */
1319e1e267c7SPeter Xu 			result = SCAN_PTE_UFFD_WP;
1320e1e267c7SPeter Xu 			goto out_unmap;
1321e1e267c7SPeter Xu 		}
1322b46e756fSKirill A. Shutemov 		if (pte_write(pteval))
1323b46e756fSKirill A. Shutemov 			writable = true;
1324b46e756fSKirill A. Shutemov 
1325b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, _address, pteval);
13263218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1327b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
1328b46e756fSKirill A. Shutemov 			goto out_unmap;
1329b46e756fSKirill A. Shutemov 		}
1330b46e756fSKirill A. Shutemov 
1331d8ea7cc8SZach O'Keefe 		if (page_mapcount(page) > 1) {
1332d8ea7cc8SZach O'Keefe 			++shared;
1333d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
1334d8ea7cc8SZach O'Keefe 			    shared > khugepaged_max_ptes_shared) {
133571a2c112SKirill A. Shutemov 				result = SCAN_EXCEED_SHARED_PTE;
1336e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
133771a2c112SKirill A. Shutemov 				goto out_unmap;
133871a2c112SKirill A. Shutemov 			}
1339d8ea7cc8SZach O'Keefe 		}
134071a2c112SKirill A. Shutemov 
13415c07ebb3SVishal Moola (Oracle) 		folio = page_folio(page);
1342b46e756fSKirill A. Shutemov 		/*
1343b46e756fSKirill A. Shutemov 		 * Record which node the original page is from and save this
134434d6b470SZach O'Keefe 		 * information to cc->node_load[].
13450b8f0d87SQuanfa Fu 		 * Khugepaged will allocate hugepage from the node has the max
1346b46e756fSKirill A. Shutemov 		 * hit record.
1347b46e756fSKirill A. Shutemov 		 */
13485c07ebb3SVishal Moola (Oracle) 		node = folio_nid(folio);
13497d2c4385SZach O'Keefe 		if (hpage_collapse_scan_abort(node, cc)) {
1350b46e756fSKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1351b46e756fSKirill A. Shutemov 			goto out_unmap;
1352b46e756fSKirill A. Shutemov 		}
135334d6b470SZach O'Keefe 		cc->node_load[node]++;
13545c07ebb3SVishal Moola (Oracle) 		if (!folio_test_lru(folio)) {
1355b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1356b46e756fSKirill A. Shutemov 			goto out_unmap;
1357b46e756fSKirill A. Shutemov 		}
13585c07ebb3SVishal Moola (Oracle) 		if (folio_test_locked(folio)) {
1359b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
1360b46e756fSKirill A. Shutemov 			goto out_unmap;
1361b46e756fSKirill A. Shutemov 		}
13625c07ebb3SVishal Moola (Oracle) 		if (!folio_test_anon(folio)) {
1363b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_ANON;
1364b46e756fSKirill A. Shutemov 			goto out_unmap;
1365b46e756fSKirill A. Shutemov 		}
1366b46e756fSKirill A. Shutemov 
1367b46e756fSKirill A. Shutemov 		/*
13689445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
13699445689fSKirill A. Shutemov 		 *
1370cb67f428SHugh Dickins 		 * Here the check may be racy:
1371cb67f428SHugh Dickins 		 * it may see total_mapcount > refcount in some cases?
13729445689fSKirill A. Shutemov 		 * But such case is ephemeral we could always retry collapse
13739445689fSKirill A. Shutemov 		 * later.  However it may report false positive if the page
13749445689fSKirill A. Shutemov 		 * has excessive GUP pins (i.e. 512).  Anyway the same check
13759445689fSKirill A. Shutemov 		 * will be done again later the risk seems low.
1376b46e756fSKirill A. Shutemov 		 */
1377dbf85c21SVishal Moola (Oracle) 		if (!is_refcount_suitable(folio)) {
1378b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1379b46e756fSKirill A. Shutemov 			goto out_unmap;
1380b46e756fSKirill A. Shutemov 		}
1381d8ea7cc8SZach O'Keefe 
1382d8ea7cc8SZach O'Keefe 		/*
1383d8ea7cc8SZach O'Keefe 		 * If collapse was initiated by khugepaged, check that there is
1384d8ea7cc8SZach O'Keefe 		 * enough young pte to justify collapsing the page
1385d8ea7cc8SZach O'Keefe 		 */
1386d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
13875c07ebb3SVishal Moola (Oracle) 		    (pte_young(pteval) || folio_test_young(folio) ||
13885c07ebb3SVishal Moola (Oracle) 		     folio_test_referenced(folio) || mmu_notifier_test_young(vma->vm_mm,
1389d8ea7cc8SZach O'Keefe 								     address)))
13900db501f7SEbru Akagunduz 			referenced++;
1391b46e756fSKirill A. Shutemov 	}
1392ffe945e6SKirill A. Shutemov 	if (!writable) {
1393ffe945e6SKirill A. Shutemov 		result = SCAN_PAGE_RO;
1394d8ea7cc8SZach O'Keefe 	} else if (cc->is_khugepaged &&
1395d8ea7cc8SZach O'Keefe 		   (!referenced ||
1396d8ea7cc8SZach O'Keefe 		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1397ffe945e6SKirill A. Shutemov 		result = SCAN_LACK_REFERENCED_PAGE;
1398ffe945e6SKirill A. Shutemov 	} else {
1399b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
1400b46e756fSKirill A. Shutemov 	}
1401b46e756fSKirill A. Shutemov out_unmap:
1402b46e756fSKirill A. Shutemov 	pte_unmap_unlock(pte, ptl);
140350ad2f24SZach O'Keefe 	if (result == SCAN_SUCCEED) {
140450ad2f24SZach O'Keefe 		result = collapse_huge_page(mm, address, referenced,
140550ad2f24SZach O'Keefe 					    unmapped, cc);
1406c1e8d7c6SMichel Lespinasse 		/* collapse_huge_page will return with the mmap_lock released */
140750ad2f24SZach O'Keefe 		*mmap_locked = false;
1408b46e756fSKirill A. Shutemov 	}
1409b46e756fSKirill A. Shutemov out:
14105c07ebb3SVishal Moola (Oracle) 	trace_mm_khugepaged_scan_pmd(mm, &folio->page, writable, referenced,
1411b46e756fSKirill A. Shutemov 				     none_or_zero, result, unmapped);
141250ad2f24SZach O'Keefe 	return result;
1413b46e756fSKirill A. Shutemov }
1414b46e756fSKirill A. Shutemov 
1415b26e2701SQi Zheng static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1416b46e756fSKirill A. Shutemov {
1417b26e2701SQi Zheng 	struct mm_slot *slot = &mm_slot->slot;
1418b26e2701SQi Zheng 	struct mm_struct *mm = slot->mm;
1419b46e756fSKirill A. Shutemov 
142035f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1421b46e756fSKirill A. Shutemov 
14227d2c4385SZach O'Keefe 	if (hpage_collapse_test_exit(mm)) {
1423b46e756fSKirill A. Shutemov 		/* free mm_slot */
1424b26e2701SQi Zheng 		hash_del(&slot->hash);
1425b26e2701SQi Zheng 		list_del(&slot->mm_node);
1426b46e756fSKirill A. Shutemov 
1427b46e756fSKirill A. Shutemov 		/*
1428b46e756fSKirill A. Shutemov 		 * Not strictly needed because the mm exited already.
1429b46e756fSKirill A. Shutemov 		 *
1430b46e756fSKirill A. Shutemov 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1431b46e756fSKirill A. Shutemov 		 */
1432b46e756fSKirill A. Shutemov 
1433b46e756fSKirill A. Shutemov 		/* khugepaged_mm_lock actually not necessary for the below */
1434b26e2701SQi Zheng 		mm_slot_free(mm_slot_cache, mm_slot);
1435b46e756fSKirill A. Shutemov 		mmdrop(mm);
1436b46e756fSKirill A. Shutemov 	}
1437b46e756fSKirill A. Shutemov }
1438b46e756fSKirill A. Shutemov 
1439396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_SHMEM
14401043173eSHugh Dickins /* hpage must be locked, and mmap_lock must be held */
144134488399SZach O'Keefe static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
144234488399SZach O'Keefe 			pmd_t *pmdp, struct page *hpage)
144334488399SZach O'Keefe {
144434488399SZach O'Keefe 	struct vm_fault vmf = {
144534488399SZach O'Keefe 		.vma = vma,
144634488399SZach O'Keefe 		.address = addr,
144734488399SZach O'Keefe 		.flags = 0,
144834488399SZach O'Keefe 		.pmd = pmdp,
144934488399SZach O'Keefe 	};
145034488399SZach O'Keefe 
145134488399SZach O'Keefe 	VM_BUG_ON(!PageTransHuge(hpage));
14521043173eSHugh Dickins 	mmap_assert_locked(vma->vm_mm);
145334488399SZach O'Keefe 
145434488399SZach O'Keefe 	if (do_set_pmd(&vmf, hpage))
145534488399SZach O'Keefe 		return SCAN_FAIL;
145634488399SZach O'Keefe 
145734488399SZach O'Keefe 	get_page(hpage);
145834488399SZach O'Keefe 	return SCAN_SUCCEED;
145927e1f827SSong Liu }
146027e1f827SSong Liu 
146127e1f827SSong Liu /**
1462336e6b53SAlex Shi  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1463336e6b53SAlex Shi  * address haddr.
1464336e6b53SAlex Shi  *
1465336e6b53SAlex Shi  * @mm: process address space where collapse happens
1466336e6b53SAlex Shi  * @addr: THP collapse address
146734488399SZach O'Keefe  * @install_pmd: If a huge PMD should be installed
146827e1f827SSong Liu  *
146927e1f827SSong Liu  * This function checks whether all the PTEs in the PMD are pointing to the
147027e1f827SSong Liu  * right THP. If so, retract the page table so the THP can refault in with
147134488399SZach O'Keefe  * as pmd-mapped. Possibly install a huge PMD mapping the THP.
147227e1f827SSong Liu  */
147334488399SZach O'Keefe int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
147434488399SZach O'Keefe 			    bool install_pmd)
147527e1f827SSong Liu {
14761043173eSHugh Dickins 	struct mmu_notifier_range range;
14771043173eSHugh Dickins 	bool notified = false;
147827e1f827SSong Liu 	unsigned long haddr = addr & HPAGE_PMD_MASK;
147994d815b2SLiam R. Howlett 	struct vm_area_struct *vma = vma_lookup(mm, haddr);
1480*98b32d29SVishal Moola (Oracle) 	struct folio *folio;
148127e1f827SSong Liu 	pte_t *start_pte, *pte;
14821043173eSHugh Dickins 	pmd_t *pmd, pgt_pmd;
1483a9846049SHugh Dickins 	spinlock_t *pml = NULL, *ptl;
14841043173eSHugh Dickins 	int nr_ptes = 0, result = SCAN_FAIL;
148527e1f827SSong Liu 	int i;
148627e1f827SSong Liu 
14871043173eSHugh Dickins 	mmap_assert_locked(mm);
14881043173eSHugh Dickins 
14891043173eSHugh Dickins 	/* First check VMA found, in case page tables are being torn down */
14901043173eSHugh Dickins 	if (!vma || !vma->vm_file ||
14911043173eSHugh Dickins 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
14921043173eSHugh Dickins 		return SCAN_VMA_CHECK;
149358ac9a89SZach O'Keefe 
149434488399SZach O'Keefe 	/* Fast check before locking page if already PMD-mapped */
149558ac9a89SZach O'Keefe 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
149634488399SZach O'Keefe 	if (result == SCAN_PMD_MAPPED)
149734488399SZach O'Keefe 		return result;
149858ac9a89SZach O'Keefe 
149927e1f827SSong Liu 	/*
1500a7f4e6e4SZach O'Keefe 	 * If we are here, we've succeeded in replacing all the native pages
1501a7f4e6e4SZach O'Keefe 	 * in the page cache with a single hugepage. If a mm were to fault-in
1502a7f4e6e4SZach O'Keefe 	 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1503a7f4e6e4SZach O'Keefe 	 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1504a7f4e6e4SZach O'Keefe 	 * analogously elide sysfs THP settings here.
150527e1f827SSong Liu 	 */
1506a7f4e6e4SZach O'Keefe 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
150734488399SZach O'Keefe 		return SCAN_VMA_CHECK;
150827e1f827SSong Liu 
1509deb4c93aSPeter Xu 	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1510deb4c93aSPeter Xu 	if (userfaultfd_wp(vma))
151134488399SZach O'Keefe 		return SCAN_PTE_UFFD_WP;
1512deb4c93aSPeter Xu 
1513*98b32d29SVishal Moola (Oracle) 	folio = filemap_lock_folio(vma->vm_file->f_mapping,
1514119a5fc1SHugh Dickins 			       linear_page_index(vma, haddr));
1515*98b32d29SVishal Moola (Oracle) 	if (IS_ERR(folio))
151634488399SZach O'Keefe 		return SCAN_PAGE_NULL;
1517119a5fc1SHugh Dickins 
1518*98b32d29SVishal Moola (Oracle) 	if (folio_order(folio) != HPAGE_PMD_ORDER) {
151934488399SZach O'Keefe 		result = SCAN_PAGE_COMPOUND;
1520*98b32d29SVishal Moola (Oracle) 		goto drop_folio;
152134488399SZach O'Keefe 	}
1522780a4b6fSZach O'Keefe 
15231043173eSHugh Dickins 	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
152434488399SZach O'Keefe 	switch (result) {
152534488399SZach O'Keefe 	case SCAN_SUCCEED:
152634488399SZach O'Keefe 		break;
152734488399SZach O'Keefe 	case SCAN_PMD_NONE:
152834488399SZach O'Keefe 		/*
15291d65b771SHugh Dickins 		 * All pte entries have been removed and pmd cleared.
15301d65b771SHugh Dickins 		 * Skip all the pte checks and just update the pmd mapping.
153134488399SZach O'Keefe 		 */
153234488399SZach O'Keefe 		goto maybe_install_pmd;
153334488399SZach O'Keefe 	default:
1534*98b32d29SVishal Moola (Oracle) 		goto drop_folio;
153534488399SZach O'Keefe 	}
153627e1f827SSong Liu 
153734488399SZach O'Keefe 	result = SCAN_FAIL;
1538895f5ee4SHugh Dickins 	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
15391043173eSHugh Dickins 	if (!start_pte)		/* mmap_lock + page lock should prevent this */
1540*98b32d29SVishal Moola (Oracle) 		goto drop_folio;
154127e1f827SSong Liu 
154227e1f827SSong Liu 	/* step 1: check all mapped PTEs are to the right huge page */
154327e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
154427e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
154527e1f827SSong Liu 		struct page *page;
1546c33c7948SRyan Roberts 		pte_t ptent = ptep_get(pte);
154727e1f827SSong Liu 
154827e1f827SSong Liu 		/* empty pte, skip */
1549c33c7948SRyan Roberts 		if (pte_none(ptent))
155027e1f827SSong Liu 			continue;
155127e1f827SSong Liu 
155227e1f827SSong Liu 		/* page swapped out, abort */
1553c33c7948SRyan Roberts 		if (!pte_present(ptent)) {
155434488399SZach O'Keefe 			result = SCAN_PTE_NON_PRESENT;
155527e1f827SSong Liu 			goto abort;
155634488399SZach O'Keefe 		}
155727e1f827SSong Liu 
1558c33c7948SRyan Roberts 		page = vm_normal_page(vma, addr, ptent);
15593218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
15603218f871SAlex Sierra 			page = NULL;
156127e1f827SSong Liu 		/*
1562119a5fc1SHugh Dickins 		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1563119a5fc1SHugh Dickins 		 * page table, but the new page will not be a subpage of hpage.
156427e1f827SSong Liu 		 */
1565*98b32d29SVishal Moola (Oracle) 		if (folio_page(folio, i) != page)
156627e1f827SSong Liu 			goto abort;
156727e1f827SSong Liu 	}
156827e1f827SSong Liu 
15691043173eSHugh Dickins 	pte_unmap_unlock(start_pte, ptl);
15701043173eSHugh Dickins 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
15711043173eSHugh Dickins 				haddr, haddr + HPAGE_PMD_SIZE);
15721043173eSHugh Dickins 	mmu_notifier_invalidate_range_start(&range);
15731043173eSHugh Dickins 	notified = true;
1574a9846049SHugh Dickins 
1575a9846049SHugh Dickins 	/*
1576a9846049SHugh Dickins 	 * pmd_lock covers a wider range than ptl, and (if split from mm's
1577a9846049SHugh Dickins 	 * page_table_lock) ptl nests inside pml. The less time we hold pml,
1578a9846049SHugh Dickins 	 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA
1579a9846049SHugh Dickins 	 * inserts a valid as-if-COWed PTE without even looking up page cache.
1580*98b32d29SVishal Moola (Oracle) 	 * So page lock of folio does not protect from it, so we must not drop
1581a9846049SHugh Dickins 	 * ptl before pgt_pmd is removed, so uffd private needs pml taken now.
1582a9846049SHugh Dickins 	 */
1583a9846049SHugh Dickins 	if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED))
1584a9846049SHugh Dickins 		pml = pmd_lock(mm, pmd);
1585a9846049SHugh Dickins 
1586a9846049SHugh Dickins 	start_pte = pte_offset_map_nolock(mm, pmd, haddr, &ptl);
15871043173eSHugh Dickins 	if (!start_pte)		/* mmap_lock + page lock should prevent this */
15881043173eSHugh Dickins 		goto abort;
1589a9846049SHugh Dickins 	if (!pml)
1590a9846049SHugh Dickins 		spin_lock(ptl);
1591a9846049SHugh Dickins 	else if (ptl != pml)
1592a9846049SHugh Dickins 		spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
15931043173eSHugh Dickins 
15941043173eSHugh Dickins 	/* step 2: clear page table and adjust rmap */
159527e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
159627e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
159727e1f827SSong Liu 		struct page *page;
1598c33c7948SRyan Roberts 		pte_t ptent = ptep_get(pte);
159927e1f827SSong Liu 
1600c33c7948SRyan Roberts 		if (pte_none(ptent))
160127e1f827SSong Liu 			continue;
16021043173eSHugh Dickins 		/*
16031043173eSHugh Dickins 		 * We dropped ptl after the first scan, to do the mmu_notifier:
1604*98b32d29SVishal Moola (Oracle) 		 * page lock stops more PTEs of the folio being faulted in, but
16051043173eSHugh Dickins 		 * does not stop write faults COWing anon copies from existing
16061043173eSHugh Dickins 		 * PTEs; and does not stop those being swapped out or migrated.
16071043173eSHugh Dickins 		 */
16081043173eSHugh Dickins 		if (!pte_present(ptent)) {
16091043173eSHugh Dickins 			result = SCAN_PTE_NON_PRESENT;
16103218f871SAlex Sierra 			goto abort;
16111043173eSHugh Dickins 		}
16121043173eSHugh Dickins 		page = vm_normal_page(vma, addr, ptent);
1613*98b32d29SVishal Moola (Oracle) 		if (folio_page(folio, i) != page)
16141043173eSHugh Dickins 			goto abort;
16151043173eSHugh Dickins 
16161043173eSHugh Dickins 		/*
16171043173eSHugh Dickins 		 * Must clear entry, or a racing truncate may re-remove it.
16181043173eSHugh Dickins 		 * TLB flush can be left until pmdp_collapse_flush() does it.
16191043173eSHugh Dickins 		 * PTE dirty? Shmem page is already dirty; file is read-only.
16201043173eSHugh Dickins 		 */
16211043173eSHugh Dickins 		ptep_clear(mm, addr, pte);
1622cea86fe2SHugh Dickins 		page_remove_rmap(page, vma, false);
16231043173eSHugh Dickins 		nr_ptes++;
162427e1f827SSong Liu 	}
162527e1f827SSong Liu 
1626a9846049SHugh Dickins 	pte_unmap(start_pte);
1627a9846049SHugh Dickins 	if (!pml)
1628a9846049SHugh Dickins 		spin_unlock(ptl);
162927e1f827SSong Liu 
163027e1f827SSong Liu 	/* step 3: set proper refcount and mm_counters. */
16311043173eSHugh Dickins 	if (nr_ptes) {
1632*98b32d29SVishal Moola (Oracle) 		folio_ref_sub(folio, nr_ptes);
1633*98b32d29SVishal Moola (Oracle) 		add_mm_counter(mm, mm_counter_file(&folio->page), -nr_ptes);
163427e1f827SSong Liu 	}
163527e1f827SSong Liu 
1636a9846049SHugh Dickins 	/* step 4: remove empty page table */
1637a9846049SHugh Dickins 	if (!pml) {
16381043173eSHugh Dickins 		pml = pmd_lock(mm, pmd);
16391043173eSHugh Dickins 		if (ptl != pml)
16401043173eSHugh Dickins 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1641a9846049SHugh Dickins 	}
16421043173eSHugh Dickins 	pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd);
16431043173eSHugh Dickins 	pmdp_get_lockless_sync();
16441043173eSHugh Dickins 	if (ptl != pml)
16451043173eSHugh Dickins 		spin_unlock(ptl);
16461043173eSHugh Dickins 	spin_unlock(pml);
1647ab0c3f12SHugh Dickins 
16481043173eSHugh Dickins 	mmu_notifier_invalidate_range_end(&range);
164934488399SZach O'Keefe 
16501043173eSHugh Dickins 	mm_dec_nr_ptes(mm);
16511043173eSHugh Dickins 	page_table_check_pte_clear_range(mm, haddr, pgt_pmd);
16521043173eSHugh Dickins 	pte_free_defer(mm, pmd_pgtable(pgt_pmd));
16538d3c106eSJann Horn 
165434488399SZach O'Keefe maybe_install_pmd:
165534488399SZach O'Keefe 	/* step 5: install pmd entry */
165634488399SZach O'Keefe 	result = install_pmd
1657*98b32d29SVishal Moola (Oracle) 			? set_huge_pmd(vma, haddr, pmd, &folio->page)
165834488399SZach O'Keefe 			: SCAN_SUCCEED;
1659*98b32d29SVishal Moola (Oracle) 	goto drop_folio;
16601043173eSHugh Dickins abort:
16611043173eSHugh Dickins 	if (nr_ptes) {
16621043173eSHugh Dickins 		flush_tlb_mm(mm);
1663*98b32d29SVishal Moola (Oracle) 		folio_ref_sub(folio, nr_ptes);
1664*98b32d29SVishal Moola (Oracle) 		add_mm_counter(mm, mm_counter_file(&folio->page), -nr_ptes);
16651043173eSHugh Dickins 	}
16661043173eSHugh Dickins 	if (start_pte)
16671043173eSHugh Dickins 		pte_unmap_unlock(start_pte, ptl);
1668a9846049SHugh Dickins 	if (pml && pml != ptl)
1669a9846049SHugh Dickins 		spin_unlock(pml);
16701043173eSHugh Dickins 	if (notified)
16711043173eSHugh Dickins 		mmu_notifier_invalidate_range_end(&range);
1672*98b32d29SVishal Moola (Oracle) drop_folio:
1673*98b32d29SVishal Moola (Oracle) 	folio_unlock(folio);
1674*98b32d29SVishal Moola (Oracle) 	folio_put(folio);
167534488399SZach O'Keefe 	return result;
167627e1f827SSong Liu }
167727e1f827SSong Liu 
16781d65b771SHugh Dickins static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1679f3f0e1d2SKirill A. Shutemov {
1680f3f0e1d2SKirill A. Shutemov 	struct vm_area_struct *vma;
1681f3f0e1d2SKirill A. Shutemov 
16821d65b771SHugh Dickins 	i_mmap_lock_read(mapping);
1683f3f0e1d2SKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
16841d65b771SHugh Dickins 		struct mmu_notifier_range range;
16851d65b771SHugh Dickins 		struct mm_struct *mm;
16861d65b771SHugh Dickins 		unsigned long addr;
16871d65b771SHugh Dickins 		pmd_t *pmd, pgt_pmd;
16881d65b771SHugh Dickins 		spinlock_t *pml;
16891d65b771SHugh Dickins 		spinlock_t *ptl;
16901d65b771SHugh Dickins 		bool skipped_uffd = false;
169134488399SZach O'Keefe 
169227e1f827SSong Liu 		/*
169327e1f827SSong Liu 		 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
16941d65b771SHugh Dickins 		 * got written to. These VMAs are likely not worth removing
16951d65b771SHugh Dickins 		 * page tables from, as PMD-mapping is likely to be split later.
169627e1f827SSong Liu 		 */
16971d65b771SHugh Dickins 		if (READ_ONCE(vma->anon_vma))
16981d65b771SHugh Dickins 			continue;
16991d65b771SHugh Dickins 
1700f3f0e1d2SKirill A. Shutemov 		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
170134488399SZach O'Keefe 		if (addr & ~HPAGE_PMD_MASK ||
17021d65b771SHugh Dickins 		    vma->vm_end < addr + HPAGE_PMD_SIZE)
170334488399SZach O'Keefe 			continue;
17041d65b771SHugh Dickins 
17051d65b771SHugh Dickins 		mm = vma->vm_mm;
17061d65b771SHugh Dickins 		if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED)
17071d65b771SHugh Dickins 			continue;
17081d65b771SHugh Dickins 
17091d65b771SHugh Dickins 		if (hpage_collapse_test_exit(mm))
17101d65b771SHugh Dickins 			continue;
17111d65b771SHugh Dickins 		/*
17121d65b771SHugh Dickins 		 * When a vma is registered with uffd-wp, we cannot recycle
17131d65b771SHugh Dickins 		 * the page table because there may be pte markers installed.
17141d65b771SHugh Dickins 		 * Other vmas can still have the same file mapped hugely, but
17151d65b771SHugh Dickins 		 * skip this one: it will always be mapped in small page size
17161d65b771SHugh Dickins 		 * for uffd-wp registered ranges.
17171d65b771SHugh Dickins 		 */
17181d65b771SHugh Dickins 		if (userfaultfd_wp(vma))
17191d65b771SHugh Dickins 			continue;
17201d65b771SHugh Dickins 
17211d65b771SHugh Dickins 		/* PTEs were notified when unmapped; but now for the PMD? */
17221d65b771SHugh Dickins 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
17231d65b771SHugh Dickins 					addr, addr + HPAGE_PMD_SIZE);
17241d65b771SHugh Dickins 		mmu_notifier_invalidate_range_start(&range);
17251d65b771SHugh Dickins 
17261d65b771SHugh Dickins 		pml = pmd_lock(mm, pmd);
17271d65b771SHugh Dickins 		ptl = pte_lockptr(mm, pmd);
17281d65b771SHugh Dickins 		if (ptl != pml)
17291d65b771SHugh Dickins 			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
17301d65b771SHugh Dickins 
17311d65b771SHugh Dickins 		/*
17321d65b771SHugh Dickins 		 * Huge page lock is still held, so normally the page table
17331d65b771SHugh Dickins 		 * must remain empty; and we have already skipped anon_vma
17341d65b771SHugh Dickins 		 * and userfaultfd_wp() vmas.  But since the mmap_lock is not
17351d65b771SHugh Dickins 		 * held, it is still possible for a racing userfaultfd_ioctl()
17361d65b771SHugh Dickins 		 * to have inserted ptes or markers.  Now that we hold ptlock,
17371d65b771SHugh Dickins 		 * repeating the anon_vma check protects from one category,
17381d65b771SHugh Dickins 		 * and repeating the userfaultfd_wp() check from another.
17391d65b771SHugh Dickins 		 */
17401d65b771SHugh Dickins 		if (unlikely(vma->anon_vma || userfaultfd_wp(vma))) {
17411d65b771SHugh Dickins 			skipped_uffd = true;
17421d65b771SHugh Dickins 		} else {
17431d65b771SHugh Dickins 			pgt_pmd = pmdp_collapse_flush(vma, addr, pmd);
17441d65b771SHugh Dickins 			pmdp_get_lockless_sync();
174534488399SZach O'Keefe 		}
17461d65b771SHugh Dickins 
17471d65b771SHugh Dickins 		if (ptl != pml)
17481d65b771SHugh Dickins 			spin_unlock(ptl);
17491d65b771SHugh Dickins 		spin_unlock(pml);
17501d65b771SHugh Dickins 
17511d65b771SHugh Dickins 		mmu_notifier_invalidate_range_end(&range);
17521d65b771SHugh Dickins 
17531d65b771SHugh Dickins 		if (!skipped_uffd) {
17541d65b771SHugh Dickins 			mm_dec_nr_ptes(mm);
17551d65b771SHugh Dickins 			page_table_check_pte_clear_range(mm, addr, pgt_pmd);
17561d65b771SHugh Dickins 			pte_free_defer(mm, pmd_pgtable(pgt_pmd));
1757f3f0e1d2SKirill A. Shutemov 		}
17581d65b771SHugh Dickins 	}
17591d65b771SHugh Dickins 	i_mmap_unlock_read(mapping);
1760f3f0e1d2SKirill A. Shutemov }
1761f3f0e1d2SKirill A. Shutemov 
1762f3f0e1d2SKirill A. Shutemov /**
176399cb0dbdSSong Liu  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1764f3f0e1d2SKirill A. Shutemov  *
1765336e6b53SAlex Shi  * @mm: process address space where collapse happens
176634488399SZach O'Keefe  * @addr: virtual collapse start address
1767336e6b53SAlex Shi  * @file: file that collapse on
1768336e6b53SAlex Shi  * @start: collapse start address
17699710a78aSZach O'Keefe  * @cc: collapse context and scratchpad
1770336e6b53SAlex Shi  *
1771f3f0e1d2SKirill A. Shutemov  * Basic scheme is simple, details are more complex:
177287c460a0SHugh Dickins  *  - allocate and lock a new huge page;
1773a2e17cc2SDavid Stevens  *  - scan page cache, locking old pages
177499cb0dbdSSong Liu  *    + swap/gup in pages if necessary;
1775a2e17cc2SDavid Stevens  *  - copy data to new page
1776a2e17cc2SDavid Stevens  *  - handle shmem holes
1777a2e17cc2SDavid Stevens  *    + re-validate that holes weren't filled by someone else
1778a2e17cc2SDavid Stevens  *    + check for userfaultfd
1779ac492b9cSDavid Stevens  *  - finalize updates to the page cache;
178077da9389SMatthew Wilcox  *  - if replacing succeeds:
178187c460a0SHugh Dickins  *    + unlock huge page;
1782a2e17cc2SDavid Stevens  *    + free old pages;
1783f3f0e1d2SKirill A. Shutemov  *  - if replacing failed;
1784a2e17cc2SDavid Stevens  *    + unlock old pages
178587c460a0SHugh Dickins  *    + unlock and free huge page;
1786f3f0e1d2SKirill A. Shutemov  */
178734488399SZach O'Keefe static int collapse_file(struct mm_struct *mm, unsigned long addr,
1788579c571eSSong Liu 			 struct file *file, pgoff_t start,
178934488399SZach O'Keefe 			 struct collapse_control *cc)
1790f3f0e1d2SKirill A. Shutemov {
1791579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
179250ad2f24SZach O'Keefe 	struct page *hpage;
179312904d95SJiaqi Yan 	struct page *page;
179412904d95SJiaqi Yan 	struct page *tmp;
179512904d95SJiaqi Yan 	struct folio *folio;
17964c9473e8SGautam Menghani 	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1797f3f0e1d2SKirill A. Shutemov 	LIST_HEAD(pagelist);
179877da9389SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1799f3f0e1d2SKirill A. Shutemov 	int nr_none = 0, result = SCAN_SUCCEED;
180099cb0dbdSSong Liu 	bool is_shmem = shmem_file(file);
18014c9473e8SGautam Menghani 	int nr = 0;
1802f3f0e1d2SKirill A. Shutemov 
180399cb0dbdSSong Liu 	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1804f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1805f3f0e1d2SKirill A. Shutemov 
180650ad2f24SZach O'Keefe 	result = alloc_charge_hpage(&hpage, mm, cc);
18079710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1808f3f0e1d2SKirill A. Shutemov 		goto out;
1809f3f0e1d2SKirill A. Shutemov 
1810cae106ddSDavid Stevens 	__SetPageLocked(hpage);
1811cae106ddSDavid Stevens 	if (is_shmem)
1812cae106ddSDavid Stevens 		__SetPageSwapBacked(hpage);
1813cae106ddSDavid Stevens 	hpage->index = start;
1814cae106ddSDavid Stevens 	hpage->mapping = mapping;
1815cae106ddSDavid Stevens 
18166b24ca4aSMatthew Wilcox (Oracle) 	/*
18176b24ca4aSMatthew Wilcox (Oracle) 	 * Ensure we have slots for all the pages in the range.  This is
18186b24ca4aSMatthew Wilcox (Oracle) 	 * almost certainly a no-op because most of the pages must be present
18196b24ca4aSMatthew Wilcox (Oracle) 	 */
182095feeabbSHugh Dickins 	do {
182195feeabbSHugh Dickins 		xas_lock_irq(&xas);
182295feeabbSHugh Dickins 		xas_create_range(&xas);
182395feeabbSHugh Dickins 		if (!xas_error(&xas))
182495feeabbSHugh Dickins 			break;
182595feeabbSHugh Dickins 		xas_unlock_irq(&xas);
182695feeabbSHugh Dickins 		if (!xas_nomem(&xas, GFP_KERNEL)) {
182795feeabbSHugh Dickins 			result = SCAN_FAIL;
1828cae106ddSDavid Stevens 			goto rollback;
182995feeabbSHugh Dickins 		}
183095feeabbSHugh Dickins 	} while (1);
183195feeabbSHugh Dickins 
183277da9389SMatthew Wilcox 	for (index = start; index < end; index++) {
1833e8c716bcSHugh Dickins 		xas_set(&xas, index);
1834e8c716bcSHugh Dickins 		page = xas_load(&xas);
183577da9389SMatthew Wilcox 
183677da9389SMatthew Wilcox 		VM_BUG_ON(index != xas.xa_index);
183799cb0dbdSSong Liu 		if (is_shmem) {
183877da9389SMatthew Wilcox 			if (!page) {
1839701270faSHugh Dickins 				/*
184099cb0dbdSSong Liu 				 * Stop if extent has been truncated or
184199cb0dbdSSong Liu 				 * hole-punched, and is now completely
184299cb0dbdSSong Liu 				 * empty.
1843701270faSHugh Dickins 				 */
1844701270faSHugh Dickins 				if (index == start) {
1845701270faSHugh Dickins 					if (!xas_next_entry(&xas, end - 1)) {
1846701270faSHugh Dickins 						result = SCAN_TRUNCATED;
1847042a3082SHugh Dickins 						goto xa_locked;
1848701270faSHugh Dickins 					}
1849701270faSHugh Dickins 				}
185077da9389SMatthew Wilcox 				nr_none++;
185177da9389SMatthew Wilcox 				continue;
1852f3f0e1d2SKirill A. Shutemov 			}
1853f3f0e1d2SKirill A. Shutemov 
18543159f943SMatthew Wilcox 			if (xa_is_value(page) || !PageUptodate(page)) {
185577da9389SMatthew Wilcox 				xas_unlock_irq(&xas);
1856f3f0e1d2SKirill A. Shutemov 				/* swap in or instantiate fallocated page */
18577459c149SMatthew Wilcox (Oracle) 				if (shmem_get_folio(mapping->host, index,
18587459c149SMatthew Wilcox (Oracle) 						&folio, SGP_NOALLOC)) {
1859f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
186077da9389SMatthew Wilcox 					goto xa_unlocked;
1861f3f0e1d2SKirill A. Shutemov 				}
18621fec6890SMatthew Wilcox (Oracle) 				/* drain lru cache to help isolate_lru_page() */
1863efa3d814SDavid Stevens 				lru_add_drain();
18647459c149SMatthew Wilcox (Oracle) 				page = folio_file_page(folio, index);
1865f3f0e1d2SKirill A. Shutemov 			} else if (trylock_page(page)) {
1866f3f0e1d2SKirill A. Shutemov 				get_page(page);
1867042a3082SHugh Dickins 				xas_unlock_irq(&xas);
1868f3f0e1d2SKirill A. Shutemov 			} else {
1869f3f0e1d2SKirill A. Shutemov 				result = SCAN_PAGE_LOCK;
1870042a3082SHugh Dickins 				goto xa_locked;
1871f3f0e1d2SKirill A. Shutemov 			}
187299cb0dbdSSong Liu 		} else {	/* !is_shmem */
187399cb0dbdSSong Liu 			if (!page || xa_is_value(page)) {
187499cb0dbdSSong Liu 				xas_unlock_irq(&xas);
187599cb0dbdSSong Liu 				page_cache_sync_readahead(mapping, &file->f_ra,
187699cb0dbdSSong Liu 							  file, index,
1877e5a59d30SDavid Howells 							  end - index);
18781fec6890SMatthew Wilcox (Oracle) 				/* drain lru cache to help isolate_lru_page() */
187999cb0dbdSSong Liu 				lru_add_drain();
188099cb0dbdSSong Liu 				page = find_lock_page(mapping, index);
188199cb0dbdSSong Liu 				if (unlikely(page == NULL)) {
188299cb0dbdSSong Liu 					result = SCAN_FAIL;
188399cb0dbdSSong Liu 					goto xa_unlocked;
188499cb0dbdSSong Liu 				}
188575f36069SSong Liu 			} else if (PageDirty(page)) {
188675f36069SSong Liu 				/*
188775f36069SSong Liu 				 * khugepaged only works on read-only fd,
188875f36069SSong Liu 				 * so this page is dirty because it hasn't
188975f36069SSong Liu 				 * been flushed since first write. There
189075f36069SSong Liu 				 * won't be new dirty pages.
189175f36069SSong Liu 				 *
189275f36069SSong Liu 				 * Trigger async flush here and hope the
189375f36069SSong Liu 				 * writeback is done when khugepaged
189475f36069SSong Liu 				 * revisits this page.
189575f36069SSong Liu 				 *
189675f36069SSong Liu 				 * This is a one-off situation. We are not
189775f36069SSong Liu 				 * forcing writeback in loop.
189875f36069SSong Liu 				 */
189975f36069SSong Liu 				xas_unlock_irq(&xas);
190075f36069SSong Liu 				filemap_flush(mapping);
190175f36069SSong Liu 				result = SCAN_FAIL;
190275f36069SSong Liu 				goto xa_unlocked;
190374c42e1bSRongwei Wang 			} else if (PageWriteback(page)) {
190474c42e1bSRongwei Wang 				xas_unlock_irq(&xas);
190574c42e1bSRongwei Wang 				result = SCAN_FAIL;
190674c42e1bSRongwei Wang 				goto xa_unlocked;
190799cb0dbdSSong Liu 			} else if (trylock_page(page)) {
190899cb0dbdSSong Liu 				get_page(page);
190999cb0dbdSSong Liu 				xas_unlock_irq(&xas);
191099cb0dbdSSong Liu 			} else {
191199cb0dbdSSong Liu 				result = SCAN_PAGE_LOCK;
191299cb0dbdSSong Liu 				goto xa_locked;
191399cb0dbdSSong Liu 			}
191499cb0dbdSSong Liu 		}
1915f3f0e1d2SKirill A. Shutemov 
1916f3f0e1d2SKirill A. Shutemov 		/*
1917b93b0163SMatthew Wilcox 		 * The page must be locked, so we can drop the i_pages lock
1918f3f0e1d2SKirill A. Shutemov 		 * without racing with truncate.
1919f3f0e1d2SKirill A. Shutemov 		 */
1920f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
19214655e5e5SSong Liu 
19224655e5e5SSong Liu 		/* make sure the page is up to date */
19234655e5e5SSong Liu 		if (unlikely(!PageUptodate(page))) {
19244655e5e5SSong Liu 			result = SCAN_FAIL;
19254655e5e5SSong Liu 			goto out_unlock;
19264655e5e5SSong Liu 		}
192706a5e126SHugh Dickins 
192806a5e126SHugh Dickins 		/*
192906a5e126SHugh Dickins 		 * If file was truncated then extended, or hole-punched, before
193006a5e126SHugh Dickins 		 * we locked the first page, then a THP might be there already.
193158ac9a89SZach O'Keefe 		 * This will be discovered on the first iteration.
193206a5e126SHugh Dickins 		 */
193306a5e126SHugh Dickins 		if (PageTransCompound(page)) {
193458ac9a89SZach O'Keefe 			struct page *head = compound_head(page);
193558ac9a89SZach O'Keefe 
193658ac9a89SZach O'Keefe 			result = compound_order(head) == HPAGE_PMD_ORDER &&
193758ac9a89SZach O'Keefe 					head->index == start
193858ac9a89SZach O'Keefe 					/* Maybe PMD-mapped */
193958ac9a89SZach O'Keefe 					? SCAN_PTE_MAPPED_HUGEPAGE
194058ac9a89SZach O'Keefe 					: SCAN_PAGE_COMPOUND;
194106a5e126SHugh Dickins 			goto out_unlock;
194206a5e126SHugh Dickins 		}
1943f3f0e1d2SKirill A. Shutemov 
194464ab3195SVishal Moola (Oracle) 		folio = page_folio(page);
194564ab3195SVishal Moola (Oracle) 
194664ab3195SVishal Moola (Oracle) 		if (folio_mapping(folio) != mapping) {
1947f3f0e1d2SKirill A. Shutemov 			result = SCAN_TRUNCATED;
1948f3f0e1d2SKirill A. Shutemov 			goto out_unlock;
1949f3f0e1d2SKirill A. Shutemov 		}
1950f3f0e1d2SKirill A. Shutemov 
195164ab3195SVishal Moola (Oracle) 		if (!is_shmem && (folio_test_dirty(folio) ||
195264ab3195SVishal Moola (Oracle) 				  folio_test_writeback(folio))) {
19534655e5e5SSong Liu 			/*
19544655e5e5SSong Liu 			 * khugepaged only works on read-only fd, so this
19554655e5e5SSong Liu 			 * page is dirty because it hasn't been flushed
19564655e5e5SSong Liu 			 * since first write.
19574655e5e5SSong Liu 			 */
19584655e5e5SSong Liu 			result = SCAN_FAIL;
19594655e5e5SSong Liu 			goto out_unlock;
19604655e5e5SSong Liu 		}
19614655e5e5SSong Liu 
1962be2d5756SBaolin Wang 		if (!folio_isolate_lru(folio)) {
1963f3f0e1d2SKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
1964042a3082SHugh Dickins 			goto out_unlock;
1965f3f0e1d2SKirill A. Shutemov 		}
1966f3f0e1d2SKirill A. Shutemov 
19670201ebf2SDavid Howells 		if (!filemap_release_folio(folio, GFP_KERNEL)) {
196899cb0dbdSSong Liu 			result = SCAN_PAGE_HAS_PRIVATE;
196964ab3195SVishal Moola (Oracle) 			folio_putback_lru(folio);
197099cb0dbdSSong Liu 			goto out_unlock;
197199cb0dbdSSong Liu 		}
197299cb0dbdSSong Liu 
197364ab3195SVishal Moola (Oracle) 		if (folio_mapped(folio))
197464ab3195SVishal Moola (Oracle) 			try_to_unmap(folio,
1975869f7ee6SMatthew Wilcox (Oracle) 					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1976f3f0e1d2SKirill A. Shutemov 
197777da9389SMatthew Wilcox 		xas_lock_irq(&xas);
1978f3f0e1d2SKirill A. Shutemov 
1979e8c716bcSHugh Dickins 		VM_BUG_ON_PAGE(page != xa_load(xas.xa, index), page);
1980f3f0e1d2SKirill A. Shutemov 
1981f3f0e1d2SKirill A. Shutemov 		/*
1982a2e17cc2SDavid Stevens 		 * We control three references to the page:
1983f3f0e1d2SKirill A. Shutemov 		 *  - we hold a pin on it;
198477da9389SMatthew Wilcox 		 *  - one reference from page cache;
1985f3f0e1d2SKirill A. Shutemov 		 *  - one from isolate_lru_page;
1986a2e17cc2SDavid Stevens 		 * If those are the only references, then any new usage of the
1987a2e17cc2SDavid Stevens 		 * page will have to fetch it from the page cache. That requires
1988a2e17cc2SDavid Stevens 		 * locking the page to handle truncate, so any new usage will be
1989a2e17cc2SDavid Stevens 		 * blocked until we unlock page after collapse/during rollback.
1990f3f0e1d2SKirill A. Shutemov 		 */
1991a2e17cc2SDavid Stevens 		if (page_count(page) != 3) {
1992f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1993042a3082SHugh Dickins 			xas_unlock_irq(&xas);
1994042a3082SHugh Dickins 			putback_lru_page(page);
1995042a3082SHugh Dickins 			goto out_unlock;
1996f3f0e1d2SKirill A. Shutemov 		}
1997f3f0e1d2SKirill A. Shutemov 
1998f3f0e1d2SKirill A. Shutemov 		/*
1999a2e17cc2SDavid Stevens 		 * Accumulate the pages that are being collapsed.
2000f3f0e1d2SKirill A. Shutemov 		 */
2001f3f0e1d2SKirill A. Shutemov 		list_add_tail(&page->lru, &pagelist);
2002f3f0e1d2SKirill A. Shutemov 		continue;
2003f3f0e1d2SKirill A. Shutemov out_unlock:
2004f3f0e1d2SKirill A. Shutemov 		unlock_page(page);
2005f3f0e1d2SKirill A. Shutemov 		put_page(page);
2006042a3082SHugh Dickins 		goto xa_unlocked;
2007f3f0e1d2SKirill A. Shutemov 	}
2008f3f0e1d2SKirill A. Shutemov 
200912904d95SJiaqi Yan 	if (!is_shmem) {
201009d91cdaSSong Liu 		filemap_nr_thps_inc(mapping);
2011eb6ecbedSCollin Fijalkovich 		/*
2012eb6ecbedSCollin Fijalkovich 		 * Paired with smp_mb() in do_dentry_open() to ensure
2013eb6ecbedSCollin Fijalkovich 		 * i_writecount is up to date and the update to nr_thps is
2014eb6ecbedSCollin Fijalkovich 		 * visible. Ensures the page cache will be truncated if the
2015eb6ecbedSCollin Fijalkovich 		 * file is opened writable.
2016eb6ecbedSCollin Fijalkovich 		 */
2017eb6ecbedSCollin Fijalkovich 		smp_mb();
2018eb6ecbedSCollin Fijalkovich 		if (inode_is_open_for_write(mapping->host)) {
2019eb6ecbedSCollin Fijalkovich 			result = SCAN_FAIL;
2020eb6ecbedSCollin Fijalkovich 			filemap_nr_thps_dec(mapping);
2021eb6ecbedSCollin Fijalkovich 		}
202209d91cdaSSong Liu 	}
202399cb0dbdSSong Liu 
2024042a3082SHugh Dickins xa_locked:
2025042a3082SHugh Dickins 	xas_unlock_irq(&xas);
202677da9389SMatthew Wilcox xa_unlocked:
2027042a3082SHugh Dickins 
20286d9df8a5SHugh Dickins 	/*
20296d9df8a5SHugh Dickins 	 * If collapse is successful, flush must be done now before copying.
20306d9df8a5SHugh Dickins 	 * If collapse is unsuccessful, does flush actually need to be done?
20316d9df8a5SHugh Dickins 	 * Do it anyway, to clear the state.
20326d9df8a5SHugh Dickins 	 */
20336d9df8a5SHugh Dickins 	try_to_unmap_flush();
20346d9df8a5SHugh Dickins 
2035509f0069SHugh Dickins 	if (result == SCAN_SUCCEED && nr_none &&
2036509f0069SHugh Dickins 	    !shmem_charge(mapping->host, nr_none))
2037509f0069SHugh Dickins 		result = SCAN_FAIL;
2038509f0069SHugh Dickins 	if (result != SCAN_SUCCEED) {
2039509f0069SHugh Dickins 		nr_none = 0;
2040cae106ddSDavid Stevens 		goto rollback;
2041509f0069SHugh Dickins 	}
2042cae106ddSDavid Stevens 
2043f3f0e1d2SKirill A. Shutemov 	/*
2044a2e17cc2SDavid Stevens 	 * The old pages are locked, so they won't change anymore.
2045f3f0e1d2SKirill A. Shutemov 	 */
20462af8ff29SHugh Dickins 	index = start;
204712904d95SJiaqi Yan 	list_for_each_entry(page, &pagelist, lru) {
20482af8ff29SHugh Dickins 		while (index < page->index) {
204950ad2f24SZach O'Keefe 			clear_highpage(hpage + (index % HPAGE_PMD_NR));
20502af8ff29SHugh Dickins 			index++;
20512af8ff29SHugh Dickins 		}
2052cae106ddSDavid Stevens 		if (copy_mc_highpage(hpage + (page->index % HPAGE_PMD_NR), page) > 0) {
205312904d95SJiaqi Yan 			result = SCAN_COPY_MC;
2054cae106ddSDavid Stevens 			goto rollback;
205512904d95SJiaqi Yan 		}
205612904d95SJiaqi Yan 		index++;
205712904d95SJiaqi Yan 	}
2058cae106ddSDavid Stevens 	while (index < end) {
205912904d95SJiaqi Yan 		clear_highpage(hpage + (index % HPAGE_PMD_NR));
206012904d95SJiaqi Yan 		index++;
206112904d95SJiaqi Yan 	}
206212904d95SJiaqi Yan 
2063ac492b9cSDavid Stevens 	if (nr_none) {
2064ac492b9cSDavid Stevens 		struct vm_area_struct *vma;
2065ac492b9cSDavid Stevens 		int nr_none_check = 0;
2066ac492b9cSDavid Stevens 
2067ac492b9cSDavid Stevens 		i_mmap_lock_read(mapping);
2068ac492b9cSDavid Stevens 		xas_lock_irq(&xas);
2069ac492b9cSDavid Stevens 
2070ac492b9cSDavid Stevens 		xas_set(&xas, start);
2071ac492b9cSDavid Stevens 		for (index = start; index < end; index++) {
2072ac492b9cSDavid Stevens 			if (!xas_next(&xas)) {
2073ac492b9cSDavid Stevens 				xas_store(&xas, XA_RETRY_ENTRY);
2074ac492b9cSDavid Stevens 				if (xas_error(&xas)) {
2075ac492b9cSDavid Stevens 					result = SCAN_STORE_FAILED;
2076ac492b9cSDavid Stevens 					goto immap_locked;
2077ac492b9cSDavid Stevens 				}
2078ac492b9cSDavid Stevens 				nr_none_check++;
2079ac492b9cSDavid Stevens 			}
2080ac492b9cSDavid Stevens 		}
2081ac492b9cSDavid Stevens 
2082ac492b9cSDavid Stevens 		if (nr_none != nr_none_check) {
2083ac492b9cSDavid Stevens 			result = SCAN_PAGE_FILLED;
2084ac492b9cSDavid Stevens 			goto immap_locked;
2085ac492b9cSDavid Stevens 		}
2086ac492b9cSDavid Stevens 
208712904d95SJiaqi Yan 		/*
2088ac492b9cSDavid Stevens 		 * If userspace observed a missing page in a VMA with a MODE_MISSING
2089ac492b9cSDavid Stevens 		 * userfaultfd, then it might expect a UFFD_EVENT_PAGEFAULT for that
2090ac492b9cSDavid Stevens 		 * page. If so, we need to roll back to avoid suppressing such an
2091ac492b9cSDavid Stevens 		 * event. Since wp/minor userfaultfds don't give userspace any
2092ac492b9cSDavid Stevens 		 * guarantees that the kernel doesn't fill a missing page with a zero
2093ac492b9cSDavid Stevens 		 * page, so they don't matter here.
2094ac492b9cSDavid Stevens 		 *
2095ac492b9cSDavid Stevens 		 * Any userfaultfds registered after this point will not be able to
2096ac492b9cSDavid Stevens 		 * observe any missing pages due to the previously inserted retry
2097ac492b9cSDavid Stevens 		 * entries.
209812904d95SJiaqi Yan 		 */
2099ac492b9cSDavid Stevens 		vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2100ac492b9cSDavid Stevens 			if (userfaultfd_missing(vma)) {
2101ac492b9cSDavid Stevens 				result = SCAN_EXCEED_NONE_PTE;
2102ac492b9cSDavid Stevens 				goto immap_locked;
2103ac492b9cSDavid Stevens 			}
2104ac492b9cSDavid Stevens 		}
2105ac492b9cSDavid Stevens 
2106ac492b9cSDavid Stevens immap_locked:
2107ac492b9cSDavid Stevens 		i_mmap_unlock_read(mapping);
2108ac492b9cSDavid Stevens 		if (result != SCAN_SUCCEED) {
2109ac492b9cSDavid Stevens 			xas_set(&xas, start);
2110ac492b9cSDavid Stevens 			for (index = start; index < end; index++) {
2111ac492b9cSDavid Stevens 				if (xas_next(&xas) == XA_RETRY_ENTRY)
2112ac492b9cSDavid Stevens 					xas_store(&xas, NULL);
2113ac492b9cSDavid Stevens 			}
2114ac492b9cSDavid Stevens 
2115ac492b9cSDavid Stevens 			xas_unlock_irq(&xas);
2116ac492b9cSDavid Stevens 			goto rollback;
2117ac492b9cSDavid Stevens 		}
2118ac492b9cSDavid Stevens 	} else {
2119ac492b9cSDavid Stevens 		xas_lock_irq(&xas);
21202af8ff29SHugh Dickins 	}
212112904d95SJiaqi Yan 
2122cae106ddSDavid Stevens 	nr = thp_nr_pages(hpage);
212312904d95SJiaqi Yan 	if (is_shmem)
212412904d95SJiaqi Yan 		__mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
212512904d95SJiaqi Yan 	else
212612904d95SJiaqi Yan 		__mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
212712904d95SJiaqi Yan 
212812904d95SJiaqi Yan 	if (nr_none) {
212912904d95SJiaqi Yan 		__mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
213012904d95SJiaqi Yan 		/* nr_none is always 0 for non-shmem. */
213112904d95SJiaqi Yan 		__mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
2132f3f0e1d2SKirill A. Shutemov 	}
2133f3f0e1d2SKirill A. Shutemov 
2134a2e17cc2SDavid Stevens 	/*
2135a2e17cc2SDavid Stevens 	 * Mark hpage as uptodate before inserting it into the page cache so
2136a2e17cc2SDavid Stevens 	 * that it isn't mistaken for an fallocated but unwritten page.
2137a2e17cc2SDavid Stevens 	 */
2138284a344eSVishal Moola (Oracle) 	folio = page_folio(hpage);
2139284a344eSVishal Moola (Oracle) 	folio_mark_uptodate(folio);
2140284a344eSVishal Moola (Oracle) 	folio_ref_add(folio, HPAGE_PMD_NR - 1);
2141284a344eSVishal Moola (Oracle) 
21426058eaecSJohannes Weiner 	if (is_shmem)
2143284a344eSVishal Moola (Oracle) 		folio_mark_dirty(folio);
2144284a344eSVishal Moola (Oracle) 	folio_add_lru(folio);
2145f3f0e1d2SKirill A. Shutemov 
2146a2e17cc2SDavid Stevens 	/* Join all the small entries into a single multi-index entry. */
2147a2e17cc2SDavid Stevens 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2148a2e17cc2SDavid Stevens 	xas_store(&xas, hpage);
21490175ab61SHugh Dickins 	WARN_ON_ONCE(xas_error(&xas));
2150a2e17cc2SDavid Stevens 	xas_unlock_irq(&xas);
2151a2e17cc2SDavid Stevens 
2152042a3082SHugh Dickins 	/*
2153042a3082SHugh Dickins 	 * Remove pte page tables, so we can re-fault the page as huge.
21541d65b771SHugh Dickins 	 * If MADV_COLLAPSE, adjust result to call collapse_pte_mapped_thp().
2155042a3082SHugh Dickins 	 */
21561d65b771SHugh Dickins 	retract_page_tables(mapping, start);
21571d65b771SHugh Dickins 	if (cc && !cc->is_khugepaged)
21581d65b771SHugh Dickins 		result = SCAN_PTE_MAPPED_HUGEPAGE;
215950ad2f24SZach O'Keefe 	unlock_page(hpage);
2160ac492b9cSDavid Stevens 
2161ac492b9cSDavid Stevens 	/*
2162ac492b9cSDavid Stevens 	 * The collapse has succeeded, so free the old pages.
2163ac492b9cSDavid Stevens 	 */
2164ac492b9cSDavid Stevens 	list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2165ac492b9cSDavid Stevens 		list_del(&page->lru);
2166ac492b9cSDavid Stevens 		page->mapping = NULL;
2167ac492b9cSDavid Stevens 		ClearPageActive(page);
2168ac492b9cSDavid Stevens 		ClearPageUnevictable(page);
2169ac492b9cSDavid Stevens 		unlock_page(page);
2170a2e17cc2SDavid Stevens 		folio_put_refs(page_folio(page), 3);
2171ac492b9cSDavid Stevens 	}
2172ac492b9cSDavid Stevens 
2173cae106ddSDavid Stevens 	goto out;
2174cae106ddSDavid Stevens 
2175cae106ddSDavid Stevens rollback:
217677da9389SMatthew Wilcox 	/* Something went wrong: roll back page cache changes */
21772f55f070SMiaohe Lin 	if (nr_none) {
2178a2e17cc2SDavid Stevens 		xas_lock_irq(&xas);
2179aaa52e34SHugh Dickins 		mapping->nrpages -= nr_none;
218077da9389SMatthew Wilcox 		xas_unlock_irq(&xas);
2181509f0069SHugh Dickins 		shmem_uncharge(mapping->host, nr_none);
2182a2e17cc2SDavid Stevens 	}
2183a2e17cc2SDavid Stevens 
2184a2e17cc2SDavid Stevens 	list_for_each_entry_safe(page, tmp, &pagelist, lru) {
2185a2e17cc2SDavid Stevens 		list_del(&page->lru);
2186f3f0e1d2SKirill A. Shutemov 		unlock_page(page);
2187042a3082SHugh Dickins 		putback_lru_page(page);
2188a2e17cc2SDavid Stevens 		put_page(page);
2189f3f0e1d2SKirill A. Shutemov 	}
219012904d95SJiaqi Yan 	/*
219112904d95SJiaqi Yan 	 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
219212904d95SJiaqi Yan 	 * file only. This undo is not needed unless failure is
219312904d95SJiaqi Yan 	 * due to SCAN_COPY_MC.
219412904d95SJiaqi Yan 	 */
219512904d95SJiaqi Yan 	if (!is_shmem && result == SCAN_COPY_MC) {
219612904d95SJiaqi Yan 		filemap_nr_thps_dec(mapping);
219712904d95SJiaqi Yan 		/*
219812904d95SJiaqi Yan 		 * Paired with smp_mb() in do_dentry_open() to
219912904d95SJiaqi Yan 		 * ensure the update to nr_thps is visible.
220012904d95SJiaqi Yan 		 */
220112904d95SJiaqi Yan 		smp_mb();
220212904d95SJiaqi Yan 	}
220312904d95SJiaqi Yan 
220450ad2f24SZach O'Keefe 	hpage->mapping = NULL;
2205042a3082SHugh Dickins 
220650ad2f24SZach O'Keefe 	unlock_page(hpage);
2207cae106ddSDavid Stevens 	put_page(hpage);
2208f3f0e1d2SKirill A. Shutemov out:
2209f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(!list_empty(&pagelist));
22104c9473e8SGautam Menghani 	trace_mm_khugepaged_collapse_file(mm, hpage, index, is_shmem, addr, file, nr, result);
221150ad2f24SZach O'Keefe 	return result;
2212f3f0e1d2SKirill A. Shutemov }
2213f3f0e1d2SKirill A. Shutemov 
221434488399SZach O'Keefe static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
221534488399SZach O'Keefe 				    struct file *file, pgoff_t start,
221634488399SZach O'Keefe 				    struct collapse_control *cc)
2217f3f0e1d2SKirill A. Shutemov {
2218f3f0e1d2SKirill A. Shutemov 	struct page *page = NULL;
2219579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
222085b392dbSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
2221f3f0e1d2SKirill A. Shutemov 	int present, swap;
2222f3f0e1d2SKirill A. Shutemov 	int node = NUMA_NO_NODE;
2223f3f0e1d2SKirill A. Shutemov 	int result = SCAN_SUCCEED;
2224f3f0e1d2SKirill A. Shutemov 
2225f3f0e1d2SKirill A. Shutemov 	present = 0;
2226f3f0e1d2SKirill A. Shutemov 	swap = 0;
222734d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
2228e031ff96SYang Shi 	nodes_clear(cc->alloc_nmask);
2229f3f0e1d2SKirill A. Shutemov 	rcu_read_lock();
223085b392dbSMatthew Wilcox 	xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
223185b392dbSMatthew Wilcox 		if (xas_retry(&xas, page))
2232f3f0e1d2SKirill A. Shutemov 			continue;
2233f3f0e1d2SKirill A. Shutemov 
223485b392dbSMatthew Wilcox 		if (xa_is_value(page)) {
2235d8ea7cc8SZach O'Keefe 			++swap;
2236d8ea7cc8SZach O'Keefe 			if (cc->is_khugepaged &&
2237d8ea7cc8SZach O'Keefe 			    swap > khugepaged_max_ptes_swap) {
2238f3f0e1d2SKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
2239e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2240f3f0e1d2SKirill A. Shutemov 				break;
2241f3f0e1d2SKirill A. Shutemov 			}
2242f3f0e1d2SKirill A. Shutemov 			continue;
2243f3f0e1d2SKirill A. Shutemov 		}
2244f3f0e1d2SKirill A. Shutemov 
22456b24ca4aSMatthew Wilcox (Oracle) 		/*
224658ac9a89SZach O'Keefe 		 * TODO: khugepaged should compact smaller compound pages
22476b24ca4aSMatthew Wilcox (Oracle) 		 * into a PMD sized page
22486b24ca4aSMatthew Wilcox (Oracle) 		 */
2249f3f0e1d2SKirill A. Shutemov 		if (PageTransCompound(page)) {
225058ac9a89SZach O'Keefe 			struct page *head = compound_head(page);
225158ac9a89SZach O'Keefe 
225258ac9a89SZach O'Keefe 			result = compound_order(head) == HPAGE_PMD_ORDER &&
225358ac9a89SZach O'Keefe 					head->index == start
225458ac9a89SZach O'Keefe 					/* Maybe PMD-mapped */
225558ac9a89SZach O'Keefe 					? SCAN_PTE_MAPPED_HUGEPAGE
225658ac9a89SZach O'Keefe 					: SCAN_PAGE_COMPOUND;
225758ac9a89SZach O'Keefe 			/*
225858ac9a89SZach O'Keefe 			 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
225958ac9a89SZach O'Keefe 			 * by the caller won't touch the page cache, and so
226058ac9a89SZach O'Keefe 			 * it's safe to skip LRU and refcount checks before
226158ac9a89SZach O'Keefe 			 * returning.
226258ac9a89SZach O'Keefe 			 */
2263f3f0e1d2SKirill A. Shutemov 			break;
2264f3f0e1d2SKirill A. Shutemov 		}
2265f3f0e1d2SKirill A. Shutemov 
2266f3f0e1d2SKirill A. Shutemov 		node = page_to_nid(page);
22677d2c4385SZach O'Keefe 		if (hpage_collapse_scan_abort(node, cc)) {
2268f3f0e1d2SKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
2269f3f0e1d2SKirill A. Shutemov 			break;
2270f3f0e1d2SKirill A. Shutemov 		}
227134d6b470SZach O'Keefe 		cc->node_load[node]++;
2272f3f0e1d2SKirill A. Shutemov 
2273f3f0e1d2SKirill A. Shutemov 		if (!PageLRU(page)) {
2274f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_LRU;
2275f3f0e1d2SKirill A. Shutemov 			break;
2276f3f0e1d2SKirill A. Shutemov 		}
2277f3f0e1d2SKirill A. Shutemov 
227899cb0dbdSSong Liu 		if (page_count(page) !=
227999cb0dbdSSong Liu 		    1 + page_mapcount(page) + page_has_private(page)) {
2280f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
2281f3f0e1d2SKirill A. Shutemov 			break;
2282f3f0e1d2SKirill A. Shutemov 		}
2283f3f0e1d2SKirill A. Shutemov 
2284f3f0e1d2SKirill A. Shutemov 		/*
2285f3f0e1d2SKirill A. Shutemov 		 * We probably should check if the page is referenced here, but
2286f3f0e1d2SKirill A. Shutemov 		 * nobody would transfer pte_young() to PageReferenced() for us.
2287f3f0e1d2SKirill A. Shutemov 		 * And rmap walk here is just too costly...
2288f3f0e1d2SKirill A. Shutemov 		 */
2289f3f0e1d2SKirill A. Shutemov 
2290f3f0e1d2SKirill A. Shutemov 		present++;
2291f3f0e1d2SKirill A. Shutemov 
2292f3f0e1d2SKirill A. Shutemov 		if (need_resched()) {
229385b392dbSMatthew Wilcox 			xas_pause(&xas);
2294f3f0e1d2SKirill A. Shutemov 			cond_resched_rcu();
2295f3f0e1d2SKirill A. Shutemov 		}
2296f3f0e1d2SKirill A. Shutemov 	}
2297f3f0e1d2SKirill A. Shutemov 	rcu_read_unlock();
2298f3f0e1d2SKirill A. Shutemov 
2299f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
2300d8ea7cc8SZach O'Keefe 		if (cc->is_khugepaged &&
2301d8ea7cc8SZach O'Keefe 		    present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2302f3f0e1d2SKirill A. Shutemov 			result = SCAN_EXCEED_NONE_PTE;
2303e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2304f3f0e1d2SKirill A. Shutemov 		} else {
230534488399SZach O'Keefe 			result = collapse_file(mm, addr, file, start, cc);
2306f3f0e1d2SKirill A. Shutemov 		}
2307f3f0e1d2SKirill A. Shutemov 	}
2308f3f0e1d2SKirill A. Shutemov 
2309045634ffSGautam Menghani 	trace_mm_khugepaged_scan_file(mm, page, file, present, swap, result);
231050ad2f24SZach O'Keefe 	return result;
2311f3f0e1d2SKirill A. Shutemov }
2312f3f0e1d2SKirill A. Shutemov #else
231334488399SZach O'Keefe static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
231434488399SZach O'Keefe 				    struct file *file, pgoff_t start,
231534488399SZach O'Keefe 				    struct collapse_control *cc)
2316f3f0e1d2SKirill A. Shutemov {
2317f3f0e1d2SKirill A. Shutemov 	BUILD_BUG();
2318f3f0e1d2SKirill A. Shutemov }
2319f3f0e1d2SKirill A. Shutemov #endif
2320f3f0e1d2SKirill A. Shutemov 
232150ad2f24SZach O'Keefe static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
232234d6b470SZach O'Keefe 					    struct collapse_control *cc)
2323b46e756fSKirill A. Shutemov 	__releases(&khugepaged_mm_lock)
2324b46e756fSKirill A. Shutemov 	__acquires(&khugepaged_mm_lock)
2325b46e756fSKirill A. Shutemov {
232668540502SMatthew Wilcox (Oracle) 	struct vma_iterator vmi;
2327b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
2328b26e2701SQi Zheng 	struct mm_slot *slot;
2329b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
2330b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
2331b46e756fSKirill A. Shutemov 	int progress = 0;
2332b46e756fSKirill A. Shutemov 
2333b46e756fSKirill A. Shutemov 	VM_BUG_ON(!pages);
233435f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
233550ad2f24SZach O'Keefe 	*result = SCAN_FAIL;
2336b46e756fSKirill A. Shutemov 
2337b26e2701SQi Zheng 	if (khugepaged_scan.mm_slot) {
2338b46e756fSKirill A. Shutemov 		mm_slot = khugepaged_scan.mm_slot;
2339b26e2701SQi Zheng 		slot = &mm_slot->slot;
2340b26e2701SQi Zheng 	} else {
2341b26e2701SQi Zheng 		slot = list_entry(khugepaged_scan.mm_head.next,
2342b46e756fSKirill A. Shutemov 				     struct mm_slot, mm_node);
2343b26e2701SQi Zheng 		mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2344b46e756fSKirill A. Shutemov 		khugepaged_scan.address = 0;
2345b46e756fSKirill A. Shutemov 		khugepaged_scan.mm_slot = mm_slot;
2346b46e756fSKirill A. Shutemov 	}
2347b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2348b46e756fSKirill A. Shutemov 
2349b26e2701SQi Zheng 	mm = slot->mm;
23503b454ad3SYang Shi 	/*
23513b454ad3SYang Shi 	 * Don't wait for semaphore (to avoid long wait times).  Just move to
23523b454ad3SYang Shi 	 * the next mm on the list.
23533b454ad3SYang Shi 	 */
2354b46e756fSKirill A. Shutemov 	vma = NULL;
2355d8ed45c5SMichel Lespinasse 	if (unlikely(!mmap_read_trylock(mm)))
2356c1e8d7c6SMichel Lespinasse 		goto breakouterloop_mmap_lock;
2357b46e756fSKirill A. Shutemov 
2358b46e756fSKirill A. Shutemov 	progress++;
235968540502SMatthew Wilcox (Oracle) 	if (unlikely(hpage_collapse_test_exit(mm)))
236068540502SMatthew Wilcox (Oracle) 		goto breakouterloop;
236168540502SMatthew Wilcox (Oracle) 
236268540502SMatthew Wilcox (Oracle) 	vma_iter_init(&vmi, mm, khugepaged_scan.address);
236368540502SMatthew Wilcox (Oracle) 	for_each_vma(vmi, vma) {
2364b46e756fSKirill A. Shutemov 		unsigned long hstart, hend;
2365b46e756fSKirill A. Shutemov 
2366b46e756fSKirill A. Shutemov 		cond_resched();
23677d2c4385SZach O'Keefe 		if (unlikely(hpage_collapse_test_exit(mm))) {
2368b46e756fSKirill A. Shutemov 			progress++;
2369b46e756fSKirill A. Shutemov 			break;
2370b46e756fSKirill A. Shutemov 		}
2371a7f4e6e4SZach O'Keefe 		if (!hugepage_vma_check(vma, vma->vm_flags, false, false, true)) {
2372b46e756fSKirill A. Shutemov skip:
2373b46e756fSKirill A. Shutemov 			progress++;
2374b46e756fSKirill A. Shutemov 			continue;
2375b46e756fSKirill A. Shutemov 		}
23764fa6893fSYang Shi 		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
23774fa6893fSYang Shi 		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2378b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address > hend)
2379b46e756fSKirill A. Shutemov 			goto skip;
2380b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address < hstart)
2381b46e756fSKirill A. Shutemov 			khugepaged_scan.address = hstart;
2382b46e756fSKirill A. Shutemov 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2383b46e756fSKirill A. Shutemov 
2384b46e756fSKirill A. Shutemov 		while (khugepaged_scan.address < hend) {
238550ad2f24SZach O'Keefe 			bool mmap_locked = true;
238650ad2f24SZach O'Keefe 
2387b46e756fSKirill A. Shutemov 			cond_resched();
23887d2c4385SZach O'Keefe 			if (unlikely(hpage_collapse_test_exit(mm)))
2389b46e756fSKirill A. Shutemov 				goto breakouterloop;
2390b46e756fSKirill A. Shutemov 
2391b46e756fSKirill A. Shutemov 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2392b46e756fSKirill A. Shutemov 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2393b46e756fSKirill A. Shutemov 				  hend);
239499cb0dbdSSong Liu 			if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2395396bcc52SMatthew Wilcox (Oracle) 				struct file *file = get_file(vma->vm_file);
2396f3f0e1d2SKirill A. Shutemov 				pgoff_t pgoff = linear_page_index(vma,
2397f3f0e1d2SKirill A. Shutemov 						khugepaged_scan.address);
239899cb0dbdSSong Liu 
2399d8ed45c5SMichel Lespinasse 				mmap_read_unlock(mm);
240050ad2f24SZach O'Keefe 				mmap_locked = false;
2401d50791c2SHugh Dickins 				*result = hpage_collapse_scan_file(mm,
2402d50791c2SHugh Dickins 					khugepaged_scan.address, file, pgoff, cc);
2403f3f0e1d2SKirill A. Shutemov 				fput(file);
2404d50791c2SHugh Dickins 				if (*result == SCAN_PTE_MAPPED_HUGEPAGE) {
2405d50791c2SHugh Dickins 					mmap_read_lock(mm);
2406d50791c2SHugh Dickins 					if (hpage_collapse_test_exit(mm))
2407d50791c2SHugh Dickins 						goto breakouterloop;
2408d50791c2SHugh Dickins 					*result = collapse_pte_mapped_thp(mm,
2409d50791c2SHugh Dickins 						khugepaged_scan.address, false);
2410d50791c2SHugh Dickins 					if (*result == SCAN_PMD_MAPPED)
2411d50791c2SHugh Dickins 						*result = SCAN_SUCCEED;
2412d50791c2SHugh Dickins 					mmap_read_unlock(mm);
2413d50791c2SHugh Dickins 				}
2414f3f0e1d2SKirill A. Shutemov 			} else {
24157d2c4385SZach O'Keefe 				*result = hpage_collapse_scan_pmd(mm, vma,
2416d50791c2SHugh Dickins 					khugepaged_scan.address, &mmap_locked, cc);
2417f3f0e1d2SKirill A. Shutemov 			}
241858ac9a89SZach O'Keefe 
2419d50791c2SHugh Dickins 			if (*result == SCAN_SUCCEED)
242050ad2f24SZach O'Keefe 				++khugepaged_pages_collapsed;
242158ac9a89SZach O'Keefe 
2422b46e756fSKirill A. Shutemov 			/* move to next address */
2423b46e756fSKirill A. Shutemov 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2424b46e756fSKirill A. Shutemov 			progress += HPAGE_PMD_NR;
242550ad2f24SZach O'Keefe 			if (!mmap_locked)
242650ad2f24SZach O'Keefe 				/*
242750ad2f24SZach O'Keefe 				 * We released mmap_lock so break loop.  Note
242850ad2f24SZach O'Keefe 				 * that we drop mmap_lock before all hugepage
242950ad2f24SZach O'Keefe 				 * allocations, so if allocation fails, we are
243050ad2f24SZach O'Keefe 				 * guaranteed to break here and report the
243150ad2f24SZach O'Keefe 				 * correct result back to caller.
243250ad2f24SZach O'Keefe 				 */
2433c1e8d7c6SMichel Lespinasse 				goto breakouterloop_mmap_lock;
2434b46e756fSKirill A. Shutemov 			if (progress >= pages)
2435b46e756fSKirill A. Shutemov 				goto breakouterloop;
2436b46e756fSKirill A. Shutemov 		}
2437b46e756fSKirill A. Shutemov 	}
2438b46e756fSKirill A. Shutemov breakouterloop:
2439d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2440c1e8d7c6SMichel Lespinasse breakouterloop_mmap_lock:
2441b46e756fSKirill A. Shutemov 
2442b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2443b46e756fSKirill A. Shutemov 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2444b46e756fSKirill A. Shutemov 	/*
2445b46e756fSKirill A. Shutemov 	 * Release the current mm_slot if this mm is about to die, or
2446b46e756fSKirill A. Shutemov 	 * if we scanned all vmas of this mm.
2447b46e756fSKirill A. Shutemov 	 */
24487d2c4385SZach O'Keefe 	if (hpage_collapse_test_exit(mm) || !vma) {
2449b46e756fSKirill A. Shutemov 		/*
2450b46e756fSKirill A. Shutemov 		 * Make sure that if mm_users is reaching zero while
2451b46e756fSKirill A. Shutemov 		 * khugepaged runs here, khugepaged_exit will find
2452b46e756fSKirill A. Shutemov 		 * mm_slot not pointing to the exiting mm.
2453b46e756fSKirill A. Shutemov 		 */
2454b26e2701SQi Zheng 		if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2455b26e2701SQi Zheng 			slot = list_entry(slot->mm_node.next,
2456b46e756fSKirill A. Shutemov 					  struct mm_slot, mm_node);
2457b26e2701SQi Zheng 			khugepaged_scan.mm_slot =
2458b26e2701SQi Zheng 				mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2459b46e756fSKirill A. Shutemov 			khugepaged_scan.address = 0;
2460b46e756fSKirill A. Shutemov 		} else {
2461b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = NULL;
2462b46e756fSKirill A. Shutemov 			khugepaged_full_scans++;
2463b46e756fSKirill A. Shutemov 		}
2464b46e756fSKirill A. Shutemov 
2465b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2466b46e756fSKirill A. Shutemov 	}
2467b46e756fSKirill A. Shutemov 
2468b46e756fSKirill A. Shutemov 	return progress;
2469b46e756fSKirill A. Shutemov }
2470b46e756fSKirill A. Shutemov 
2471b46e756fSKirill A. Shutemov static int khugepaged_has_work(void)
2472b46e756fSKirill A. Shutemov {
2473b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) &&
24741064026bSYang Shi 		hugepage_flags_enabled();
2475b46e756fSKirill A. Shutemov }
2476b46e756fSKirill A. Shutemov 
2477b46e756fSKirill A. Shutemov static int khugepaged_wait_event(void)
2478b46e756fSKirill A. Shutemov {
2479b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) ||
2480b46e756fSKirill A. Shutemov 		kthread_should_stop();
2481b46e756fSKirill A. Shutemov }
2482b46e756fSKirill A. Shutemov 
248334d6b470SZach O'Keefe static void khugepaged_do_scan(struct collapse_control *cc)
2484b46e756fSKirill A. Shutemov {
2485b46e756fSKirill A. Shutemov 	unsigned int progress = 0, pass_through_head = 0;
248689dc6a96SYanfei Xu 	unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2487b46e756fSKirill A. Shutemov 	bool wait = true;
248850ad2f24SZach O'Keefe 	int result = SCAN_SUCCEED;
2489b46e756fSKirill A. Shutemov 
2490a980df33SKirill A. Shutemov 	lru_add_drain_all();
2491a980df33SKirill A. Shutemov 
2492c6a7f445SYang Shi 	while (true) {
2493b46e756fSKirill A. Shutemov 		cond_resched();
2494b46e756fSKirill A. Shutemov 
2495b46e756fSKirill A. Shutemov 		if (unlikely(kthread_should_stop() || try_to_freeze()))
2496b46e756fSKirill A. Shutemov 			break;
2497b46e756fSKirill A. Shutemov 
2498b46e756fSKirill A. Shutemov 		spin_lock(&khugepaged_mm_lock);
2499b46e756fSKirill A. Shutemov 		if (!khugepaged_scan.mm_slot)
2500b46e756fSKirill A. Shutemov 			pass_through_head++;
2501b46e756fSKirill A. Shutemov 		if (khugepaged_has_work() &&
2502b46e756fSKirill A. Shutemov 		    pass_through_head < 2)
2503b46e756fSKirill A. Shutemov 			progress += khugepaged_scan_mm_slot(pages - progress,
250450ad2f24SZach O'Keefe 							    &result, cc);
2505b46e756fSKirill A. Shutemov 		else
2506b46e756fSKirill A. Shutemov 			progress = pages;
2507b46e756fSKirill A. Shutemov 		spin_unlock(&khugepaged_mm_lock);
2508b46e756fSKirill A. Shutemov 
2509c6a7f445SYang Shi 		if (progress >= pages)
2510c6a7f445SYang Shi 			break;
2511c6a7f445SYang Shi 
251250ad2f24SZach O'Keefe 		if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2513c6a7f445SYang Shi 			/*
2514c6a7f445SYang Shi 			 * If fail to allocate the first time, try to sleep for
2515c6a7f445SYang Shi 			 * a while.  When hit again, cancel the scan.
2516c6a7f445SYang Shi 			 */
2517c6a7f445SYang Shi 			if (!wait)
2518c6a7f445SYang Shi 				break;
2519c6a7f445SYang Shi 			wait = false;
2520c6a7f445SYang Shi 			khugepaged_alloc_sleep();
2521c6a7f445SYang Shi 		}
2522c6a7f445SYang Shi 	}
2523b46e756fSKirill A. Shutemov }
2524b46e756fSKirill A. Shutemov 
2525b46e756fSKirill A. Shutemov static bool khugepaged_should_wakeup(void)
2526b46e756fSKirill A. Shutemov {
2527b46e756fSKirill A. Shutemov 	return kthread_should_stop() ||
2528b46e756fSKirill A. Shutemov 	       time_after_eq(jiffies, khugepaged_sleep_expire);
2529b46e756fSKirill A. Shutemov }
2530b46e756fSKirill A. Shutemov 
2531b46e756fSKirill A. Shutemov static void khugepaged_wait_work(void)
2532b46e756fSKirill A. Shutemov {
2533b46e756fSKirill A. Shutemov 	if (khugepaged_has_work()) {
2534b46e756fSKirill A. Shutemov 		const unsigned long scan_sleep_jiffies =
2535b46e756fSKirill A. Shutemov 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2536b46e756fSKirill A. Shutemov 
2537b46e756fSKirill A. Shutemov 		if (!scan_sleep_jiffies)
2538b46e756fSKirill A. Shutemov 			return;
2539b46e756fSKirill A. Shutemov 
2540b46e756fSKirill A. Shutemov 		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2541b46e756fSKirill A. Shutemov 		wait_event_freezable_timeout(khugepaged_wait,
2542b46e756fSKirill A. Shutemov 					     khugepaged_should_wakeup(),
2543b46e756fSKirill A. Shutemov 					     scan_sleep_jiffies);
2544b46e756fSKirill A. Shutemov 		return;
2545b46e756fSKirill A. Shutemov 	}
2546b46e756fSKirill A. Shutemov 
25471064026bSYang Shi 	if (hugepage_flags_enabled())
2548b46e756fSKirill A. Shutemov 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2549b46e756fSKirill A. Shutemov }
2550b46e756fSKirill A. Shutemov 
2551b46e756fSKirill A. Shutemov static int khugepaged(void *none)
2552b46e756fSKirill A. Shutemov {
2553b26e2701SQi Zheng 	struct khugepaged_mm_slot *mm_slot;
2554b46e756fSKirill A. Shutemov 
2555b46e756fSKirill A. Shutemov 	set_freezable();
2556b46e756fSKirill A. Shutemov 	set_user_nice(current, MAX_NICE);
2557b46e756fSKirill A. Shutemov 
2558b46e756fSKirill A. Shutemov 	while (!kthread_should_stop()) {
255934d6b470SZach O'Keefe 		khugepaged_do_scan(&khugepaged_collapse_control);
2560b46e756fSKirill A. Shutemov 		khugepaged_wait_work();
2561b46e756fSKirill A. Shutemov 	}
2562b46e756fSKirill A. Shutemov 
2563b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2564b46e756fSKirill A. Shutemov 	mm_slot = khugepaged_scan.mm_slot;
2565b46e756fSKirill A. Shutemov 	khugepaged_scan.mm_slot = NULL;
2566b46e756fSKirill A. Shutemov 	if (mm_slot)
2567b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2568b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2569b46e756fSKirill A. Shutemov 	return 0;
2570b46e756fSKirill A. Shutemov }
2571b46e756fSKirill A. Shutemov 
2572b46e756fSKirill A. Shutemov static void set_recommended_min_free_kbytes(void)
2573b46e756fSKirill A. Shutemov {
2574b46e756fSKirill A. Shutemov 	struct zone *zone;
2575b46e756fSKirill A. Shutemov 	int nr_zones = 0;
2576b46e756fSKirill A. Shutemov 	unsigned long recommended_min;
2577b46e756fSKirill A. Shutemov 
25781064026bSYang Shi 	if (!hugepage_flags_enabled()) {
2579bd3400eaSLiangcai Fan 		calculate_min_free_kbytes();
2580bd3400eaSLiangcai Fan 		goto update_wmarks;
2581bd3400eaSLiangcai Fan 	}
2582bd3400eaSLiangcai Fan 
2583b7d349c7SJoonsoo Kim 	for_each_populated_zone(zone) {
2584b7d349c7SJoonsoo Kim 		/*
2585b7d349c7SJoonsoo Kim 		 * We don't need to worry about fragmentation of
2586b7d349c7SJoonsoo Kim 		 * ZONE_MOVABLE since it only has movable pages.
2587b7d349c7SJoonsoo Kim 		 */
2588b7d349c7SJoonsoo Kim 		if (zone_idx(zone) > gfp_zone(GFP_USER))
2589b7d349c7SJoonsoo Kim 			continue;
2590b7d349c7SJoonsoo Kim 
2591b46e756fSKirill A. Shutemov 		nr_zones++;
2592b7d349c7SJoonsoo Kim 	}
2593b46e756fSKirill A. Shutemov 
2594b46e756fSKirill A. Shutemov 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2595b46e756fSKirill A. Shutemov 	recommended_min = pageblock_nr_pages * nr_zones * 2;
2596b46e756fSKirill A. Shutemov 
2597b46e756fSKirill A. Shutemov 	/*
2598b46e756fSKirill A. Shutemov 	 * Make sure that on average at least two pageblocks are almost free
2599b46e756fSKirill A. Shutemov 	 * of another type, one for a migratetype to fall back to and a
2600b46e756fSKirill A. Shutemov 	 * second to avoid subsequent fallbacks of other types There are 3
2601b46e756fSKirill A. Shutemov 	 * MIGRATE_TYPES we care about.
2602b46e756fSKirill A. Shutemov 	 */
2603b46e756fSKirill A. Shutemov 	recommended_min += pageblock_nr_pages * nr_zones *
2604b46e756fSKirill A. Shutemov 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2605b46e756fSKirill A. Shutemov 
2606b46e756fSKirill A. Shutemov 	/* don't ever allow to reserve more than 5% of the lowmem */
2607b46e756fSKirill A. Shutemov 	recommended_min = min(recommended_min,
2608b46e756fSKirill A. Shutemov 			      (unsigned long) nr_free_buffer_pages() / 20);
2609b46e756fSKirill A. Shutemov 	recommended_min <<= (PAGE_SHIFT-10);
2610b46e756fSKirill A. Shutemov 
2611b46e756fSKirill A. Shutemov 	if (recommended_min > min_free_kbytes) {
2612b46e756fSKirill A. Shutemov 		if (user_min_free_kbytes >= 0)
2613b46e756fSKirill A. Shutemov 			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2614b46e756fSKirill A. Shutemov 				min_free_kbytes, recommended_min);
2615b46e756fSKirill A. Shutemov 
2616b46e756fSKirill A. Shutemov 		min_free_kbytes = recommended_min;
2617b46e756fSKirill A. Shutemov 	}
2618bd3400eaSLiangcai Fan 
2619bd3400eaSLiangcai Fan update_wmarks:
2620b46e756fSKirill A. Shutemov 	setup_per_zone_wmarks();
2621b46e756fSKirill A. Shutemov }
2622b46e756fSKirill A. Shutemov 
2623b46e756fSKirill A. Shutemov int start_stop_khugepaged(void)
2624b46e756fSKirill A. Shutemov {
2625b46e756fSKirill A. Shutemov 	int err = 0;
2626b46e756fSKirill A. Shutemov 
2627b46e756fSKirill A. Shutemov 	mutex_lock(&khugepaged_mutex);
26281064026bSYang Shi 	if (hugepage_flags_enabled()) {
2629b46e756fSKirill A. Shutemov 		if (!khugepaged_thread)
2630b46e756fSKirill A. Shutemov 			khugepaged_thread = kthread_run(khugepaged, NULL,
2631b46e756fSKirill A. Shutemov 							"khugepaged");
2632b46e756fSKirill A. Shutemov 		if (IS_ERR(khugepaged_thread)) {
2633b46e756fSKirill A. Shutemov 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2634b46e756fSKirill A. Shutemov 			err = PTR_ERR(khugepaged_thread);
2635b46e756fSKirill A. Shutemov 			khugepaged_thread = NULL;
2636b46e756fSKirill A. Shutemov 			goto fail;
2637b46e756fSKirill A. Shutemov 		}
2638b46e756fSKirill A. Shutemov 
2639b46e756fSKirill A. Shutemov 		if (!list_empty(&khugepaged_scan.mm_head))
2640b46e756fSKirill A. Shutemov 			wake_up_interruptible(&khugepaged_wait);
2641b46e756fSKirill A. Shutemov 	} else if (khugepaged_thread) {
2642b46e756fSKirill A. Shutemov 		kthread_stop(khugepaged_thread);
2643b46e756fSKirill A. Shutemov 		khugepaged_thread = NULL;
2644b46e756fSKirill A. Shutemov 	}
2645bd3400eaSLiangcai Fan 	set_recommended_min_free_kbytes();
2646b46e756fSKirill A. Shutemov fail:
2647b46e756fSKirill A. Shutemov 	mutex_unlock(&khugepaged_mutex);
2648b46e756fSKirill A. Shutemov 	return err;
2649b46e756fSKirill A. Shutemov }
26504aab2be0SVijay Balakrishna 
26514aab2be0SVijay Balakrishna void khugepaged_min_free_kbytes_update(void)
26524aab2be0SVijay Balakrishna {
26534aab2be0SVijay Balakrishna 	mutex_lock(&khugepaged_mutex);
26541064026bSYang Shi 	if (hugepage_flags_enabled() && khugepaged_thread)
26554aab2be0SVijay Balakrishna 		set_recommended_min_free_kbytes();
26564aab2be0SVijay Balakrishna 	mutex_unlock(&khugepaged_mutex);
26574aab2be0SVijay Balakrishna }
26587d8faaf1SZach O'Keefe 
265957e9cc50SJohannes Weiner bool current_is_khugepaged(void)
266057e9cc50SJohannes Weiner {
266157e9cc50SJohannes Weiner 	return kthread_func(current) == khugepaged;
266257e9cc50SJohannes Weiner }
266357e9cc50SJohannes Weiner 
26647d8faaf1SZach O'Keefe static int madvise_collapse_errno(enum scan_result r)
26657d8faaf1SZach O'Keefe {
26667d8faaf1SZach O'Keefe 	/*
26677d8faaf1SZach O'Keefe 	 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
26687d8faaf1SZach O'Keefe 	 * actionable feedback to caller, so they may take an appropriate
26697d8faaf1SZach O'Keefe 	 * fallback measure depending on the nature of the failure.
26707d8faaf1SZach O'Keefe 	 */
26717d8faaf1SZach O'Keefe 	switch (r) {
26727d8faaf1SZach O'Keefe 	case SCAN_ALLOC_HUGE_PAGE_FAIL:
26737d8faaf1SZach O'Keefe 		return -ENOMEM;
26747d8faaf1SZach O'Keefe 	case SCAN_CGROUP_CHARGE_FAIL:
2675ac492b9cSDavid Stevens 	case SCAN_EXCEED_NONE_PTE:
26767d8faaf1SZach O'Keefe 		return -EBUSY;
26777d8faaf1SZach O'Keefe 	/* Resource temporary unavailable - trying again might succeed */
2678ae63c898SZach O'Keefe 	case SCAN_PAGE_COUNT:
26797d8faaf1SZach O'Keefe 	case SCAN_PAGE_LOCK:
26807d8faaf1SZach O'Keefe 	case SCAN_PAGE_LRU:
26810f3e2a2cSZach O'Keefe 	case SCAN_DEL_PAGE_LRU:
2682ac492b9cSDavid Stevens 	case SCAN_PAGE_FILLED:
26837d8faaf1SZach O'Keefe 		return -EAGAIN;
26847d8faaf1SZach O'Keefe 	/*
26857d8faaf1SZach O'Keefe 	 * Other: Trying again likely not to succeed / error intrinsic to
26867d8faaf1SZach O'Keefe 	 * specified memory range. khugepaged likely won't be able to collapse
26877d8faaf1SZach O'Keefe 	 * either.
26887d8faaf1SZach O'Keefe 	 */
26897d8faaf1SZach O'Keefe 	default:
26907d8faaf1SZach O'Keefe 		return -EINVAL;
26917d8faaf1SZach O'Keefe 	}
26927d8faaf1SZach O'Keefe }
26937d8faaf1SZach O'Keefe 
26947d8faaf1SZach O'Keefe int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
26957d8faaf1SZach O'Keefe 		     unsigned long start, unsigned long end)
26967d8faaf1SZach O'Keefe {
26977d8faaf1SZach O'Keefe 	struct collapse_control *cc;
26987d8faaf1SZach O'Keefe 	struct mm_struct *mm = vma->vm_mm;
26997d8faaf1SZach O'Keefe 	unsigned long hstart, hend, addr;
27007d8faaf1SZach O'Keefe 	int thps = 0, last_fail = SCAN_FAIL;
27017d8faaf1SZach O'Keefe 	bool mmap_locked = true;
27027d8faaf1SZach O'Keefe 
27037d8faaf1SZach O'Keefe 	BUG_ON(vma->vm_start > start);
27047d8faaf1SZach O'Keefe 	BUG_ON(vma->vm_end < end);
27057d8faaf1SZach O'Keefe 
27067d8faaf1SZach O'Keefe 	*prev = vma;
27077d8faaf1SZach O'Keefe 
27087d8faaf1SZach O'Keefe 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false, false))
27097d8faaf1SZach O'Keefe 		return -EINVAL;
27107d8faaf1SZach O'Keefe 
27117d8faaf1SZach O'Keefe 	cc = kmalloc(sizeof(*cc), GFP_KERNEL);
27127d8faaf1SZach O'Keefe 	if (!cc)
27137d8faaf1SZach O'Keefe 		return -ENOMEM;
27147d8faaf1SZach O'Keefe 	cc->is_khugepaged = false;
27157d8faaf1SZach O'Keefe 
27167d8faaf1SZach O'Keefe 	mmgrab(mm);
27177d8faaf1SZach O'Keefe 	lru_add_drain_all();
27187d8faaf1SZach O'Keefe 
27197d8faaf1SZach O'Keefe 	hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
27207d8faaf1SZach O'Keefe 	hend = end & HPAGE_PMD_MASK;
27217d8faaf1SZach O'Keefe 
27227d8faaf1SZach O'Keefe 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
27237d8faaf1SZach O'Keefe 		int result = SCAN_FAIL;
27247d8faaf1SZach O'Keefe 
27257d8faaf1SZach O'Keefe 		if (!mmap_locked) {
27267d8faaf1SZach O'Keefe 			cond_resched();
27277d8faaf1SZach O'Keefe 			mmap_read_lock(mm);
27287d8faaf1SZach O'Keefe 			mmap_locked = true;
272934488399SZach O'Keefe 			result = hugepage_vma_revalidate(mm, addr, false, &vma,
273034488399SZach O'Keefe 							 cc);
27317d8faaf1SZach O'Keefe 			if (result  != SCAN_SUCCEED) {
27327d8faaf1SZach O'Keefe 				last_fail = result;
27337d8faaf1SZach O'Keefe 				goto out_nolock;
27347d8faaf1SZach O'Keefe 			}
27354d24de94SYang Shi 
273652dc0310SZach O'Keefe 			hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
27377d8faaf1SZach O'Keefe 		}
27387d8faaf1SZach O'Keefe 		mmap_assert_locked(mm);
27397d8faaf1SZach O'Keefe 		memset(cc->node_load, 0, sizeof(cc->node_load));
2740e031ff96SYang Shi 		nodes_clear(cc->alloc_nmask);
274134488399SZach O'Keefe 		if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
274234488399SZach O'Keefe 			struct file *file = get_file(vma->vm_file);
274334488399SZach O'Keefe 			pgoff_t pgoff = linear_page_index(vma, addr);
274434488399SZach O'Keefe 
274534488399SZach O'Keefe 			mmap_read_unlock(mm);
274634488399SZach O'Keefe 			mmap_locked = false;
274734488399SZach O'Keefe 			result = hpage_collapse_scan_file(mm, addr, file, pgoff,
27487d2c4385SZach O'Keefe 							  cc);
274934488399SZach O'Keefe 			fput(file);
275034488399SZach O'Keefe 		} else {
275134488399SZach O'Keefe 			result = hpage_collapse_scan_pmd(mm, vma, addr,
275234488399SZach O'Keefe 							 &mmap_locked, cc);
275334488399SZach O'Keefe 		}
27547d8faaf1SZach O'Keefe 		if (!mmap_locked)
27557d8faaf1SZach O'Keefe 			*prev = NULL;  /* Tell caller we dropped mmap_lock */
27567d8faaf1SZach O'Keefe 
275734488399SZach O'Keefe handle_result:
27587d8faaf1SZach O'Keefe 		switch (result) {
27597d8faaf1SZach O'Keefe 		case SCAN_SUCCEED:
27607d8faaf1SZach O'Keefe 		case SCAN_PMD_MAPPED:
27617d8faaf1SZach O'Keefe 			++thps;
27627d8faaf1SZach O'Keefe 			break;
276334488399SZach O'Keefe 		case SCAN_PTE_MAPPED_HUGEPAGE:
276434488399SZach O'Keefe 			BUG_ON(mmap_locked);
276534488399SZach O'Keefe 			BUG_ON(*prev);
27661043173eSHugh Dickins 			mmap_read_lock(mm);
276734488399SZach O'Keefe 			result = collapse_pte_mapped_thp(mm, addr, true);
27681043173eSHugh Dickins 			mmap_read_unlock(mm);
276934488399SZach O'Keefe 			goto handle_result;
27707d8faaf1SZach O'Keefe 		/* Whitelisted set of results where continuing OK */
27717d8faaf1SZach O'Keefe 		case SCAN_PMD_NULL:
27727d8faaf1SZach O'Keefe 		case SCAN_PTE_NON_PRESENT:
27737d8faaf1SZach O'Keefe 		case SCAN_PTE_UFFD_WP:
27747d8faaf1SZach O'Keefe 		case SCAN_PAGE_RO:
27757d8faaf1SZach O'Keefe 		case SCAN_LACK_REFERENCED_PAGE:
27767d8faaf1SZach O'Keefe 		case SCAN_PAGE_NULL:
27777d8faaf1SZach O'Keefe 		case SCAN_PAGE_COUNT:
27787d8faaf1SZach O'Keefe 		case SCAN_PAGE_LOCK:
27797d8faaf1SZach O'Keefe 		case SCAN_PAGE_COMPOUND:
27807d8faaf1SZach O'Keefe 		case SCAN_PAGE_LRU:
27810f3e2a2cSZach O'Keefe 		case SCAN_DEL_PAGE_LRU:
27827d8faaf1SZach O'Keefe 			last_fail = result;
27837d8faaf1SZach O'Keefe 			break;
27847d8faaf1SZach O'Keefe 		default:
27857d8faaf1SZach O'Keefe 			last_fail = result;
27867d8faaf1SZach O'Keefe 			/* Other error, exit */
27877d8faaf1SZach O'Keefe 			goto out_maybelock;
27887d8faaf1SZach O'Keefe 		}
27897d8faaf1SZach O'Keefe 	}
27907d8faaf1SZach O'Keefe 
27917d8faaf1SZach O'Keefe out_maybelock:
27927d8faaf1SZach O'Keefe 	/* Caller expects us to hold mmap_lock on return */
27937d8faaf1SZach O'Keefe 	if (!mmap_locked)
27947d8faaf1SZach O'Keefe 		mmap_read_lock(mm);
27957d8faaf1SZach O'Keefe out_nolock:
27967d8faaf1SZach O'Keefe 	mmap_assert_locked(mm);
27977d8faaf1SZach O'Keefe 	mmdrop(mm);
27987d8faaf1SZach O'Keefe 	kfree(cc);
27997d8faaf1SZach O'Keefe 
28007d8faaf1SZach O'Keefe 	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
28017d8faaf1SZach O'Keefe 			: madvise_collapse_errno(last_fail);
28027d8faaf1SZach O'Keefe }
2803