xref: /linux/mm/khugepaged.c (revision 50ad2f24b3b48c7123e0d61a467baf35875a9ba5)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2b46e756fSKirill A. Shutemov #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3b46e756fSKirill A. Shutemov 
4b46e756fSKirill A. Shutemov #include <linux/mm.h>
5b46e756fSKirill A. Shutemov #include <linux/sched.h>
66e84f315SIngo Molnar #include <linux/sched/mm.h>
7f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
8b46e756fSKirill A. Shutemov #include <linux/mmu_notifier.h>
9b46e756fSKirill A. Shutemov #include <linux/rmap.h>
10b46e756fSKirill A. Shutemov #include <linux/swap.h>
11b46e756fSKirill A. Shutemov #include <linux/mm_inline.h>
12b46e756fSKirill A. Shutemov #include <linux/kthread.h>
13b46e756fSKirill A. Shutemov #include <linux/khugepaged.h>
14b46e756fSKirill A. Shutemov #include <linux/freezer.h>
15b46e756fSKirill A. Shutemov #include <linux/mman.h>
16b46e756fSKirill A. Shutemov #include <linux/hashtable.h>
17b46e756fSKirill A. Shutemov #include <linux/userfaultfd_k.h>
18b46e756fSKirill A. Shutemov #include <linux/page_idle.h>
1980110bbfSPasha Tatashin #include <linux/page_table_check.h>
20b46e756fSKirill A. Shutemov #include <linux/swapops.h>
21f3f0e1d2SKirill A. Shutemov #include <linux/shmem_fs.h>
22b46e756fSKirill A. Shutemov 
23b46e756fSKirill A. Shutemov #include <asm/tlb.h>
24b46e756fSKirill A. Shutemov #include <asm/pgalloc.h>
25b46e756fSKirill A. Shutemov #include "internal.h"
26b46e756fSKirill A. Shutemov 
27b46e756fSKirill A. Shutemov enum scan_result {
28b46e756fSKirill A. Shutemov 	SCAN_FAIL,
29b46e756fSKirill A. Shutemov 	SCAN_SUCCEED,
30b46e756fSKirill A. Shutemov 	SCAN_PMD_NULL,
31b46e756fSKirill A. Shutemov 	SCAN_EXCEED_NONE_PTE,
3271a2c112SKirill A. Shutemov 	SCAN_EXCEED_SWAP_PTE,
3371a2c112SKirill A. Shutemov 	SCAN_EXCEED_SHARED_PTE,
34b46e756fSKirill A. Shutemov 	SCAN_PTE_NON_PRESENT,
35e1e267c7SPeter Xu 	SCAN_PTE_UFFD_WP,
36b46e756fSKirill A. Shutemov 	SCAN_PAGE_RO,
370db501f7SEbru Akagunduz 	SCAN_LACK_REFERENCED_PAGE,
38b46e756fSKirill A. Shutemov 	SCAN_PAGE_NULL,
39b46e756fSKirill A. Shutemov 	SCAN_SCAN_ABORT,
40b46e756fSKirill A. Shutemov 	SCAN_PAGE_COUNT,
41b46e756fSKirill A. Shutemov 	SCAN_PAGE_LRU,
42b46e756fSKirill A. Shutemov 	SCAN_PAGE_LOCK,
43b46e756fSKirill A. Shutemov 	SCAN_PAGE_ANON,
44b46e756fSKirill A. Shutemov 	SCAN_PAGE_COMPOUND,
45b46e756fSKirill A. Shutemov 	SCAN_ANY_PROCESS,
46b46e756fSKirill A. Shutemov 	SCAN_VMA_NULL,
47b46e756fSKirill A. Shutemov 	SCAN_VMA_CHECK,
48b46e756fSKirill A. Shutemov 	SCAN_ADDRESS_RANGE,
49b46e756fSKirill A. Shutemov 	SCAN_DEL_PAGE_LRU,
50b46e756fSKirill A. Shutemov 	SCAN_ALLOC_HUGE_PAGE_FAIL,
51b46e756fSKirill A. Shutemov 	SCAN_CGROUP_CHARGE_FAIL,
52f3f0e1d2SKirill A. Shutemov 	SCAN_TRUNCATED,
5399cb0dbdSSong Liu 	SCAN_PAGE_HAS_PRIVATE,
54b46e756fSKirill A. Shutemov };
55b46e756fSKirill A. Shutemov 
56b46e756fSKirill A. Shutemov #define CREATE_TRACE_POINTS
57b46e756fSKirill A. Shutemov #include <trace/events/huge_memory.h>
58b46e756fSKirill A. Shutemov 
594aab2be0SVijay Balakrishna static struct task_struct *khugepaged_thread __read_mostly;
604aab2be0SVijay Balakrishna static DEFINE_MUTEX(khugepaged_mutex);
614aab2be0SVijay Balakrishna 
62b46e756fSKirill A. Shutemov /* default scan 8*512 pte (or vmas) every 30 second */
63b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_to_scan __read_mostly;
64b46e756fSKirill A. Shutemov static unsigned int khugepaged_pages_collapsed;
65b46e756fSKirill A. Shutemov static unsigned int khugepaged_full_scans;
66b46e756fSKirill A. Shutemov static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
67b46e756fSKirill A. Shutemov /* during fragmentation poll the hugepage allocator once every minute */
68b46e756fSKirill A. Shutemov static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
69b46e756fSKirill A. Shutemov static unsigned long khugepaged_sleep_expire;
70b46e756fSKirill A. Shutemov static DEFINE_SPINLOCK(khugepaged_mm_lock);
71b46e756fSKirill A. Shutemov static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
72b46e756fSKirill A. Shutemov /*
73b46e756fSKirill A. Shutemov  * default collapse hugepages if there is at least one pte mapped like
74b46e756fSKirill A. Shutemov  * it would have happened if the vma was large enough during page
75b46e756fSKirill A. Shutemov  * fault.
76b46e756fSKirill A. Shutemov  */
77b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_none __read_mostly;
78b46e756fSKirill A. Shutemov static unsigned int khugepaged_max_ptes_swap __read_mostly;
7971a2c112SKirill A. Shutemov static unsigned int khugepaged_max_ptes_shared __read_mostly;
80b46e756fSKirill A. Shutemov 
81b46e756fSKirill A. Shutemov #define MM_SLOTS_HASH_BITS 10
82b46e756fSKirill A. Shutemov static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
83b46e756fSKirill A. Shutemov 
84b46e756fSKirill A. Shutemov static struct kmem_cache *mm_slot_cache __read_mostly;
85b46e756fSKirill A. Shutemov 
8627e1f827SSong Liu #define MAX_PTE_MAPPED_THP 8
8727e1f827SSong Liu 
8834d6b470SZach O'Keefe struct collapse_control {
8934d6b470SZach O'Keefe 	/* Num pages scanned per node */
9034d6b470SZach O'Keefe 	u32 node_load[MAX_NUMNODES];
9134d6b470SZach O'Keefe 
9234d6b470SZach O'Keefe 	/* Last target selected in khugepaged_find_target_node() */
9334d6b470SZach O'Keefe 	int last_target_node;
9434d6b470SZach O'Keefe };
9534d6b470SZach O'Keefe 
96b46e756fSKirill A. Shutemov /**
97b46e756fSKirill A. Shutemov  * struct mm_slot - hash lookup from mm to mm_slot
98b46e756fSKirill A. Shutemov  * @hash: hash collision list
99b46e756fSKirill A. Shutemov  * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
100b46e756fSKirill A. Shutemov  * @mm: the mm that this information is valid for
101336e6b53SAlex Shi  * @nr_pte_mapped_thp: number of pte mapped THP
102336e6b53SAlex Shi  * @pte_mapped_thp: address array corresponding pte mapped THP
103b46e756fSKirill A. Shutemov  */
104b46e756fSKirill A. Shutemov struct mm_slot {
105b46e756fSKirill A. Shutemov 	struct hlist_node hash;
106b46e756fSKirill A. Shutemov 	struct list_head mm_node;
107b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
10827e1f827SSong Liu 
10927e1f827SSong Liu 	/* pte-mapped THP in this mm */
11027e1f827SSong Liu 	int nr_pte_mapped_thp;
11127e1f827SSong Liu 	unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
112b46e756fSKirill A. Shutemov };
113b46e756fSKirill A. Shutemov 
114b46e756fSKirill A. Shutemov /**
115b46e756fSKirill A. Shutemov  * struct khugepaged_scan - cursor for scanning
116b46e756fSKirill A. Shutemov  * @mm_head: the head of the mm list to scan
117b46e756fSKirill A. Shutemov  * @mm_slot: the current mm_slot we are scanning
118b46e756fSKirill A. Shutemov  * @address: the next address inside that to be scanned
119b46e756fSKirill A. Shutemov  *
120b46e756fSKirill A. Shutemov  * There is only the one khugepaged_scan instance of this cursor structure.
121b46e756fSKirill A. Shutemov  */
122b46e756fSKirill A. Shutemov struct khugepaged_scan {
123b46e756fSKirill A. Shutemov 	struct list_head mm_head;
124b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
125b46e756fSKirill A. Shutemov 	unsigned long address;
126b46e756fSKirill A. Shutemov };
127b46e756fSKirill A. Shutemov 
128b46e756fSKirill A. Shutemov static struct khugepaged_scan khugepaged_scan = {
129b46e756fSKirill A. Shutemov 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
130b46e756fSKirill A. Shutemov };
131b46e756fSKirill A. Shutemov 
132e1465d12SJérémy Lefaure #ifdef CONFIG_SYSFS
133b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
134b46e756fSKirill A. Shutemov 					 struct kobj_attribute *attr,
135b46e756fSKirill A. Shutemov 					 char *buf)
136b46e756fSKirill A. Shutemov {
137ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
138b46e756fSKirill A. Shutemov }
139b46e756fSKirill A. Shutemov 
140b46e756fSKirill A. Shutemov static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
141b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
142b46e756fSKirill A. Shutemov 					  const char *buf, size_t count)
143b46e756fSKirill A. Shutemov {
144dfefd226SAlexey Dobriyan 	unsigned int msecs;
145b46e756fSKirill A. Shutemov 	int err;
146b46e756fSKirill A. Shutemov 
147dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
148dfefd226SAlexey Dobriyan 	if (err)
149b46e756fSKirill A. Shutemov 		return -EINVAL;
150b46e756fSKirill A. Shutemov 
151b46e756fSKirill A. Shutemov 	khugepaged_scan_sleep_millisecs = msecs;
152b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
153b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
154b46e756fSKirill A. Shutemov 
155b46e756fSKirill A. Shutemov 	return count;
156b46e756fSKirill A. Shutemov }
157b46e756fSKirill A. Shutemov static struct kobj_attribute scan_sleep_millisecs_attr =
1586dcdc94dSMiaohe Lin 	__ATTR_RW(scan_sleep_millisecs);
159b46e756fSKirill A. Shutemov 
160b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
161b46e756fSKirill A. Shutemov 					  struct kobj_attribute *attr,
162b46e756fSKirill A. Shutemov 					  char *buf)
163b46e756fSKirill A. Shutemov {
164ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
165b46e756fSKirill A. Shutemov }
166b46e756fSKirill A. Shutemov 
167b46e756fSKirill A. Shutemov static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
168b46e756fSKirill A. Shutemov 					   struct kobj_attribute *attr,
169b46e756fSKirill A. Shutemov 					   const char *buf, size_t count)
170b46e756fSKirill A. Shutemov {
171dfefd226SAlexey Dobriyan 	unsigned int msecs;
172b46e756fSKirill A. Shutemov 	int err;
173b46e756fSKirill A. Shutemov 
174dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &msecs);
175dfefd226SAlexey Dobriyan 	if (err)
176b46e756fSKirill A. Shutemov 		return -EINVAL;
177b46e756fSKirill A. Shutemov 
178b46e756fSKirill A. Shutemov 	khugepaged_alloc_sleep_millisecs = msecs;
179b46e756fSKirill A. Shutemov 	khugepaged_sleep_expire = 0;
180b46e756fSKirill A. Shutemov 	wake_up_interruptible(&khugepaged_wait);
181b46e756fSKirill A. Shutemov 
182b46e756fSKirill A. Shutemov 	return count;
183b46e756fSKirill A. Shutemov }
184b46e756fSKirill A. Shutemov static struct kobj_attribute alloc_sleep_millisecs_attr =
1856dcdc94dSMiaohe Lin 	__ATTR_RW(alloc_sleep_millisecs);
186b46e756fSKirill A. Shutemov 
187b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_show(struct kobject *kobj,
188b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
189b46e756fSKirill A. Shutemov 				  char *buf)
190b46e756fSKirill A. Shutemov {
191ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
192b46e756fSKirill A. Shutemov }
193b46e756fSKirill A. Shutemov static ssize_t pages_to_scan_store(struct kobject *kobj,
194b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
195b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
196b46e756fSKirill A. Shutemov {
197dfefd226SAlexey Dobriyan 	unsigned int pages;
198b46e756fSKirill A. Shutemov 	int err;
199b46e756fSKirill A. Shutemov 
200dfefd226SAlexey Dobriyan 	err = kstrtouint(buf, 10, &pages);
201dfefd226SAlexey Dobriyan 	if (err || !pages)
202b46e756fSKirill A. Shutemov 		return -EINVAL;
203b46e756fSKirill A. Shutemov 
204b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = pages;
205b46e756fSKirill A. Shutemov 
206b46e756fSKirill A. Shutemov 	return count;
207b46e756fSKirill A. Shutemov }
208b46e756fSKirill A. Shutemov static struct kobj_attribute pages_to_scan_attr =
2096dcdc94dSMiaohe Lin 	__ATTR_RW(pages_to_scan);
210b46e756fSKirill A. Shutemov 
211b46e756fSKirill A. Shutemov static ssize_t pages_collapsed_show(struct kobject *kobj,
212b46e756fSKirill A. Shutemov 				    struct kobj_attribute *attr,
213b46e756fSKirill A. Shutemov 				    char *buf)
214b46e756fSKirill A. Shutemov {
215ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
216b46e756fSKirill A. Shutemov }
217b46e756fSKirill A. Shutemov static struct kobj_attribute pages_collapsed_attr =
218b46e756fSKirill A. Shutemov 	__ATTR_RO(pages_collapsed);
219b46e756fSKirill A. Shutemov 
220b46e756fSKirill A. Shutemov static ssize_t full_scans_show(struct kobject *kobj,
221b46e756fSKirill A. Shutemov 			       struct kobj_attribute *attr,
222b46e756fSKirill A. Shutemov 			       char *buf)
223b46e756fSKirill A. Shutemov {
224ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
225b46e756fSKirill A. Shutemov }
226b46e756fSKirill A. Shutemov static struct kobj_attribute full_scans_attr =
227b46e756fSKirill A. Shutemov 	__ATTR_RO(full_scans);
228b46e756fSKirill A. Shutemov 
2296dcdc94dSMiaohe Lin static ssize_t defrag_show(struct kobject *kobj,
230b46e756fSKirill A. Shutemov 			   struct kobj_attribute *attr, char *buf)
231b46e756fSKirill A. Shutemov {
232b46e756fSKirill A. Shutemov 	return single_hugepage_flag_show(kobj, attr, buf,
233b46e756fSKirill A. Shutemov 					 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
234b46e756fSKirill A. Shutemov }
2356dcdc94dSMiaohe Lin static ssize_t defrag_store(struct kobject *kobj,
236b46e756fSKirill A. Shutemov 			    struct kobj_attribute *attr,
237b46e756fSKirill A. Shutemov 			    const char *buf, size_t count)
238b46e756fSKirill A. Shutemov {
239b46e756fSKirill A. Shutemov 	return single_hugepage_flag_store(kobj, attr, buf, count,
240b46e756fSKirill A. Shutemov 				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
241b46e756fSKirill A. Shutemov }
242b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_defrag_attr =
2436dcdc94dSMiaohe Lin 	__ATTR_RW(defrag);
244b46e756fSKirill A. Shutemov 
245b46e756fSKirill A. Shutemov /*
246b46e756fSKirill A. Shutemov  * max_ptes_none controls if khugepaged should collapse hugepages over
247b46e756fSKirill A. Shutemov  * any unmapped ptes in turn potentially increasing the memory
248b46e756fSKirill A. Shutemov  * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
249b46e756fSKirill A. Shutemov  * reduce the available free memory in the system as it
250b46e756fSKirill A. Shutemov  * runs. Increasing max_ptes_none will instead potentially reduce the
251b46e756fSKirill A. Shutemov  * free memory in the system during the khugepaged scan.
252b46e756fSKirill A. Shutemov  */
2536dcdc94dSMiaohe Lin static ssize_t max_ptes_none_show(struct kobject *kobj,
254b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
255b46e756fSKirill A. Shutemov 				  char *buf)
256b46e756fSKirill A. Shutemov {
257ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
258b46e756fSKirill A. Shutemov }
2596dcdc94dSMiaohe Lin static ssize_t max_ptes_none_store(struct kobject *kobj,
260b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
261b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
262b46e756fSKirill A. Shutemov {
263b46e756fSKirill A. Shutemov 	int err;
264b46e756fSKirill A. Shutemov 	unsigned long max_ptes_none;
265b46e756fSKirill A. Shutemov 
266b46e756fSKirill A. Shutemov 	err = kstrtoul(buf, 10, &max_ptes_none);
267b46e756fSKirill A. Shutemov 	if (err || max_ptes_none > HPAGE_PMD_NR - 1)
268b46e756fSKirill A. Shutemov 		return -EINVAL;
269b46e756fSKirill A. Shutemov 
270b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = max_ptes_none;
271b46e756fSKirill A. Shutemov 
272b46e756fSKirill A. Shutemov 	return count;
273b46e756fSKirill A. Shutemov }
274b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_none_attr =
2756dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_none);
276b46e756fSKirill A. Shutemov 
2776dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_show(struct kobject *kobj,
278b46e756fSKirill A. Shutemov 				  struct kobj_attribute *attr,
279b46e756fSKirill A. Shutemov 				  char *buf)
280b46e756fSKirill A. Shutemov {
281ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
282b46e756fSKirill A. Shutemov }
283b46e756fSKirill A. Shutemov 
2846dcdc94dSMiaohe Lin static ssize_t max_ptes_swap_store(struct kobject *kobj,
285b46e756fSKirill A. Shutemov 				   struct kobj_attribute *attr,
286b46e756fSKirill A. Shutemov 				   const char *buf, size_t count)
287b46e756fSKirill A. Shutemov {
288b46e756fSKirill A. Shutemov 	int err;
289b46e756fSKirill A. Shutemov 	unsigned long max_ptes_swap;
290b46e756fSKirill A. Shutemov 
291b46e756fSKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_swap);
292b46e756fSKirill A. Shutemov 	if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
293b46e756fSKirill A. Shutemov 		return -EINVAL;
294b46e756fSKirill A. Shutemov 
295b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = max_ptes_swap;
296b46e756fSKirill A. Shutemov 
297b46e756fSKirill A. Shutemov 	return count;
298b46e756fSKirill A. Shutemov }
299b46e756fSKirill A. Shutemov 
300b46e756fSKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_swap_attr =
3016dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_swap);
302b46e756fSKirill A. Shutemov 
3036dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_show(struct kobject *kobj,
30471a2c112SKirill A. Shutemov 				    struct kobj_attribute *attr,
30571a2c112SKirill A. Shutemov 				    char *buf)
30671a2c112SKirill A. Shutemov {
307ae7a927dSJoe Perches 	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
30871a2c112SKirill A. Shutemov }
30971a2c112SKirill A. Shutemov 
3106dcdc94dSMiaohe Lin static ssize_t max_ptes_shared_store(struct kobject *kobj,
31171a2c112SKirill A. Shutemov 				     struct kobj_attribute *attr,
31271a2c112SKirill A. Shutemov 				     const char *buf, size_t count)
31371a2c112SKirill A. Shutemov {
31471a2c112SKirill A. Shutemov 	int err;
31571a2c112SKirill A. Shutemov 	unsigned long max_ptes_shared;
31671a2c112SKirill A. Shutemov 
31771a2c112SKirill A. Shutemov 	err  = kstrtoul(buf, 10, &max_ptes_shared);
31871a2c112SKirill A. Shutemov 	if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
31971a2c112SKirill A. Shutemov 		return -EINVAL;
32071a2c112SKirill A. Shutemov 
32171a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = max_ptes_shared;
32271a2c112SKirill A. Shutemov 
32371a2c112SKirill A. Shutemov 	return count;
32471a2c112SKirill A. Shutemov }
32571a2c112SKirill A. Shutemov 
32671a2c112SKirill A. Shutemov static struct kobj_attribute khugepaged_max_ptes_shared_attr =
3276dcdc94dSMiaohe Lin 	__ATTR_RW(max_ptes_shared);
32871a2c112SKirill A. Shutemov 
329b46e756fSKirill A. Shutemov static struct attribute *khugepaged_attr[] = {
330b46e756fSKirill A. Shutemov 	&khugepaged_defrag_attr.attr,
331b46e756fSKirill A. Shutemov 	&khugepaged_max_ptes_none_attr.attr,
33271a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_swap_attr.attr,
33371a2c112SKirill A. Shutemov 	&khugepaged_max_ptes_shared_attr.attr,
334b46e756fSKirill A. Shutemov 	&pages_to_scan_attr.attr,
335b46e756fSKirill A. Shutemov 	&pages_collapsed_attr.attr,
336b46e756fSKirill A. Shutemov 	&full_scans_attr.attr,
337b46e756fSKirill A. Shutemov 	&scan_sleep_millisecs_attr.attr,
338b46e756fSKirill A. Shutemov 	&alloc_sleep_millisecs_attr.attr,
339b46e756fSKirill A. Shutemov 	NULL,
340b46e756fSKirill A. Shutemov };
341b46e756fSKirill A. Shutemov 
342b46e756fSKirill A. Shutemov struct attribute_group khugepaged_attr_group = {
343b46e756fSKirill A. Shutemov 	.attrs = khugepaged_attr,
344b46e756fSKirill A. Shutemov 	.name = "khugepaged",
345b46e756fSKirill A. Shutemov };
346e1465d12SJérémy Lefaure #endif /* CONFIG_SYSFS */
347b46e756fSKirill A. Shutemov 
348b46e756fSKirill A. Shutemov int hugepage_madvise(struct vm_area_struct *vma,
349b46e756fSKirill A. Shutemov 		     unsigned long *vm_flags, int advice)
350b46e756fSKirill A. Shutemov {
351b46e756fSKirill A. Shutemov 	switch (advice) {
352b46e756fSKirill A. Shutemov 	case MADV_HUGEPAGE:
353b46e756fSKirill A. Shutemov #ifdef CONFIG_S390
354b46e756fSKirill A. Shutemov 		/*
355b46e756fSKirill A. Shutemov 		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
356b46e756fSKirill A. Shutemov 		 * can't handle this properly after s390_enable_sie, so we simply
357b46e756fSKirill A. Shutemov 		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
358b46e756fSKirill A. Shutemov 		 */
359b46e756fSKirill A. Shutemov 		if (mm_has_pgste(vma->vm_mm))
360b46e756fSKirill A. Shutemov 			return 0;
361b46e756fSKirill A. Shutemov #endif
362b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_NOHUGEPAGE;
363b46e756fSKirill A. Shutemov 		*vm_flags |= VM_HUGEPAGE;
364b46e756fSKirill A. Shutemov 		/*
365b46e756fSKirill A. Shutemov 		 * If the vma become good for khugepaged to scan,
366b46e756fSKirill A. Shutemov 		 * register it here without waiting a page fault that
367b46e756fSKirill A. Shutemov 		 * may not happen any time soon.
368b46e756fSKirill A. Shutemov 		 */
369c791576cSYang Shi 		khugepaged_enter_vma(vma, *vm_flags);
370b46e756fSKirill A. Shutemov 		break;
371b46e756fSKirill A. Shutemov 	case MADV_NOHUGEPAGE:
372b46e756fSKirill A. Shutemov 		*vm_flags &= ~VM_HUGEPAGE;
373b46e756fSKirill A. Shutemov 		*vm_flags |= VM_NOHUGEPAGE;
374b46e756fSKirill A. Shutemov 		/*
375b46e756fSKirill A. Shutemov 		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
376b46e756fSKirill A. Shutemov 		 * this vma even if we leave the mm registered in khugepaged if
377b46e756fSKirill A. Shutemov 		 * it got registered before VM_NOHUGEPAGE was set.
378b46e756fSKirill A. Shutemov 		 */
379b46e756fSKirill A. Shutemov 		break;
380b46e756fSKirill A. Shutemov 	}
381b46e756fSKirill A. Shutemov 
382b46e756fSKirill A. Shutemov 	return 0;
383b46e756fSKirill A. Shutemov }
384b46e756fSKirill A. Shutemov 
385b46e756fSKirill A. Shutemov int __init khugepaged_init(void)
386b46e756fSKirill A. Shutemov {
387b46e756fSKirill A. Shutemov 	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
388b46e756fSKirill A. Shutemov 					  sizeof(struct mm_slot),
389b46e756fSKirill A. Shutemov 					  __alignof__(struct mm_slot), 0, NULL);
390b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)
391b46e756fSKirill A. Shutemov 		return -ENOMEM;
392b46e756fSKirill A. Shutemov 
393b46e756fSKirill A. Shutemov 	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
394b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
395b46e756fSKirill A. Shutemov 	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
39671a2c112SKirill A. Shutemov 	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
397b46e756fSKirill A. Shutemov 
398b46e756fSKirill A. Shutemov 	return 0;
399b46e756fSKirill A. Shutemov }
400b46e756fSKirill A. Shutemov 
401b46e756fSKirill A. Shutemov void __init khugepaged_destroy(void)
402b46e756fSKirill A. Shutemov {
403b46e756fSKirill A. Shutemov 	kmem_cache_destroy(mm_slot_cache);
404b46e756fSKirill A. Shutemov }
405b46e756fSKirill A. Shutemov 
406b46e756fSKirill A. Shutemov static inline struct mm_slot *alloc_mm_slot(void)
407b46e756fSKirill A. Shutemov {
408b46e756fSKirill A. Shutemov 	if (!mm_slot_cache)	/* initialization failed */
409b46e756fSKirill A. Shutemov 		return NULL;
410b46e756fSKirill A. Shutemov 	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
411b46e756fSKirill A. Shutemov }
412b46e756fSKirill A. Shutemov 
413b46e756fSKirill A. Shutemov static inline void free_mm_slot(struct mm_slot *mm_slot)
414b46e756fSKirill A. Shutemov {
415b46e756fSKirill A. Shutemov 	kmem_cache_free(mm_slot_cache, mm_slot);
416b46e756fSKirill A. Shutemov }
417b46e756fSKirill A. Shutemov 
418b46e756fSKirill A. Shutemov static struct mm_slot *get_mm_slot(struct mm_struct *mm)
419b46e756fSKirill A. Shutemov {
420b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
421b46e756fSKirill A. Shutemov 
422b46e756fSKirill A. Shutemov 	hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
423b46e756fSKirill A. Shutemov 		if (mm == mm_slot->mm)
424b46e756fSKirill A. Shutemov 			return mm_slot;
425b46e756fSKirill A. Shutemov 
426b46e756fSKirill A. Shutemov 	return NULL;
427b46e756fSKirill A. Shutemov }
428b46e756fSKirill A. Shutemov 
429b46e756fSKirill A. Shutemov static void insert_to_mm_slots_hash(struct mm_struct *mm,
430b46e756fSKirill A. Shutemov 				    struct mm_slot *mm_slot)
431b46e756fSKirill A. Shutemov {
432b46e756fSKirill A. Shutemov 	mm_slot->mm = mm;
433b46e756fSKirill A. Shutemov 	hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
434b46e756fSKirill A. Shutemov }
435b46e756fSKirill A. Shutemov 
436b46e756fSKirill A. Shutemov static inline int khugepaged_test_exit(struct mm_struct *mm)
437b46e756fSKirill A. Shutemov {
4384d45e75aSJann Horn 	return atomic_read(&mm->mm_users) == 0;
439b46e756fSKirill A. Shutemov }
440b46e756fSKirill A. Shutemov 
441d2081b2bSYang Shi void __khugepaged_enter(struct mm_struct *mm)
442b46e756fSKirill A. Shutemov {
443b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
444b46e756fSKirill A. Shutemov 	int wakeup;
445b46e756fSKirill A. Shutemov 
446b46e756fSKirill A. Shutemov 	mm_slot = alloc_mm_slot();
447b46e756fSKirill A. Shutemov 	if (!mm_slot)
448d2081b2bSYang Shi 		return;
449b46e756fSKirill A. Shutemov 
450b46e756fSKirill A. Shutemov 	/* __khugepaged_exit() must not run from under us */
45128ff0a3cSMiaohe Lin 	VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
452b46e756fSKirill A. Shutemov 	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
453b46e756fSKirill A. Shutemov 		free_mm_slot(mm_slot);
454d2081b2bSYang Shi 		return;
455b46e756fSKirill A. Shutemov 	}
456b46e756fSKirill A. Shutemov 
457b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
458b46e756fSKirill A. Shutemov 	insert_to_mm_slots_hash(mm, mm_slot);
459b46e756fSKirill A. Shutemov 	/*
460b46e756fSKirill A. Shutemov 	 * Insert just behind the scanning cursor, to let the area settle
461b46e756fSKirill A. Shutemov 	 * down a little.
462b46e756fSKirill A. Shutemov 	 */
463b46e756fSKirill A. Shutemov 	wakeup = list_empty(&khugepaged_scan.mm_head);
464b46e756fSKirill A. Shutemov 	list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
465b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
466b46e756fSKirill A. Shutemov 
467f1f10076SVegard Nossum 	mmgrab(mm);
468b46e756fSKirill A. Shutemov 	if (wakeup)
469b46e756fSKirill A. Shutemov 		wake_up_interruptible(&khugepaged_wait);
470b46e756fSKirill A. Shutemov }
471b46e756fSKirill A. Shutemov 
472c791576cSYang Shi void khugepaged_enter_vma(struct vm_area_struct *vma,
473b46e756fSKirill A. Shutemov 			  unsigned long vm_flags)
474b46e756fSKirill A. Shutemov {
4752647d11bSYang Shi 	if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
4761064026bSYang Shi 	    hugepage_flags_enabled()) {
4777da4e2cbSYang Shi 		if (hugepage_vma_check(vma, vm_flags, false, false))
4782647d11bSYang Shi 			__khugepaged_enter(vma->vm_mm);
4792647d11bSYang Shi 	}
480b46e756fSKirill A. Shutemov }
481b46e756fSKirill A. Shutemov 
482b46e756fSKirill A. Shutemov void __khugepaged_exit(struct mm_struct *mm)
483b46e756fSKirill A. Shutemov {
484b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
485b46e756fSKirill A. Shutemov 	int free = 0;
486b46e756fSKirill A. Shutemov 
487b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
488b46e756fSKirill A. Shutemov 	mm_slot = get_mm_slot(mm);
489b46e756fSKirill A. Shutemov 	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
490b46e756fSKirill A. Shutemov 		hash_del(&mm_slot->hash);
491b46e756fSKirill A. Shutemov 		list_del(&mm_slot->mm_node);
492b46e756fSKirill A. Shutemov 		free = 1;
493b46e756fSKirill A. Shutemov 	}
494b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
495b46e756fSKirill A. Shutemov 
496b46e756fSKirill A. Shutemov 	if (free) {
497b46e756fSKirill A. Shutemov 		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
498b46e756fSKirill A. Shutemov 		free_mm_slot(mm_slot);
499b46e756fSKirill A. Shutemov 		mmdrop(mm);
500b46e756fSKirill A. Shutemov 	} else if (mm_slot) {
501b46e756fSKirill A. Shutemov 		/*
502b46e756fSKirill A. Shutemov 		 * This is required to serialize against
503b46e756fSKirill A. Shutemov 		 * khugepaged_test_exit() (which is guaranteed to run
504b46e756fSKirill A. Shutemov 		 * under mmap sem read mode). Stop here (after we
505b46e756fSKirill A. Shutemov 		 * return all pagetables will be destroyed) until
506b46e756fSKirill A. Shutemov 		 * khugepaged has finished working on the pagetables
507c1e8d7c6SMichel Lespinasse 		 * under the mmap_lock.
508b46e756fSKirill A. Shutemov 		 */
509d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
510d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
511b46e756fSKirill A. Shutemov 	}
512b46e756fSKirill A. Shutemov }
513b46e756fSKirill A. Shutemov 
514b46e756fSKirill A. Shutemov static void release_pte_page(struct page *page)
515b46e756fSKirill A. Shutemov {
5165503fbf2SKirill A. Shutemov 	mod_node_page_state(page_pgdat(page),
5175503fbf2SKirill A. Shutemov 			NR_ISOLATED_ANON + page_is_file_lru(page),
5185503fbf2SKirill A. Shutemov 			-compound_nr(page));
519b46e756fSKirill A. Shutemov 	unlock_page(page);
520b46e756fSKirill A. Shutemov 	putback_lru_page(page);
521b46e756fSKirill A. Shutemov }
522b46e756fSKirill A. Shutemov 
5235503fbf2SKirill A. Shutemov static void release_pte_pages(pte_t *pte, pte_t *_pte,
5245503fbf2SKirill A. Shutemov 		struct list_head *compound_pagelist)
525b46e756fSKirill A. Shutemov {
5265503fbf2SKirill A. Shutemov 	struct page *page, *tmp;
5275503fbf2SKirill A. Shutemov 
528b46e756fSKirill A. Shutemov 	while (--_pte >= pte) {
529b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
5305503fbf2SKirill A. Shutemov 
5315503fbf2SKirill A. Shutemov 		page = pte_page(pteval);
5325503fbf2SKirill A. Shutemov 		if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
5335503fbf2SKirill A. Shutemov 				!PageCompound(page))
5345503fbf2SKirill A. Shutemov 			release_pte_page(page);
5355503fbf2SKirill A. Shutemov 	}
5365503fbf2SKirill A. Shutemov 
5375503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
5385503fbf2SKirill A. Shutemov 		list_del(&page->lru);
5395503fbf2SKirill A. Shutemov 		release_pte_page(page);
540b46e756fSKirill A. Shutemov 	}
541b46e756fSKirill A. Shutemov }
542b46e756fSKirill A. Shutemov 
5439445689fSKirill A. Shutemov static bool is_refcount_suitable(struct page *page)
5449445689fSKirill A. Shutemov {
5459445689fSKirill A. Shutemov 	int expected_refcount;
5469445689fSKirill A. Shutemov 
5479445689fSKirill A. Shutemov 	expected_refcount = total_mapcount(page);
5489445689fSKirill A. Shutemov 	if (PageSwapCache(page))
5499445689fSKirill A. Shutemov 		expected_refcount += compound_nr(page);
5509445689fSKirill A. Shutemov 
5519445689fSKirill A. Shutemov 	return page_count(page) == expected_refcount;
5529445689fSKirill A. Shutemov }
5539445689fSKirill A. Shutemov 
554b46e756fSKirill A. Shutemov static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
555b46e756fSKirill A. Shutemov 					unsigned long address,
5565503fbf2SKirill A. Shutemov 					pte_t *pte,
5575503fbf2SKirill A. Shutemov 					struct list_head *compound_pagelist)
558b46e756fSKirill A. Shutemov {
559b46e756fSKirill A. Shutemov 	struct page *page = NULL;
560b46e756fSKirill A. Shutemov 	pte_t *_pte;
561*50ad2f24SZach O'Keefe 	int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
5620db501f7SEbru Akagunduz 	bool writable = false;
563b46e756fSKirill A. Shutemov 
564b46e756fSKirill A. Shutemov 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
565b46e756fSKirill A. Shutemov 	     _pte++, address += PAGE_SIZE) {
566b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
567b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || (pte_present(pteval) &&
568b46e756fSKirill A. Shutemov 				is_zero_pfn(pte_pfn(pteval)))) {
569b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
570b46e756fSKirill A. Shutemov 			    ++none_or_zero <= khugepaged_max_ptes_none) {
571b46e756fSKirill A. Shutemov 				continue;
572b46e756fSKirill A. Shutemov 			} else {
573b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
574e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
575b46e756fSKirill A. Shutemov 				goto out;
576b46e756fSKirill A. Shutemov 			}
577b46e756fSKirill A. Shutemov 		}
578b46e756fSKirill A. Shutemov 		if (!pte_present(pteval)) {
579b46e756fSKirill A. Shutemov 			result = SCAN_PTE_NON_PRESENT;
580b46e756fSKirill A. Shutemov 			goto out;
581b46e756fSKirill A. Shutemov 		}
582b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, address, pteval);
5833218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
584b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
585b46e756fSKirill A. Shutemov 			goto out;
586b46e756fSKirill A. Shutemov 		}
587b46e756fSKirill A. Shutemov 
588b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageAnon(page), page);
589b46e756fSKirill A. Shutemov 
59071a2c112SKirill A. Shutemov 		if (page_mapcount(page) > 1 &&
59171a2c112SKirill A. Shutemov 				++shared > khugepaged_max_ptes_shared) {
59271a2c112SKirill A. Shutemov 			result = SCAN_EXCEED_SHARED_PTE;
593e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
59471a2c112SKirill A. Shutemov 			goto out;
59571a2c112SKirill A. Shutemov 		}
59671a2c112SKirill A. Shutemov 
5975503fbf2SKirill A. Shutemov 		if (PageCompound(page)) {
5985503fbf2SKirill A. Shutemov 			struct page *p;
5995503fbf2SKirill A. Shutemov 			page = compound_head(page);
6005503fbf2SKirill A. Shutemov 
6015503fbf2SKirill A. Shutemov 			/*
6025503fbf2SKirill A. Shutemov 			 * Check if we have dealt with the compound page
6035503fbf2SKirill A. Shutemov 			 * already
6045503fbf2SKirill A. Shutemov 			 */
6055503fbf2SKirill A. Shutemov 			list_for_each_entry(p, compound_pagelist, lru) {
6065503fbf2SKirill A. Shutemov 				if (page == p)
6075503fbf2SKirill A. Shutemov 					goto next;
6085503fbf2SKirill A. Shutemov 			}
6095503fbf2SKirill A. Shutemov 		}
6105503fbf2SKirill A. Shutemov 
611b46e756fSKirill A. Shutemov 		/*
612b46e756fSKirill A. Shutemov 		 * We can do it before isolate_lru_page because the
613b46e756fSKirill A. Shutemov 		 * page can't be freed from under us. NOTE: PG_lock
614b46e756fSKirill A. Shutemov 		 * is needed to serialize against split_huge_page
615b46e756fSKirill A. Shutemov 		 * when invoked from the VM.
616b46e756fSKirill A. Shutemov 		 */
617b46e756fSKirill A. Shutemov 		if (!trylock_page(page)) {
618b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
619b46e756fSKirill A. Shutemov 			goto out;
620b46e756fSKirill A. Shutemov 		}
621b46e756fSKirill A. Shutemov 
622b46e756fSKirill A. Shutemov 		/*
6239445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
6249445689fSKirill A. Shutemov 		 *
6259445689fSKirill A. Shutemov 		 * The page table that maps the page has been already unlinked
6269445689fSKirill A. Shutemov 		 * from the page table tree and this process cannot get
627f0953a1bSIngo Molnar 		 * an additional pin on the page.
6289445689fSKirill A. Shutemov 		 *
6299445689fSKirill A. Shutemov 		 * New pins can come later if the page is shared across fork,
6309445689fSKirill A. Shutemov 		 * but not from this process. The other process cannot write to
6319445689fSKirill A. Shutemov 		 * the page, only trigger CoW.
632b46e756fSKirill A. Shutemov 		 */
6339445689fSKirill A. Shutemov 		if (!is_refcount_suitable(page)) {
634b46e756fSKirill A. Shutemov 			unlock_page(page);
635b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
636b46e756fSKirill A. Shutemov 			goto out;
637b46e756fSKirill A. Shutemov 		}
638b46e756fSKirill A. Shutemov 
639b46e756fSKirill A. Shutemov 		/*
640b46e756fSKirill A. Shutemov 		 * Isolate the page to avoid collapsing an hugepage
641b46e756fSKirill A. Shutemov 		 * currently in use by the VM.
642b46e756fSKirill A. Shutemov 		 */
643b46e756fSKirill A. Shutemov 		if (isolate_lru_page(page)) {
644b46e756fSKirill A. Shutemov 			unlock_page(page);
645b46e756fSKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
646b46e756fSKirill A. Shutemov 			goto out;
647b46e756fSKirill A. Shutemov 		}
6485503fbf2SKirill A. Shutemov 		mod_node_page_state(page_pgdat(page),
6495503fbf2SKirill A. Shutemov 				NR_ISOLATED_ANON + page_is_file_lru(page),
6505503fbf2SKirill A. Shutemov 				compound_nr(page));
651b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
652b46e756fSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageLRU(page), page);
653b46e756fSKirill A. Shutemov 
6545503fbf2SKirill A. Shutemov 		if (PageCompound(page))
6555503fbf2SKirill A. Shutemov 			list_add_tail(&page->lru, compound_pagelist);
6565503fbf2SKirill A. Shutemov next:
6570db501f7SEbru Akagunduz 		/* There should be enough young pte to collapse the page */
658b46e756fSKirill A. Shutemov 		if (pte_young(pteval) ||
659b46e756fSKirill A. Shutemov 		    page_is_young(page) || PageReferenced(page) ||
660b46e756fSKirill A. Shutemov 		    mmu_notifier_test_young(vma->vm_mm, address))
6610db501f7SEbru Akagunduz 			referenced++;
6625503fbf2SKirill A. Shutemov 
6635503fbf2SKirill A. Shutemov 		if (pte_write(pteval))
6645503fbf2SKirill A. Shutemov 			writable = true;
665b46e756fSKirill A. Shutemov 	}
66674e579bfSMiaohe Lin 
66774e579bfSMiaohe Lin 	if (unlikely(!writable)) {
66874e579bfSMiaohe Lin 		result = SCAN_PAGE_RO;
66974e579bfSMiaohe Lin 	} else if (unlikely(!referenced)) {
67074e579bfSMiaohe Lin 		result = SCAN_LACK_REFERENCED_PAGE;
67174e579bfSMiaohe Lin 	} else {
672b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
673b46e756fSKirill A. Shutemov 		trace_mm_collapse_huge_page_isolate(page, none_or_zero,
674b46e756fSKirill A. Shutemov 						    referenced, writable, result);
675*50ad2f24SZach O'Keefe 		return result;
676b46e756fSKirill A. Shutemov 	}
677b46e756fSKirill A. Shutemov out:
6785503fbf2SKirill A. Shutemov 	release_pte_pages(pte, _pte, compound_pagelist);
679b46e756fSKirill A. Shutemov 	trace_mm_collapse_huge_page_isolate(page, none_or_zero,
680b46e756fSKirill A. Shutemov 					    referenced, writable, result);
681*50ad2f24SZach O'Keefe 	return result;
682b46e756fSKirill A. Shutemov }
683b46e756fSKirill A. Shutemov 
684b46e756fSKirill A. Shutemov static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
685b46e756fSKirill A. Shutemov 				      struct vm_area_struct *vma,
686b46e756fSKirill A. Shutemov 				      unsigned long address,
6875503fbf2SKirill A. Shutemov 				      spinlock_t *ptl,
6885503fbf2SKirill A. Shutemov 				      struct list_head *compound_pagelist)
689b46e756fSKirill A. Shutemov {
6905503fbf2SKirill A. Shutemov 	struct page *src_page, *tmp;
691b46e756fSKirill A. Shutemov 	pte_t *_pte;
692338a16baSDavid Rientjes 	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
693338a16baSDavid Rientjes 				_pte++, page++, address += PAGE_SIZE) {
694b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
695b46e756fSKirill A. Shutemov 
696b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
697b46e756fSKirill A. Shutemov 			clear_user_highpage(page, address);
698b46e756fSKirill A. Shutemov 			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
699b46e756fSKirill A. Shutemov 			if (is_zero_pfn(pte_pfn(pteval))) {
700b46e756fSKirill A. Shutemov 				/*
701b46e756fSKirill A. Shutemov 				 * ptl mostly unnecessary.
702b46e756fSKirill A. Shutemov 				 */
703b46e756fSKirill A. Shutemov 				spin_lock(ptl);
70408d5b29eSPasha Tatashin 				ptep_clear(vma->vm_mm, address, _pte);
705b46e756fSKirill A. Shutemov 				spin_unlock(ptl);
706b46e756fSKirill A. Shutemov 			}
707b46e756fSKirill A. Shutemov 		} else {
708b46e756fSKirill A. Shutemov 			src_page = pte_page(pteval);
709b46e756fSKirill A. Shutemov 			copy_user_highpage(page, src_page, address, vma);
7105503fbf2SKirill A. Shutemov 			if (!PageCompound(src_page))
711b46e756fSKirill A. Shutemov 				release_pte_page(src_page);
712b46e756fSKirill A. Shutemov 			/*
713b46e756fSKirill A. Shutemov 			 * ptl mostly unnecessary, but preempt has to
714b46e756fSKirill A. Shutemov 			 * be disabled to update the per-cpu stats
715b46e756fSKirill A. Shutemov 			 * inside page_remove_rmap().
716b46e756fSKirill A. Shutemov 			 */
717b46e756fSKirill A. Shutemov 			spin_lock(ptl);
71808d5b29eSPasha Tatashin 			ptep_clear(vma->vm_mm, address, _pte);
719cea86fe2SHugh Dickins 			page_remove_rmap(src_page, vma, false);
720b46e756fSKirill A. Shutemov 			spin_unlock(ptl);
721b46e756fSKirill A. Shutemov 			free_page_and_swap_cache(src_page);
722b46e756fSKirill A. Shutemov 		}
723b46e756fSKirill A. Shutemov 	}
7245503fbf2SKirill A. Shutemov 
7255503fbf2SKirill A. Shutemov 	list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
7265503fbf2SKirill A. Shutemov 		list_del(&src_page->lru);
7271baec203SMiaohe Lin 		mod_node_page_state(page_pgdat(src_page),
7281baec203SMiaohe Lin 				    NR_ISOLATED_ANON + page_is_file_lru(src_page),
7291baec203SMiaohe Lin 				    -compound_nr(src_page));
7301baec203SMiaohe Lin 		unlock_page(src_page);
7311baec203SMiaohe Lin 		free_swap_cache(src_page);
7321baec203SMiaohe Lin 		putback_lru_page(src_page);
7335503fbf2SKirill A. Shutemov 	}
734b46e756fSKirill A. Shutemov }
735b46e756fSKirill A. Shutemov 
736b46e756fSKirill A. Shutemov static void khugepaged_alloc_sleep(void)
737b46e756fSKirill A. Shutemov {
738b46e756fSKirill A. Shutemov 	DEFINE_WAIT(wait);
739b46e756fSKirill A. Shutemov 
740b46e756fSKirill A. Shutemov 	add_wait_queue(&khugepaged_wait, &wait);
741b46e756fSKirill A. Shutemov 	freezable_schedule_timeout_interruptible(
742b46e756fSKirill A. Shutemov 		msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
743b46e756fSKirill A. Shutemov 	remove_wait_queue(&khugepaged_wait, &wait);
744b46e756fSKirill A. Shutemov }
745b46e756fSKirill A. Shutemov 
746b46e756fSKirill A. Shutemov 
74734d6b470SZach O'Keefe struct collapse_control khugepaged_collapse_control = {
74834d6b470SZach O'Keefe 	.last_target_node = NUMA_NO_NODE,
74934d6b470SZach O'Keefe };
75034d6b470SZach O'Keefe 
75134d6b470SZach O'Keefe static bool khugepaged_scan_abort(int nid, struct collapse_control *cc)
752b46e756fSKirill A. Shutemov {
753b46e756fSKirill A. Shutemov 	int i;
754b46e756fSKirill A. Shutemov 
755b46e756fSKirill A. Shutemov 	/*
756a5f5f91dSMel Gorman 	 * If node_reclaim_mode is disabled, then no extra effort is made to
757b46e756fSKirill A. Shutemov 	 * allocate memory locally.
758b46e756fSKirill A. Shutemov 	 */
759202e35dbSDave Hansen 	if (!node_reclaim_enabled())
760b46e756fSKirill A. Shutemov 		return false;
761b46e756fSKirill A. Shutemov 
762b46e756fSKirill A. Shutemov 	/* If there is a count for this node already, it must be acceptable */
76334d6b470SZach O'Keefe 	if (cc->node_load[nid])
764b46e756fSKirill A. Shutemov 		return false;
765b46e756fSKirill A. Shutemov 
766b46e756fSKirill A. Shutemov 	for (i = 0; i < MAX_NUMNODES; i++) {
76734d6b470SZach O'Keefe 		if (!cc->node_load[i])
768b46e756fSKirill A. Shutemov 			continue;
769a55c7454SMatt Fleming 		if (node_distance(nid, i) > node_reclaim_distance)
770b46e756fSKirill A. Shutemov 			return true;
771b46e756fSKirill A. Shutemov 	}
772b46e756fSKirill A. Shutemov 	return false;
773b46e756fSKirill A. Shutemov }
774b46e756fSKirill A. Shutemov 
7751064026bSYang Shi #define khugepaged_defrag()					\
7761064026bSYang Shi 	(transparent_hugepage_flags &				\
7771064026bSYang Shi 	 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
7781064026bSYang Shi 
779b46e756fSKirill A. Shutemov /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
780b46e756fSKirill A. Shutemov static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
781b46e756fSKirill A. Shutemov {
78225160354SVlastimil Babka 	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
783b46e756fSKirill A. Shutemov }
784b46e756fSKirill A. Shutemov 
785b46e756fSKirill A. Shutemov #ifdef CONFIG_NUMA
78634d6b470SZach O'Keefe static int khugepaged_find_target_node(struct collapse_control *cc)
787b46e756fSKirill A. Shutemov {
788b46e756fSKirill A. Shutemov 	int nid, target_node = 0, max_value = 0;
789b46e756fSKirill A. Shutemov 
790b46e756fSKirill A. Shutemov 	/* find first node with max normal pages hit */
791b46e756fSKirill A. Shutemov 	for (nid = 0; nid < MAX_NUMNODES; nid++)
79234d6b470SZach O'Keefe 		if (cc->node_load[nid] > max_value) {
79334d6b470SZach O'Keefe 			max_value = cc->node_load[nid];
794b46e756fSKirill A. Shutemov 			target_node = nid;
795b46e756fSKirill A. Shutemov 		}
796b46e756fSKirill A. Shutemov 
797b46e756fSKirill A. Shutemov 	/* do some balance if several nodes have the same hit record */
79834d6b470SZach O'Keefe 	if (target_node <= cc->last_target_node)
79934d6b470SZach O'Keefe 		for (nid = cc->last_target_node + 1; nid < MAX_NUMNODES;
800b46e756fSKirill A. Shutemov 		     nid++)
80134d6b470SZach O'Keefe 			if (max_value == cc->node_load[nid]) {
802b46e756fSKirill A. Shutemov 				target_node = nid;
803b46e756fSKirill A. Shutemov 				break;
804b46e756fSKirill A. Shutemov 			}
805b46e756fSKirill A. Shutemov 
80634d6b470SZach O'Keefe 	cc->last_target_node = target_node;
807b46e756fSKirill A. Shutemov 	return target_node;
808b46e756fSKirill A. Shutemov }
809c6a7f445SYang Shi #else
81034d6b470SZach O'Keefe static int khugepaged_find_target_node(struct collapse_control *cc)
811b46e756fSKirill A. Shutemov {
812c6a7f445SYang Shi 	return 0;
813b46e756fSKirill A. Shutemov }
814c6a7f445SYang Shi #endif
815b46e756fSKirill A. Shutemov 
8169710a78aSZach O'Keefe static bool khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
817b46e756fSKirill A. Shutemov {
818b46e756fSKirill A. Shutemov 	*hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
819b46e756fSKirill A. Shutemov 	if (unlikely(!*hpage)) {
820b46e756fSKirill A. Shutemov 		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
8219710a78aSZach O'Keefe 		return false;
822b46e756fSKirill A. Shutemov 	}
823b46e756fSKirill A. Shutemov 
824b46e756fSKirill A. Shutemov 	prep_transhuge_page(*hpage);
825b46e756fSKirill A. Shutemov 	count_vm_event(THP_COLLAPSE_ALLOC);
8269710a78aSZach O'Keefe 	return true;
827b46e756fSKirill A. Shutemov }
828b46e756fSKirill A. Shutemov 
829b46e756fSKirill A. Shutemov /*
830c1e8d7c6SMichel Lespinasse  * If mmap_lock temporarily dropped, revalidate vma
831c1e8d7c6SMichel Lespinasse  * before taking mmap_lock.
832*50ad2f24SZach O'Keefe  * Returns enum scan_result value.
833b46e756fSKirill A. Shutemov  */
834b46e756fSKirill A. Shutemov 
835c131f751SKirill A. Shutemov static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
836c131f751SKirill A. Shutemov 		struct vm_area_struct **vmap)
837b46e756fSKirill A. Shutemov {
838b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
839b46e756fSKirill A. Shutemov 
840b46e756fSKirill A. Shutemov 	if (unlikely(khugepaged_test_exit(mm)))
841b46e756fSKirill A. Shutemov 		return SCAN_ANY_PROCESS;
842b46e756fSKirill A. Shutemov 
843c131f751SKirill A. Shutemov 	*vmap = vma = find_vma(mm, address);
844b46e756fSKirill A. Shutemov 	if (!vma)
845b46e756fSKirill A. Shutemov 		return SCAN_VMA_NULL;
846b46e756fSKirill A. Shutemov 
8474fa6893fSYang Shi 	if (!transhuge_vma_suitable(vma, address))
848b46e756fSKirill A. Shutemov 		return SCAN_ADDRESS_RANGE;
8497da4e2cbSYang Shi 	if (!hugepage_vma_check(vma, vma->vm_flags, false, false))
850b46e756fSKirill A. Shutemov 		return SCAN_VMA_CHECK;
851f707fa49SYang Shi 	/*
852f707fa49SYang Shi 	 * Anon VMA expected, the address may be unmapped then
853f707fa49SYang Shi 	 * remapped to file after khugepaged reaquired the mmap_lock.
854f707fa49SYang Shi 	 *
855f707fa49SYang Shi 	 * hugepage_vma_check may return true for qualified file
856f707fa49SYang Shi 	 * vmas.
857f707fa49SYang Shi 	 */
85825fa414aSxu xin 	if (!vma->anon_vma || !vma_is_anonymous(vma))
859594cced1SKirill A. Shutemov 		return SCAN_VMA_CHECK;
860*50ad2f24SZach O'Keefe 	return SCAN_SUCCEED;
861b46e756fSKirill A. Shutemov }
862b46e756fSKirill A. Shutemov 
863b46e756fSKirill A. Shutemov /*
864b46e756fSKirill A. Shutemov  * Bring missing pages in from swap, to complete THP collapse.
865b46e756fSKirill A. Shutemov  * Only done if khugepaged_scan_pmd believes it is worthwhile.
866b46e756fSKirill A. Shutemov  *
8674d928e20SMiaohe Lin  * Called and returns without pte mapped or spinlocks held.
8684d928e20SMiaohe Lin  * Note that if false is returned, mmap_lock will be released.
869b46e756fSKirill A. Shutemov  */
870b46e756fSKirill A. Shutemov 
871*50ad2f24SZach O'Keefe static int __collapse_huge_page_swapin(struct mm_struct *mm,
872b46e756fSKirill A. Shutemov 				       struct vm_area_struct *vma,
8732b635dd3SWill Deacon 				       unsigned long haddr, pmd_t *pmd,
8740db501f7SEbru Akagunduz 				       int referenced)
875b46e756fSKirill A. Shutemov {
8762b740303SSouptick Joarder 	int swapped_in = 0;
8772b740303SSouptick Joarder 	vm_fault_t ret = 0;
8782b635dd3SWill Deacon 	unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
8792b635dd3SWill Deacon 
8802b635dd3SWill Deacon 	for (address = haddr; address < end; address += PAGE_SIZE) {
88182b0f8c3SJan Kara 		struct vm_fault vmf = {
882b46e756fSKirill A. Shutemov 			.vma = vma,
883b46e756fSKirill A. Shutemov 			.address = address,
8842b635dd3SWill Deacon 			.pgoff = linear_page_index(vma, haddr),
885b46e756fSKirill A. Shutemov 			.flags = FAULT_FLAG_ALLOW_RETRY,
886b46e756fSKirill A. Shutemov 			.pmd = pmd,
887b46e756fSKirill A. Shutemov 		};
888b46e756fSKirill A. Shutemov 
88982b0f8c3SJan Kara 		vmf.pte = pte_offset_map(pmd, address);
8902994302bSJan Kara 		vmf.orig_pte = *vmf.pte;
8912b635dd3SWill Deacon 		if (!is_swap_pte(vmf.orig_pte)) {
8922b635dd3SWill Deacon 			pte_unmap(vmf.pte);
893b46e756fSKirill A. Shutemov 			continue;
8942b635dd3SWill Deacon 		}
8952994302bSJan Kara 		ret = do_swap_page(&vmf);
8960db501f7SEbru Akagunduz 
8974d928e20SMiaohe Lin 		/*
8984d928e20SMiaohe Lin 		 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
8994d928e20SMiaohe Lin 		 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
9004d928e20SMiaohe Lin 		 * we do not retry here and swap entry will remain in pagetable
9014d928e20SMiaohe Lin 		 * resulting in later failure.
9024d928e20SMiaohe Lin 		 */
903b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_RETRY) {
9040db501f7SEbru Akagunduz 			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
905*50ad2f24SZach O'Keefe 			/* Likely, but not guaranteed, that page lock failed */
906*50ad2f24SZach O'Keefe 			return SCAN_PAGE_LOCK;
90747f863eaSEbru Akagunduz 		}
908b46e756fSKirill A. Shutemov 		if (ret & VM_FAULT_ERROR) {
9094d928e20SMiaohe Lin 			mmap_read_unlock(mm);
9100db501f7SEbru Akagunduz 			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
911*50ad2f24SZach O'Keefe 			return SCAN_FAIL;
912b46e756fSKirill A. Shutemov 		}
9134d928e20SMiaohe Lin 		swapped_in++;
914b46e756fSKirill A. Shutemov 	}
915ae2c5d80SKirill A. Shutemov 
916ae2c5d80SKirill A. Shutemov 	/* Drain LRU add pagevec to remove extra pin on the swapped in pages */
917ae2c5d80SKirill A. Shutemov 	if (swapped_in)
918ae2c5d80SKirill A. Shutemov 		lru_add_drain();
919ae2c5d80SKirill A. Shutemov 
9200db501f7SEbru Akagunduz 	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
921*50ad2f24SZach O'Keefe 	return SCAN_SUCCEED;
922b46e756fSKirill A. Shutemov }
923b46e756fSKirill A. Shutemov 
9249710a78aSZach O'Keefe static int alloc_charge_hpage(struct page **hpage, struct mm_struct *mm,
9259710a78aSZach O'Keefe 			      struct collapse_control *cc)
9269710a78aSZach O'Keefe {
9279710a78aSZach O'Keefe 	/* Only allocate from the target node */
9289710a78aSZach O'Keefe 	gfp_t gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
9299710a78aSZach O'Keefe 	int node = khugepaged_find_target_node(cc);
9309710a78aSZach O'Keefe 
9319710a78aSZach O'Keefe 	if (!khugepaged_alloc_page(hpage, gfp, node))
9329710a78aSZach O'Keefe 		return SCAN_ALLOC_HUGE_PAGE_FAIL;
9339710a78aSZach O'Keefe 	if (unlikely(mem_cgroup_charge(page_folio(*hpage), mm, gfp)))
9349710a78aSZach O'Keefe 		return SCAN_CGROUP_CHARGE_FAIL;
9359710a78aSZach O'Keefe 	count_memcg_page_event(*hpage, THP_COLLAPSE_ALLOC);
9369710a78aSZach O'Keefe 	return SCAN_SUCCEED;
9379710a78aSZach O'Keefe }
9389710a78aSZach O'Keefe 
939*50ad2f24SZach O'Keefe static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
940*50ad2f24SZach O'Keefe 			      int referenced, int unmapped,
941*50ad2f24SZach O'Keefe 			      struct collapse_control *cc)
942b46e756fSKirill A. Shutemov {
9435503fbf2SKirill A. Shutemov 	LIST_HEAD(compound_pagelist);
944b46e756fSKirill A. Shutemov 	pmd_t *pmd, _pmd;
945b46e756fSKirill A. Shutemov 	pte_t *pte;
946b46e756fSKirill A. Shutemov 	pgtable_t pgtable;
947*50ad2f24SZach O'Keefe 	struct page *hpage;
948b46e756fSKirill A. Shutemov 	spinlock_t *pmd_ptl, *pte_ptl;
949*50ad2f24SZach O'Keefe 	int result = SCAN_FAIL;
950c131f751SKirill A. Shutemov 	struct vm_area_struct *vma;
951ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
952b46e756fSKirill A. Shutemov 
953b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
954b46e756fSKirill A. Shutemov 
955988ddb71SKirill A. Shutemov 	/*
956c1e8d7c6SMichel Lespinasse 	 * Before allocating the hugepage, release the mmap_lock read lock.
957988ddb71SKirill A. Shutemov 	 * The allocation can take potentially a long time if it involves
958c1e8d7c6SMichel Lespinasse 	 * sync compaction, and we do not need to hold the mmap_lock during
959988ddb71SKirill A. Shutemov 	 * that. We will recheck the vma after taking it again in write mode.
960988ddb71SKirill A. Shutemov 	 */
961d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
962b46e756fSKirill A. Shutemov 
963*50ad2f24SZach O'Keefe 	result = alloc_charge_hpage(&hpage, mm, cc);
9649710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
965b46e756fSKirill A. Shutemov 		goto out_nolock;
9669710a78aSZach O'Keefe 
967d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
968c131f751SKirill A. Shutemov 	result = hugepage_vma_revalidate(mm, address, &vma);
969*50ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED) {
970d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
971b46e756fSKirill A. Shutemov 		goto out_nolock;
972b46e756fSKirill A. Shutemov 	}
973b46e756fSKirill A. Shutemov 
974b46e756fSKirill A. Shutemov 	pmd = mm_find_pmd(mm, address);
975b46e756fSKirill A. Shutemov 	if (!pmd) {
976b46e756fSKirill A. Shutemov 		result = SCAN_PMD_NULL;
977d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
978b46e756fSKirill A. Shutemov 		goto out_nolock;
979b46e756fSKirill A. Shutemov 	}
980b46e756fSKirill A. Shutemov 
981*50ad2f24SZach O'Keefe 	if (unmapped) {
982b46e756fSKirill A. Shutemov 		/*
983*50ad2f24SZach O'Keefe 		 * __collapse_huge_page_swapin will return with mmap_lock
984*50ad2f24SZach O'Keefe 		 * released when it fails. So we jump out_nolock directly in
985*50ad2f24SZach O'Keefe 		 * that case.  Continuing to collapse causes inconsistency.
986b46e756fSKirill A. Shutemov 		 */
987*50ad2f24SZach O'Keefe 		result = __collapse_huge_page_swapin(mm, vma, address, pmd,
988*50ad2f24SZach O'Keefe 						     referenced);
989*50ad2f24SZach O'Keefe 		if (result != SCAN_SUCCEED)
990b46e756fSKirill A. Shutemov 			goto out_nolock;
991b46e756fSKirill A. Shutemov 	}
992b46e756fSKirill A. Shutemov 
993d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
994b46e756fSKirill A. Shutemov 	/*
995b46e756fSKirill A. Shutemov 	 * Prevent all access to pagetables with the exception of
996b46e756fSKirill A. Shutemov 	 * gup_fast later handled by the ptep_clear_flush and the VM
997b46e756fSKirill A. Shutemov 	 * handled by the anon_vma lock + PG_lock.
998b46e756fSKirill A. Shutemov 	 */
999d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
1000c131f751SKirill A. Shutemov 	result = hugepage_vma_revalidate(mm, address, &vma);
1001*50ad2f24SZach O'Keefe 	if (result != SCAN_SUCCEED)
100218d24a7cSMiaohe Lin 		goto out_up_write;
1003b46e756fSKirill A. Shutemov 	/* check if the pmd is still valid */
1004b46e756fSKirill A. Shutemov 	if (mm_find_pmd(mm, address) != pmd)
100518d24a7cSMiaohe Lin 		goto out_up_write;
1006b46e756fSKirill A. Shutemov 
1007b46e756fSKirill A. Shutemov 	anon_vma_lock_write(vma->anon_vma);
1008b46e756fSKirill A. Shutemov 
10097269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
10106f4f13e8SJérôme Glisse 				address, address + HPAGE_PMD_SIZE);
1011ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1012ec649c9dSVille Syrjälä 
1013ec649c9dSVille Syrjälä 	pte = pte_offset_map(pmd, address);
1014ec649c9dSVille Syrjälä 	pte_ptl = pte_lockptr(mm, pmd);
1015ec649c9dSVille Syrjälä 
1016b46e756fSKirill A. Shutemov 	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1017b46e756fSKirill A. Shutemov 	/*
1018b46e756fSKirill A. Shutemov 	 * After this gup_fast can't run anymore. This also removes
1019b46e756fSKirill A. Shutemov 	 * any huge TLB entry from the CPU so we won't allow
1020b46e756fSKirill A. Shutemov 	 * huge and small TLB entries for the same virtual address
1021b46e756fSKirill A. Shutemov 	 * to avoid the risk of CPU bugs in that area.
1022b46e756fSKirill A. Shutemov 	 */
1023b46e756fSKirill A. Shutemov 	_pmd = pmdp_collapse_flush(vma, address, pmd);
1024b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1025ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
1026b46e756fSKirill A. Shutemov 
1027b46e756fSKirill A. Shutemov 	spin_lock(pte_ptl);
1028*50ad2f24SZach O'Keefe 	result =  __collapse_huge_page_isolate(vma, address, pte,
10295503fbf2SKirill A. Shutemov 					       &compound_pagelist);
1030b46e756fSKirill A. Shutemov 	spin_unlock(pte_ptl);
1031b46e756fSKirill A. Shutemov 
1032*50ad2f24SZach O'Keefe 	if (unlikely(result != SCAN_SUCCEED)) {
1033b46e756fSKirill A. Shutemov 		pte_unmap(pte);
1034b46e756fSKirill A. Shutemov 		spin_lock(pmd_ptl);
1035b46e756fSKirill A. Shutemov 		BUG_ON(!pmd_none(*pmd));
1036b46e756fSKirill A. Shutemov 		/*
1037b46e756fSKirill A. Shutemov 		 * We can only use set_pmd_at when establishing
1038b46e756fSKirill A. Shutemov 		 * hugepmds and never for establishing regular pmds that
1039b46e756fSKirill A. Shutemov 		 * points to regular pagetables. Use pmd_populate for that
1040b46e756fSKirill A. Shutemov 		 */
1041b46e756fSKirill A. Shutemov 		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1042b46e756fSKirill A. Shutemov 		spin_unlock(pmd_ptl);
1043b46e756fSKirill A. Shutemov 		anon_vma_unlock_write(vma->anon_vma);
104418d24a7cSMiaohe Lin 		goto out_up_write;
1045b46e756fSKirill A. Shutemov 	}
1046b46e756fSKirill A. Shutemov 
1047b46e756fSKirill A. Shutemov 	/*
1048b46e756fSKirill A. Shutemov 	 * All pages are isolated and locked so anon_vma rmap
1049b46e756fSKirill A. Shutemov 	 * can't run anymore.
1050b46e756fSKirill A. Shutemov 	 */
1051b46e756fSKirill A. Shutemov 	anon_vma_unlock_write(vma->anon_vma);
1052b46e756fSKirill A. Shutemov 
1053*50ad2f24SZach O'Keefe 	__collapse_huge_page_copy(pte, hpage, vma, address, pte_ptl,
10545503fbf2SKirill A. Shutemov 				  &compound_pagelist);
1055b46e756fSKirill A. Shutemov 	pte_unmap(pte);
1056588d01f9SMiaohe Lin 	/*
1057588d01f9SMiaohe Lin 	 * spin_lock() below is not the equivalent of smp_wmb(), but
1058588d01f9SMiaohe Lin 	 * the smp_wmb() inside __SetPageUptodate() can be reused to
1059588d01f9SMiaohe Lin 	 * avoid the copy_huge_page writes to become visible after
1060588d01f9SMiaohe Lin 	 * the set_pmd_at() write.
1061588d01f9SMiaohe Lin 	 */
1062*50ad2f24SZach O'Keefe 	__SetPageUptodate(hpage);
1063b46e756fSKirill A. Shutemov 	pgtable = pmd_pgtable(_pmd);
1064b46e756fSKirill A. Shutemov 
1065*50ad2f24SZach O'Keefe 	_pmd = mk_huge_pmd(hpage, vma->vm_page_prot);
1066f55e1014SLinus Torvalds 	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1067b46e756fSKirill A. Shutemov 
1068b46e756fSKirill A. Shutemov 	spin_lock(pmd_ptl);
1069b46e756fSKirill A. Shutemov 	BUG_ON(!pmd_none(*pmd));
1070*50ad2f24SZach O'Keefe 	page_add_new_anon_rmap(hpage, vma, address);
1071*50ad2f24SZach O'Keefe 	lru_cache_add_inactive_or_unevictable(hpage, vma);
1072b46e756fSKirill A. Shutemov 	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1073b46e756fSKirill A. Shutemov 	set_pmd_at(mm, address, pmd, _pmd);
1074b46e756fSKirill A. Shutemov 	update_mmu_cache_pmd(vma, address, pmd);
1075b46e756fSKirill A. Shutemov 	spin_unlock(pmd_ptl);
1076b46e756fSKirill A. Shutemov 
1077*50ad2f24SZach O'Keefe 	hpage = NULL;
1078b46e756fSKirill A. Shutemov 
1079b46e756fSKirill A. Shutemov 	result = SCAN_SUCCEED;
1080b46e756fSKirill A. Shutemov out_up_write:
1081d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1082b46e756fSKirill A. Shutemov out_nolock:
1083*50ad2f24SZach O'Keefe 	if (hpage) {
1084*50ad2f24SZach O'Keefe 		mem_cgroup_uncharge(page_folio(hpage));
1085*50ad2f24SZach O'Keefe 		put_page(hpage);
1086c6a7f445SYang Shi 	}
1087*50ad2f24SZach O'Keefe 	trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1088*50ad2f24SZach O'Keefe 	return result;
1089b46e756fSKirill A. Shutemov }
1090b46e756fSKirill A. Shutemov 
109134d6b470SZach O'Keefe static int khugepaged_scan_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1092*50ad2f24SZach O'Keefe 			       unsigned long address, bool *mmap_locked,
109334d6b470SZach O'Keefe 			       struct collapse_control *cc)
1094b46e756fSKirill A. Shutemov {
1095b46e756fSKirill A. Shutemov 	pmd_t *pmd;
1096b46e756fSKirill A. Shutemov 	pte_t *pte, *_pte;
1097*50ad2f24SZach O'Keefe 	int result = SCAN_FAIL, referenced = 0;
109871a2c112SKirill A. Shutemov 	int none_or_zero = 0, shared = 0;
1099b46e756fSKirill A. Shutemov 	struct page *page = NULL;
1100b46e756fSKirill A. Shutemov 	unsigned long _address;
1101b46e756fSKirill A. Shutemov 	spinlock_t *ptl;
1102b46e756fSKirill A. Shutemov 	int node = NUMA_NO_NODE, unmapped = 0;
11030db501f7SEbru Akagunduz 	bool writable = false;
1104b46e756fSKirill A. Shutemov 
1105b46e756fSKirill A. Shutemov 	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1106b46e756fSKirill A. Shutemov 
1107b46e756fSKirill A. Shutemov 	pmd = mm_find_pmd(mm, address);
1108b46e756fSKirill A. Shutemov 	if (!pmd) {
1109b46e756fSKirill A. Shutemov 		result = SCAN_PMD_NULL;
1110b46e756fSKirill A. Shutemov 		goto out;
1111b46e756fSKirill A. Shutemov 	}
1112b46e756fSKirill A. Shutemov 
111334d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1114b46e756fSKirill A. Shutemov 	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1115b46e756fSKirill A. Shutemov 	for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
1116b46e756fSKirill A. Shutemov 	     _pte++, _address += PAGE_SIZE) {
1117b46e756fSKirill A. Shutemov 		pte_t pteval = *_pte;
1118b46e756fSKirill A. Shutemov 		if (is_swap_pte(pteval)) {
1119b46e756fSKirill A. Shutemov 			if (++unmapped <= khugepaged_max_ptes_swap) {
1120e1e267c7SPeter Xu 				/*
1121e1e267c7SPeter Xu 				 * Always be strict with uffd-wp
1122e1e267c7SPeter Xu 				 * enabled swap entries.  Please see
1123e1e267c7SPeter Xu 				 * comment below for pte_uffd_wp().
1124e1e267c7SPeter Xu 				 */
1125e1e267c7SPeter Xu 				if (pte_swp_uffd_wp(pteval)) {
1126e1e267c7SPeter Xu 					result = SCAN_PTE_UFFD_WP;
1127e1e267c7SPeter Xu 					goto out_unmap;
1128e1e267c7SPeter Xu 				}
1129b46e756fSKirill A. Shutemov 				continue;
1130b46e756fSKirill A. Shutemov 			} else {
1131b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1132e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1133b46e756fSKirill A. Shutemov 				goto out_unmap;
1134b46e756fSKirill A. Shutemov 			}
1135b46e756fSKirill A. Shutemov 		}
1136b46e756fSKirill A. Shutemov 		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1137b46e756fSKirill A. Shutemov 			if (!userfaultfd_armed(vma) &&
1138b46e756fSKirill A. Shutemov 			    ++none_or_zero <= khugepaged_max_ptes_none) {
1139b46e756fSKirill A. Shutemov 				continue;
1140b46e756fSKirill A. Shutemov 			} else {
1141b46e756fSKirill A. Shutemov 				result = SCAN_EXCEED_NONE_PTE;
1142e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1143b46e756fSKirill A. Shutemov 				goto out_unmap;
1144b46e756fSKirill A. Shutemov 			}
1145b46e756fSKirill A. Shutemov 		}
1146e1e267c7SPeter Xu 		if (pte_uffd_wp(pteval)) {
1147e1e267c7SPeter Xu 			/*
1148e1e267c7SPeter Xu 			 * Don't collapse the page if any of the small
1149e1e267c7SPeter Xu 			 * PTEs are armed with uffd write protection.
1150e1e267c7SPeter Xu 			 * Here we can also mark the new huge pmd as
1151e1e267c7SPeter Xu 			 * write protected if any of the small ones is
11528958b249SHaitao Shi 			 * marked but that could bring unknown
1153e1e267c7SPeter Xu 			 * userfault messages that falls outside of
1154e1e267c7SPeter Xu 			 * the registered range.  So, just be simple.
1155e1e267c7SPeter Xu 			 */
1156e1e267c7SPeter Xu 			result = SCAN_PTE_UFFD_WP;
1157e1e267c7SPeter Xu 			goto out_unmap;
1158e1e267c7SPeter Xu 		}
1159b46e756fSKirill A. Shutemov 		if (pte_write(pteval))
1160b46e756fSKirill A. Shutemov 			writable = true;
1161b46e756fSKirill A. Shutemov 
1162b46e756fSKirill A. Shutemov 		page = vm_normal_page(vma, _address, pteval);
11633218f871SAlex Sierra 		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1164b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_NULL;
1165b46e756fSKirill A. Shutemov 			goto out_unmap;
1166b46e756fSKirill A. Shutemov 		}
1167b46e756fSKirill A. Shutemov 
116871a2c112SKirill A. Shutemov 		if (page_mapcount(page) > 1 &&
116971a2c112SKirill A. Shutemov 				++shared > khugepaged_max_ptes_shared) {
117071a2c112SKirill A. Shutemov 			result = SCAN_EXCEED_SHARED_PTE;
1171e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
117271a2c112SKirill A. Shutemov 			goto out_unmap;
117371a2c112SKirill A. Shutemov 		}
117471a2c112SKirill A. Shutemov 
11755503fbf2SKirill A. Shutemov 		page = compound_head(page);
1176b46e756fSKirill A. Shutemov 
1177b46e756fSKirill A. Shutemov 		/*
1178b46e756fSKirill A. Shutemov 		 * Record which node the original page is from and save this
117934d6b470SZach O'Keefe 		 * information to cc->node_load[].
11800b8f0d87SQuanfa Fu 		 * Khugepaged will allocate hugepage from the node has the max
1181b46e756fSKirill A. Shutemov 		 * hit record.
1182b46e756fSKirill A. Shutemov 		 */
1183b46e756fSKirill A. Shutemov 		node = page_to_nid(page);
118434d6b470SZach O'Keefe 		if (khugepaged_scan_abort(node, cc)) {
1185b46e756fSKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1186b46e756fSKirill A. Shutemov 			goto out_unmap;
1187b46e756fSKirill A. Shutemov 		}
118834d6b470SZach O'Keefe 		cc->node_load[node]++;
1189b46e756fSKirill A. Shutemov 		if (!PageLRU(page)) {
1190b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1191b46e756fSKirill A. Shutemov 			goto out_unmap;
1192b46e756fSKirill A. Shutemov 		}
1193b46e756fSKirill A. Shutemov 		if (PageLocked(page)) {
1194b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_LOCK;
1195b46e756fSKirill A. Shutemov 			goto out_unmap;
1196b46e756fSKirill A. Shutemov 		}
1197b46e756fSKirill A. Shutemov 		if (!PageAnon(page)) {
1198b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_ANON;
1199b46e756fSKirill A. Shutemov 			goto out_unmap;
1200b46e756fSKirill A. Shutemov 		}
1201b46e756fSKirill A. Shutemov 
1202b46e756fSKirill A. Shutemov 		/*
12039445689fSKirill A. Shutemov 		 * Check if the page has any GUP (or other external) pins.
12049445689fSKirill A. Shutemov 		 *
120536ee2c78SMiaohe Lin 		 * Here the check is racy it may see total_mapcount > refcount
12069445689fSKirill A. Shutemov 		 * in some cases.
12079445689fSKirill A. Shutemov 		 * For example, one process with one forked child process.
12089445689fSKirill A. Shutemov 		 * The parent has the PMD split due to MADV_DONTNEED, then
12099445689fSKirill A. Shutemov 		 * the child is trying unmap the whole PMD, but khugepaged
12109445689fSKirill A. Shutemov 		 * may be scanning the parent between the child has
12119445689fSKirill A. Shutemov 		 * PageDoubleMap flag cleared and dec the mapcount.  So
12129445689fSKirill A. Shutemov 		 * khugepaged may see total_mapcount > refcount.
12139445689fSKirill A. Shutemov 		 *
12149445689fSKirill A. Shutemov 		 * But such case is ephemeral we could always retry collapse
12159445689fSKirill A. Shutemov 		 * later.  However it may report false positive if the page
12169445689fSKirill A. Shutemov 		 * has excessive GUP pins (i.e. 512).  Anyway the same check
12179445689fSKirill A. Shutemov 		 * will be done again later the risk seems low.
1218b46e756fSKirill A. Shutemov 		 */
12199445689fSKirill A. Shutemov 		if (!is_refcount_suitable(page)) {
1220b46e756fSKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1221b46e756fSKirill A. Shutemov 			goto out_unmap;
1222b46e756fSKirill A. Shutemov 		}
1223b46e756fSKirill A. Shutemov 		if (pte_young(pteval) ||
1224b46e756fSKirill A. Shutemov 		    page_is_young(page) || PageReferenced(page) ||
1225b46e756fSKirill A. Shutemov 		    mmu_notifier_test_young(vma->vm_mm, address))
12260db501f7SEbru Akagunduz 			referenced++;
1227b46e756fSKirill A. Shutemov 	}
1228ffe945e6SKirill A. Shutemov 	if (!writable) {
1229ffe945e6SKirill A. Shutemov 		result = SCAN_PAGE_RO;
1230ffe945e6SKirill A. Shutemov 	} else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
1231ffe945e6SKirill A. Shutemov 		result = SCAN_LACK_REFERENCED_PAGE;
1232ffe945e6SKirill A. Shutemov 	} else {
1233b46e756fSKirill A. Shutemov 		result = SCAN_SUCCEED;
1234b46e756fSKirill A. Shutemov 	}
1235b46e756fSKirill A. Shutemov out_unmap:
1236b46e756fSKirill A. Shutemov 	pte_unmap_unlock(pte, ptl);
1237*50ad2f24SZach O'Keefe 	if (result == SCAN_SUCCEED) {
1238*50ad2f24SZach O'Keefe 		result = collapse_huge_page(mm, address, referenced,
1239*50ad2f24SZach O'Keefe 					    unmapped, cc);
1240c1e8d7c6SMichel Lespinasse 		/* collapse_huge_page will return with the mmap_lock released */
1241*50ad2f24SZach O'Keefe 		*mmap_locked = false;
1242b46e756fSKirill A. Shutemov 	}
1243b46e756fSKirill A. Shutemov out:
1244b46e756fSKirill A. Shutemov 	trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1245b46e756fSKirill A. Shutemov 				     none_or_zero, result, unmapped);
1246*50ad2f24SZach O'Keefe 	return result;
1247b46e756fSKirill A. Shutemov }
1248b46e756fSKirill A. Shutemov 
1249b46e756fSKirill A. Shutemov static void collect_mm_slot(struct mm_slot *mm_slot)
1250b46e756fSKirill A. Shutemov {
1251b46e756fSKirill A. Shutemov 	struct mm_struct *mm = mm_slot->mm;
1252b46e756fSKirill A. Shutemov 
125335f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1254b46e756fSKirill A. Shutemov 
1255b46e756fSKirill A. Shutemov 	if (khugepaged_test_exit(mm)) {
1256b46e756fSKirill A. Shutemov 		/* free mm_slot */
1257b46e756fSKirill A. Shutemov 		hash_del(&mm_slot->hash);
1258b46e756fSKirill A. Shutemov 		list_del(&mm_slot->mm_node);
1259b46e756fSKirill A. Shutemov 
1260b46e756fSKirill A. Shutemov 		/*
1261b46e756fSKirill A. Shutemov 		 * Not strictly needed because the mm exited already.
1262b46e756fSKirill A. Shutemov 		 *
1263b46e756fSKirill A. Shutemov 		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1264b46e756fSKirill A. Shutemov 		 */
1265b46e756fSKirill A. Shutemov 
1266b46e756fSKirill A. Shutemov 		/* khugepaged_mm_lock actually not necessary for the below */
1267b46e756fSKirill A. Shutemov 		free_mm_slot(mm_slot);
1268b46e756fSKirill A. Shutemov 		mmdrop(mm);
1269b46e756fSKirill A. Shutemov 	}
1270b46e756fSKirill A. Shutemov }
1271b46e756fSKirill A. Shutemov 
1272396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_SHMEM
127327e1f827SSong Liu /*
127427e1f827SSong Liu  * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
127527e1f827SSong Liu  * khugepaged should try to collapse the page table.
127627e1f827SSong Liu  */
1277081c3256SMiaohe Lin static void khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
127827e1f827SSong Liu 					  unsigned long addr)
127927e1f827SSong Liu {
128027e1f827SSong Liu 	struct mm_slot *mm_slot;
128127e1f827SSong Liu 
128227e1f827SSong Liu 	VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
128327e1f827SSong Liu 
128427e1f827SSong Liu 	spin_lock(&khugepaged_mm_lock);
128527e1f827SSong Liu 	mm_slot = get_mm_slot(mm);
128627e1f827SSong Liu 	if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
128727e1f827SSong Liu 		mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
128827e1f827SSong Liu 	spin_unlock(&khugepaged_mm_lock);
128927e1f827SSong Liu }
129027e1f827SSong Liu 
1291e59a47b8SPasha Tatashin static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
1292e59a47b8SPasha Tatashin 				  unsigned long addr, pmd_t *pmdp)
1293e59a47b8SPasha Tatashin {
1294e59a47b8SPasha Tatashin 	spinlock_t *ptl;
1295e59a47b8SPasha Tatashin 	pmd_t pmd;
1296e59a47b8SPasha Tatashin 
129780110bbfSPasha Tatashin 	mmap_assert_write_locked(mm);
1298e59a47b8SPasha Tatashin 	ptl = pmd_lock(vma->vm_mm, pmdp);
1299e59a47b8SPasha Tatashin 	pmd = pmdp_collapse_flush(vma, addr, pmdp);
1300e59a47b8SPasha Tatashin 	spin_unlock(ptl);
1301e59a47b8SPasha Tatashin 	mm_dec_nr_ptes(mm);
130280110bbfSPasha Tatashin 	page_table_check_pte_clear_range(mm, addr, pmd);
1303e59a47b8SPasha Tatashin 	pte_free(mm, pmd_pgtable(pmd));
1304e59a47b8SPasha Tatashin }
1305e59a47b8SPasha Tatashin 
130627e1f827SSong Liu /**
1307336e6b53SAlex Shi  * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1308336e6b53SAlex Shi  * address haddr.
1309336e6b53SAlex Shi  *
1310336e6b53SAlex Shi  * @mm: process address space where collapse happens
1311336e6b53SAlex Shi  * @addr: THP collapse address
131227e1f827SSong Liu  *
131327e1f827SSong Liu  * This function checks whether all the PTEs in the PMD are pointing to the
131427e1f827SSong Liu  * right THP. If so, retract the page table so the THP can refault in with
131527e1f827SSong Liu  * as pmd-mapped.
131627e1f827SSong Liu  */
131727e1f827SSong Liu void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
131827e1f827SSong Liu {
131927e1f827SSong Liu 	unsigned long haddr = addr & HPAGE_PMD_MASK;
132027e1f827SSong Liu 	struct vm_area_struct *vma = find_vma(mm, haddr);
1321119a5fc1SHugh Dickins 	struct page *hpage;
132227e1f827SSong Liu 	pte_t *start_pte, *pte;
1323e59a47b8SPasha Tatashin 	pmd_t *pmd;
132427e1f827SSong Liu 	spinlock_t *ptl;
132527e1f827SSong Liu 	int count = 0;
132627e1f827SSong Liu 	int i;
132727e1f827SSong Liu 
132827e1f827SSong Liu 	if (!vma || !vma->vm_file ||
1329fef792a4SMiaohe Lin 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
133027e1f827SSong Liu 		return;
133127e1f827SSong Liu 
133227e1f827SSong Liu 	/*
133327e1f827SSong Liu 	 * This vm_flags may not have VM_HUGEPAGE if the page was not
133427e1f827SSong Liu 	 * collapsed by this mm. But we can still collapse if the page is
133527e1f827SSong Liu 	 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
133627e1f827SSong Liu 	 * will not fail the vma for missing VM_HUGEPAGE
133727e1f827SSong Liu 	 */
13387da4e2cbSYang Shi 	if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE, false, false))
133927e1f827SSong Liu 		return;
134027e1f827SSong Liu 
1341deb4c93aSPeter Xu 	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1342deb4c93aSPeter Xu 	if (userfaultfd_wp(vma))
1343deb4c93aSPeter Xu 		return;
1344deb4c93aSPeter Xu 
1345119a5fc1SHugh Dickins 	hpage = find_lock_page(vma->vm_file->f_mapping,
1346119a5fc1SHugh Dickins 			       linear_page_index(vma, haddr));
1347119a5fc1SHugh Dickins 	if (!hpage)
1348119a5fc1SHugh Dickins 		return;
1349119a5fc1SHugh Dickins 
1350119a5fc1SHugh Dickins 	if (!PageHead(hpage))
1351119a5fc1SHugh Dickins 		goto drop_hpage;
1352119a5fc1SHugh Dickins 
135327e1f827SSong Liu 	pmd = mm_find_pmd(mm, haddr);
135427e1f827SSong Liu 	if (!pmd)
1355119a5fc1SHugh Dickins 		goto drop_hpage;
135627e1f827SSong Liu 
135727e1f827SSong Liu 	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
135827e1f827SSong Liu 
135927e1f827SSong Liu 	/* step 1: check all mapped PTEs are to the right huge page */
136027e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
136127e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
136227e1f827SSong Liu 		struct page *page;
136327e1f827SSong Liu 
136427e1f827SSong Liu 		/* empty pte, skip */
136527e1f827SSong Liu 		if (pte_none(*pte))
136627e1f827SSong Liu 			continue;
136727e1f827SSong Liu 
136827e1f827SSong Liu 		/* page swapped out, abort */
136927e1f827SSong Liu 		if (!pte_present(*pte))
137027e1f827SSong Liu 			goto abort;
137127e1f827SSong Liu 
137227e1f827SSong Liu 		page = vm_normal_page(vma, addr, *pte);
13733218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
13743218f871SAlex Sierra 			page = NULL;
137527e1f827SSong Liu 		/*
1376119a5fc1SHugh Dickins 		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1377119a5fc1SHugh Dickins 		 * page table, but the new page will not be a subpage of hpage.
137827e1f827SSong Liu 		 */
1379119a5fc1SHugh Dickins 		if (hpage + i != page)
138027e1f827SSong Liu 			goto abort;
138127e1f827SSong Liu 		count++;
138227e1f827SSong Liu 	}
138327e1f827SSong Liu 
138427e1f827SSong Liu 	/* step 2: adjust rmap */
138527e1f827SSong Liu 	for (i = 0, addr = haddr, pte = start_pte;
138627e1f827SSong Liu 	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
138727e1f827SSong Liu 		struct page *page;
138827e1f827SSong Liu 
138927e1f827SSong Liu 		if (pte_none(*pte))
139027e1f827SSong Liu 			continue;
139127e1f827SSong Liu 		page = vm_normal_page(vma, addr, *pte);
13923218f871SAlex Sierra 		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
13933218f871SAlex Sierra 			goto abort;
1394cea86fe2SHugh Dickins 		page_remove_rmap(page, vma, false);
139527e1f827SSong Liu 	}
139627e1f827SSong Liu 
139727e1f827SSong Liu 	pte_unmap_unlock(start_pte, ptl);
139827e1f827SSong Liu 
139927e1f827SSong Liu 	/* step 3: set proper refcount and mm_counters. */
1400119a5fc1SHugh Dickins 	if (count) {
140127e1f827SSong Liu 		page_ref_sub(hpage, count);
140227e1f827SSong Liu 		add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
140327e1f827SSong Liu 	}
140427e1f827SSong Liu 
140527e1f827SSong Liu 	/* step 4: collapse pmd */
1406e59a47b8SPasha Tatashin 	collapse_and_free_pmd(mm, vma, haddr, pmd);
1407119a5fc1SHugh Dickins drop_hpage:
1408119a5fc1SHugh Dickins 	unlock_page(hpage);
1409119a5fc1SHugh Dickins 	put_page(hpage);
141027e1f827SSong Liu 	return;
141127e1f827SSong Liu 
141227e1f827SSong Liu abort:
141327e1f827SSong Liu 	pte_unmap_unlock(start_pte, ptl);
1414119a5fc1SHugh Dickins 	goto drop_hpage;
141527e1f827SSong Liu }
141627e1f827SSong Liu 
14170edf61e5SMiaohe Lin static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
141827e1f827SSong Liu {
141927e1f827SSong Liu 	struct mm_struct *mm = mm_slot->mm;
142027e1f827SSong Liu 	int i;
142127e1f827SSong Liu 
142227e1f827SSong Liu 	if (likely(mm_slot->nr_pte_mapped_thp == 0))
14230edf61e5SMiaohe Lin 		return;
142427e1f827SSong Liu 
1425d8ed45c5SMichel Lespinasse 	if (!mmap_write_trylock(mm))
14260edf61e5SMiaohe Lin 		return;
142727e1f827SSong Liu 
142827e1f827SSong Liu 	if (unlikely(khugepaged_test_exit(mm)))
142927e1f827SSong Liu 		goto out;
143027e1f827SSong Liu 
143127e1f827SSong Liu 	for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
143227e1f827SSong Liu 		collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
143327e1f827SSong Liu 
143427e1f827SSong Liu out:
143527e1f827SSong Liu 	mm_slot->nr_pte_mapped_thp = 0;
1436d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
143727e1f827SSong Liu }
143827e1f827SSong Liu 
1439f3f0e1d2SKirill A. Shutemov static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1440f3f0e1d2SKirill A. Shutemov {
1441f3f0e1d2SKirill A. Shutemov 	struct vm_area_struct *vma;
144218e77600SHugh Dickins 	struct mm_struct *mm;
1443f3f0e1d2SKirill A. Shutemov 	unsigned long addr;
1444e59a47b8SPasha Tatashin 	pmd_t *pmd;
1445f3f0e1d2SKirill A. Shutemov 
1446f3f0e1d2SKirill A. Shutemov 	i_mmap_lock_write(mapping);
1447f3f0e1d2SKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
144827e1f827SSong Liu 		/*
144927e1f827SSong Liu 		 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
145027e1f827SSong Liu 		 * got written to. These VMAs are likely not worth investing
14513e4e28c5SMichel Lespinasse 		 * mmap_write_lock(mm) as PMD-mapping is likely to be split
145227e1f827SSong Liu 		 * later.
145327e1f827SSong Liu 		 *
145436ee2c78SMiaohe Lin 		 * Note that vma->anon_vma check is racy: it can be set up after
1455c1e8d7c6SMichel Lespinasse 		 * the check but before we took mmap_lock by the fault path.
145627e1f827SSong Liu 		 * But page lock would prevent establishing any new ptes of the
145727e1f827SSong Liu 		 * page, so we are safe.
145827e1f827SSong Liu 		 *
145927e1f827SSong Liu 		 * An alternative would be drop the check, but check that page
146027e1f827SSong Liu 		 * table is clear before calling pmdp_collapse_flush() under
146127e1f827SSong Liu 		 * ptl. It has higher chance to recover THP for the VMA, but
146227e1f827SSong Liu 		 * has higher cost too.
146327e1f827SSong Liu 		 */
1464f3f0e1d2SKirill A. Shutemov 		if (vma->anon_vma)
1465f3f0e1d2SKirill A. Shutemov 			continue;
1466f3f0e1d2SKirill A. Shutemov 		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1467f3f0e1d2SKirill A. Shutemov 		if (addr & ~HPAGE_PMD_MASK)
1468f3f0e1d2SKirill A. Shutemov 			continue;
1469f3f0e1d2SKirill A. Shutemov 		if (vma->vm_end < addr + HPAGE_PMD_SIZE)
1470f3f0e1d2SKirill A. Shutemov 			continue;
147118e77600SHugh Dickins 		mm = vma->vm_mm;
147218e77600SHugh Dickins 		pmd = mm_find_pmd(mm, addr);
1473f3f0e1d2SKirill A. Shutemov 		if (!pmd)
1474f3f0e1d2SKirill A. Shutemov 			continue;
1475f3f0e1d2SKirill A. Shutemov 		/*
1476c1e8d7c6SMichel Lespinasse 		 * We need exclusive mmap_lock to retract page table.
147727e1f827SSong Liu 		 *
147827e1f827SSong Liu 		 * We use trylock due to lock inversion: we need to acquire
1479c1e8d7c6SMichel Lespinasse 		 * mmap_lock while holding page lock. Fault path does it in
148027e1f827SSong Liu 		 * reverse order. Trylock is a way to avoid deadlock.
1481f3f0e1d2SKirill A. Shutemov 		 */
148218e77600SHugh Dickins 		if (mmap_write_trylock(mm)) {
1483deb4c93aSPeter Xu 			/*
1484deb4c93aSPeter Xu 			 * When a vma is registered with uffd-wp, we can't
1485deb4c93aSPeter Xu 			 * recycle the pmd pgtable because there can be pte
1486deb4c93aSPeter Xu 			 * markers installed.  Skip it only, so the rest mm/vma
1487deb4c93aSPeter Xu 			 * can still have the same file mapped hugely, however
1488deb4c93aSPeter Xu 			 * it'll always mapped in small page size for uffd-wp
1489deb4c93aSPeter Xu 			 * registered ranges.
1490deb4c93aSPeter Xu 			 */
1491deb4c93aSPeter Xu 			if (!khugepaged_test_exit(mm) && !userfaultfd_wp(vma))
1492e59a47b8SPasha Tatashin 				collapse_and_free_pmd(mm, vma, addr, pmd);
149318e77600SHugh Dickins 			mmap_write_unlock(mm);
149427e1f827SSong Liu 		} else {
149527e1f827SSong Liu 			/* Try again later */
149618e77600SHugh Dickins 			khugepaged_add_pte_mapped_thp(mm, addr);
1497f3f0e1d2SKirill A. Shutemov 		}
1498f3f0e1d2SKirill A. Shutemov 	}
1499f3f0e1d2SKirill A. Shutemov 	i_mmap_unlock_write(mapping);
1500f3f0e1d2SKirill A. Shutemov }
1501f3f0e1d2SKirill A. Shutemov 
1502f3f0e1d2SKirill A. Shutemov /**
150399cb0dbdSSong Liu  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1504f3f0e1d2SKirill A. Shutemov  *
1505336e6b53SAlex Shi  * @mm: process address space where collapse happens
1506336e6b53SAlex Shi  * @file: file that collapse on
1507336e6b53SAlex Shi  * @start: collapse start address
15089710a78aSZach O'Keefe  * @cc: collapse context and scratchpad
1509336e6b53SAlex Shi  *
1510f3f0e1d2SKirill A. Shutemov  * Basic scheme is simple, details are more complex:
151187c460a0SHugh Dickins  *  - allocate and lock a new huge page;
151277da9389SMatthew Wilcox  *  - scan page cache replacing old pages with the new one
151399cb0dbdSSong Liu  *    + swap/gup in pages if necessary;
1514f3f0e1d2SKirill A. Shutemov  *    + fill in gaps;
151577da9389SMatthew Wilcox  *    + keep old pages around in case rollback is required;
151677da9389SMatthew Wilcox  *  - if replacing succeeds:
1517f3f0e1d2SKirill A. Shutemov  *    + copy data over;
1518f3f0e1d2SKirill A. Shutemov  *    + free old pages;
151987c460a0SHugh Dickins  *    + unlock huge page;
1520f3f0e1d2SKirill A. Shutemov  *  - if replacing failed;
1521f3f0e1d2SKirill A. Shutemov  *    + put all pages back and unfreeze them;
152277da9389SMatthew Wilcox  *    + restore gaps in the page cache;
152387c460a0SHugh Dickins  *    + unlock and free huge page;
1524f3f0e1d2SKirill A. Shutemov  */
1525*50ad2f24SZach O'Keefe static int collapse_file(struct mm_struct *mm, struct file *file,
1526*50ad2f24SZach O'Keefe 			 pgoff_t start, struct collapse_control *cc)
1527f3f0e1d2SKirill A. Shutemov {
1528579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
1529*50ad2f24SZach O'Keefe 	struct page *hpage;
1530f3f0e1d2SKirill A. Shutemov 	pgoff_t index, end = start + HPAGE_PMD_NR;
1531f3f0e1d2SKirill A. Shutemov 	LIST_HEAD(pagelist);
153277da9389SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
1533f3f0e1d2SKirill A. Shutemov 	int nr_none = 0, result = SCAN_SUCCEED;
153499cb0dbdSSong Liu 	bool is_shmem = shmem_file(file);
1535bf9eceadSMuchun Song 	int nr;
1536f3f0e1d2SKirill A. Shutemov 
153799cb0dbdSSong Liu 	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1538f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1539f3f0e1d2SKirill A. Shutemov 
1540*50ad2f24SZach O'Keefe 	result = alloc_charge_hpage(&hpage, mm, cc);
15419710a78aSZach O'Keefe 	if (result != SCAN_SUCCEED)
1542f3f0e1d2SKirill A. Shutemov 		goto out;
1543f3f0e1d2SKirill A. Shutemov 
15446b24ca4aSMatthew Wilcox (Oracle) 	/*
15456b24ca4aSMatthew Wilcox (Oracle) 	 * Ensure we have slots for all the pages in the range.  This is
15466b24ca4aSMatthew Wilcox (Oracle) 	 * almost certainly a no-op because most of the pages must be present
15476b24ca4aSMatthew Wilcox (Oracle) 	 */
154895feeabbSHugh Dickins 	do {
154995feeabbSHugh Dickins 		xas_lock_irq(&xas);
155095feeabbSHugh Dickins 		xas_create_range(&xas);
155195feeabbSHugh Dickins 		if (!xas_error(&xas))
155295feeabbSHugh Dickins 			break;
155395feeabbSHugh Dickins 		xas_unlock_irq(&xas);
155495feeabbSHugh Dickins 		if (!xas_nomem(&xas, GFP_KERNEL)) {
155595feeabbSHugh Dickins 			result = SCAN_FAIL;
155695feeabbSHugh Dickins 			goto out;
155795feeabbSHugh Dickins 		}
155895feeabbSHugh Dickins 	} while (1);
155995feeabbSHugh Dickins 
1560*50ad2f24SZach O'Keefe 	__SetPageLocked(hpage);
156199cb0dbdSSong Liu 	if (is_shmem)
1562*50ad2f24SZach O'Keefe 		__SetPageSwapBacked(hpage);
1563*50ad2f24SZach O'Keefe 	hpage->index = start;
1564*50ad2f24SZach O'Keefe 	hpage->mapping = mapping;
1565f3f0e1d2SKirill A. Shutemov 
1566f3f0e1d2SKirill A. Shutemov 	/*
1567*50ad2f24SZach O'Keefe 	 * At this point the hpage is locked and not up-to-date.
156887c460a0SHugh Dickins 	 * It's safe to insert it into the page cache, because nobody would
156987c460a0SHugh Dickins 	 * be able to map it or use it in another way until we unlock it.
1570f3f0e1d2SKirill A. Shutemov 	 */
1571f3f0e1d2SKirill A. Shutemov 
157277da9389SMatthew Wilcox 	xas_set(&xas, start);
157377da9389SMatthew Wilcox 	for (index = start; index < end; index++) {
157477da9389SMatthew Wilcox 		struct page *page = xas_next(&xas);
157577da9389SMatthew Wilcox 
157677da9389SMatthew Wilcox 		VM_BUG_ON(index != xas.xa_index);
157799cb0dbdSSong Liu 		if (is_shmem) {
157877da9389SMatthew Wilcox 			if (!page) {
1579701270faSHugh Dickins 				/*
158099cb0dbdSSong Liu 				 * Stop if extent has been truncated or
158199cb0dbdSSong Liu 				 * hole-punched, and is now completely
158299cb0dbdSSong Liu 				 * empty.
1583701270faSHugh Dickins 				 */
1584701270faSHugh Dickins 				if (index == start) {
1585701270faSHugh Dickins 					if (!xas_next_entry(&xas, end - 1)) {
1586701270faSHugh Dickins 						result = SCAN_TRUNCATED;
1587042a3082SHugh Dickins 						goto xa_locked;
1588701270faSHugh Dickins 					}
1589701270faSHugh Dickins 					xas_set(&xas, index);
1590701270faSHugh Dickins 				}
159177da9389SMatthew Wilcox 				if (!shmem_charge(mapping->host, 1)) {
1592f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
1593042a3082SHugh Dickins 					goto xa_locked;
1594f3f0e1d2SKirill A. Shutemov 				}
1595*50ad2f24SZach O'Keefe 				xas_store(&xas, hpage);
159677da9389SMatthew Wilcox 				nr_none++;
159777da9389SMatthew Wilcox 				continue;
1598f3f0e1d2SKirill A. Shutemov 			}
1599f3f0e1d2SKirill A. Shutemov 
16003159f943SMatthew Wilcox 			if (xa_is_value(page) || !PageUptodate(page)) {
160177da9389SMatthew Wilcox 				xas_unlock_irq(&xas);
1602f3f0e1d2SKirill A. Shutemov 				/* swap in or instantiate fallocated page */
1603f3f0e1d2SKirill A. Shutemov 				if (shmem_getpage(mapping->host, index, &page,
1604acdd9f8eSHugh Dickins 						  SGP_NOALLOC)) {
1605f3f0e1d2SKirill A. Shutemov 					result = SCAN_FAIL;
160677da9389SMatthew Wilcox 					goto xa_unlocked;
1607f3f0e1d2SKirill A. Shutemov 				}
1608f3f0e1d2SKirill A. Shutemov 			} else if (trylock_page(page)) {
1609f3f0e1d2SKirill A. Shutemov 				get_page(page);
1610042a3082SHugh Dickins 				xas_unlock_irq(&xas);
1611f3f0e1d2SKirill A. Shutemov 			} else {
1612f3f0e1d2SKirill A. Shutemov 				result = SCAN_PAGE_LOCK;
1613042a3082SHugh Dickins 				goto xa_locked;
1614f3f0e1d2SKirill A. Shutemov 			}
161599cb0dbdSSong Liu 		} else {	/* !is_shmem */
161699cb0dbdSSong Liu 			if (!page || xa_is_value(page)) {
161799cb0dbdSSong Liu 				xas_unlock_irq(&xas);
161899cb0dbdSSong Liu 				page_cache_sync_readahead(mapping, &file->f_ra,
161999cb0dbdSSong Liu 							  file, index,
1620e5a59d30SDavid Howells 							  end - index);
162199cb0dbdSSong Liu 				/* drain pagevecs to help isolate_lru_page() */
162299cb0dbdSSong Liu 				lru_add_drain();
162399cb0dbdSSong Liu 				page = find_lock_page(mapping, index);
162499cb0dbdSSong Liu 				if (unlikely(page == NULL)) {
162599cb0dbdSSong Liu 					result = SCAN_FAIL;
162699cb0dbdSSong Liu 					goto xa_unlocked;
162799cb0dbdSSong Liu 				}
162875f36069SSong Liu 			} else if (PageDirty(page)) {
162975f36069SSong Liu 				/*
163075f36069SSong Liu 				 * khugepaged only works on read-only fd,
163175f36069SSong Liu 				 * so this page is dirty because it hasn't
163275f36069SSong Liu 				 * been flushed since first write. There
163375f36069SSong Liu 				 * won't be new dirty pages.
163475f36069SSong Liu 				 *
163575f36069SSong Liu 				 * Trigger async flush here and hope the
163675f36069SSong Liu 				 * writeback is done when khugepaged
163775f36069SSong Liu 				 * revisits this page.
163875f36069SSong Liu 				 *
163975f36069SSong Liu 				 * This is a one-off situation. We are not
164075f36069SSong Liu 				 * forcing writeback in loop.
164175f36069SSong Liu 				 */
164275f36069SSong Liu 				xas_unlock_irq(&xas);
164375f36069SSong Liu 				filemap_flush(mapping);
164475f36069SSong Liu 				result = SCAN_FAIL;
164575f36069SSong Liu 				goto xa_unlocked;
164674c42e1bSRongwei Wang 			} else if (PageWriteback(page)) {
164774c42e1bSRongwei Wang 				xas_unlock_irq(&xas);
164874c42e1bSRongwei Wang 				result = SCAN_FAIL;
164974c42e1bSRongwei Wang 				goto xa_unlocked;
165099cb0dbdSSong Liu 			} else if (trylock_page(page)) {
165199cb0dbdSSong Liu 				get_page(page);
165299cb0dbdSSong Liu 				xas_unlock_irq(&xas);
165399cb0dbdSSong Liu 			} else {
165499cb0dbdSSong Liu 				result = SCAN_PAGE_LOCK;
165599cb0dbdSSong Liu 				goto xa_locked;
165699cb0dbdSSong Liu 			}
165799cb0dbdSSong Liu 		}
1658f3f0e1d2SKirill A. Shutemov 
1659f3f0e1d2SKirill A. Shutemov 		/*
1660b93b0163SMatthew Wilcox 		 * The page must be locked, so we can drop the i_pages lock
1661f3f0e1d2SKirill A. Shutemov 		 * without racing with truncate.
1662f3f0e1d2SKirill A. Shutemov 		 */
1663f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
16644655e5e5SSong Liu 
16654655e5e5SSong Liu 		/* make sure the page is up to date */
16664655e5e5SSong Liu 		if (unlikely(!PageUptodate(page))) {
16674655e5e5SSong Liu 			result = SCAN_FAIL;
16684655e5e5SSong Liu 			goto out_unlock;
16694655e5e5SSong Liu 		}
167006a5e126SHugh Dickins 
167106a5e126SHugh Dickins 		/*
167206a5e126SHugh Dickins 		 * If file was truncated then extended, or hole-punched, before
167306a5e126SHugh Dickins 		 * we locked the first page, then a THP might be there already.
167406a5e126SHugh Dickins 		 */
167506a5e126SHugh Dickins 		if (PageTransCompound(page)) {
167606a5e126SHugh Dickins 			result = SCAN_PAGE_COMPOUND;
167706a5e126SHugh Dickins 			goto out_unlock;
167806a5e126SHugh Dickins 		}
1679f3f0e1d2SKirill A. Shutemov 
1680f3f0e1d2SKirill A. Shutemov 		if (page_mapping(page) != mapping) {
1681f3f0e1d2SKirill A. Shutemov 			result = SCAN_TRUNCATED;
1682f3f0e1d2SKirill A. Shutemov 			goto out_unlock;
1683f3f0e1d2SKirill A. Shutemov 		}
1684f3f0e1d2SKirill A. Shutemov 
168574c42e1bSRongwei Wang 		if (!is_shmem && (PageDirty(page) ||
168674c42e1bSRongwei Wang 				  PageWriteback(page))) {
16874655e5e5SSong Liu 			/*
16884655e5e5SSong Liu 			 * khugepaged only works on read-only fd, so this
16894655e5e5SSong Liu 			 * page is dirty because it hasn't been flushed
16904655e5e5SSong Liu 			 * since first write.
16914655e5e5SSong Liu 			 */
16924655e5e5SSong Liu 			result = SCAN_FAIL;
16934655e5e5SSong Liu 			goto out_unlock;
16944655e5e5SSong Liu 		}
16954655e5e5SSong Liu 
1696f3f0e1d2SKirill A. Shutemov 		if (isolate_lru_page(page)) {
1697f3f0e1d2SKirill A. Shutemov 			result = SCAN_DEL_PAGE_LRU;
1698042a3082SHugh Dickins 			goto out_unlock;
1699f3f0e1d2SKirill A. Shutemov 		}
1700f3f0e1d2SKirill A. Shutemov 
170199cb0dbdSSong Liu 		if (page_has_private(page) &&
170299cb0dbdSSong Liu 		    !try_to_release_page(page, GFP_KERNEL)) {
170399cb0dbdSSong Liu 			result = SCAN_PAGE_HAS_PRIVATE;
17042f33a706SHugh Dickins 			putback_lru_page(page);
170599cb0dbdSSong Liu 			goto out_unlock;
170699cb0dbdSSong Liu 		}
170799cb0dbdSSong Liu 
1708f3f0e1d2SKirill A. Shutemov 		if (page_mapped(page))
1709869f7ee6SMatthew Wilcox (Oracle) 			try_to_unmap(page_folio(page),
1710869f7ee6SMatthew Wilcox (Oracle) 					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
1711f3f0e1d2SKirill A. Shutemov 
171277da9389SMatthew Wilcox 		xas_lock_irq(&xas);
171377da9389SMatthew Wilcox 		xas_set(&xas, index);
1714f3f0e1d2SKirill A. Shutemov 
171577da9389SMatthew Wilcox 		VM_BUG_ON_PAGE(page != xas_load(&xas), page);
1716f3f0e1d2SKirill A. Shutemov 
1717f3f0e1d2SKirill A. Shutemov 		/*
1718f3f0e1d2SKirill A. Shutemov 		 * The page is expected to have page_count() == 3:
1719f3f0e1d2SKirill A. Shutemov 		 *  - we hold a pin on it;
172077da9389SMatthew Wilcox 		 *  - one reference from page cache;
1721f3f0e1d2SKirill A. Shutemov 		 *  - one from isolate_lru_page;
1722f3f0e1d2SKirill A. Shutemov 		 */
1723f3f0e1d2SKirill A. Shutemov 		if (!page_ref_freeze(page, 3)) {
1724f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1725042a3082SHugh Dickins 			xas_unlock_irq(&xas);
1726042a3082SHugh Dickins 			putback_lru_page(page);
1727042a3082SHugh Dickins 			goto out_unlock;
1728f3f0e1d2SKirill A. Shutemov 		}
1729f3f0e1d2SKirill A. Shutemov 
1730f3f0e1d2SKirill A. Shutemov 		/*
1731f3f0e1d2SKirill A. Shutemov 		 * Add the page to the list to be able to undo the collapse if
1732f3f0e1d2SKirill A. Shutemov 		 * something go wrong.
1733f3f0e1d2SKirill A. Shutemov 		 */
1734f3f0e1d2SKirill A. Shutemov 		list_add_tail(&page->lru, &pagelist);
1735f3f0e1d2SKirill A. Shutemov 
1736f3f0e1d2SKirill A. Shutemov 		/* Finally, replace with the new page. */
1737*50ad2f24SZach O'Keefe 		xas_store(&xas, hpage);
1738f3f0e1d2SKirill A. Shutemov 		continue;
1739f3f0e1d2SKirill A. Shutemov out_unlock:
1740f3f0e1d2SKirill A. Shutemov 		unlock_page(page);
1741f3f0e1d2SKirill A. Shutemov 		put_page(page);
1742042a3082SHugh Dickins 		goto xa_unlocked;
1743f3f0e1d2SKirill A. Shutemov 	}
1744*50ad2f24SZach O'Keefe 	nr = thp_nr_pages(hpage);
1745f3f0e1d2SKirill A. Shutemov 
174699cb0dbdSSong Liu 	if (is_shmem)
1747*50ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_SHMEM_THPS, nr);
174809d91cdaSSong Liu 	else {
1749*50ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_FILE_THPS, nr);
175009d91cdaSSong Liu 		filemap_nr_thps_inc(mapping);
1751eb6ecbedSCollin Fijalkovich 		/*
1752eb6ecbedSCollin Fijalkovich 		 * Paired with smp_mb() in do_dentry_open() to ensure
1753eb6ecbedSCollin Fijalkovich 		 * i_writecount is up to date and the update to nr_thps is
1754eb6ecbedSCollin Fijalkovich 		 * visible. Ensures the page cache will be truncated if the
1755eb6ecbedSCollin Fijalkovich 		 * file is opened writable.
1756eb6ecbedSCollin Fijalkovich 		 */
1757eb6ecbedSCollin Fijalkovich 		smp_mb();
1758eb6ecbedSCollin Fijalkovich 		if (inode_is_open_for_write(mapping->host)) {
1759eb6ecbedSCollin Fijalkovich 			result = SCAN_FAIL;
1760*50ad2f24SZach O'Keefe 			__mod_lruvec_page_state(hpage, NR_FILE_THPS, -nr);
1761eb6ecbedSCollin Fijalkovich 			filemap_nr_thps_dec(mapping);
1762eb6ecbedSCollin Fijalkovich 			goto xa_locked;
1763eb6ecbedSCollin Fijalkovich 		}
176409d91cdaSSong Liu 	}
176599cb0dbdSSong Liu 
1766042a3082SHugh Dickins 	if (nr_none) {
1767*50ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_FILE_PAGES, nr_none);
17682f55f070SMiaohe Lin 		/* nr_none is always 0 for non-shmem. */
1769*50ad2f24SZach O'Keefe 		__mod_lruvec_page_state(hpage, NR_SHMEM, nr_none);
1770042a3082SHugh Dickins 	}
1771042a3082SHugh Dickins 
17726b24ca4aSMatthew Wilcox (Oracle) 	/* Join all the small entries into a single multi-index entry */
17736b24ca4aSMatthew Wilcox (Oracle) 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
1774*50ad2f24SZach O'Keefe 	xas_store(&xas, hpage);
1775042a3082SHugh Dickins xa_locked:
1776042a3082SHugh Dickins 	xas_unlock_irq(&xas);
177777da9389SMatthew Wilcox xa_unlocked:
1778042a3082SHugh Dickins 
17796d9df8a5SHugh Dickins 	/*
17806d9df8a5SHugh Dickins 	 * If collapse is successful, flush must be done now before copying.
17816d9df8a5SHugh Dickins 	 * If collapse is unsuccessful, does flush actually need to be done?
17826d9df8a5SHugh Dickins 	 * Do it anyway, to clear the state.
17836d9df8a5SHugh Dickins 	 */
17846d9df8a5SHugh Dickins 	try_to_unmap_flush();
17856d9df8a5SHugh Dickins 
1786f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
178777da9389SMatthew Wilcox 		struct page *page, *tmp;
1788f3f0e1d2SKirill A. Shutemov 
1789f3f0e1d2SKirill A. Shutemov 		/*
179077da9389SMatthew Wilcox 		 * Replacing old pages with new one has succeeded, now we
179177da9389SMatthew Wilcox 		 * need to copy the content and free the old pages.
1792f3f0e1d2SKirill A. Shutemov 		 */
17932af8ff29SHugh Dickins 		index = start;
1794f3f0e1d2SKirill A. Shutemov 		list_for_each_entry_safe(page, tmp, &pagelist, lru) {
17952af8ff29SHugh Dickins 			while (index < page->index) {
1796*50ad2f24SZach O'Keefe 				clear_highpage(hpage + (index % HPAGE_PMD_NR));
17972af8ff29SHugh Dickins 				index++;
17982af8ff29SHugh Dickins 			}
1799*50ad2f24SZach O'Keefe 			copy_highpage(hpage + (page->index % HPAGE_PMD_NR),
1800f3f0e1d2SKirill A. Shutemov 				      page);
1801f3f0e1d2SKirill A. Shutemov 			list_del(&page->lru);
1802f3f0e1d2SKirill A. Shutemov 			page->mapping = NULL;
1803042a3082SHugh Dickins 			page_ref_unfreeze(page, 1);
1804f3f0e1d2SKirill A. Shutemov 			ClearPageActive(page);
1805f3f0e1d2SKirill A. Shutemov 			ClearPageUnevictable(page);
1806042a3082SHugh Dickins 			unlock_page(page);
1807f3f0e1d2SKirill A. Shutemov 			put_page(page);
18082af8ff29SHugh Dickins 			index++;
18092af8ff29SHugh Dickins 		}
18102af8ff29SHugh Dickins 		while (index < end) {
1811*50ad2f24SZach O'Keefe 			clear_highpage(hpage + (index % HPAGE_PMD_NR));
18122af8ff29SHugh Dickins 			index++;
1813f3f0e1d2SKirill A. Shutemov 		}
1814f3f0e1d2SKirill A. Shutemov 
1815*50ad2f24SZach O'Keefe 		SetPageUptodate(hpage);
1816*50ad2f24SZach O'Keefe 		page_ref_add(hpage, HPAGE_PMD_NR - 1);
18176058eaecSJohannes Weiner 		if (is_shmem)
1818*50ad2f24SZach O'Keefe 			set_page_dirty(hpage);
1819*50ad2f24SZach O'Keefe 		lru_cache_add(hpage);
1820f3f0e1d2SKirill A. Shutemov 
1821042a3082SHugh Dickins 		/*
1822042a3082SHugh Dickins 		 * Remove pte page tables, so we can re-fault the page as huge.
1823042a3082SHugh Dickins 		 */
1824042a3082SHugh Dickins 		retract_page_tables(mapping, start);
1825*50ad2f24SZach O'Keefe 		unlock_page(hpage);
1826*50ad2f24SZach O'Keefe 		hpage = NULL;
1827f3f0e1d2SKirill A. Shutemov 	} else {
182877da9389SMatthew Wilcox 		struct page *page;
1829aaa52e34SHugh Dickins 
183077da9389SMatthew Wilcox 		/* Something went wrong: roll back page cache changes */
183177da9389SMatthew Wilcox 		xas_lock_irq(&xas);
18322f55f070SMiaohe Lin 		if (nr_none) {
1833aaa52e34SHugh Dickins 			mapping->nrpages -= nr_none;
1834aaa52e34SHugh Dickins 			shmem_uncharge(mapping->host, nr_none);
18352f55f070SMiaohe Lin 		}
1836aaa52e34SHugh Dickins 
183777da9389SMatthew Wilcox 		xas_set(&xas, start);
183877da9389SMatthew Wilcox 		xas_for_each(&xas, page, end - 1) {
1839f3f0e1d2SKirill A. Shutemov 			page = list_first_entry_or_null(&pagelist,
1840f3f0e1d2SKirill A. Shutemov 					struct page, lru);
184177da9389SMatthew Wilcox 			if (!page || xas.xa_index < page->index) {
1842f3f0e1d2SKirill A. Shutemov 				if (!nr_none)
1843f3f0e1d2SKirill A. Shutemov 					break;
1844f3f0e1d2SKirill A. Shutemov 				nr_none--;
184559749e6cSJohannes Weiner 				/* Put holes back where they were */
184677da9389SMatthew Wilcox 				xas_store(&xas, NULL);
1847f3f0e1d2SKirill A. Shutemov 				continue;
1848f3f0e1d2SKirill A. Shutemov 			}
1849f3f0e1d2SKirill A. Shutemov 
185077da9389SMatthew Wilcox 			VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
1851f3f0e1d2SKirill A. Shutemov 
1852f3f0e1d2SKirill A. Shutemov 			/* Unfreeze the page. */
1853f3f0e1d2SKirill A. Shutemov 			list_del(&page->lru);
1854f3f0e1d2SKirill A. Shutemov 			page_ref_unfreeze(page, 2);
185577da9389SMatthew Wilcox 			xas_store(&xas, page);
185677da9389SMatthew Wilcox 			xas_pause(&xas);
185777da9389SMatthew Wilcox 			xas_unlock_irq(&xas);
1858f3f0e1d2SKirill A. Shutemov 			unlock_page(page);
1859042a3082SHugh Dickins 			putback_lru_page(page);
186077da9389SMatthew Wilcox 			xas_lock_irq(&xas);
1861f3f0e1d2SKirill A. Shutemov 		}
1862f3f0e1d2SKirill A. Shutemov 		VM_BUG_ON(nr_none);
186377da9389SMatthew Wilcox 		xas_unlock_irq(&xas);
1864f3f0e1d2SKirill A. Shutemov 
1865*50ad2f24SZach O'Keefe 		hpage->mapping = NULL;
1866f3f0e1d2SKirill A. Shutemov 	}
1867042a3082SHugh Dickins 
1868*50ad2f24SZach O'Keefe 	if (hpage)
1869*50ad2f24SZach O'Keefe 		unlock_page(hpage);
1870f3f0e1d2SKirill A. Shutemov out:
1871f3f0e1d2SKirill A. Shutemov 	VM_BUG_ON(!list_empty(&pagelist));
1872*50ad2f24SZach O'Keefe 	if (hpage) {
1873*50ad2f24SZach O'Keefe 		mem_cgroup_uncharge(page_folio(hpage));
1874*50ad2f24SZach O'Keefe 		put_page(hpage);
1875c6a7f445SYang Shi 	}
1876f3f0e1d2SKirill A. Shutemov 	/* TODO: tracepoints */
1877*50ad2f24SZach O'Keefe 	return result;
1878f3f0e1d2SKirill A. Shutemov }
1879f3f0e1d2SKirill A. Shutemov 
1880*50ad2f24SZach O'Keefe static int khugepaged_scan_file(struct mm_struct *mm, struct file *file,
1881*50ad2f24SZach O'Keefe 				pgoff_t start, struct collapse_control *cc)
1882f3f0e1d2SKirill A. Shutemov {
1883f3f0e1d2SKirill A. Shutemov 	struct page *page = NULL;
1884579c571eSSong Liu 	struct address_space *mapping = file->f_mapping;
188585b392dbSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
1886f3f0e1d2SKirill A. Shutemov 	int present, swap;
1887f3f0e1d2SKirill A. Shutemov 	int node = NUMA_NO_NODE;
1888f3f0e1d2SKirill A. Shutemov 	int result = SCAN_SUCCEED;
1889f3f0e1d2SKirill A. Shutemov 
1890f3f0e1d2SKirill A. Shutemov 	present = 0;
1891f3f0e1d2SKirill A. Shutemov 	swap = 0;
189234d6b470SZach O'Keefe 	memset(cc->node_load, 0, sizeof(cc->node_load));
1893f3f0e1d2SKirill A. Shutemov 	rcu_read_lock();
189485b392dbSMatthew Wilcox 	xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
189585b392dbSMatthew Wilcox 		if (xas_retry(&xas, page))
1896f3f0e1d2SKirill A. Shutemov 			continue;
1897f3f0e1d2SKirill A. Shutemov 
189885b392dbSMatthew Wilcox 		if (xa_is_value(page)) {
1899f3f0e1d2SKirill A. Shutemov 			if (++swap > khugepaged_max_ptes_swap) {
1900f3f0e1d2SKirill A. Shutemov 				result = SCAN_EXCEED_SWAP_PTE;
1901e9ea874aSYang Yang 				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1902f3f0e1d2SKirill A. Shutemov 				break;
1903f3f0e1d2SKirill A. Shutemov 			}
1904f3f0e1d2SKirill A. Shutemov 			continue;
1905f3f0e1d2SKirill A. Shutemov 		}
1906f3f0e1d2SKirill A. Shutemov 
19076b24ca4aSMatthew Wilcox (Oracle) 		/*
19086b24ca4aSMatthew Wilcox (Oracle) 		 * XXX: khugepaged should compact smaller compound pages
19096b24ca4aSMatthew Wilcox (Oracle) 		 * into a PMD sized page
19106b24ca4aSMatthew Wilcox (Oracle) 		 */
1911f3f0e1d2SKirill A. Shutemov 		if (PageTransCompound(page)) {
1912f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COMPOUND;
1913f3f0e1d2SKirill A. Shutemov 			break;
1914f3f0e1d2SKirill A. Shutemov 		}
1915f3f0e1d2SKirill A. Shutemov 
1916f3f0e1d2SKirill A. Shutemov 		node = page_to_nid(page);
191734d6b470SZach O'Keefe 		if (khugepaged_scan_abort(node, cc)) {
1918f3f0e1d2SKirill A. Shutemov 			result = SCAN_SCAN_ABORT;
1919f3f0e1d2SKirill A. Shutemov 			break;
1920f3f0e1d2SKirill A. Shutemov 		}
192134d6b470SZach O'Keefe 		cc->node_load[node]++;
1922f3f0e1d2SKirill A. Shutemov 
1923f3f0e1d2SKirill A. Shutemov 		if (!PageLRU(page)) {
1924f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_LRU;
1925f3f0e1d2SKirill A. Shutemov 			break;
1926f3f0e1d2SKirill A. Shutemov 		}
1927f3f0e1d2SKirill A. Shutemov 
192899cb0dbdSSong Liu 		if (page_count(page) !=
192999cb0dbdSSong Liu 		    1 + page_mapcount(page) + page_has_private(page)) {
1930f3f0e1d2SKirill A. Shutemov 			result = SCAN_PAGE_COUNT;
1931f3f0e1d2SKirill A. Shutemov 			break;
1932f3f0e1d2SKirill A. Shutemov 		}
1933f3f0e1d2SKirill A. Shutemov 
1934f3f0e1d2SKirill A. Shutemov 		/*
1935f3f0e1d2SKirill A. Shutemov 		 * We probably should check if the page is referenced here, but
1936f3f0e1d2SKirill A. Shutemov 		 * nobody would transfer pte_young() to PageReferenced() for us.
1937f3f0e1d2SKirill A. Shutemov 		 * And rmap walk here is just too costly...
1938f3f0e1d2SKirill A. Shutemov 		 */
1939f3f0e1d2SKirill A. Shutemov 
1940f3f0e1d2SKirill A. Shutemov 		present++;
1941f3f0e1d2SKirill A. Shutemov 
1942f3f0e1d2SKirill A. Shutemov 		if (need_resched()) {
194385b392dbSMatthew Wilcox 			xas_pause(&xas);
1944f3f0e1d2SKirill A. Shutemov 			cond_resched_rcu();
1945f3f0e1d2SKirill A. Shutemov 		}
1946f3f0e1d2SKirill A. Shutemov 	}
1947f3f0e1d2SKirill A. Shutemov 	rcu_read_unlock();
1948f3f0e1d2SKirill A. Shutemov 
1949f3f0e1d2SKirill A. Shutemov 	if (result == SCAN_SUCCEED) {
1950f3f0e1d2SKirill A. Shutemov 		if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
1951f3f0e1d2SKirill A. Shutemov 			result = SCAN_EXCEED_NONE_PTE;
1952e9ea874aSYang Yang 			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1953f3f0e1d2SKirill A. Shutemov 		} else {
1954*50ad2f24SZach O'Keefe 			result = collapse_file(mm, file, start, cc);
1955f3f0e1d2SKirill A. Shutemov 		}
1956f3f0e1d2SKirill A. Shutemov 	}
1957f3f0e1d2SKirill A. Shutemov 
1958f3f0e1d2SKirill A. Shutemov 	/* TODO: tracepoints */
1959*50ad2f24SZach O'Keefe 	return result;
1960f3f0e1d2SKirill A. Shutemov }
1961f3f0e1d2SKirill A. Shutemov #else
1962*50ad2f24SZach O'Keefe static int khugepaged_scan_file(struct mm_struct *mm, struct file *file,
1963*50ad2f24SZach O'Keefe 				pgoff_t start, struct collapse_control *cc)
1964f3f0e1d2SKirill A. Shutemov {
1965f3f0e1d2SKirill A. Shutemov 	BUILD_BUG();
1966f3f0e1d2SKirill A. Shutemov }
196727e1f827SSong Liu 
19680edf61e5SMiaohe Lin static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
196927e1f827SSong Liu {
197027e1f827SSong Liu }
1971f3f0e1d2SKirill A. Shutemov #endif
1972f3f0e1d2SKirill A. Shutemov 
1973*50ad2f24SZach O'Keefe static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
197434d6b470SZach O'Keefe 					    struct collapse_control *cc)
1975b46e756fSKirill A. Shutemov 	__releases(&khugepaged_mm_lock)
1976b46e756fSKirill A. Shutemov 	__acquires(&khugepaged_mm_lock)
1977b46e756fSKirill A. Shutemov {
1978b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
1979b46e756fSKirill A. Shutemov 	struct mm_struct *mm;
1980b46e756fSKirill A. Shutemov 	struct vm_area_struct *vma;
1981b46e756fSKirill A. Shutemov 	int progress = 0;
1982b46e756fSKirill A. Shutemov 
1983b46e756fSKirill A. Shutemov 	VM_BUG_ON(!pages);
198435f3aa39SLance Roy 	lockdep_assert_held(&khugepaged_mm_lock);
1985*50ad2f24SZach O'Keefe 	*result = SCAN_FAIL;
1986b46e756fSKirill A. Shutemov 
1987b46e756fSKirill A. Shutemov 	if (khugepaged_scan.mm_slot)
1988b46e756fSKirill A. Shutemov 		mm_slot = khugepaged_scan.mm_slot;
1989b46e756fSKirill A. Shutemov 	else {
1990b46e756fSKirill A. Shutemov 		mm_slot = list_entry(khugepaged_scan.mm_head.next,
1991b46e756fSKirill A. Shutemov 				     struct mm_slot, mm_node);
1992b46e756fSKirill A. Shutemov 		khugepaged_scan.address = 0;
1993b46e756fSKirill A. Shutemov 		khugepaged_scan.mm_slot = mm_slot;
1994b46e756fSKirill A. Shutemov 	}
1995b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
199627e1f827SSong Liu 	khugepaged_collapse_pte_mapped_thps(mm_slot);
1997b46e756fSKirill A. Shutemov 
1998b46e756fSKirill A. Shutemov 	mm = mm_slot->mm;
19993b454ad3SYang Shi 	/*
20003b454ad3SYang Shi 	 * Don't wait for semaphore (to avoid long wait times).  Just move to
20013b454ad3SYang Shi 	 * the next mm on the list.
20023b454ad3SYang Shi 	 */
2003b46e756fSKirill A. Shutemov 	vma = NULL;
2004d8ed45c5SMichel Lespinasse 	if (unlikely(!mmap_read_trylock(mm)))
2005c1e8d7c6SMichel Lespinasse 		goto breakouterloop_mmap_lock;
20063b454ad3SYang Shi 	if (likely(!khugepaged_test_exit(mm)))
2007b46e756fSKirill A. Shutemov 		vma = find_vma(mm, khugepaged_scan.address);
2008b46e756fSKirill A. Shutemov 
2009b46e756fSKirill A. Shutemov 	progress++;
2010b46e756fSKirill A. Shutemov 	for (; vma; vma = vma->vm_next) {
2011b46e756fSKirill A. Shutemov 		unsigned long hstart, hend;
2012b46e756fSKirill A. Shutemov 
2013b46e756fSKirill A. Shutemov 		cond_resched();
2014b46e756fSKirill A. Shutemov 		if (unlikely(khugepaged_test_exit(mm))) {
2015b46e756fSKirill A. Shutemov 			progress++;
2016b46e756fSKirill A. Shutemov 			break;
2017b46e756fSKirill A. Shutemov 		}
20187da4e2cbSYang Shi 		if (!hugepage_vma_check(vma, vma->vm_flags, false, false)) {
2019b46e756fSKirill A. Shutemov skip:
2020b46e756fSKirill A. Shutemov 			progress++;
2021b46e756fSKirill A. Shutemov 			continue;
2022b46e756fSKirill A. Shutemov 		}
20234fa6893fSYang Shi 		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
20244fa6893fSYang Shi 		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
2025b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address > hend)
2026b46e756fSKirill A. Shutemov 			goto skip;
2027b46e756fSKirill A. Shutemov 		if (khugepaged_scan.address < hstart)
2028b46e756fSKirill A. Shutemov 			khugepaged_scan.address = hstart;
2029b46e756fSKirill A. Shutemov 		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2030b46e756fSKirill A. Shutemov 
2031b46e756fSKirill A. Shutemov 		while (khugepaged_scan.address < hend) {
2032*50ad2f24SZach O'Keefe 			bool mmap_locked = true;
2033*50ad2f24SZach O'Keefe 
2034b46e756fSKirill A. Shutemov 			cond_resched();
2035b46e756fSKirill A. Shutemov 			if (unlikely(khugepaged_test_exit(mm)))
2036b46e756fSKirill A. Shutemov 				goto breakouterloop;
2037b46e756fSKirill A. Shutemov 
2038b46e756fSKirill A. Shutemov 			VM_BUG_ON(khugepaged_scan.address < hstart ||
2039b46e756fSKirill A. Shutemov 				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2040b46e756fSKirill A. Shutemov 				  hend);
204199cb0dbdSSong Liu 			if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
2042396bcc52SMatthew Wilcox (Oracle) 				struct file *file = get_file(vma->vm_file);
2043f3f0e1d2SKirill A. Shutemov 				pgoff_t pgoff = linear_page_index(vma,
2044f3f0e1d2SKirill A. Shutemov 						khugepaged_scan.address);
204599cb0dbdSSong Liu 
2046d8ed45c5SMichel Lespinasse 				mmap_read_unlock(mm);
2047*50ad2f24SZach O'Keefe 				*result = khugepaged_scan_file(mm, file, pgoff,
204834d6b470SZach O'Keefe 							       cc);
2049*50ad2f24SZach O'Keefe 				mmap_locked = false;
2050f3f0e1d2SKirill A. Shutemov 				fput(file);
2051f3f0e1d2SKirill A. Shutemov 			} else {
2052*50ad2f24SZach O'Keefe 				*result = khugepaged_scan_pmd(mm, vma,
2053b46e756fSKirill A. Shutemov 							      khugepaged_scan.address,
2054*50ad2f24SZach O'Keefe 							      &mmap_locked, cc);
2055f3f0e1d2SKirill A. Shutemov 			}
2056*50ad2f24SZach O'Keefe 			if (*result == SCAN_SUCCEED)
2057*50ad2f24SZach O'Keefe 				++khugepaged_pages_collapsed;
2058b46e756fSKirill A. Shutemov 			/* move to next address */
2059b46e756fSKirill A. Shutemov 			khugepaged_scan.address += HPAGE_PMD_SIZE;
2060b46e756fSKirill A. Shutemov 			progress += HPAGE_PMD_NR;
2061*50ad2f24SZach O'Keefe 			if (!mmap_locked)
2062*50ad2f24SZach O'Keefe 				/*
2063*50ad2f24SZach O'Keefe 				 * We released mmap_lock so break loop.  Note
2064*50ad2f24SZach O'Keefe 				 * that we drop mmap_lock before all hugepage
2065*50ad2f24SZach O'Keefe 				 * allocations, so if allocation fails, we are
2066*50ad2f24SZach O'Keefe 				 * guaranteed to break here and report the
2067*50ad2f24SZach O'Keefe 				 * correct result back to caller.
2068*50ad2f24SZach O'Keefe 				 */
2069c1e8d7c6SMichel Lespinasse 				goto breakouterloop_mmap_lock;
2070b46e756fSKirill A. Shutemov 			if (progress >= pages)
2071b46e756fSKirill A. Shutemov 				goto breakouterloop;
2072b46e756fSKirill A. Shutemov 		}
2073b46e756fSKirill A. Shutemov 	}
2074b46e756fSKirill A. Shutemov breakouterloop:
2075d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2076c1e8d7c6SMichel Lespinasse breakouterloop_mmap_lock:
2077b46e756fSKirill A. Shutemov 
2078b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2079b46e756fSKirill A. Shutemov 	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2080b46e756fSKirill A. Shutemov 	/*
2081b46e756fSKirill A. Shutemov 	 * Release the current mm_slot if this mm is about to die, or
2082b46e756fSKirill A. Shutemov 	 * if we scanned all vmas of this mm.
2083b46e756fSKirill A. Shutemov 	 */
2084b46e756fSKirill A. Shutemov 	if (khugepaged_test_exit(mm) || !vma) {
2085b46e756fSKirill A. Shutemov 		/*
2086b46e756fSKirill A. Shutemov 		 * Make sure that if mm_users is reaching zero while
2087b46e756fSKirill A. Shutemov 		 * khugepaged runs here, khugepaged_exit will find
2088b46e756fSKirill A. Shutemov 		 * mm_slot not pointing to the exiting mm.
2089b46e756fSKirill A. Shutemov 		 */
2090b46e756fSKirill A. Shutemov 		if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
2091b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = list_entry(
2092b46e756fSKirill A. Shutemov 				mm_slot->mm_node.next,
2093b46e756fSKirill A. Shutemov 				struct mm_slot, mm_node);
2094b46e756fSKirill A. Shutemov 			khugepaged_scan.address = 0;
2095b46e756fSKirill A. Shutemov 		} else {
2096b46e756fSKirill A. Shutemov 			khugepaged_scan.mm_slot = NULL;
2097b46e756fSKirill A. Shutemov 			khugepaged_full_scans++;
2098b46e756fSKirill A. Shutemov 		}
2099b46e756fSKirill A. Shutemov 
2100b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2101b46e756fSKirill A. Shutemov 	}
2102b46e756fSKirill A. Shutemov 
2103b46e756fSKirill A. Shutemov 	return progress;
2104b46e756fSKirill A. Shutemov }
2105b46e756fSKirill A. Shutemov 
2106b46e756fSKirill A. Shutemov static int khugepaged_has_work(void)
2107b46e756fSKirill A. Shutemov {
2108b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) &&
21091064026bSYang Shi 		hugepage_flags_enabled();
2110b46e756fSKirill A. Shutemov }
2111b46e756fSKirill A. Shutemov 
2112b46e756fSKirill A. Shutemov static int khugepaged_wait_event(void)
2113b46e756fSKirill A. Shutemov {
2114b46e756fSKirill A. Shutemov 	return !list_empty(&khugepaged_scan.mm_head) ||
2115b46e756fSKirill A. Shutemov 		kthread_should_stop();
2116b46e756fSKirill A. Shutemov }
2117b46e756fSKirill A. Shutemov 
211834d6b470SZach O'Keefe static void khugepaged_do_scan(struct collapse_control *cc)
2119b46e756fSKirill A. Shutemov {
2120b46e756fSKirill A. Shutemov 	unsigned int progress = 0, pass_through_head = 0;
212189dc6a96SYanfei Xu 	unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2122b46e756fSKirill A. Shutemov 	bool wait = true;
2123*50ad2f24SZach O'Keefe 	int result = SCAN_SUCCEED;
2124b46e756fSKirill A. Shutemov 
2125a980df33SKirill A. Shutemov 	lru_add_drain_all();
2126a980df33SKirill A. Shutemov 
2127c6a7f445SYang Shi 	while (true) {
2128b46e756fSKirill A. Shutemov 		cond_resched();
2129b46e756fSKirill A. Shutemov 
2130b46e756fSKirill A. Shutemov 		if (unlikely(kthread_should_stop() || try_to_freeze()))
2131b46e756fSKirill A. Shutemov 			break;
2132b46e756fSKirill A. Shutemov 
2133b46e756fSKirill A. Shutemov 		spin_lock(&khugepaged_mm_lock);
2134b46e756fSKirill A. Shutemov 		if (!khugepaged_scan.mm_slot)
2135b46e756fSKirill A. Shutemov 			pass_through_head++;
2136b46e756fSKirill A. Shutemov 		if (khugepaged_has_work() &&
2137b46e756fSKirill A. Shutemov 		    pass_through_head < 2)
2138b46e756fSKirill A. Shutemov 			progress += khugepaged_scan_mm_slot(pages - progress,
2139*50ad2f24SZach O'Keefe 							    &result, cc);
2140b46e756fSKirill A. Shutemov 		else
2141b46e756fSKirill A. Shutemov 			progress = pages;
2142b46e756fSKirill A. Shutemov 		spin_unlock(&khugepaged_mm_lock);
2143b46e756fSKirill A. Shutemov 
2144c6a7f445SYang Shi 		if (progress >= pages)
2145c6a7f445SYang Shi 			break;
2146c6a7f445SYang Shi 
2147*50ad2f24SZach O'Keefe 		if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2148c6a7f445SYang Shi 			/*
2149c6a7f445SYang Shi 			 * If fail to allocate the first time, try to sleep for
2150c6a7f445SYang Shi 			 * a while.  When hit again, cancel the scan.
2151c6a7f445SYang Shi 			 */
2152c6a7f445SYang Shi 			if (!wait)
2153c6a7f445SYang Shi 				break;
2154c6a7f445SYang Shi 			wait = false;
2155c6a7f445SYang Shi 			khugepaged_alloc_sleep();
2156c6a7f445SYang Shi 		}
2157c6a7f445SYang Shi 	}
2158b46e756fSKirill A. Shutemov }
2159b46e756fSKirill A. Shutemov 
2160b46e756fSKirill A. Shutemov static bool khugepaged_should_wakeup(void)
2161b46e756fSKirill A. Shutemov {
2162b46e756fSKirill A. Shutemov 	return kthread_should_stop() ||
2163b46e756fSKirill A. Shutemov 	       time_after_eq(jiffies, khugepaged_sleep_expire);
2164b46e756fSKirill A. Shutemov }
2165b46e756fSKirill A. Shutemov 
2166b46e756fSKirill A. Shutemov static void khugepaged_wait_work(void)
2167b46e756fSKirill A. Shutemov {
2168b46e756fSKirill A. Shutemov 	if (khugepaged_has_work()) {
2169b46e756fSKirill A. Shutemov 		const unsigned long scan_sleep_jiffies =
2170b46e756fSKirill A. Shutemov 			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2171b46e756fSKirill A. Shutemov 
2172b46e756fSKirill A. Shutemov 		if (!scan_sleep_jiffies)
2173b46e756fSKirill A. Shutemov 			return;
2174b46e756fSKirill A. Shutemov 
2175b46e756fSKirill A. Shutemov 		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2176b46e756fSKirill A. Shutemov 		wait_event_freezable_timeout(khugepaged_wait,
2177b46e756fSKirill A. Shutemov 					     khugepaged_should_wakeup(),
2178b46e756fSKirill A. Shutemov 					     scan_sleep_jiffies);
2179b46e756fSKirill A. Shutemov 		return;
2180b46e756fSKirill A. Shutemov 	}
2181b46e756fSKirill A. Shutemov 
21821064026bSYang Shi 	if (hugepage_flags_enabled())
2183b46e756fSKirill A. Shutemov 		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2184b46e756fSKirill A. Shutemov }
2185b46e756fSKirill A. Shutemov 
2186b46e756fSKirill A. Shutemov static int khugepaged(void *none)
2187b46e756fSKirill A. Shutemov {
2188b46e756fSKirill A. Shutemov 	struct mm_slot *mm_slot;
2189b46e756fSKirill A. Shutemov 
2190b46e756fSKirill A. Shutemov 	set_freezable();
2191b46e756fSKirill A. Shutemov 	set_user_nice(current, MAX_NICE);
2192b46e756fSKirill A. Shutemov 
2193b46e756fSKirill A. Shutemov 	while (!kthread_should_stop()) {
219434d6b470SZach O'Keefe 		khugepaged_do_scan(&khugepaged_collapse_control);
2195b46e756fSKirill A. Shutemov 		khugepaged_wait_work();
2196b46e756fSKirill A. Shutemov 	}
2197b46e756fSKirill A. Shutemov 
2198b46e756fSKirill A. Shutemov 	spin_lock(&khugepaged_mm_lock);
2199b46e756fSKirill A. Shutemov 	mm_slot = khugepaged_scan.mm_slot;
2200b46e756fSKirill A. Shutemov 	khugepaged_scan.mm_slot = NULL;
2201b46e756fSKirill A. Shutemov 	if (mm_slot)
2202b46e756fSKirill A. Shutemov 		collect_mm_slot(mm_slot);
2203b46e756fSKirill A. Shutemov 	spin_unlock(&khugepaged_mm_lock);
2204b46e756fSKirill A. Shutemov 	return 0;
2205b46e756fSKirill A. Shutemov }
2206b46e756fSKirill A. Shutemov 
2207b46e756fSKirill A. Shutemov static void set_recommended_min_free_kbytes(void)
2208b46e756fSKirill A. Shutemov {
2209b46e756fSKirill A. Shutemov 	struct zone *zone;
2210b46e756fSKirill A. Shutemov 	int nr_zones = 0;
2211b46e756fSKirill A. Shutemov 	unsigned long recommended_min;
2212b46e756fSKirill A. Shutemov 
22131064026bSYang Shi 	if (!hugepage_flags_enabled()) {
2214bd3400eaSLiangcai Fan 		calculate_min_free_kbytes();
2215bd3400eaSLiangcai Fan 		goto update_wmarks;
2216bd3400eaSLiangcai Fan 	}
2217bd3400eaSLiangcai Fan 
2218b7d349c7SJoonsoo Kim 	for_each_populated_zone(zone) {
2219b7d349c7SJoonsoo Kim 		/*
2220b7d349c7SJoonsoo Kim 		 * We don't need to worry about fragmentation of
2221b7d349c7SJoonsoo Kim 		 * ZONE_MOVABLE since it only has movable pages.
2222b7d349c7SJoonsoo Kim 		 */
2223b7d349c7SJoonsoo Kim 		if (zone_idx(zone) > gfp_zone(GFP_USER))
2224b7d349c7SJoonsoo Kim 			continue;
2225b7d349c7SJoonsoo Kim 
2226b46e756fSKirill A. Shutemov 		nr_zones++;
2227b7d349c7SJoonsoo Kim 	}
2228b46e756fSKirill A. Shutemov 
2229b46e756fSKirill A. Shutemov 	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2230b46e756fSKirill A. Shutemov 	recommended_min = pageblock_nr_pages * nr_zones * 2;
2231b46e756fSKirill A. Shutemov 
2232b46e756fSKirill A. Shutemov 	/*
2233b46e756fSKirill A. Shutemov 	 * Make sure that on average at least two pageblocks are almost free
2234b46e756fSKirill A. Shutemov 	 * of another type, one for a migratetype to fall back to and a
2235b46e756fSKirill A. Shutemov 	 * second to avoid subsequent fallbacks of other types There are 3
2236b46e756fSKirill A. Shutemov 	 * MIGRATE_TYPES we care about.
2237b46e756fSKirill A. Shutemov 	 */
2238b46e756fSKirill A. Shutemov 	recommended_min += pageblock_nr_pages * nr_zones *
2239b46e756fSKirill A. Shutemov 			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2240b46e756fSKirill A. Shutemov 
2241b46e756fSKirill A. Shutemov 	/* don't ever allow to reserve more than 5% of the lowmem */
2242b46e756fSKirill A. Shutemov 	recommended_min = min(recommended_min,
2243b46e756fSKirill A. Shutemov 			      (unsigned long) nr_free_buffer_pages() / 20);
2244b46e756fSKirill A. Shutemov 	recommended_min <<= (PAGE_SHIFT-10);
2245b46e756fSKirill A. Shutemov 
2246b46e756fSKirill A. Shutemov 	if (recommended_min > min_free_kbytes) {
2247b46e756fSKirill A. Shutemov 		if (user_min_free_kbytes >= 0)
2248b46e756fSKirill A. Shutemov 			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2249b46e756fSKirill A. Shutemov 				min_free_kbytes, recommended_min);
2250b46e756fSKirill A. Shutemov 
2251b46e756fSKirill A. Shutemov 		min_free_kbytes = recommended_min;
2252b46e756fSKirill A. Shutemov 	}
2253bd3400eaSLiangcai Fan 
2254bd3400eaSLiangcai Fan update_wmarks:
2255b46e756fSKirill A. Shutemov 	setup_per_zone_wmarks();
2256b46e756fSKirill A. Shutemov }
2257b46e756fSKirill A. Shutemov 
2258b46e756fSKirill A. Shutemov int start_stop_khugepaged(void)
2259b46e756fSKirill A. Shutemov {
2260b46e756fSKirill A. Shutemov 	int err = 0;
2261b46e756fSKirill A. Shutemov 
2262b46e756fSKirill A. Shutemov 	mutex_lock(&khugepaged_mutex);
22631064026bSYang Shi 	if (hugepage_flags_enabled()) {
2264b46e756fSKirill A. Shutemov 		if (!khugepaged_thread)
2265b46e756fSKirill A. Shutemov 			khugepaged_thread = kthread_run(khugepaged, NULL,
2266b46e756fSKirill A. Shutemov 							"khugepaged");
2267b46e756fSKirill A. Shutemov 		if (IS_ERR(khugepaged_thread)) {
2268b46e756fSKirill A. Shutemov 			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2269b46e756fSKirill A. Shutemov 			err = PTR_ERR(khugepaged_thread);
2270b46e756fSKirill A. Shutemov 			khugepaged_thread = NULL;
2271b46e756fSKirill A. Shutemov 			goto fail;
2272b46e756fSKirill A. Shutemov 		}
2273b46e756fSKirill A. Shutemov 
2274b46e756fSKirill A. Shutemov 		if (!list_empty(&khugepaged_scan.mm_head))
2275b46e756fSKirill A. Shutemov 			wake_up_interruptible(&khugepaged_wait);
2276b46e756fSKirill A. Shutemov 	} else if (khugepaged_thread) {
2277b46e756fSKirill A. Shutemov 		kthread_stop(khugepaged_thread);
2278b46e756fSKirill A. Shutemov 		khugepaged_thread = NULL;
2279b46e756fSKirill A. Shutemov 	}
2280bd3400eaSLiangcai Fan 	set_recommended_min_free_kbytes();
2281b46e756fSKirill A. Shutemov fail:
2282b46e756fSKirill A. Shutemov 	mutex_unlock(&khugepaged_mutex);
2283b46e756fSKirill A. Shutemov 	return err;
2284b46e756fSKirill A. Shutemov }
22854aab2be0SVijay Balakrishna 
22864aab2be0SVijay Balakrishna void khugepaged_min_free_kbytes_update(void)
22874aab2be0SVijay Balakrishna {
22884aab2be0SVijay Balakrishna 	mutex_lock(&khugepaged_mutex);
22891064026bSYang Shi 	if (hugepage_flags_enabled() && khugepaged_thread)
22904aab2be0SVijay Balakrishna 		set_recommended_min_free_kbytes();
22914aab2be0SVijay Balakrishna 	mutex_unlock(&khugepaged_mutex);
22924aab2be0SVijay Balakrishna }
2293