Linux Audio

Check our new training course

Loading...
v4.17
   1// SPDX-License-Identifier: GPL-2.0
   2#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
   3
   4#include <linux/mm.h>
   5#include <linux/sched.h>
   6#include <linux/sched/mm.h>
   7#include <linux/sched/coredump.h>
   8#include <linux/mmu_notifier.h>
   9#include <linux/rmap.h>
  10#include <linux/swap.h>
  11#include <linux/mm_inline.h>
  12#include <linux/kthread.h>
  13#include <linux/khugepaged.h>
  14#include <linux/freezer.h>
  15#include <linux/mman.h>
  16#include <linux/hashtable.h>
  17#include <linux/userfaultfd_k.h>
  18#include <linux/page_idle.h>
 
 
  19#include <linux/swapops.h>
  20#include <linux/shmem_fs.h>
 
 
  21
  22#include <asm/tlb.h>
  23#include <asm/pgalloc.h>
  24#include "internal.h"
 
  25
  26enum scan_result {
  27	SCAN_FAIL,
  28	SCAN_SUCCEED,
  29	SCAN_PMD_NULL,
 
 
  30	SCAN_EXCEED_NONE_PTE,
 
 
  31	SCAN_PTE_NON_PRESENT,
 
 
  32	SCAN_PAGE_RO,
  33	SCAN_LACK_REFERENCED_PAGE,
  34	SCAN_PAGE_NULL,
  35	SCAN_SCAN_ABORT,
  36	SCAN_PAGE_COUNT,
  37	SCAN_PAGE_LRU,
  38	SCAN_PAGE_LOCK,
  39	SCAN_PAGE_ANON,
  40	SCAN_PAGE_COMPOUND,
  41	SCAN_ANY_PROCESS,
  42	SCAN_VMA_NULL,
  43	SCAN_VMA_CHECK,
  44	SCAN_ADDRESS_RANGE,
  45	SCAN_SWAP_CACHE_PAGE,
  46	SCAN_DEL_PAGE_LRU,
  47	SCAN_ALLOC_HUGE_PAGE_FAIL,
  48	SCAN_CGROUP_CHARGE_FAIL,
  49	SCAN_EXCEED_SWAP_PTE,
  50	SCAN_TRUNCATED,
 
 
 
 
  51};
  52
  53#define CREATE_TRACE_POINTS
  54#include <trace/events/huge_memory.h>
  55
 
 
 
  56/* default scan 8*512 pte (or vmas) every 30 second */
  57static unsigned int khugepaged_pages_to_scan __read_mostly;
  58static unsigned int khugepaged_pages_collapsed;
  59static unsigned int khugepaged_full_scans;
  60static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
  61/* during fragmentation poll the hugepage allocator once every minute */
  62static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
  63static unsigned long khugepaged_sleep_expire;
  64static DEFINE_SPINLOCK(khugepaged_mm_lock);
  65static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
  66/*
  67 * default collapse hugepages if there is at least one pte mapped like
  68 * it would have happened if the vma was large enough during page
  69 * fault.
 
 
  70 */
  71static unsigned int khugepaged_max_ptes_none __read_mostly;
  72static unsigned int khugepaged_max_ptes_swap __read_mostly;
 
  73
  74#define MM_SLOTS_HASH_BITS 10
  75static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
 
 
  76
  77static struct kmem_cache *mm_slot_cache __read_mostly;
 
 
 
 
 
 
 
 
  78
  79/**
  80 * struct mm_slot - hash lookup from mm to mm_slot
  81 * @hash: hash collision list
  82 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
  83 * @mm: the mm that this information is valid for
  84 */
  85struct mm_slot {
  86	struct hlist_node hash;
  87	struct list_head mm_node;
  88	struct mm_struct *mm;
  89};
  90
  91/**
  92 * struct khugepaged_scan - cursor for scanning
  93 * @mm_head: the head of the mm list to scan
  94 * @mm_slot: the current mm_slot we are scanning
  95 * @address: the next address inside that to be scanned
  96 *
  97 * There is only the one khugepaged_scan instance of this cursor structure.
  98 */
  99struct khugepaged_scan {
 100	struct list_head mm_head;
 101	struct mm_slot *mm_slot;
 102	unsigned long address;
 103};
 104
 105static struct khugepaged_scan khugepaged_scan = {
 106	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
 107};
 108
 109#ifdef CONFIG_SYSFS
 110static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
 111					 struct kobj_attribute *attr,
 112					 char *buf)
 113{
 114	return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
 115}
 116
 117static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
 118					  struct kobj_attribute *attr,
 119					  const char *buf, size_t count)
 120{
 121	unsigned long msecs;
 122	int err;
 123
 124	err = kstrtoul(buf, 10, &msecs);
 125	if (err || msecs > UINT_MAX)
 126		return -EINVAL;
 127
 128	khugepaged_scan_sleep_millisecs = msecs;
 129	khugepaged_sleep_expire = 0;
 130	wake_up_interruptible(&khugepaged_wait);
 131
 132	return count;
 133}
 134static struct kobj_attribute scan_sleep_millisecs_attr =
 135	__ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
 136	       scan_sleep_millisecs_store);
 137
 138static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
 139					  struct kobj_attribute *attr,
 140					  char *buf)
 141{
 142	return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
 143}
 144
 145static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
 146					   struct kobj_attribute *attr,
 147					   const char *buf, size_t count)
 148{
 149	unsigned long msecs;
 150	int err;
 151
 152	err = kstrtoul(buf, 10, &msecs);
 153	if (err || msecs > UINT_MAX)
 154		return -EINVAL;
 155
 156	khugepaged_alloc_sleep_millisecs = msecs;
 157	khugepaged_sleep_expire = 0;
 158	wake_up_interruptible(&khugepaged_wait);
 159
 160	return count;
 161}
 162static struct kobj_attribute alloc_sleep_millisecs_attr =
 163	__ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
 164	       alloc_sleep_millisecs_store);
 165
 166static ssize_t pages_to_scan_show(struct kobject *kobj,
 167				  struct kobj_attribute *attr,
 168				  char *buf)
 169{
 170	return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
 171}
 172static ssize_t pages_to_scan_store(struct kobject *kobj,
 173				   struct kobj_attribute *attr,
 174				   const char *buf, size_t count)
 175{
 
 176	int err;
 177	unsigned long pages;
 178
 179	err = kstrtoul(buf, 10, &pages);
 180	if (err || !pages || pages > UINT_MAX)
 181		return -EINVAL;
 182
 183	khugepaged_pages_to_scan = pages;
 184
 185	return count;
 186}
 187static struct kobj_attribute pages_to_scan_attr =
 188	__ATTR(pages_to_scan, 0644, pages_to_scan_show,
 189	       pages_to_scan_store);
 190
 191static ssize_t pages_collapsed_show(struct kobject *kobj,
 192				    struct kobj_attribute *attr,
 193				    char *buf)
 194{
 195	return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
 196}
 197static struct kobj_attribute pages_collapsed_attr =
 198	__ATTR_RO(pages_collapsed);
 199
 200static ssize_t full_scans_show(struct kobject *kobj,
 201			       struct kobj_attribute *attr,
 202			       char *buf)
 203{
 204	return sprintf(buf, "%u\n", khugepaged_full_scans);
 205}
 206static struct kobj_attribute full_scans_attr =
 207	__ATTR_RO(full_scans);
 208
 209static ssize_t khugepaged_defrag_show(struct kobject *kobj,
 210				      struct kobj_attribute *attr, char *buf)
 211{
 212	return single_hugepage_flag_show(kobj, attr, buf,
 213				TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
 214}
 215static ssize_t khugepaged_defrag_store(struct kobject *kobj,
 216				       struct kobj_attribute *attr,
 217				       const char *buf, size_t count)
 218{
 219	return single_hugepage_flag_store(kobj, attr, buf, count,
 220				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
 221}
 222static struct kobj_attribute khugepaged_defrag_attr =
 223	__ATTR(defrag, 0644, khugepaged_defrag_show,
 224	       khugepaged_defrag_store);
 225
 226/*
 227 * max_ptes_none controls if khugepaged should collapse hugepages over
 228 * any unmapped ptes in turn potentially increasing the memory
 229 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
 230 * reduce the available free memory in the system as it
 231 * runs. Increasing max_ptes_none will instead potentially reduce the
 232 * free memory in the system during the khugepaged scan.
 233 */
 234static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
 235					     struct kobj_attribute *attr,
 236					     char *buf)
 237{
 238	return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
 239}
 240static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
 241					      struct kobj_attribute *attr,
 242					      const char *buf, size_t count)
 243{
 244	int err;
 245	unsigned long max_ptes_none;
 246
 247	err = kstrtoul(buf, 10, &max_ptes_none);
 248	if (err || max_ptes_none > HPAGE_PMD_NR-1)
 249		return -EINVAL;
 250
 251	khugepaged_max_ptes_none = max_ptes_none;
 252
 253	return count;
 254}
 255static struct kobj_attribute khugepaged_max_ptes_none_attr =
 256	__ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
 257	       khugepaged_max_ptes_none_store);
 258
 259static ssize_t khugepaged_max_ptes_swap_show(struct kobject *kobj,
 260					     struct kobj_attribute *attr,
 261					     char *buf)
 262{
 263	return sprintf(buf, "%u\n", khugepaged_max_ptes_swap);
 264}
 265
 266static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
 267					      struct kobj_attribute *attr,
 268					      const char *buf, size_t count)
 269{
 270	int err;
 271	unsigned long max_ptes_swap;
 272
 273	err  = kstrtoul(buf, 10, &max_ptes_swap);
 274	if (err || max_ptes_swap > HPAGE_PMD_NR-1)
 275		return -EINVAL;
 276
 277	khugepaged_max_ptes_swap = max_ptes_swap;
 278
 279	return count;
 280}
 281
 282static struct kobj_attribute khugepaged_max_ptes_swap_attr =
 283	__ATTR(max_ptes_swap, 0644, khugepaged_max_ptes_swap_show,
 284	       khugepaged_max_ptes_swap_store);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 285
 286static struct attribute *khugepaged_attr[] = {
 287	&khugepaged_defrag_attr.attr,
 288	&khugepaged_max_ptes_none_attr.attr,
 
 
 289	&pages_to_scan_attr.attr,
 290	&pages_collapsed_attr.attr,
 291	&full_scans_attr.attr,
 292	&scan_sleep_millisecs_attr.attr,
 293	&alloc_sleep_millisecs_attr.attr,
 294	&khugepaged_max_ptes_swap_attr.attr,
 295	NULL,
 296};
 297
 298struct attribute_group khugepaged_attr_group = {
 299	.attrs = khugepaged_attr,
 300	.name = "khugepaged",
 301};
 302#endif /* CONFIG_SYSFS */
 303
 304#define VM_NO_KHUGEPAGED (VM_SPECIAL | VM_HUGETLB)
 305
 306int hugepage_madvise(struct vm_area_struct *vma,
 307		     unsigned long *vm_flags, int advice)
 308{
 309	switch (advice) {
 310	case MADV_HUGEPAGE:
 311#ifdef CONFIG_S390
 312		/*
 313		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
 314		 * can't handle this properly after s390_enable_sie, so we simply
 315		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
 316		 */
 317		if (mm_has_pgste(vma->vm_mm))
 318			return 0;
 319#endif
 320		*vm_flags &= ~VM_NOHUGEPAGE;
 321		*vm_flags |= VM_HUGEPAGE;
 322		/*
 323		 * If the vma become good for khugepaged to scan,
 324		 * register it here without waiting a page fault that
 325		 * may not happen any time soon.
 326		 */
 327		if (!(*vm_flags & VM_NO_KHUGEPAGED) &&
 328				khugepaged_enter_vma_merge(vma, *vm_flags))
 329			return -ENOMEM;
 330		break;
 331	case MADV_NOHUGEPAGE:
 332		*vm_flags &= ~VM_HUGEPAGE;
 333		*vm_flags |= VM_NOHUGEPAGE;
 334		/*
 335		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
 336		 * this vma even if we leave the mm registered in khugepaged if
 337		 * it got registered before VM_NOHUGEPAGE was set.
 338		 */
 339		break;
 340	}
 341
 342	return 0;
 343}
 344
 345int __init khugepaged_init(void)
 346{
 347	mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
 348					  sizeof(struct mm_slot),
 349					  __alignof__(struct mm_slot), 0, NULL);
 350	if (!mm_slot_cache)
 351		return -ENOMEM;
 352
 353	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
 354	khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
 355	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
 
 356
 357	return 0;
 358}
 359
 360void __init khugepaged_destroy(void)
 361{
 362	kmem_cache_destroy(mm_slot_cache);
 363}
 364
 365static inline struct mm_slot *alloc_mm_slot(void)
 366{
 367	if (!mm_slot_cache)	/* initialization failed */
 368		return NULL;
 369	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
 370}
 371
 372static inline void free_mm_slot(struct mm_slot *mm_slot)
 373{
 374	kmem_cache_free(mm_slot_cache, mm_slot);
 375}
 376
 377static struct mm_slot *get_mm_slot(struct mm_struct *mm)
 378{
 379	struct mm_slot *mm_slot;
 380
 381	hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
 382		if (mm == mm_slot->mm)
 383			return mm_slot;
 384
 385	return NULL;
 386}
 387
 388static void insert_to_mm_slots_hash(struct mm_struct *mm,
 389				    struct mm_slot *mm_slot)
 390{
 391	mm_slot->mm = mm;
 392	hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
 393}
 394
 395static inline int khugepaged_test_exit(struct mm_struct *mm)
 396{
 397	return atomic_read(&mm->mm_users) == 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 398}
 399
 400int __khugepaged_enter(struct mm_struct *mm)
 401{
 402	struct mm_slot *mm_slot;
 
 403	int wakeup;
 404
 405	mm_slot = alloc_mm_slot();
 
 
 
 
 
 406	if (!mm_slot)
 407		return -ENOMEM;
 408
 409	/* __khugepaged_exit() must not run from under us */
 410	VM_BUG_ON_MM(khugepaged_test_exit(mm), mm);
 411	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
 412		free_mm_slot(mm_slot);
 413		return 0;
 414	}
 415
 416	spin_lock(&khugepaged_mm_lock);
 417	insert_to_mm_slots_hash(mm, mm_slot);
 418	/*
 419	 * Insert just behind the scanning cursor, to let the area settle
 420	 * down a little.
 421	 */
 422	wakeup = list_empty(&khugepaged_scan.mm_head);
 423	list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
 424	spin_unlock(&khugepaged_mm_lock);
 425
 426	mmgrab(mm);
 427	if (wakeup)
 428		wake_up_interruptible(&khugepaged_wait);
 429
 430	return 0;
 431}
 432
 433int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
 434			       unsigned long vm_flags)
 435{
 436	unsigned long hstart, hend;
 437	if (!vma->anon_vma)
 438		/*
 439		 * Not yet faulted in so we will register later in the
 440		 * page fault if needed.
 441		 */
 442		return 0;
 443	if (vma->vm_ops || (vm_flags & VM_NO_KHUGEPAGED))
 444		/* khugepaged not yet working on file or special mappings */
 445		return 0;
 446	hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
 447	hend = vma->vm_end & HPAGE_PMD_MASK;
 448	if (hstart < hend)
 449		return khugepaged_enter(vma, vm_flags);
 450	return 0;
 451}
 452
 453void __khugepaged_exit(struct mm_struct *mm)
 454{
 455	struct mm_slot *mm_slot;
 
 456	int free = 0;
 457
 458	spin_lock(&khugepaged_mm_lock);
 459	mm_slot = get_mm_slot(mm);
 
 460	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
 461		hash_del(&mm_slot->hash);
 462		list_del(&mm_slot->mm_node);
 463		free = 1;
 464	}
 465	spin_unlock(&khugepaged_mm_lock);
 466
 467	if (free) {
 468		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
 469		free_mm_slot(mm_slot);
 470		mmdrop(mm);
 471	} else if (mm_slot) {
 472		/*
 473		 * This is required to serialize against
 474		 * khugepaged_test_exit() (which is guaranteed to run
 475		 * under mmap sem read mode). Stop here (after we
 476		 * return all pagetables will be destroyed) until
 477		 * khugepaged has finished working on the pagetables
 478		 * under the mmap_sem.
 479		 */
 480		down_write(&mm->mmap_sem);
 481		up_write(&mm->mmap_sem);
 482	}
 483}
 484
 485static void release_pte_page(struct page *page)
 486{
 487	dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
 488	unlock_page(page);
 489	putback_lru_page(page);
 
 
 490}
 491
 492static void release_pte_pages(pte_t *pte, pte_t *_pte)
 
 493{
 
 
 494	while (--_pte >= pte) {
 495		pte_t pteval = *_pte;
 496		if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)))
 497			release_pte_page(pte_page(pteval));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 498	}
 499}
 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 501static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 502					unsigned long address,
 503					pte_t *pte)
 
 
 504{
 505	struct page *page = NULL;
 
 506	pte_t *_pte;
 507	int none_or_zero = 0, result = 0, referenced = 0;
 508	bool writable = false;
 509
 510	for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
 511	     _pte++, address += PAGE_SIZE) {
 512		pte_t pteval = *_pte;
 513		if (pte_none(pteval) || (pte_present(pteval) &&
 514				is_zero_pfn(pte_pfn(pteval)))) {
 
 515			if (!userfaultfd_armed(vma) &&
 516			    ++none_or_zero <= khugepaged_max_ptes_none) {
 
 517				continue;
 518			} else {
 519				result = SCAN_EXCEED_NONE_PTE;
 
 520				goto out;
 521			}
 522		}
 523		if (!pte_present(pteval)) {
 524			result = SCAN_PTE_NON_PRESENT;
 525			goto out;
 526		}
 
 
 
 
 527		page = vm_normal_page(vma, address, pteval);
 528		if (unlikely(!page)) {
 529			result = SCAN_PAGE_NULL;
 530			goto out;
 531		}
 532
 533		/* TODO: teach khugepaged to collapse THP mapped with pte */
 534		if (PageCompound(page)) {
 535			result = SCAN_PAGE_COMPOUND;
 536			goto out;
 
 
 
 
 
 
 
 
 537		}
 538
 539		VM_BUG_ON_PAGE(!PageAnon(page), page);
 
 
 
 
 
 
 
 
 
 
 
 540
 541		/*
 542		 * We can do it before isolate_lru_page because the
 543		 * page can't be freed from under us. NOTE: PG_lock
 544		 * is needed to serialize against split_huge_page
 545		 * when invoked from the VM.
 546		 */
 547		if (!trylock_page(page)) {
 548			result = SCAN_PAGE_LOCK;
 549			goto out;
 550		}
 551
 552		/*
 553		 * cannot use mapcount: can't collapse if there's a gup pin.
 554		 * The page must only be referenced by the scanned process
 555		 * and page swap cache.
 
 
 
 
 
 
 556		 */
 557		if (page_count(page) != 1 + PageSwapCache(page)) {
 558			unlock_page(page);
 559			result = SCAN_PAGE_COUNT;
 560			goto out;
 561		}
 562		if (pte_write(pteval)) {
 563			writable = true;
 564		} else {
 565			if (PageSwapCache(page) &&
 566			    !reuse_swap_page(page, NULL)) {
 567				unlock_page(page);
 568				result = SCAN_SWAP_CACHE_PAGE;
 569				goto out;
 570			}
 571			/*
 572			 * Page is not in the swap cache. It can be collapsed
 573			 * into a THP.
 574			 */
 575		}
 576
 577		/*
 578		 * Isolate the page to avoid collapsing an hugepage
 579		 * currently in use by the VM.
 580		 */
 581		if (isolate_lru_page(page)) {
 582			unlock_page(page);
 583			result = SCAN_DEL_PAGE_LRU;
 584			goto out;
 585		}
 586		inc_node_page_state(page,
 587				NR_ISOLATED_ANON + page_is_file_cache(page));
 588		VM_BUG_ON_PAGE(!PageLocked(page), page);
 589		VM_BUG_ON_PAGE(PageLRU(page), page);
 590
 591		/* There should be enough young pte to collapse the page */
 592		if (pte_young(pteval) ||
 593		    page_is_young(page) || PageReferenced(page) ||
 594		    mmu_notifier_test_young(vma->vm_mm, address))
 
 
 
 
 
 
 
 
 595			referenced++;
 
 
 
 596	}
 597	if (likely(writable)) {
 598		if (likely(referenced)) {
 599			result = SCAN_SUCCEED;
 600			trace_mm_collapse_huge_page_isolate(page, none_or_zero,
 601							    referenced, writable, result);
 602			return 1;
 603		}
 604	} else {
 605		result = SCAN_PAGE_RO;
 
 
 
 
 
 
 
 606	}
 607
 608out:
 609	release_pte_pages(pte, _pte);
 610	trace_mm_collapse_huge_page_isolate(page, none_or_zero,
 611					    referenced, writable, result);
 612	return 0;
 613}
 614
 615static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
 616				      struct vm_area_struct *vma,
 617				      unsigned long address,
 618				      spinlock_t *ptl)
 
 619{
 
 620	pte_t *_pte;
 621	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
 622				_pte++, page++, address += PAGE_SIZE) {
 623		pte_t pteval = *_pte;
 624		struct page *src_page;
 625
 
 
 
 626		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
 627			clear_user_highpage(page, address);
 628			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
 629			if (is_zero_pfn(pte_pfn(pteval))) {
 630				/*
 631				 * ptl mostly unnecessary.
 632				 */
 633				spin_lock(ptl);
 634				/*
 635				 * paravirt calls inside pte_clear here are
 636				 * superfluous.
 637				 */
 638				pte_clear(vma->vm_mm, address, _pte);
 639				spin_unlock(ptl);
 
 640			}
 641		} else {
 642			src_page = pte_page(pteval);
 643			copy_user_highpage(page, src_page, address, vma);
 644			VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
 645			release_pte_page(src_page);
 
 646			/*
 647			 * ptl mostly unnecessary, but preempt has to
 648			 * be disabled to update the per-cpu stats
 649			 * inside page_remove_rmap().
 650			 */
 651			spin_lock(ptl);
 652			/*
 653			 * paravirt calls inside pte_clear here are
 654			 * superfluous.
 655			 */
 656			pte_clear(vma->vm_mm, address, _pte);
 657			page_remove_rmap(src_page, false);
 658			spin_unlock(ptl);
 659			free_page_and_swap_cache(src_page);
 660		}
 661	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 662}
 663
 664static void khugepaged_alloc_sleep(void)
 665{
 666	DEFINE_WAIT(wait);
 667
 668	add_wait_queue(&khugepaged_wait, &wait);
 669	freezable_schedule_timeout_interruptible(
 670		msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
 671	remove_wait_queue(&khugepaged_wait, &wait);
 672}
 673
 674static int khugepaged_node_load[MAX_NUMNODES];
 
 
 675
 676static bool khugepaged_scan_abort(int nid)
 677{
 678	int i;
 679
 680	/*
 681	 * If node_reclaim_mode is disabled, then no extra effort is made to
 682	 * allocate memory locally.
 683	 */
 684	if (!node_reclaim_mode)
 685		return false;
 686
 687	/* If there is a count for this node already, it must be acceptable */
 688	if (khugepaged_node_load[nid])
 689		return false;
 690
 691	for (i = 0; i < MAX_NUMNODES; i++) {
 692		if (!khugepaged_node_load[i])
 693			continue;
 694		if (node_distance(nid, i) > RECLAIM_DISTANCE)
 695			return true;
 696	}
 697	return false;
 698}
 699
 
 
 
 
 700/* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
 701static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
 702{
 703	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
 704}
 705
 706#ifdef CONFIG_NUMA
 707static int khugepaged_find_target_node(void)
 708{
 709	static int last_khugepaged_target_node = NUMA_NO_NODE;
 710	int nid, target_node = 0, max_value = 0;
 711
 712	/* find first node with max normal pages hit */
 713	for (nid = 0; nid < MAX_NUMNODES; nid++)
 714		if (khugepaged_node_load[nid] > max_value) {
 715			max_value = khugepaged_node_load[nid];
 716			target_node = nid;
 717		}
 718
 719	/* do some balance if several nodes have the same hit record */
 720	if (target_node <= last_khugepaged_target_node)
 721		for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
 722				nid++)
 723			if (max_value == khugepaged_node_load[nid]) {
 724				target_node = nid;
 725				break;
 726			}
 727
 728	last_khugepaged_target_node = target_node;
 729	return target_node;
 730}
 731
 732static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
 733{
 734	if (IS_ERR(*hpage)) {
 735		if (!*wait)
 736			return false;
 737
 738		*wait = false;
 739		*hpage = NULL;
 740		khugepaged_alloc_sleep();
 741	} else if (*hpage) {
 742		put_page(*hpage);
 743		*hpage = NULL;
 744	}
 745
 746	return true;
 747}
 748
 749static struct page *
 750khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
 751{
 752	VM_BUG_ON_PAGE(*hpage, *hpage);
 753
 754	*hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
 755	if (unlikely(!*hpage)) {
 756		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
 757		*hpage = ERR_PTR(-ENOMEM);
 758		return NULL;
 759	}
 760
 761	prep_transhuge_page(*hpage);
 762	count_vm_event(THP_COLLAPSE_ALLOC);
 763	return *hpage;
 764}
 765#else
 766static int khugepaged_find_target_node(void)
 767{
 768	return 0;
 769}
 770
 771static inline struct page *alloc_khugepaged_hugepage(void)
 772{
 773	struct page *page;
 774
 775	page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
 776			   HPAGE_PMD_ORDER);
 777	if (page)
 778		prep_transhuge_page(page);
 779	return page;
 780}
 781
 782static struct page *khugepaged_alloc_hugepage(bool *wait)
 783{
 784	struct page *hpage;
 785
 786	do {
 787		hpage = alloc_khugepaged_hugepage();
 788		if (!hpage) {
 789			count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
 790			if (!*wait)
 791				return NULL;
 792
 793			*wait = false;
 794			khugepaged_alloc_sleep();
 795		} else
 796			count_vm_event(THP_COLLAPSE_ALLOC);
 797	} while (unlikely(!hpage) && likely(khugepaged_enabled()));
 798
 799	return hpage;
 800}
 801
 802static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
 803{
 804	if (!*hpage)
 805		*hpage = khugepaged_alloc_hugepage(wait);
 806
 807	if (unlikely(!*hpage))
 808		return false;
 809
 810	return true;
 811}
 812
 813static struct page *
 814khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
 815{
 816	VM_BUG_ON(!*hpage);
 817
 818	return  *hpage;
 819}
 820#endif
 821
 822static bool hugepage_vma_check(struct vm_area_struct *vma)
 823{
 824	if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
 825	    (vma->vm_flags & VM_NOHUGEPAGE) ||
 826	    test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
 827		return false;
 828	if (shmem_file(vma->vm_file)) {
 829		if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
 830			return false;
 831		return IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) - vma->vm_pgoff,
 832				HPAGE_PMD_NR);
 833	}
 834	if (!vma->anon_vma || vma->vm_ops)
 835		return false;
 836	if (is_vma_temporary_stack(vma))
 837		return false;
 838	return !(vma->vm_flags & VM_NO_KHUGEPAGED);
 839}
 840
 841/*
 842 * If mmap_sem temporarily dropped, revalidate vma
 843 * before taking mmap_sem.
 844 * Return 0 if succeeds, otherwise return none-zero
 845 * value (scan code).
 846 */
 847
 848static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
 849		struct vm_area_struct **vmap)
 
 
 850{
 851	struct vm_area_struct *vma;
 852	unsigned long hstart, hend;
 853
 854	if (unlikely(khugepaged_test_exit(mm)))
 855		return SCAN_ANY_PROCESS;
 856
 857	*vmap = vma = find_vma(mm, address);
 858	if (!vma)
 859		return SCAN_VMA_NULL;
 860
 861	hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
 862	hend = vma->vm_end & HPAGE_PMD_MASK;
 863	if (address < hstart || address + HPAGE_PMD_SIZE > hend)
 864		return SCAN_ADDRESS_RANGE;
 865	if (!hugepage_vma_check(vma))
 866		return SCAN_VMA_CHECK;
 867	return 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 868}
 869
 870/*
 871 * Bring missing pages in from swap, to complete THP collapse.
 872 * Only done if khugepaged_scan_pmd believes it is worthwhile.
 873 *
 874 * Called and returns without pte mapped or spinlocks held,
 875 * but with mmap_sem held to protect against vma changes.
 876 */
 
 
 
 
 
 
 
 
 
 
 
 877
 878static bool __collapse_huge_page_swapin(struct mm_struct *mm,
 879					struct vm_area_struct *vma,
 880					unsigned long address, pmd_t *pmd,
 881					int referenced)
 882{
 883	int swapped_in = 0, ret = 0;
 884	struct vm_fault vmf = {
 885		.vma = vma,
 886		.address = address,
 887		.flags = FAULT_FLAG_ALLOW_RETRY,
 888		.pmd = pmd,
 889		.pgoff = linear_page_index(vma, address),
 890	};
 891
 892	/* we only decide to swapin, if there is enough young ptes */
 893	if (referenced < HPAGE_PMD_NR/2) {
 894		trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
 895		return false;
 896	}
 897	vmf.pte = pte_offset_map(pmd, address);
 898	for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
 899			vmf.pte++, vmf.address += PAGE_SIZE) {
 900		vmf.orig_pte = *vmf.pte;
 
 
 
 
 
 901		if (!is_swap_pte(vmf.orig_pte))
 902			continue;
 903		swapped_in++;
 
 
 904		ret = do_swap_page(&vmf);
 
 
 905
 906		/* do_swap_page returns VM_FAULT_RETRY with released mmap_sem */
 
 
 
 
 
 907		if (ret & VM_FAULT_RETRY) {
 908			down_read(&mm->mmap_sem);
 909			if (hugepage_vma_revalidate(mm, address, &vmf.vma)) {
 910				/* vma is no longer available, don't continue to swapin */
 911				trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
 912				return false;
 913			}
 914			/* check if the pmd is still valid */
 915			if (mm_find_pmd(mm, address) != pmd) {
 916				trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
 917				return false;
 918			}
 919		}
 920		if (ret & VM_FAULT_ERROR) {
 921			trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
 922			return false;
 
 923		}
 924		/* pte is unmapped now, we need to map it */
 925		vmf.pte = pte_offset_map(pmd, vmf.address);
 926	}
 927	vmf.pte--;
 928	pte_unmap(vmf.pte);
 929	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
 930	return true;
 
 
 
 
 
 
 
 
 931}
 932
 933static void collapse_huge_page(struct mm_struct *mm,
 934				   unsigned long address,
 935				   struct page **hpage,
 936				   int node, int referenced)
 937{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 938	pmd_t *pmd, _pmd;
 939	pte_t *pte;
 940	pgtable_t pgtable;
 941	struct page *new_page;
 942	spinlock_t *pmd_ptl, *pte_ptl;
 943	int isolated = 0, result = 0;
 944	struct mem_cgroup *memcg;
 945	struct vm_area_struct *vma;
 946	unsigned long mmun_start;	/* For mmu_notifiers */
 947	unsigned long mmun_end;		/* For mmu_notifiers */
 948	gfp_t gfp;
 949
 950	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
 951
 952	/* Only allocate from the target node */
 953	gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
 954
 955	/*
 956	 * Before allocating the hugepage, release the mmap_sem read lock.
 957	 * The allocation can take potentially a long time if it involves
 958	 * sync compaction, and we do not need to hold the mmap_sem during
 959	 * that. We will recheck the vma after taking it again in write mode.
 960	 */
 961	up_read(&mm->mmap_sem);
 962	new_page = khugepaged_alloc_page(hpage, gfp, node);
 963	if (!new_page) {
 964		result = SCAN_ALLOC_HUGE_PAGE_FAIL;
 965		goto out_nolock;
 966	}
 967
 968	if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
 969		result = SCAN_CGROUP_CHARGE_FAIL;
 970		goto out_nolock;
 971	}
 972
 973	down_read(&mm->mmap_sem);
 974	result = hugepage_vma_revalidate(mm, address, &vma);
 975	if (result) {
 976		mem_cgroup_cancel_charge(new_page, memcg, true);
 977		up_read(&mm->mmap_sem);
 978		goto out_nolock;
 979	}
 980
 981	pmd = mm_find_pmd(mm, address);
 982	if (!pmd) {
 983		result = SCAN_PMD_NULL;
 984		mem_cgroup_cancel_charge(new_page, memcg, true);
 985		up_read(&mm->mmap_sem);
 986		goto out_nolock;
 987	}
 988
 989	/*
 990	 * __collapse_huge_page_swapin always returns with mmap_sem locked.
 991	 * If it fails, we release mmap_sem and jump out_nolock.
 992	 * Continuing to collapse causes inconsistency.
 993	 */
 994	if (!__collapse_huge_page_swapin(mm, vma, address, pmd, referenced)) {
 995		mem_cgroup_cancel_charge(new_page, memcg, true);
 996		up_read(&mm->mmap_sem);
 997		goto out_nolock;
 
 998	}
 999
1000	up_read(&mm->mmap_sem);
1001	/*
1002	 * Prevent all access to pagetables with the exception of
1003	 * gup_fast later handled by the ptep_clear_flush and the VM
1004	 * handled by the anon_vma lock + PG_lock.
 
 
 
1005	 */
1006	down_write(&mm->mmap_sem);
1007	result = hugepage_vma_revalidate(mm, address, &vma);
1008	if (result)
1009		goto out;
1010	/* check if the pmd is still valid */
1011	if (mm_find_pmd(mm, address) != pmd)
1012		goto out;
 
1013
 
1014	anon_vma_lock_write(vma->anon_vma);
1015
1016	pte = pte_offset_map(pmd, address);
1017	pte_ptl = pte_lockptr(mm, pmd);
 
1018
1019	mmun_start = address;
1020	mmun_end   = address + HPAGE_PMD_SIZE;
1021	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1022	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1023	/*
1024	 * After this gup_fast can't run anymore. This also removes
1025	 * any huge TLB entry from the CPU so we won't allow
1026	 * huge and small TLB entries for the same virtual address
1027	 * to avoid the risk of CPU bugs in that area.
 
 
1028	 */
1029	_pmd = pmdp_collapse_flush(vma, address, pmd);
1030	spin_unlock(pmd_ptl);
1031	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
 
1032
1033	spin_lock(pte_ptl);
1034	isolated = __collapse_huge_page_isolate(vma, address, pte);
1035	spin_unlock(pte_ptl);
 
 
 
 
 
1036
1037	if (unlikely(!isolated)) {
1038		pte_unmap(pte);
 
1039		spin_lock(pmd_ptl);
1040		BUG_ON(!pmd_none(*pmd));
1041		/*
1042		 * We can only use set_pmd_at when establishing
1043		 * hugepmds and never for establishing regular pmds that
1044		 * points to regular pagetables. Use pmd_populate for that
1045		 */
1046		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1047		spin_unlock(pmd_ptl);
1048		anon_vma_unlock_write(vma->anon_vma);
1049		result = SCAN_FAIL;
1050		goto out;
1051	}
1052
1053	/*
1054	 * All pages are isolated and locked so anon_vma rmap
1055	 * can't run anymore.
1056	 */
1057	anon_vma_unlock_write(vma->anon_vma);
1058
1059	__collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl);
 
 
1060	pte_unmap(pte);
1061	__SetPageUptodate(new_page);
1062	pgtable = pmd_pgtable(_pmd);
1063
1064	_pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
1065	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1066
1067	/*
1068	 * spin_lock() below is not the equivalent of smp_wmb(), so
1069	 * this is needed to avoid the copy_huge_page writes to become
1070	 * visible after the set_pmd_at() write.
1071	 */
1072	smp_wmb();
 
 
 
 
1073
1074	spin_lock(pmd_ptl);
1075	BUG_ON(!pmd_none(*pmd));
1076	page_add_new_anon_rmap(new_page, vma, address, true);
1077	mem_cgroup_commit_charge(new_page, memcg, false, true);
1078	lru_cache_add_active_or_unevictable(new_page, vma);
1079	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1080	set_pmd_at(mm, address, pmd, _pmd);
1081	update_mmu_cache_pmd(vma, address, pmd);
 
1082	spin_unlock(pmd_ptl);
1083
1084	*hpage = NULL;
1085
1086	khugepaged_pages_collapsed++;
1087	result = SCAN_SUCCEED;
1088out_up_write:
1089	up_write(&mm->mmap_sem);
1090out_nolock:
1091	trace_mm_collapse_huge_page(mm, isolated, result);
1092	return;
1093out:
1094	mem_cgroup_cancel_charge(new_page, memcg, true);
1095	goto out_up_write;
1096}
1097
1098static int khugepaged_scan_pmd(struct mm_struct *mm,
1099			       struct vm_area_struct *vma,
1100			       unsigned long address,
1101			       struct page **hpage)
1102{
1103	pmd_t *pmd;
1104	pte_t *pte, *_pte;
1105	int ret = 0, none_or_zero = 0, result = 0, referenced = 0;
 
1106	struct page *page = NULL;
 
1107	unsigned long _address;
1108	spinlock_t *ptl;
1109	int node = NUMA_NO_NODE, unmapped = 0;
1110	bool writable = false;
1111
1112	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1113
1114	pmd = mm_find_pmd(mm, address);
1115	if (!pmd) {
 
 
 
 
 
 
1116		result = SCAN_PMD_NULL;
1117		goto out;
1118	}
1119
1120	memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
1121	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1122	for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
1123	     _pte++, _address += PAGE_SIZE) {
1124		pte_t pteval = *_pte;
1125		if (is_swap_pte(pteval)) {
1126			if (++unmapped <= khugepaged_max_ptes_swap) {
 
 
 
 
 
 
 
 
 
 
 
1127				continue;
1128			} else {
1129				result = SCAN_EXCEED_SWAP_PTE;
 
1130				goto out_unmap;
1131			}
1132		}
1133		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
 
1134			if (!userfaultfd_armed(vma) &&
1135			    ++none_or_zero <= khugepaged_max_ptes_none) {
 
1136				continue;
1137			} else {
1138				result = SCAN_EXCEED_NONE_PTE;
 
1139				goto out_unmap;
1140			}
1141		}
1142		if (!pte_present(pteval)) {
1143			result = SCAN_PTE_NON_PRESENT;
 
 
 
 
 
 
 
 
 
1144			goto out_unmap;
1145		}
1146		if (pte_write(pteval))
1147			writable = true;
1148
1149		page = vm_normal_page(vma, _address, pteval);
1150		if (unlikely(!page)) {
1151			result = SCAN_PAGE_NULL;
1152			goto out_unmap;
1153		}
 
1154
1155		/* TODO: teach khugepaged to collapse THP mapped with pte */
1156		if (PageCompound(page)) {
1157			result = SCAN_PAGE_COMPOUND;
1158			goto out_unmap;
1159		}
1160
1161		/*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1162		 * Record which node the original page is from and save this
1163		 * information to khugepaged_node_load[].
1164		 * Khupaged will allocate hugepage from the node has the max
1165		 * hit record.
1166		 */
1167		node = page_to_nid(page);
1168		if (khugepaged_scan_abort(node)) {
1169			result = SCAN_SCAN_ABORT;
1170			goto out_unmap;
1171		}
1172		khugepaged_node_load[node]++;
1173		if (!PageLRU(page)) {
1174			result = SCAN_PAGE_LRU;
1175			goto out_unmap;
1176		}
1177		if (PageLocked(page)) {
1178			result = SCAN_PAGE_LOCK;
1179			goto out_unmap;
1180		}
1181		if (!PageAnon(page)) {
1182			result = SCAN_PAGE_ANON;
1183			goto out_unmap;
1184		}
1185
1186		/*
1187		 * cannot use mapcount: can't collapse if there's a gup pin.
1188		 * The page must only be referenced by the scanned process
1189		 * and page swap cache.
 
 
 
 
 
1190		 */
1191		if (page_count(page) != 1 + PageSwapCache(page)) {
1192			result = SCAN_PAGE_COUNT;
1193			goto out_unmap;
1194		}
1195		if (pte_young(pteval) ||
1196		    page_is_young(page) || PageReferenced(page) ||
1197		    mmu_notifier_test_young(vma->vm_mm, address))
 
 
 
 
 
 
1198			referenced++;
1199	}
1200	if (writable) {
1201		if (referenced) {
1202			result = SCAN_SUCCEED;
1203			ret = 1;
1204		} else {
1205			result = SCAN_LACK_REFERENCED_PAGE;
1206		}
1207	} else {
1208		result = SCAN_PAGE_RO;
 
 
 
 
 
 
1209	}
1210out_unmap:
1211	pte_unmap_unlock(pte, ptl);
1212	if (ret) {
1213		node = khugepaged_find_target_node();
1214		/* collapse_huge_page will return with the mmap_sem released */
1215		collapse_huge_page(mm, address, hpage, node, referenced);
 
1216	}
1217out:
1218	trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
1219				     none_or_zero, result, unmapped);
1220	return ret;
1221}
1222
1223static void collect_mm_slot(struct mm_slot *mm_slot)
1224{
1225	struct mm_struct *mm = mm_slot->mm;
 
1226
1227	VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
1228
1229	if (khugepaged_test_exit(mm)) {
1230		/* free mm_slot */
1231		hash_del(&mm_slot->hash);
1232		list_del(&mm_slot->mm_node);
1233
1234		/*
1235		 * Not strictly needed because the mm exited already.
1236		 *
1237		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1238		 */
1239
1240		/* khugepaged_mm_lock actually not necessary for the below */
1241		free_mm_slot(mm_slot);
1242		mmdrop(mm);
1243	}
1244}
1245
1246#if defined(CONFIG_SHMEM) && defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1247static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1248{
1249	struct vm_area_struct *vma;
1250	unsigned long addr;
1251	pmd_t *pmd, _pmd;
1252
1253	i_mmap_lock_write(mapping);
1254	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1255		/* probably overkill */
1256		if (vma->anon_vma)
 
 
 
 
 
 
 
 
 
 
 
 
1257			continue;
 
1258		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1259		if (addr & ~HPAGE_PMD_MASK)
 
1260			continue;
1261		if (vma->vm_end < addr + HPAGE_PMD_SIZE)
 
 
1262			continue;
1263		pmd = mm_find_pmd(vma->vm_mm, addr);
1264		if (!pmd)
1265			continue;
1266		/*
1267		 * We need exclusive mmap_sem to retract page table.
1268		 * If trylock fails we would end up with pte-mapped THP after
1269		 * re-fault. Not ideal, but it's more important to not disturb
1270		 * the system too much.
1271		 */
1272		if (down_write_trylock(&vma->vm_mm->mmap_sem)) {
1273			spinlock_t *ptl = pmd_lock(vma->vm_mm, pmd);
1274			/* assume page table is clear */
1275			_pmd = pmdp_collapse_flush(vma, addr, pmd);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1276			spin_unlock(ptl);
1277			up_write(&vma->vm_mm->mmap_sem);
1278			mm_dec_nr_ptes(vma->vm_mm);
1279			pte_free(vma->vm_mm, pmd_pgtable(_pmd));
 
 
 
 
 
1280		}
1281	}
1282	i_mmap_unlock_write(mapping);
1283}
1284
1285/**
1286 * collapse_shmem - collapse small tmpfs/shmem pages into huge one.
 
 
 
 
 
 
1287 *
1288 * Basic scheme is simple, details are more complex:
1289 *  - allocate and freeze a new huge page;
1290 *  - scan over radix tree replacing old pages the new one
1291 *    + swap in pages if necessary;
1292 *    + fill in gaps;
1293 *    + keep old pages around in case if rollback is required;
1294 *  - if replacing succeed:
1295 *    + copy data over;
 
 
 
1296 *    + free old pages;
1297 *    + unfreeze huge page;
1298 *  - if replacing failed;
1299 *    + put all pages back and unfreeze them;
1300 *    + restore gaps in the radix-tree;
1301 *    + free huge page;
1302 */
1303static void collapse_shmem(struct mm_struct *mm,
1304		struct address_space *mapping, pgoff_t start,
1305		struct page **hpage, int node)
1306{
1307	gfp_t gfp;
1308	struct page *page, *new_page, *tmp;
1309	struct mem_cgroup *memcg;
1310	pgoff_t index, end = start + HPAGE_PMD_NR;
1311	LIST_HEAD(pagelist);
1312	struct radix_tree_iter iter;
1313	void **slot;
1314	int nr_none = 0, result = SCAN_SUCCEED;
 
1315
 
1316	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1317
1318	/* Only allocate from the target node */
1319	gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
1320
1321	new_page = khugepaged_alloc_page(hpage, gfp, node);
1322	if (!new_page) {
1323		result = SCAN_ALLOC_HUGE_PAGE_FAIL;
1324		goto out;
1325	}
1326
1327	if (unlikely(mem_cgroup_try_charge(new_page, mm, gfp, &memcg, true))) {
1328		result = SCAN_CGROUP_CHARGE_FAIL;
1329		goto out;
1330	}
1331
1332	new_page->index = start;
1333	new_page->mapping = mapping;
1334	__SetPageSwapBacked(new_page);
1335	__SetPageLocked(new_page);
1336	BUG_ON(!page_ref_freeze(new_page, 1));
1337
 
 
 
 
 
1338
1339	/*
1340	 * At this point the new_page is 'frozen' (page_count() is zero), locked
1341	 * and not up-to-date. It's safe to insert it into radix tree, because
1342	 * nobody would be able to map it or use it in other way until we
1343	 * unfreeze it.
1344	 */
1345
1346	index = start;
1347	xa_lock_irq(&mapping->i_pages);
1348	radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1349		int n = min(iter.index, end) - index;
1350
1351		/*
1352		 * Handle holes in the radix tree: charge it from shmem and
1353		 * insert relevant subpage of new_page into the radix-tree.
1354		 */
1355		if (n && !shmem_charge(mapping->host, n)) {
1356			result = SCAN_FAIL;
1357			break;
 
 
 
 
1358		}
1359		nr_none += n;
1360		for (; index < min(iter.index, end); index++) {
1361			radix_tree_insert(&mapping->i_pages, index,
1362					new_page + (index % HPAGE_PMD_NR));
1363		}
1364
1365		/* We are done. */
1366		if (index >= end)
1367			break;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1368
1369		page = radix_tree_deref_slot_protected(slot,
1370				&mapping->i_pages.xa_lock);
1371		if (radix_tree_exceptional_entry(page) || !PageUptodate(page)) {
1372			xa_unlock_irq(&mapping->i_pages);
1373			/* swap in or instantiate fallocated page */
1374			if (shmem_getpage(mapping->host, index, &page,
1375						SGP_NOHUGE)) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1376				result = SCAN_FAIL;
1377				goto tree_unlocked;
 
 
 
 
 
 
1378			}
1379			xa_lock_irq(&mapping->i_pages);
1380		} else if (trylock_page(page)) {
1381			get_page(page);
1382		} else {
1383			result = SCAN_PAGE_LOCK;
1384			break;
1385		}
1386
1387		/*
1388		 * The page must be locked, so we can drop the i_pages lock
1389		 * without racing with truncate.
1390		 */
1391		VM_BUG_ON_PAGE(!PageLocked(page), page);
1392		VM_BUG_ON_PAGE(!PageUptodate(page), page);
1393		VM_BUG_ON_PAGE(PageTransCompound(page), page);
1394
1395		if (page_mapping(page) != mapping) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1396			result = SCAN_TRUNCATED;
1397			goto out_unlock;
1398		}
1399		xa_unlock_irq(&mapping->i_pages);
1400
1401		if (isolate_lru_page(page)) {
 
 
 
 
 
 
 
 
 
 
 
1402			result = SCAN_DEL_PAGE_LRU;
1403			goto out_isolate_failed;
1404		}
1405
1406		if (page_mapped(page))
1407			unmap_mapping_pages(mapping, index, 1, false);
 
 
 
 
 
 
 
1408
1409		xa_lock_irq(&mapping->i_pages);
1410
1411		slot = radix_tree_lookup_slot(&mapping->i_pages, index);
1412		VM_BUG_ON_PAGE(page != radix_tree_deref_slot_protected(slot,
1413					&mapping->i_pages.xa_lock), page);
1414		VM_BUG_ON_PAGE(page_mapped(page), page);
1415
1416		/*
1417		 * The page is expected to have page_count() == 3:
1418		 *  - we hold a pin on it;
1419		 *  - one reference from radix tree;
1420		 *  - one from isolate_lru_page;
 
 
 
 
 
1421		 */
1422		if (!page_ref_freeze(page, 3)) {
1423			result = SCAN_PAGE_COUNT;
1424			goto out_lru;
 
 
1425		}
1426
1427		/*
1428		 * Add the page to the list to be able to undo the collapse if
1429		 * something go wrong.
1430		 */
1431		list_add_tail(&page->lru, &pagelist);
1432
1433		/* Finally, replace with the new page. */
1434		radix_tree_replace_slot(&mapping->i_pages, slot,
1435				new_page + (index % HPAGE_PMD_NR));
1436
1437		slot = radix_tree_iter_resume(slot, &iter);
1438		index++;
1439		continue;
1440out_lru:
1441		xa_unlock_irq(&mapping->i_pages);
1442		putback_lru_page(page);
1443out_isolate_failed:
1444		unlock_page(page);
1445		put_page(page);
1446		goto tree_unlocked;
1447out_unlock:
1448		unlock_page(page);
1449		put_page(page);
1450		break;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1451	}
1452
 
 
 
 
1453	/*
1454	 * Handle hole in radix tree at the end of the range.
1455	 * This code only triggers if there's nothing in radix tree
1456	 * beyond 'end'.
1457	 */
1458	if (result == SCAN_SUCCEED && index < end) {
1459		int n = end - index;
1460
1461		if (!shmem_charge(mapping->host, n)) {
1462			result = SCAN_FAIL;
1463			goto tree_locked;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1464		}
1465
1466		for (; index < end; index++) {
1467			radix_tree_insert(&mapping->i_pages, index,
1468					new_page + (index % HPAGE_PMD_NR));
 
 
 
 
1469		}
1470		nr_none += n;
 
 
 
 
1471	}
1472
1473tree_locked:
1474	xa_unlock_irq(&mapping->i_pages);
1475tree_unlocked:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1476
1477	if (result == SCAN_SUCCEED) {
1478		unsigned long flags;
1479		struct zone *zone = page_zone(new_page);
 
1480
1481		/*
1482		 * Replacing old pages with new one has succeed, now we need to
1483		 * copy the content and free old pages.
 
 
 
 
 
 
 
 
 
1484		 */
1485		list_for_each_entry_safe(page, tmp, &pagelist, lru) {
1486			copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
1487					page);
1488			list_del(&page->lru);
1489			unlock_page(page);
1490			page_ref_unfreeze(page, 1);
1491			page->mapping = NULL;
1492			ClearPageActive(page);
1493			ClearPageUnevictable(page);
1494			put_page(page);
1495		}
1496
1497		local_irq_save(flags);
1498		__inc_node_page_state(new_page, NR_SHMEM_THPS);
1499		if (nr_none) {
1500			__mod_node_page_state(zone->zone_pgdat, NR_FILE_PAGES, nr_none);
1501			__mod_node_page_state(zone->zone_pgdat, NR_SHMEM, nr_none);
 
 
 
 
 
 
1502		}
1503		local_irq_restore(flags);
 
 
1504
1505		/*
1506		 * Remove pte page tables, so we can re-faulti
1507		 * the page as huge.
1508		 */
1509		retract_page_tables(mapping, start);
 
 
 
 
 
1510
1511		/* Everything is ready, let's unfreeze the new_page */
1512		set_page_dirty(new_page);
1513		SetPageUptodate(new_page);
1514		page_ref_unfreeze(new_page, HPAGE_PMD_NR);
1515		mem_cgroup_commit_charge(new_page, memcg, false, true);
1516		lru_cache_add_anon(new_page);
1517		unlock_page(new_page);
1518
1519		*hpage = NULL;
1520	} else {
1521		/* Something went wrong: rollback changes to the radix-tree */
1522		shmem_uncharge(mapping->host, nr_none);
1523		xa_lock_irq(&mapping->i_pages);
1524		radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1525			if (iter.index >= end)
1526				break;
1527			page = list_first_entry_or_null(&pagelist,
1528					struct page, lru);
1529			if (!page || iter.index < page->index) {
1530				if (!nr_none)
1531					break;
1532				nr_none--;
1533				/* Put holes back where they were */
1534				radix_tree_delete(&mapping->i_pages, iter.index);
1535				continue;
1536			}
1537
1538			VM_BUG_ON_PAGE(page->index != iter.index, page);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1539
1540			/* Unfreeze the page. */
1541			list_del(&page->lru);
1542			page_ref_unfreeze(page, 2);
1543			radix_tree_replace_slot(&mapping->i_pages, slot, page);
1544			slot = radix_tree_iter_resume(slot, &iter);
1545			xa_unlock_irq(&mapping->i_pages);
1546			putback_lru_page(page);
1547			unlock_page(page);
1548			xa_lock_irq(&mapping->i_pages);
1549		}
1550		VM_BUG_ON(nr_none);
1551		xa_unlock_irq(&mapping->i_pages);
1552
1553		/* Unfreeze new_page, caller would take care about freeing it */
1554		page_ref_unfreeze(new_page, 1);
1555		mem_cgroup_cancel_charge(new_page, memcg, true);
1556		unlock_page(new_page);
1557		new_page->mapping = NULL;
1558	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1559out:
1560	VM_BUG_ON(!list_empty(&pagelist));
1561	/* TODO: tracepoints */
 
1562}
1563
1564static void khugepaged_scan_shmem(struct mm_struct *mm,
1565		struct address_space *mapping,
1566		pgoff_t start, struct page **hpage)
1567{
1568	struct page *page = NULL;
1569	struct radix_tree_iter iter;
1570	void **slot;
1571	int present, swap;
1572	int node = NUMA_NO_NODE;
1573	int result = SCAN_SUCCEED;
1574
1575	present = 0;
1576	swap = 0;
1577	memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
 
1578	rcu_read_lock();
1579	radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1580		if (iter.index >= start + HPAGE_PMD_NR)
1581			break;
1582
1583		page = radix_tree_deref_slot(slot);
1584		if (radix_tree_deref_retry(page)) {
1585			slot = radix_tree_iter_retry(&iter);
1586			continue;
1587		}
1588
1589		if (radix_tree_exception(page)) {
1590			if (++swap > khugepaged_max_ptes_swap) {
 
 
1591				result = SCAN_EXCEED_SWAP_PTE;
 
1592				break;
1593			}
1594			continue;
1595		}
1596
1597		if (PageTransCompound(page)) {
1598			result = SCAN_PAGE_COMPOUND;
 
 
 
 
 
 
 
 
1599			break;
1600		}
1601
1602		node = page_to_nid(page);
1603		if (khugepaged_scan_abort(node)) {
1604			result = SCAN_SCAN_ABORT;
1605			break;
1606		}
1607		khugepaged_node_load[node]++;
1608
1609		if (!PageLRU(page)) {
1610			result = SCAN_PAGE_LRU;
1611			break;
1612		}
1613
1614		if (page_count(page) != 1 + page_mapcount(page)) {
1615			result = SCAN_PAGE_COUNT;
1616			break;
1617		}
1618
1619		/*
1620		 * We probably should check if the page is referenced here, but
1621		 * nobody would transfer pte_young() to PageReferenced() for us.
1622		 * And rmap walk here is just too costly...
 
1623		 */
1624
1625		present++;
1626
1627		if (need_resched()) {
1628			slot = radix_tree_iter_resume(slot, &iter);
1629			cond_resched_rcu();
1630		}
1631	}
1632	rcu_read_unlock();
1633
1634	if (result == SCAN_SUCCEED) {
1635		if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
 
1636			result = SCAN_EXCEED_NONE_PTE;
 
1637		} else {
1638			node = khugepaged_find_target_node();
1639			collapse_shmem(mm, mapping, start, hpage, node);
1640		}
1641	}
1642
1643	/* TODO: tracepoints */
 
1644}
1645#else
1646static void khugepaged_scan_shmem(struct mm_struct *mm,
1647		struct address_space *mapping,
1648		pgoff_t start, struct page **hpage)
1649{
1650	BUILD_BUG();
1651}
1652#endif
1653
1654static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
1655					    struct page **hpage)
1656	__releases(&khugepaged_mm_lock)
1657	__acquires(&khugepaged_mm_lock)
1658{
1659	struct mm_slot *mm_slot;
 
 
1660	struct mm_struct *mm;
1661	struct vm_area_struct *vma;
1662	int progress = 0;
1663
1664	VM_BUG_ON(!pages);
1665	VM_BUG_ON(NR_CPUS != 1 && !spin_is_locked(&khugepaged_mm_lock));
 
1666
1667	if (khugepaged_scan.mm_slot)
1668		mm_slot = khugepaged_scan.mm_slot;
1669	else {
1670		mm_slot = list_entry(khugepaged_scan.mm_head.next,
 
1671				     struct mm_slot, mm_node);
 
1672		khugepaged_scan.address = 0;
1673		khugepaged_scan.mm_slot = mm_slot;
1674	}
1675	spin_unlock(&khugepaged_mm_lock);
1676
1677	mm = mm_slot->mm;
1678	/*
1679	 * Don't wait for semaphore (to avoid long wait times).  Just move to
1680	 * the next mm on the list.
1681	 */
1682	vma = NULL;
1683	if (unlikely(!down_read_trylock(&mm->mmap_sem)))
1684		goto breakouterloop_mmap_sem;
1685	if (likely(!khugepaged_test_exit(mm)))
1686		vma = find_vma(mm, khugepaged_scan.address);
1687
1688	progress++;
1689	for (; vma; vma = vma->vm_next) {
 
 
 
 
1690		unsigned long hstart, hend;
1691
1692		cond_resched();
1693		if (unlikely(khugepaged_test_exit(mm))) {
1694			progress++;
1695			break;
1696		}
1697		if (!hugepage_vma_check(vma)) {
 
1698skip:
1699			progress++;
1700			continue;
1701		}
1702		hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
1703		hend = vma->vm_end & HPAGE_PMD_MASK;
1704		if (hstart >= hend)
1705			goto skip;
1706		if (khugepaged_scan.address > hend)
1707			goto skip;
1708		if (khugepaged_scan.address < hstart)
1709			khugepaged_scan.address = hstart;
1710		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
1711
1712		while (khugepaged_scan.address < hend) {
1713			int ret;
 
1714			cond_resched();
1715			if (unlikely(khugepaged_test_exit(mm)))
1716				goto breakouterloop;
1717
1718			VM_BUG_ON(khugepaged_scan.address < hstart ||
1719				  khugepaged_scan.address + HPAGE_PMD_SIZE >
1720				  hend);
1721			if (shmem_file(vma->vm_file)) {
1722				struct file *file;
1723				pgoff_t pgoff = linear_page_index(vma,
1724						khugepaged_scan.address);
1725				if (!shmem_huge_enabled(vma))
1726					goto skip;
1727				file = get_file(vma->vm_file);
1728				up_read(&mm->mmap_sem);
1729				ret = 1;
1730				khugepaged_scan_shmem(mm, file->f_mapping,
1731						pgoff, hpage);
1732				fput(file);
 
 
 
 
 
 
 
 
 
 
1733			} else {
1734				ret = khugepaged_scan_pmd(mm, vma,
1735						khugepaged_scan.address,
1736						hpage);
1737			}
 
 
 
 
1738			/* move to next address */
1739			khugepaged_scan.address += HPAGE_PMD_SIZE;
1740			progress += HPAGE_PMD_NR;
1741			if (ret)
1742				/* we released mmap_sem so break loop */
1743				goto breakouterloop_mmap_sem;
 
 
 
 
 
 
1744			if (progress >= pages)
1745				goto breakouterloop;
1746		}
1747	}
1748breakouterloop:
1749	up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */
1750breakouterloop_mmap_sem:
1751
1752	spin_lock(&khugepaged_mm_lock);
1753	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
1754	/*
1755	 * Release the current mm_slot if this mm is about to die, or
1756	 * if we scanned all vmas of this mm.
1757	 */
1758	if (khugepaged_test_exit(mm) || !vma) {
1759		/*
1760		 * Make sure that if mm_users is reaching zero while
1761		 * khugepaged runs here, khugepaged_exit will find
1762		 * mm_slot not pointing to the exiting mm.
1763		 */
1764		if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
1765			khugepaged_scan.mm_slot = list_entry(
1766				mm_slot->mm_node.next,
1767				struct mm_slot, mm_node);
 
1768			khugepaged_scan.address = 0;
1769		} else {
1770			khugepaged_scan.mm_slot = NULL;
1771			khugepaged_full_scans++;
1772		}
1773
1774		collect_mm_slot(mm_slot);
1775	}
1776
1777	return progress;
1778}
1779
1780static int khugepaged_has_work(void)
1781{
1782	return !list_empty(&khugepaged_scan.mm_head) &&
1783		khugepaged_enabled();
1784}
1785
1786static int khugepaged_wait_event(void)
1787{
1788	return !list_empty(&khugepaged_scan.mm_head) ||
1789		kthread_should_stop();
1790}
1791
1792static void khugepaged_do_scan(void)
1793{
1794	struct page *hpage = NULL;
1795	unsigned int progress = 0, pass_through_head = 0;
1796	unsigned int pages = khugepaged_pages_to_scan;
1797	bool wait = true;
 
1798
1799	barrier(); /* write khugepaged_pages_to_scan to local stack */
1800
1801	while (progress < pages) {
1802		if (!khugepaged_prealloc_page(&hpage, &wait))
1803			break;
1804
 
1805		cond_resched();
1806
1807		if (unlikely(kthread_should_stop() || try_to_freeze()))
1808			break;
1809
1810		spin_lock(&khugepaged_mm_lock);
1811		if (!khugepaged_scan.mm_slot)
1812			pass_through_head++;
1813		if (khugepaged_has_work() &&
1814		    pass_through_head < 2)
1815			progress += khugepaged_scan_mm_slot(pages - progress,
1816							    &hpage);
1817		else
1818			progress = pages;
1819		spin_unlock(&khugepaged_mm_lock);
1820	}
1821
1822	if (!IS_ERR_OR_NULL(hpage))
1823		put_page(hpage);
 
 
 
 
 
 
 
 
 
 
 
 
1824}
1825
1826static bool khugepaged_should_wakeup(void)
1827{
1828	return kthread_should_stop() ||
1829	       time_after_eq(jiffies, khugepaged_sleep_expire);
1830}
1831
1832static void khugepaged_wait_work(void)
1833{
1834	if (khugepaged_has_work()) {
1835		const unsigned long scan_sleep_jiffies =
1836			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
1837
1838		if (!scan_sleep_jiffies)
1839			return;
1840
1841		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
1842		wait_event_freezable_timeout(khugepaged_wait,
1843					     khugepaged_should_wakeup(),
1844					     scan_sleep_jiffies);
1845		return;
1846	}
1847
1848	if (khugepaged_enabled())
1849		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
1850}
1851
1852static int khugepaged(void *none)
1853{
1854	struct mm_slot *mm_slot;
1855
1856	set_freezable();
1857	set_user_nice(current, MAX_NICE);
1858
1859	while (!kthread_should_stop()) {
1860		khugepaged_do_scan();
1861		khugepaged_wait_work();
1862	}
1863
1864	spin_lock(&khugepaged_mm_lock);
1865	mm_slot = khugepaged_scan.mm_slot;
1866	khugepaged_scan.mm_slot = NULL;
1867	if (mm_slot)
1868		collect_mm_slot(mm_slot);
1869	spin_unlock(&khugepaged_mm_lock);
1870	return 0;
1871}
1872
1873static void set_recommended_min_free_kbytes(void)
1874{
1875	struct zone *zone;
1876	int nr_zones = 0;
1877	unsigned long recommended_min;
1878
 
 
 
 
 
1879	for_each_populated_zone(zone) {
1880		/*
1881		 * We don't need to worry about fragmentation of
1882		 * ZONE_MOVABLE since it only has movable pages.
1883		 */
1884		if (zone_idx(zone) > gfp_zone(GFP_USER))
1885			continue;
1886
1887		nr_zones++;
1888	}
1889
1890	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
1891	recommended_min = pageblock_nr_pages * nr_zones * 2;
1892
1893	/*
1894	 * Make sure that on average at least two pageblocks are almost free
1895	 * of another type, one for a migratetype to fall back to and a
1896	 * second to avoid subsequent fallbacks of other types There are 3
1897	 * MIGRATE_TYPES we care about.
1898	 */
1899	recommended_min += pageblock_nr_pages * nr_zones *
1900			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
1901
1902	/* don't ever allow to reserve more than 5% of the lowmem */
1903	recommended_min = min(recommended_min,
1904			      (unsigned long) nr_free_buffer_pages() / 20);
1905	recommended_min <<= (PAGE_SHIFT-10);
1906
1907	if (recommended_min > min_free_kbytes) {
1908		if (user_min_free_kbytes >= 0)
1909			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
1910				min_free_kbytes, recommended_min);
1911
1912		min_free_kbytes = recommended_min;
1913	}
 
 
1914	setup_per_zone_wmarks();
1915}
1916
1917int start_stop_khugepaged(void)
1918{
1919	static struct task_struct *khugepaged_thread __read_mostly;
1920	static DEFINE_MUTEX(khugepaged_mutex);
1921	int err = 0;
1922
1923	mutex_lock(&khugepaged_mutex);
1924	if (khugepaged_enabled()) {
1925		if (!khugepaged_thread)
1926			khugepaged_thread = kthread_run(khugepaged, NULL,
1927							"khugepaged");
1928		if (IS_ERR(khugepaged_thread)) {
1929			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
1930			err = PTR_ERR(khugepaged_thread);
1931			khugepaged_thread = NULL;
1932			goto fail;
1933		}
1934
1935		if (!list_empty(&khugepaged_scan.mm_head))
1936			wake_up_interruptible(&khugepaged_wait);
1937
1938		set_recommended_min_free_kbytes();
1939	} else if (khugepaged_thread) {
1940		kthread_stop(khugepaged_thread);
1941		khugepaged_thread = NULL;
1942	}
 
1943fail:
1944	mutex_unlock(&khugepaged_mutex);
1945	return err;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1946}
v6.13.7
   1// SPDX-License-Identifier: GPL-2.0
   2#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
   3
   4#include <linux/mm.h>
   5#include <linux/sched.h>
   6#include <linux/sched/mm.h>
 
   7#include <linux/mmu_notifier.h>
   8#include <linux/rmap.h>
   9#include <linux/swap.h>
  10#include <linux/mm_inline.h>
  11#include <linux/kthread.h>
  12#include <linux/khugepaged.h>
  13#include <linux/freezer.h>
  14#include <linux/mman.h>
  15#include <linux/hashtable.h>
  16#include <linux/userfaultfd_k.h>
  17#include <linux/page_idle.h>
  18#include <linux/page_table_check.h>
  19#include <linux/rcupdate_wait.h>
  20#include <linux/swapops.h>
  21#include <linux/shmem_fs.h>
  22#include <linux/dax.h>
  23#include <linux/ksm.h>
  24
  25#include <asm/tlb.h>
  26#include <asm/pgalloc.h>
  27#include "internal.h"
  28#include "mm_slot.h"
  29
  30enum scan_result {
  31	SCAN_FAIL,
  32	SCAN_SUCCEED,
  33	SCAN_PMD_NULL,
  34	SCAN_PMD_NONE,
  35	SCAN_PMD_MAPPED,
  36	SCAN_EXCEED_NONE_PTE,
  37	SCAN_EXCEED_SWAP_PTE,
  38	SCAN_EXCEED_SHARED_PTE,
  39	SCAN_PTE_NON_PRESENT,
  40	SCAN_PTE_UFFD_WP,
  41	SCAN_PTE_MAPPED_HUGEPAGE,
  42	SCAN_PAGE_RO,
  43	SCAN_LACK_REFERENCED_PAGE,
  44	SCAN_PAGE_NULL,
  45	SCAN_SCAN_ABORT,
  46	SCAN_PAGE_COUNT,
  47	SCAN_PAGE_LRU,
  48	SCAN_PAGE_LOCK,
  49	SCAN_PAGE_ANON,
  50	SCAN_PAGE_COMPOUND,
  51	SCAN_ANY_PROCESS,
  52	SCAN_VMA_NULL,
  53	SCAN_VMA_CHECK,
  54	SCAN_ADDRESS_RANGE,
 
  55	SCAN_DEL_PAGE_LRU,
  56	SCAN_ALLOC_HUGE_PAGE_FAIL,
  57	SCAN_CGROUP_CHARGE_FAIL,
 
  58	SCAN_TRUNCATED,
  59	SCAN_PAGE_HAS_PRIVATE,
  60	SCAN_STORE_FAILED,
  61	SCAN_COPY_MC,
  62	SCAN_PAGE_FILLED,
  63};
  64
  65#define CREATE_TRACE_POINTS
  66#include <trace/events/huge_memory.h>
  67
  68static struct task_struct *khugepaged_thread __read_mostly;
  69static DEFINE_MUTEX(khugepaged_mutex);
  70
  71/* default scan 8*512 pte (or vmas) every 30 second */
  72static unsigned int khugepaged_pages_to_scan __read_mostly;
  73static unsigned int khugepaged_pages_collapsed;
  74static unsigned int khugepaged_full_scans;
  75static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
  76/* during fragmentation poll the hugepage allocator once every minute */
  77static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
  78static unsigned long khugepaged_sleep_expire;
  79static DEFINE_SPINLOCK(khugepaged_mm_lock);
  80static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
  81/*
  82 * default collapse hugepages if there is at least one pte mapped like
  83 * it would have happened if the vma was large enough during page
  84 * fault.
  85 *
  86 * Note that these are only respected if collapse was initiated by khugepaged.
  87 */
  88unsigned int khugepaged_max_ptes_none __read_mostly;
  89static unsigned int khugepaged_max_ptes_swap __read_mostly;
  90static unsigned int khugepaged_max_ptes_shared __read_mostly;
  91
  92#define MM_SLOTS_HASH_BITS 10
  93static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
  94
  95static struct kmem_cache *mm_slot_cache __ro_after_init;
  96
  97struct collapse_control {
  98	bool is_khugepaged;
  99
 100	/* Num pages scanned per node */
 101	u32 node_load[MAX_NUMNODES];
 102
 103	/* nodemask for allocation fallback */
 104	nodemask_t alloc_nmask;
 105};
 106
 107/**
 108 * struct khugepaged_mm_slot - khugepaged information per mm that is being scanned
 109 * @slot: hash lookup from mm to mm_slot
 
 
 110 */
 111struct khugepaged_mm_slot {
 112	struct mm_slot slot;
 
 
 113};
 114
 115/**
 116 * struct khugepaged_scan - cursor for scanning
 117 * @mm_head: the head of the mm list to scan
 118 * @mm_slot: the current mm_slot we are scanning
 119 * @address: the next address inside that to be scanned
 120 *
 121 * There is only the one khugepaged_scan instance of this cursor structure.
 122 */
 123struct khugepaged_scan {
 124	struct list_head mm_head;
 125	struct khugepaged_mm_slot *mm_slot;
 126	unsigned long address;
 127};
 128
 129static struct khugepaged_scan khugepaged_scan = {
 130	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
 131};
 132
 133#ifdef CONFIG_SYSFS
 134static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
 135					 struct kobj_attribute *attr,
 136					 char *buf)
 137{
 138	return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs);
 139}
 140
 141static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
 142					  struct kobj_attribute *attr,
 143					  const char *buf, size_t count)
 144{
 145	unsigned int msecs;
 146	int err;
 147
 148	err = kstrtouint(buf, 10, &msecs);
 149	if (err)
 150		return -EINVAL;
 151
 152	khugepaged_scan_sleep_millisecs = msecs;
 153	khugepaged_sleep_expire = 0;
 154	wake_up_interruptible(&khugepaged_wait);
 155
 156	return count;
 157}
 158static struct kobj_attribute scan_sleep_millisecs_attr =
 159	__ATTR_RW(scan_sleep_millisecs);
 
 160
 161static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
 162					  struct kobj_attribute *attr,
 163					  char *buf)
 164{
 165	return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
 166}
 167
 168static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
 169					   struct kobj_attribute *attr,
 170					   const char *buf, size_t count)
 171{
 172	unsigned int msecs;
 173	int err;
 174
 175	err = kstrtouint(buf, 10, &msecs);
 176	if (err)
 177		return -EINVAL;
 178
 179	khugepaged_alloc_sleep_millisecs = msecs;
 180	khugepaged_sleep_expire = 0;
 181	wake_up_interruptible(&khugepaged_wait);
 182
 183	return count;
 184}
 185static struct kobj_attribute alloc_sleep_millisecs_attr =
 186	__ATTR_RW(alloc_sleep_millisecs);
 
 187
 188static ssize_t pages_to_scan_show(struct kobject *kobj,
 189				  struct kobj_attribute *attr,
 190				  char *buf)
 191{
 192	return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan);
 193}
 194static ssize_t pages_to_scan_store(struct kobject *kobj,
 195				   struct kobj_attribute *attr,
 196				   const char *buf, size_t count)
 197{
 198	unsigned int pages;
 199	int err;
 
 200
 201	err = kstrtouint(buf, 10, &pages);
 202	if (err || !pages)
 203		return -EINVAL;
 204
 205	khugepaged_pages_to_scan = pages;
 206
 207	return count;
 208}
 209static struct kobj_attribute pages_to_scan_attr =
 210	__ATTR_RW(pages_to_scan);
 
 211
 212static ssize_t pages_collapsed_show(struct kobject *kobj,
 213				    struct kobj_attribute *attr,
 214				    char *buf)
 215{
 216	return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed);
 217}
 218static struct kobj_attribute pages_collapsed_attr =
 219	__ATTR_RO(pages_collapsed);
 220
 221static ssize_t full_scans_show(struct kobject *kobj,
 222			       struct kobj_attribute *attr,
 223			       char *buf)
 224{
 225	return sysfs_emit(buf, "%u\n", khugepaged_full_scans);
 226}
 227static struct kobj_attribute full_scans_attr =
 228	__ATTR_RO(full_scans);
 229
 230static ssize_t defrag_show(struct kobject *kobj,
 231			   struct kobj_attribute *attr, char *buf)
 232{
 233	return single_hugepage_flag_show(kobj, attr, buf,
 234					 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
 235}
 236static ssize_t defrag_store(struct kobject *kobj,
 237			    struct kobj_attribute *attr,
 238			    const char *buf, size_t count)
 239{
 240	return single_hugepage_flag_store(kobj, attr, buf, count,
 241				 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
 242}
 243static struct kobj_attribute khugepaged_defrag_attr =
 244	__ATTR_RW(defrag);
 
 245
 246/*
 247 * max_ptes_none controls if khugepaged should collapse hugepages over
 248 * any unmapped ptes in turn potentially increasing the memory
 249 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
 250 * reduce the available free memory in the system as it
 251 * runs. Increasing max_ptes_none will instead potentially reduce the
 252 * free memory in the system during the khugepaged scan.
 253 */
 254static ssize_t max_ptes_none_show(struct kobject *kobj,
 255				  struct kobj_attribute *attr,
 256				  char *buf)
 257{
 258	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none);
 259}
 260static ssize_t max_ptes_none_store(struct kobject *kobj,
 261				   struct kobj_attribute *attr,
 262				   const char *buf, size_t count)
 263{
 264	int err;
 265	unsigned long max_ptes_none;
 266
 267	err = kstrtoul(buf, 10, &max_ptes_none);
 268	if (err || max_ptes_none > HPAGE_PMD_NR - 1)
 269		return -EINVAL;
 270
 271	khugepaged_max_ptes_none = max_ptes_none;
 272
 273	return count;
 274}
 275static struct kobj_attribute khugepaged_max_ptes_none_attr =
 276	__ATTR_RW(max_ptes_none);
 
 277
 278static ssize_t max_ptes_swap_show(struct kobject *kobj,
 279				  struct kobj_attribute *attr,
 280				  char *buf)
 281{
 282	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap);
 283}
 284
 285static ssize_t max_ptes_swap_store(struct kobject *kobj,
 286				   struct kobj_attribute *attr,
 287				   const char *buf, size_t count)
 288{
 289	int err;
 290	unsigned long max_ptes_swap;
 291
 292	err  = kstrtoul(buf, 10, &max_ptes_swap);
 293	if (err || max_ptes_swap > HPAGE_PMD_NR - 1)
 294		return -EINVAL;
 295
 296	khugepaged_max_ptes_swap = max_ptes_swap;
 297
 298	return count;
 299}
 300
 301static struct kobj_attribute khugepaged_max_ptes_swap_attr =
 302	__ATTR_RW(max_ptes_swap);
 303
 304static ssize_t max_ptes_shared_show(struct kobject *kobj,
 305				    struct kobj_attribute *attr,
 306				    char *buf)
 307{
 308	return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared);
 309}
 310
 311static ssize_t max_ptes_shared_store(struct kobject *kobj,
 312				     struct kobj_attribute *attr,
 313				     const char *buf, size_t count)
 314{
 315	int err;
 316	unsigned long max_ptes_shared;
 317
 318	err  = kstrtoul(buf, 10, &max_ptes_shared);
 319	if (err || max_ptes_shared > HPAGE_PMD_NR - 1)
 320		return -EINVAL;
 321
 322	khugepaged_max_ptes_shared = max_ptes_shared;
 323
 324	return count;
 325}
 326
 327static struct kobj_attribute khugepaged_max_ptes_shared_attr =
 328	__ATTR_RW(max_ptes_shared);
 329
 330static struct attribute *khugepaged_attr[] = {
 331	&khugepaged_defrag_attr.attr,
 332	&khugepaged_max_ptes_none_attr.attr,
 333	&khugepaged_max_ptes_swap_attr.attr,
 334	&khugepaged_max_ptes_shared_attr.attr,
 335	&pages_to_scan_attr.attr,
 336	&pages_collapsed_attr.attr,
 337	&full_scans_attr.attr,
 338	&scan_sleep_millisecs_attr.attr,
 339	&alloc_sleep_millisecs_attr.attr,
 
 340	NULL,
 341};
 342
 343struct attribute_group khugepaged_attr_group = {
 344	.attrs = khugepaged_attr,
 345	.name = "khugepaged",
 346};
 347#endif /* CONFIG_SYSFS */
 348
 
 
 349int hugepage_madvise(struct vm_area_struct *vma,
 350		     unsigned long *vm_flags, int advice)
 351{
 352	switch (advice) {
 353	case MADV_HUGEPAGE:
 354#ifdef CONFIG_S390
 355		/*
 356		 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
 357		 * can't handle this properly after s390_enable_sie, so we simply
 358		 * ignore the madvise to prevent qemu from causing a SIGSEGV.
 359		 */
 360		if (mm_has_pgste(vma->vm_mm))
 361			return 0;
 362#endif
 363		*vm_flags &= ~VM_NOHUGEPAGE;
 364		*vm_flags |= VM_HUGEPAGE;
 365		/*
 366		 * If the vma become good for khugepaged to scan,
 367		 * register it here without waiting a page fault that
 368		 * may not happen any time soon.
 369		 */
 370		khugepaged_enter_vma(vma, *vm_flags);
 
 
 371		break;
 372	case MADV_NOHUGEPAGE:
 373		*vm_flags &= ~VM_HUGEPAGE;
 374		*vm_flags |= VM_NOHUGEPAGE;
 375		/*
 376		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
 377		 * this vma even if we leave the mm registered in khugepaged if
 378		 * it got registered before VM_NOHUGEPAGE was set.
 379		 */
 380		break;
 381	}
 382
 383	return 0;
 384}
 385
 386int __init khugepaged_init(void)
 387{
 388	mm_slot_cache = KMEM_CACHE(khugepaged_mm_slot, 0);
 
 
 389	if (!mm_slot_cache)
 390		return -ENOMEM;
 391
 392	khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
 393	khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
 394	khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
 395	khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
 396
 397	return 0;
 398}
 399
 400void __init khugepaged_destroy(void)
 401{
 402	kmem_cache_destroy(mm_slot_cache);
 403}
 404
 405static inline int hpage_collapse_test_exit(struct mm_struct *mm)
 
 
 
 
 
 
 
 406{
 407	return atomic_read(&mm->mm_users) == 0;
 
 
 
 
 
 
 
 
 
 
 
 408}
 409
 410static inline int hpage_collapse_test_exit_or_disable(struct mm_struct *mm)
 
 411{
 412	return hpage_collapse_test_exit(mm) ||
 413	       test_bit(MMF_DISABLE_THP, &mm->flags);
 414}
 415
 416static bool hugepage_pmd_enabled(void)
 417{
 418	/*
 419	 * We cover the anon, shmem and the file-backed case here; file-backed
 420	 * hugepages, when configured in, are determined by the global control.
 421	 * Anon pmd-sized hugepages are determined by the pmd-size control.
 422	 * Shmem pmd-sized hugepages are also determined by its pmd-size control,
 423	 * except when the global shmem_huge is set to SHMEM_HUGE_DENY.
 424	 */
 425	if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) &&
 426	    hugepage_global_enabled())
 427		return true;
 428	if (test_bit(PMD_ORDER, &huge_anon_orders_always))
 429		return true;
 430	if (test_bit(PMD_ORDER, &huge_anon_orders_madvise))
 431		return true;
 432	if (test_bit(PMD_ORDER, &huge_anon_orders_inherit) &&
 433	    hugepage_global_enabled())
 434		return true;
 435	if (IS_ENABLED(CONFIG_SHMEM) && shmem_hpage_pmd_enabled())
 436		return true;
 437	return false;
 438}
 439
 440void __khugepaged_enter(struct mm_struct *mm)
 441{
 442	struct khugepaged_mm_slot *mm_slot;
 443	struct mm_slot *slot;
 444	int wakeup;
 445
 446	/* __khugepaged_exit() must not run from under us */
 447	VM_BUG_ON_MM(hpage_collapse_test_exit(mm), mm);
 448	if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags)))
 449		return;
 450
 451	mm_slot = mm_slot_alloc(mm_slot_cache);
 452	if (!mm_slot)
 453		return;
 454
 455	slot = &mm_slot->slot;
 
 
 
 
 
 456
 457	spin_lock(&khugepaged_mm_lock);
 458	mm_slot_insert(mm_slots_hash, mm, slot);
 459	/*
 460	 * Insert just behind the scanning cursor, to let the area settle
 461	 * down a little.
 462	 */
 463	wakeup = list_empty(&khugepaged_scan.mm_head);
 464	list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head);
 465	spin_unlock(&khugepaged_mm_lock);
 466
 467	mmgrab(mm);
 468	if (wakeup)
 469		wake_up_interruptible(&khugepaged_wait);
 
 
 470}
 471
 472void khugepaged_enter_vma(struct vm_area_struct *vma,
 473			  unsigned long vm_flags)
 474{
 475	if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) &&
 476	    hugepage_pmd_enabled()) {
 477		if (thp_vma_allowable_order(vma, vm_flags, TVA_ENFORCE_SYSFS,
 478					    PMD_ORDER))
 479			__khugepaged_enter(vma->vm_mm);
 480	}
 
 
 
 
 
 
 
 
 
 481}
 482
 483void __khugepaged_exit(struct mm_struct *mm)
 484{
 485	struct khugepaged_mm_slot *mm_slot;
 486	struct mm_slot *slot;
 487	int free = 0;
 488
 489	spin_lock(&khugepaged_mm_lock);
 490	slot = mm_slot_lookup(mm_slots_hash, mm);
 491	mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
 492	if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
 493		hash_del(&slot->hash);
 494		list_del(&slot->mm_node);
 495		free = 1;
 496	}
 497	spin_unlock(&khugepaged_mm_lock);
 498
 499	if (free) {
 500		clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
 501		mm_slot_free(mm_slot_cache, mm_slot);
 502		mmdrop(mm);
 503	} else if (mm_slot) {
 504		/*
 505		 * This is required to serialize against
 506		 * hpage_collapse_test_exit() (which is guaranteed to run
 507		 * under mmap sem read mode). Stop here (after we return all
 508		 * pagetables will be destroyed) until khugepaged has finished
 509		 * working on the pagetables under the mmap_lock.
 
 510		 */
 511		mmap_write_lock(mm);
 512		mmap_write_unlock(mm);
 513	}
 514}
 515
 516static void release_pte_folio(struct folio *folio)
 517{
 518	node_stat_mod_folio(folio,
 519			NR_ISOLATED_ANON + folio_is_file_lru(folio),
 520			-folio_nr_pages(folio));
 521	folio_unlock(folio);
 522	folio_putback_lru(folio);
 523}
 524
 525static void release_pte_pages(pte_t *pte, pte_t *_pte,
 526		struct list_head *compound_pagelist)
 527{
 528	struct folio *folio, *tmp;
 529
 530	while (--_pte >= pte) {
 531		pte_t pteval = ptep_get(_pte);
 532		unsigned long pfn;
 533
 534		if (pte_none(pteval))
 535			continue;
 536		pfn = pte_pfn(pteval);
 537		if (is_zero_pfn(pfn))
 538			continue;
 539		folio = pfn_folio(pfn);
 540		if (folio_test_large(folio))
 541			continue;
 542		release_pte_folio(folio);
 543	}
 544
 545	list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) {
 546		list_del(&folio->lru);
 547		release_pte_folio(folio);
 548	}
 549}
 550
 551static bool is_refcount_suitable(struct folio *folio)
 552{
 553	int expected_refcount = folio_mapcount(folio);
 554
 555	if (!folio_test_anon(folio) || folio_test_swapcache(folio))
 556		expected_refcount += folio_nr_pages(folio);
 557
 558	if (folio_test_private(folio))
 559		expected_refcount++;
 560
 561	return folio_ref_count(folio) == expected_refcount;
 562}
 563
 564static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 565					unsigned long address,
 566					pte_t *pte,
 567					struct collapse_control *cc,
 568					struct list_head *compound_pagelist)
 569{
 570	struct page *page = NULL;
 571	struct folio *folio = NULL;
 572	pte_t *_pte;
 573	int none_or_zero = 0, shared = 0, result = SCAN_FAIL, referenced = 0;
 574	bool writable = false;
 575
 576	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
 577	     _pte++, address += PAGE_SIZE) {
 578		pte_t pteval = ptep_get(_pte);
 579		if (pte_none(pteval) || (pte_present(pteval) &&
 580				is_zero_pfn(pte_pfn(pteval)))) {
 581			++none_or_zero;
 582			if (!userfaultfd_armed(vma) &&
 583			    (!cc->is_khugepaged ||
 584			     none_or_zero <= khugepaged_max_ptes_none)) {
 585				continue;
 586			} else {
 587				result = SCAN_EXCEED_NONE_PTE;
 588				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
 589				goto out;
 590			}
 591		}
 592		if (!pte_present(pteval)) {
 593			result = SCAN_PTE_NON_PRESENT;
 594			goto out;
 595		}
 596		if (pte_uffd_wp(pteval)) {
 597			result = SCAN_PTE_UFFD_WP;
 598			goto out;
 599		}
 600		page = vm_normal_page(vma, address, pteval);
 601		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
 602			result = SCAN_PAGE_NULL;
 603			goto out;
 604		}
 605
 606		folio = page_folio(page);
 607		VM_BUG_ON_FOLIO(!folio_test_anon(folio), folio);
 608
 609		/* See hpage_collapse_scan_pmd(). */
 610		if (folio_likely_mapped_shared(folio)) {
 611			++shared;
 612			if (cc->is_khugepaged &&
 613			    shared > khugepaged_max_ptes_shared) {
 614				result = SCAN_EXCEED_SHARED_PTE;
 615				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
 616				goto out;
 617			}
 618		}
 619
 620		if (folio_test_large(folio)) {
 621			struct folio *f;
 622
 623			/*
 624			 * Check if we have dealt with the compound page
 625			 * already
 626			 */
 627			list_for_each_entry(f, compound_pagelist, lru) {
 628				if (folio == f)
 629					goto next;
 630			}
 631		}
 632
 633		/*
 634		 * We can do it before folio_isolate_lru because the
 635		 * folio can't be freed from under us. NOTE: PG_lock
 636		 * is needed to serialize against split_huge_page
 637		 * when invoked from the VM.
 638		 */
 639		if (!folio_trylock(folio)) {
 640			result = SCAN_PAGE_LOCK;
 641			goto out;
 642		}
 643
 644		/*
 645		 * Check if the page has any GUP (or other external) pins.
 646		 *
 647		 * The page table that maps the page has been already unlinked
 648		 * from the page table tree and this process cannot get
 649		 * an additional pin on the page.
 650		 *
 651		 * New pins can come later if the page is shared across fork,
 652		 * but not from this process. The other process cannot write to
 653		 * the page, only trigger CoW.
 654		 */
 655		if (!is_refcount_suitable(folio)) {
 656			folio_unlock(folio);
 657			result = SCAN_PAGE_COUNT;
 658			goto out;
 659		}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 660
 661		/*
 662		 * Isolate the page to avoid collapsing an hugepage
 663		 * currently in use by the VM.
 664		 */
 665		if (!folio_isolate_lru(folio)) {
 666			folio_unlock(folio);
 667			result = SCAN_DEL_PAGE_LRU;
 668			goto out;
 669		}
 670		node_stat_mod_folio(folio,
 671				NR_ISOLATED_ANON + folio_is_file_lru(folio),
 672				folio_nr_pages(folio));
 673		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 674		VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
 675
 676		if (folio_test_large(folio))
 677			list_add_tail(&folio->lru, compound_pagelist);
 678next:
 679		/*
 680		 * If collapse was initiated by khugepaged, check that there is
 681		 * enough young pte to justify collapsing the page
 682		 */
 683		if (cc->is_khugepaged &&
 684		    (pte_young(pteval) || folio_test_young(folio) ||
 685		     folio_test_referenced(folio) || mmu_notifier_test_young(vma->vm_mm,
 686								     address)))
 687			referenced++;
 688
 689		if (pte_write(pteval))
 690			writable = true;
 691	}
 692
 693	if (unlikely(!writable)) {
 
 
 
 
 
 
 694		result = SCAN_PAGE_RO;
 695	} else if (unlikely(cc->is_khugepaged && !referenced)) {
 696		result = SCAN_LACK_REFERENCED_PAGE;
 697	} else {
 698		result = SCAN_SUCCEED;
 699		trace_mm_collapse_huge_page_isolate(&folio->page, none_or_zero,
 700						    referenced, writable, result);
 701		return result;
 702	}
 
 703out:
 704	release_pte_pages(pte, _pte, compound_pagelist);
 705	trace_mm_collapse_huge_page_isolate(&folio->page, none_or_zero,
 706					    referenced, writable, result);
 707	return result;
 708}
 709
 710static void __collapse_huge_page_copy_succeeded(pte_t *pte,
 711						struct vm_area_struct *vma,
 712						unsigned long address,
 713						spinlock_t *ptl,
 714						struct list_head *compound_pagelist)
 715{
 716	struct folio *src, *tmp;
 717	pte_t *_pte;
 718	pte_t pteval;
 
 
 
 719
 720	for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
 721	     _pte++, address += PAGE_SIZE) {
 722		pteval = ptep_get(_pte);
 723		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
 
 724			add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
 725			if (is_zero_pfn(pte_pfn(pteval))) {
 726				/*
 727				 * ptl mostly unnecessary.
 728				 */
 729				spin_lock(ptl);
 730				ptep_clear(vma->vm_mm, address, _pte);
 
 
 
 
 731				spin_unlock(ptl);
 732				ksm_might_unmap_zero_page(vma->vm_mm, pteval);
 733			}
 734		} else {
 735			struct page *src_page = pte_page(pteval);
 736
 737			src = page_folio(src_page);
 738			if (!folio_test_large(src))
 739				release_pte_folio(src);
 740			/*
 741			 * ptl mostly unnecessary, but preempt has to
 742			 * be disabled to update the per-cpu stats
 743			 * inside folio_remove_rmap_pte().
 744			 */
 745			spin_lock(ptl);
 746			ptep_clear(vma->vm_mm, address, _pte);
 747			folio_remove_rmap_pte(src, src_page, vma);
 
 
 
 
 748			spin_unlock(ptl);
 749			free_page_and_swap_cache(src_page);
 750		}
 751	}
 752
 753	list_for_each_entry_safe(src, tmp, compound_pagelist, lru) {
 754		list_del(&src->lru);
 755		node_stat_sub_folio(src, NR_ISOLATED_ANON +
 756				folio_is_file_lru(src));
 757		folio_unlock(src);
 758		free_swap_cache(src);
 759		folio_putback_lru(src);
 760	}
 761}
 762
 763static void __collapse_huge_page_copy_failed(pte_t *pte,
 764					     pmd_t *pmd,
 765					     pmd_t orig_pmd,
 766					     struct vm_area_struct *vma,
 767					     struct list_head *compound_pagelist)
 768{
 769	spinlock_t *pmd_ptl;
 770
 771	/*
 772	 * Re-establish the PMD to point to the original page table
 773	 * entry. Restoring PMD needs to be done prior to releasing
 774	 * pages. Since pages are still isolated and locked here,
 775	 * acquiring anon_vma_lock_write is unnecessary.
 776	 */
 777	pmd_ptl = pmd_lock(vma->vm_mm, pmd);
 778	pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd));
 779	spin_unlock(pmd_ptl);
 780	/*
 781	 * Release both raw and compound pages isolated
 782	 * in __collapse_huge_page_isolate.
 783	 */
 784	release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist);
 785}
 786
 787/*
 788 * __collapse_huge_page_copy - attempts to copy memory contents from raw
 789 * pages to a hugepage. Cleans up the raw pages if copying succeeds;
 790 * otherwise restores the original page table and releases isolated raw pages.
 791 * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC.
 792 *
 793 * @pte: starting of the PTEs to copy from
 794 * @folio: the new hugepage to copy contents to
 795 * @pmd: pointer to the new hugepage's PMD
 796 * @orig_pmd: the original raw pages' PMD
 797 * @vma: the original raw pages' virtual memory area
 798 * @address: starting address to copy
 799 * @ptl: lock on raw pages' PTEs
 800 * @compound_pagelist: list that stores compound pages
 801 */
 802static int __collapse_huge_page_copy(pte_t *pte, struct folio *folio,
 803		pmd_t *pmd, pmd_t orig_pmd, struct vm_area_struct *vma,
 804		unsigned long address, spinlock_t *ptl,
 805		struct list_head *compound_pagelist)
 806{
 807	unsigned int i;
 808	int result = SCAN_SUCCEED;
 809
 810	/*
 811	 * Copying pages' contents is subject to memory poison at any iteration.
 812	 */
 813	for (i = 0; i < HPAGE_PMD_NR; i++) {
 814		pte_t pteval = ptep_get(pte + i);
 815		struct page *page = folio_page(folio, i);
 816		unsigned long src_addr = address + i * PAGE_SIZE;
 817		struct page *src_page;
 818
 819		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
 820			clear_user_highpage(page, src_addr);
 821			continue;
 822		}
 823		src_page = pte_page(pteval);
 824		if (copy_mc_user_highpage(page, src_page, src_addr, vma) > 0) {
 825			result = SCAN_COPY_MC;
 826			break;
 827		}
 828	}
 829
 830	if (likely(result == SCAN_SUCCEED))
 831		__collapse_huge_page_copy_succeeded(pte, vma, address, ptl,
 832						    compound_pagelist);
 833	else
 834		__collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma,
 835						 compound_pagelist);
 836
 837	return result;
 838}
 839
 840static void khugepaged_alloc_sleep(void)
 841{
 842	DEFINE_WAIT(wait);
 843
 844	add_wait_queue(&khugepaged_wait, &wait);
 845	__set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
 846	schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
 847	remove_wait_queue(&khugepaged_wait, &wait);
 848}
 849
 850struct collapse_control khugepaged_collapse_control = {
 851	.is_khugepaged = true,
 852};
 853
 854static bool hpage_collapse_scan_abort(int nid, struct collapse_control *cc)
 855{
 856	int i;
 857
 858	/*
 859	 * If node_reclaim_mode is disabled, then no extra effort is made to
 860	 * allocate memory locally.
 861	 */
 862	if (!node_reclaim_enabled())
 863		return false;
 864
 865	/* If there is a count for this node already, it must be acceptable */
 866	if (cc->node_load[nid])
 867		return false;
 868
 869	for (i = 0; i < MAX_NUMNODES; i++) {
 870		if (!cc->node_load[i])
 871			continue;
 872		if (node_distance(nid, i) > node_reclaim_distance)
 873			return true;
 874	}
 875	return false;
 876}
 877
 878#define khugepaged_defrag()					\
 879	(transparent_hugepage_flags &				\
 880	 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))
 881
 882/* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
 883static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
 884{
 885	return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
 886}
 887
 888#ifdef CONFIG_NUMA
 889static int hpage_collapse_find_target_node(struct collapse_control *cc)
 890{
 
 891	int nid, target_node = 0, max_value = 0;
 892
 893	/* find first node with max normal pages hit */
 894	for (nid = 0; nid < MAX_NUMNODES; nid++)
 895		if (cc->node_load[nid] > max_value) {
 896			max_value = cc->node_load[nid];
 897			target_node = nid;
 898		}
 899
 900	for_each_online_node(nid) {
 901		if (max_value == cc->node_load[nid])
 902			node_set(nid, cc->alloc_nmask);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 903	}
 904
 905	return target_node;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 906}
 907#else
 908static int hpage_collapse_find_target_node(struct collapse_control *cc)
 909{
 910	return 0;
 911}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 912#endif
 913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 914/*
 915 * If mmap_lock temporarily dropped, revalidate vma
 916 * before taking mmap_lock.
 917 * Returns enum scan_result value.
 
 918 */
 919
 920static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
 921				   bool expect_anon,
 922				   struct vm_area_struct **vmap,
 923				   struct collapse_control *cc)
 924{
 925	struct vm_area_struct *vma;
 926	unsigned long tva_flags = cc->is_khugepaged ? TVA_ENFORCE_SYSFS : 0;
 927
 928	if (unlikely(hpage_collapse_test_exit_or_disable(mm)))
 929		return SCAN_ANY_PROCESS;
 930
 931	*vmap = vma = find_vma(mm, address);
 932	if (!vma)
 933		return SCAN_VMA_NULL;
 934
 935	if (!thp_vma_suitable_order(vma, address, PMD_ORDER))
 
 
 936		return SCAN_ADDRESS_RANGE;
 937	if (!thp_vma_allowable_order(vma, vma->vm_flags, tva_flags, PMD_ORDER))
 938		return SCAN_VMA_CHECK;
 939	/*
 940	 * Anon VMA expected, the address may be unmapped then
 941	 * remapped to file after khugepaged reaquired the mmap_lock.
 942	 *
 943	 * thp_vma_allowable_order may return true for qualified file
 944	 * vmas.
 945	 */
 946	if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap)))
 947		return SCAN_PAGE_ANON;
 948	return SCAN_SUCCEED;
 949}
 950
 951static int find_pmd_or_thp_or_none(struct mm_struct *mm,
 952				   unsigned long address,
 953				   pmd_t **pmd)
 954{
 955	pmd_t pmde;
 956
 957	*pmd = mm_find_pmd(mm, address);
 958	if (!*pmd)
 959		return SCAN_PMD_NULL;
 960
 961	pmde = pmdp_get_lockless(*pmd);
 962	if (pmd_none(pmde))
 963		return SCAN_PMD_NONE;
 964	if (!pmd_present(pmde))
 965		return SCAN_PMD_NULL;
 966	if (pmd_trans_huge(pmde))
 967		return SCAN_PMD_MAPPED;
 968	if (pmd_devmap(pmde))
 969		return SCAN_PMD_NULL;
 970	if (pmd_bad(pmde))
 971		return SCAN_PMD_NULL;
 972	return SCAN_SUCCEED;
 973}
 974
 975static int check_pmd_still_valid(struct mm_struct *mm,
 976				 unsigned long address,
 977				 pmd_t *pmd)
 978{
 979	pmd_t *new_pmd;
 980	int result = find_pmd_or_thp_or_none(mm, address, &new_pmd);
 981
 982	if (result != SCAN_SUCCEED)
 983		return result;
 984	if (new_pmd != pmd)
 985		return SCAN_FAIL;
 986	return SCAN_SUCCEED;
 987}
 988
 989/*
 990 * Bring missing pages in from swap, to complete THP collapse.
 991 * Only done if hpage_collapse_scan_pmd believes it is worthwhile.
 992 *
 993 * Called and returns without pte mapped or spinlocks held.
 994 * Returns result: if not SCAN_SUCCEED, mmap_lock has been released.
 995 */
 996static int __collapse_huge_page_swapin(struct mm_struct *mm,
 997				       struct vm_area_struct *vma,
 998				       unsigned long haddr, pmd_t *pmd,
 999				       int referenced)
1000{
1001	int swapped_in = 0;
1002	vm_fault_t ret = 0;
1003	unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
1004	int result;
1005	pte_t *pte = NULL;
1006	spinlock_t *ptl;
1007
1008	for (address = haddr; address < end; address += PAGE_SIZE) {
1009		struct vm_fault vmf = {
1010			.vma = vma,
1011			.address = address,
1012			.pgoff = linear_page_index(vma, address),
1013			.flags = FAULT_FLAG_ALLOW_RETRY,
1014			.pmd = pmd,
1015		};
 
 
 
 
 
1016
1017		if (!pte++) {
1018			/*
1019			 * Here the ptl is only used to check pte_same() in
1020			 * do_swap_page(), so readonly version is enough.
1021			 */
1022			pte = pte_offset_map_ro_nolock(mm, pmd, address, &ptl);
1023			if (!pte) {
1024				mmap_read_unlock(mm);
1025				result = SCAN_PMD_NULL;
1026				goto out;
1027			}
1028		}
1029
1030		vmf.orig_pte = ptep_get_lockless(pte);
1031		if (!is_swap_pte(vmf.orig_pte))
1032			continue;
1033
1034		vmf.pte = pte;
1035		vmf.ptl = ptl;
1036		ret = do_swap_page(&vmf);
1037		/* Which unmaps pte (after perhaps re-checking the entry) */
1038		pte = NULL;
1039
1040		/*
1041		 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock.
1042		 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because
1043		 * we do not retry here and swap entry will remain in pagetable
1044		 * resulting in later failure.
1045		 */
1046		if (ret & VM_FAULT_RETRY) {
1047			/* Likely, but not guaranteed, that page lock failed */
1048			result = SCAN_PAGE_LOCK;
1049			goto out;
 
 
 
 
 
 
 
 
1050		}
1051		if (ret & VM_FAULT_ERROR) {
1052			mmap_read_unlock(mm);
1053			result = SCAN_FAIL;
1054			goto out;
1055		}
1056		swapped_in++;
 
1057	}
1058
1059	if (pte)
1060		pte_unmap(pte);
1061
1062	/* Drain LRU cache to remove extra pin on the swapped in pages */
1063	if (swapped_in)
1064		lru_add_drain();
1065
1066	result = SCAN_SUCCEED;
1067out:
1068	trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, result);
1069	return result;
1070}
1071
1072static int alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,
1073			      struct collapse_control *cc)
 
 
1074{
1075	gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() :
1076		     GFP_TRANSHUGE);
1077	int node = hpage_collapse_find_target_node(cc);
1078	struct folio *folio;
1079
1080	folio = __folio_alloc(gfp, HPAGE_PMD_ORDER, node, &cc->alloc_nmask);
1081	if (!folio) {
1082		*foliop = NULL;
1083		count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
1084		return SCAN_ALLOC_HUGE_PAGE_FAIL;
1085	}
1086
1087	count_vm_event(THP_COLLAPSE_ALLOC);
1088	if (unlikely(mem_cgroup_charge(folio, mm, gfp))) {
1089		folio_put(folio);
1090		*foliop = NULL;
1091		return SCAN_CGROUP_CHARGE_FAIL;
1092	}
1093
1094	count_memcg_folio_events(folio, THP_COLLAPSE_ALLOC, 1);
1095
1096	*foliop = folio;
1097	return SCAN_SUCCEED;
1098}
1099
1100static int collapse_huge_page(struct mm_struct *mm, unsigned long address,
1101			      int referenced, int unmapped,
1102			      struct collapse_control *cc)
1103{
1104	LIST_HEAD(compound_pagelist);
1105	pmd_t *pmd, _pmd;
1106	pte_t *pte;
1107	pgtable_t pgtable;
1108	struct folio *folio;
1109	spinlock_t *pmd_ptl, *pte_ptl;
1110	int result = SCAN_FAIL;
 
1111	struct vm_area_struct *vma;
1112	struct mmu_notifier_range range;
 
 
1113
1114	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1115
 
 
 
1116	/*
1117	 * Before allocating the hugepage, release the mmap_lock read lock.
1118	 * The allocation can take potentially a long time if it involves
1119	 * sync compaction, and we do not need to hold the mmap_lock during
1120	 * that. We will recheck the vma after taking it again in write mode.
1121	 */
1122	mmap_read_unlock(mm);
 
 
 
 
 
1123
1124	result = alloc_charge_folio(&folio, mm, cc);
1125	if (result != SCAN_SUCCEED)
1126		goto out_nolock;
 
1127
1128	mmap_read_lock(mm);
1129	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1130	if (result != SCAN_SUCCEED) {
1131		mmap_read_unlock(mm);
 
1132		goto out_nolock;
1133	}
1134
1135	result = find_pmd_or_thp_or_none(mm, address, &pmd);
1136	if (result != SCAN_SUCCEED) {
1137		mmap_read_unlock(mm);
 
 
1138		goto out_nolock;
1139	}
1140
1141	if (unmapped) {
1142		/*
1143		 * __collapse_huge_page_swapin will return with mmap_lock
1144		 * released when it fails. So we jump out_nolock directly in
1145		 * that case.  Continuing to collapse causes inconsistency.
1146		 */
1147		result = __collapse_huge_page_swapin(mm, vma, address, pmd,
1148						     referenced);
1149		if (result != SCAN_SUCCEED)
1150			goto out_nolock;
1151	}
1152
1153	mmap_read_unlock(mm);
1154	/*
1155	 * Prevent all access to pagetables with the exception of
1156	 * gup_fast later handled by the ptep_clear_flush and the VM
1157	 * handled by the anon_vma lock + PG_lock.
1158	 *
1159	 * UFFDIO_MOVE is prevented to race as well thanks to the
1160	 * mmap_lock.
1161	 */
1162	mmap_write_lock(mm);
1163	result = hugepage_vma_revalidate(mm, address, true, &vma, cc);
1164	if (result != SCAN_SUCCEED)
1165		goto out_up_write;
1166	/* check if the pmd is still valid */
1167	result = check_pmd_still_valid(mm, address, pmd);
1168	if (result != SCAN_SUCCEED)
1169		goto out_up_write;
1170
1171	vma_start_write(vma);
1172	anon_vma_lock_write(vma->anon_vma);
1173
1174	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address,
1175				address + HPAGE_PMD_SIZE);
1176	mmu_notifier_invalidate_range_start(&range);
1177
 
 
 
1178	pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
1179	/*
1180	 * This removes any huge TLB entry from the CPU so we won't allow
1181	 * huge and small TLB entries for the same virtual address to
1182	 * avoid the risk of CPU bugs in that area.
1183	 *
1184	 * Parallel GUP-fast is fine since GUP-fast will back off when
1185	 * it detects PMD is changed.
1186	 */
1187	_pmd = pmdp_collapse_flush(vma, address, pmd);
1188	spin_unlock(pmd_ptl);
1189	mmu_notifier_invalidate_range_end(&range);
1190	tlb_remove_table_sync_one();
1191
1192	pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl);
1193	if (pte) {
1194		result = __collapse_huge_page_isolate(vma, address, pte, cc,
1195						      &compound_pagelist);
1196		spin_unlock(pte_ptl);
1197	} else {
1198		result = SCAN_PMD_NULL;
1199	}
1200
1201	if (unlikely(result != SCAN_SUCCEED)) {
1202		if (pte)
1203			pte_unmap(pte);
1204		spin_lock(pmd_ptl);
1205		BUG_ON(!pmd_none(*pmd));
1206		/*
1207		 * We can only use set_pmd_at when establishing
1208		 * hugepmds and never for establishing regular pmds that
1209		 * points to regular pagetables. Use pmd_populate for that
1210		 */
1211		pmd_populate(mm, pmd, pmd_pgtable(_pmd));
1212		spin_unlock(pmd_ptl);
1213		anon_vma_unlock_write(vma->anon_vma);
1214		goto out_up_write;
 
1215	}
1216
1217	/*
1218	 * All pages are isolated and locked so anon_vma rmap
1219	 * can't run anymore.
1220	 */
1221	anon_vma_unlock_write(vma->anon_vma);
1222
1223	result = __collapse_huge_page_copy(pte, folio, pmd, _pmd,
1224					   vma, address, pte_ptl,
1225					   &compound_pagelist);
1226	pte_unmap(pte);
1227	if (unlikely(result != SCAN_SUCCEED))
1228		goto out_up_write;
 
 
 
1229
1230	/*
1231	 * The smp_wmb() inside __folio_mark_uptodate() ensures the
1232	 * copy_huge_page writes become visible before the set_pmd_at()
1233	 * write.
1234	 */
1235	__folio_mark_uptodate(folio);
1236	pgtable = pmd_pgtable(_pmd);
1237
1238	_pmd = mk_huge_pmd(&folio->page, vma->vm_page_prot);
1239	_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
1240
1241	spin_lock(pmd_ptl);
1242	BUG_ON(!pmd_none(*pmd));
1243	folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE);
1244	folio_add_lru_vma(folio, vma);
 
1245	pgtable_trans_huge_deposit(mm, pmd, pgtable);
1246	set_pmd_at(mm, address, pmd, _pmd);
1247	update_mmu_cache_pmd(vma, address, pmd);
1248	deferred_split_folio(folio, false);
1249	spin_unlock(pmd_ptl);
1250
1251	folio = NULL;
1252
 
1253	result = SCAN_SUCCEED;
1254out_up_write:
1255	mmap_write_unlock(mm);
1256out_nolock:
1257	if (folio)
1258		folio_put(folio);
1259	trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result);
1260	return result;
 
1261}
1262
1263static int hpage_collapse_scan_pmd(struct mm_struct *mm,
1264				   struct vm_area_struct *vma,
1265				   unsigned long address, bool *mmap_locked,
1266				   struct collapse_control *cc)
1267{
1268	pmd_t *pmd;
1269	pte_t *pte, *_pte;
1270	int result = SCAN_FAIL, referenced = 0;
1271	int none_or_zero = 0, shared = 0;
1272	struct page *page = NULL;
1273	struct folio *folio = NULL;
1274	unsigned long _address;
1275	spinlock_t *ptl;
1276	int node = NUMA_NO_NODE, unmapped = 0;
1277	bool writable = false;
1278
1279	VM_BUG_ON(address & ~HPAGE_PMD_MASK);
1280
1281	result = find_pmd_or_thp_or_none(mm, address, &pmd);
1282	if (result != SCAN_SUCCEED)
1283		goto out;
1284
1285	memset(cc->node_load, 0, sizeof(cc->node_load));
1286	nodes_clear(cc->alloc_nmask);
1287	pte = pte_offset_map_lock(mm, pmd, address, &ptl);
1288	if (!pte) {
1289		result = SCAN_PMD_NULL;
1290		goto out;
1291	}
1292
1293	for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR;
 
 
1294	     _pte++, _address += PAGE_SIZE) {
1295		pte_t pteval = ptep_get(_pte);
1296		if (is_swap_pte(pteval)) {
1297			++unmapped;
1298			if (!cc->is_khugepaged ||
1299			    unmapped <= khugepaged_max_ptes_swap) {
1300				/*
1301				 * Always be strict with uffd-wp
1302				 * enabled swap entries.  Please see
1303				 * comment below for pte_uffd_wp().
1304				 */
1305				if (pte_swp_uffd_wp_any(pteval)) {
1306					result = SCAN_PTE_UFFD_WP;
1307					goto out_unmap;
1308				}
1309				continue;
1310			} else {
1311				result = SCAN_EXCEED_SWAP_PTE;
1312				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
1313				goto out_unmap;
1314			}
1315		}
1316		if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
1317			++none_or_zero;
1318			if (!userfaultfd_armed(vma) &&
1319			    (!cc->is_khugepaged ||
1320			     none_or_zero <= khugepaged_max_ptes_none)) {
1321				continue;
1322			} else {
1323				result = SCAN_EXCEED_NONE_PTE;
1324				count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
1325				goto out_unmap;
1326			}
1327		}
1328		if (pte_uffd_wp(pteval)) {
1329			/*
1330			 * Don't collapse the page if any of the small
1331			 * PTEs are armed with uffd write protection.
1332			 * Here we can also mark the new huge pmd as
1333			 * write protected if any of the small ones is
1334			 * marked but that could bring unknown
1335			 * userfault messages that falls outside of
1336			 * the registered range.  So, just be simple.
1337			 */
1338			result = SCAN_PTE_UFFD_WP;
1339			goto out_unmap;
1340		}
1341		if (pte_write(pteval))
1342			writable = true;
1343
1344		page = vm_normal_page(vma, _address, pteval);
1345		if (unlikely(!page) || unlikely(is_zone_device_page(page))) {
1346			result = SCAN_PAGE_NULL;
1347			goto out_unmap;
1348		}
1349		folio = page_folio(page);
1350
1351		if (!folio_test_anon(folio)) {
1352			result = SCAN_PAGE_ANON;
 
1353			goto out_unmap;
1354		}
1355
1356		/*
1357		 * We treat a single page as shared if any part of the THP
1358		 * is shared. "False negatives" from
1359		 * folio_likely_mapped_shared() are not expected to matter
1360		 * much in practice.
1361		 */
1362		if (folio_likely_mapped_shared(folio)) {
1363			++shared;
1364			if (cc->is_khugepaged &&
1365			    shared > khugepaged_max_ptes_shared) {
1366				result = SCAN_EXCEED_SHARED_PTE;
1367				count_vm_event(THP_SCAN_EXCEED_SHARED_PTE);
1368				goto out_unmap;
1369			}
1370		}
1371
1372		/*
1373		 * Record which node the original page is from and save this
1374		 * information to cc->node_load[].
1375		 * Khugepaged will allocate hugepage from the node has the max
1376		 * hit record.
1377		 */
1378		node = folio_nid(folio);
1379		if (hpage_collapse_scan_abort(node, cc)) {
1380			result = SCAN_SCAN_ABORT;
1381			goto out_unmap;
1382		}
1383		cc->node_load[node]++;
1384		if (!folio_test_lru(folio)) {
1385			result = SCAN_PAGE_LRU;
1386			goto out_unmap;
1387		}
1388		if (folio_test_locked(folio)) {
1389			result = SCAN_PAGE_LOCK;
1390			goto out_unmap;
1391		}
 
 
 
 
1392
1393		/*
1394		 * Check if the page has any GUP (or other external) pins.
1395		 *
1396		 * Here the check may be racy:
1397		 * it may see folio_mapcount() > folio_ref_count().
1398		 * But such case is ephemeral we could always retry collapse
1399		 * later.  However it may report false positive if the page
1400		 * has excessive GUP pins (i.e. 512).  Anyway the same check
1401		 * will be done again later the risk seems low.
1402		 */
1403		if (!is_refcount_suitable(folio)) {
1404			result = SCAN_PAGE_COUNT;
1405			goto out_unmap;
1406		}
1407
1408		/*
1409		 * If collapse was initiated by khugepaged, check that there is
1410		 * enough young pte to justify collapsing the page
1411		 */
1412		if (cc->is_khugepaged &&
1413		    (pte_young(pteval) || folio_test_young(folio) ||
1414		     folio_test_referenced(folio) || mmu_notifier_test_young(vma->vm_mm,
1415								     address)))
1416			referenced++;
1417	}
1418	if (!writable) {
 
 
 
 
 
 
 
1419		result = SCAN_PAGE_RO;
1420	} else if (cc->is_khugepaged &&
1421		   (!referenced ||
1422		    (unmapped && referenced < HPAGE_PMD_NR / 2))) {
1423		result = SCAN_LACK_REFERENCED_PAGE;
1424	} else {
1425		result = SCAN_SUCCEED;
1426	}
1427out_unmap:
1428	pte_unmap_unlock(pte, ptl);
1429	if (result == SCAN_SUCCEED) {
1430		result = collapse_huge_page(mm, address, referenced,
1431					    unmapped, cc);
1432		/* collapse_huge_page will return with the mmap_lock released */
1433		*mmap_locked = false;
1434	}
1435out:
1436	trace_mm_khugepaged_scan_pmd(mm, &folio->page, writable, referenced,
1437				     none_or_zero, result, unmapped);
1438	return result;
1439}
1440
1441static void collect_mm_slot(struct khugepaged_mm_slot *mm_slot)
1442{
1443	struct mm_slot *slot = &mm_slot->slot;
1444	struct mm_struct *mm = slot->mm;
1445
1446	lockdep_assert_held(&khugepaged_mm_lock);
1447
1448	if (hpage_collapse_test_exit(mm)) {
1449		/* free mm_slot */
1450		hash_del(&slot->hash);
1451		list_del(&slot->mm_node);
1452
1453		/*
1454		 * Not strictly needed because the mm exited already.
1455		 *
1456		 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
1457		 */
1458
1459		/* khugepaged_mm_lock actually not necessary for the below */
1460		mm_slot_free(mm_slot_cache, mm_slot);
1461		mmdrop(mm);
1462	}
1463}
1464
1465#ifdef CONFIG_SHMEM
1466/* hpage must be locked, and mmap_lock must be held */
1467static int set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,
1468			pmd_t *pmdp, struct page *hpage)
1469{
1470	struct vm_fault vmf = {
1471		.vma = vma,
1472		.address = addr,
1473		.flags = 0,
1474		.pmd = pmdp,
1475	};
1476
1477	VM_BUG_ON(!PageTransHuge(hpage));
1478	mmap_assert_locked(vma->vm_mm);
1479
1480	if (do_set_pmd(&vmf, hpage))
1481		return SCAN_FAIL;
1482
1483	get_page(hpage);
1484	return SCAN_SUCCEED;
1485}
1486
1487/**
1488 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at
1489 * address haddr.
1490 *
1491 * @mm: process address space where collapse happens
1492 * @addr: THP collapse address
1493 * @install_pmd: If a huge PMD should be installed
1494 *
1495 * This function checks whether all the PTEs in the PMD are pointing to the
1496 * right THP. If so, retract the page table so the THP can refault in with
1497 * as pmd-mapped. Possibly install a huge PMD mapping the THP.
1498 */
1499int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,
1500			    bool install_pmd)
1501{
1502	struct mmu_notifier_range range;
1503	bool notified = false;
1504	unsigned long haddr = addr & HPAGE_PMD_MASK;
1505	struct vm_area_struct *vma = vma_lookup(mm, haddr);
1506	struct folio *folio;
1507	pte_t *start_pte, *pte;
1508	pmd_t *pmd, pgt_pmd;
1509	spinlock_t *pml = NULL, *ptl;
1510	int nr_ptes = 0, result = SCAN_FAIL;
1511	int i;
1512
1513	mmap_assert_locked(mm);
1514
1515	/* First check VMA found, in case page tables are being torn down */
1516	if (!vma || !vma->vm_file ||
1517	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
1518		return SCAN_VMA_CHECK;
1519
1520	/* Fast check before locking page if already PMD-mapped */
1521	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1522	if (result == SCAN_PMD_MAPPED)
1523		return result;
1524
1525	/*
1526	 * If we are here, we've succeeded in replacing all the native pages
1527	 * in the page cache with a single hugepage. If a mm were to fault-in
1528	 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage
1529	 * and map it by a PMD, regardless of sysfs THP settings. As such, let's
1530	 * analogously elide sysfs THP settings here.
1531	 */
1532	if (!thp_vma_allowable_order(vma, vma->vm_flags, 0, PMD_ORDER))
1533		return SCAN_VMA_CHECK;
1534
1535	/* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */
1536	if (userfaultfd_wp(vma))
1537		return SCAN_PTE_UFFD_WP;
1538
1539	folio = filemap_lock_folio(vma->vm_file->f_mapping,
1540			       linear_page_index(vma, haddr));
1541	if (IS_ERR(folio))
1542		return SCAN_PAGE_NULL;
1543
1544	if (folio_order(folio) != HPAGE_PMD_ORDER) {
1545		result = SCAN_PAGE_COMPOUND;
1546		goto drop_folio;
1547	}
1548
1549	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
1550	switch (result) {
1551	case SCAN_SUCCEED:
1552		break;
1553	case SCAN_PMD_NONE:
1554		/*
1555		 * All pte entries have been removed and pmd cleared.
1556		 * Skip all the pte checks and just update the pmd mapping.
1557		 */
1558		goto maybe_install_pmd;
1559	default:
1560		goto drop_folio;
1561	}
1562
1563	result = SCAN_FAIL;
1564	start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
1565	if (!start_pte)		/* mmap_lock + page lock should prevent this */
1566		goto drop_folio;
1567
1568	/* step 1: check all mapped PTEs are to the right huge page */
1569	for (i = 0, addr = haddr, pte = start_pte;
1570	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1571		struct page *page;
1572		pte_t ptent = ptep_get(pte);
1573
1574		/* empty pte, skip */
1575		if (pte_none(ptent))
1576			continue;
1577
1578		/* page swapped out, abort */
1579		if (!pte_present(ptent)) {
1580			result = SCAN_PTE_NON_PRESENT;
1581			goto abort;
1582		}
1583
1584		page = vm_normal_page(vma, addr, ptent);
1585		if (WARN_ON_ONCE(page && is_zone_device_page(page)))
1586			page = NULL;
1587		/*
1588		 * Note that uprobe, debugger, or MAP_PRIVATE may change the
1589		 * page table, but the new page will not be a subpage of hpage.
1590		 */
1591		if (folio_page(folio, i) != page)
1592			goto abort;
1593	}
1594
1595	pte_unmap_unlock(start_pte, ptl);
1596	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1597				haddr, haddr + HPAGE_PMD_SIZE);
1598	mmu_notifier_invalidate_range_start(&range);
1599	notified = true;
1600
1601	/*
1602	 * pmd_lock covers a wider range than ptl, and (if split from mm's
1603	 * page_table_lock) ptl nests inside pml. The less time we hold pml,
1604	 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA
1605	 * inserts a valid as-if-COWed PTE without even looking up page cache.
1606	 * So page lock of folio does not protect from it, so we must not drop
1607	 * ptl before pgt_pmd is removed, so uffd private needs pml taken now.
1608	 */
1609	if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED))
1610		pml = pmd_lock(mm, pmd);
1611
1612	start_pte = pte_offset_map_rw_nolock(mm, pmd, haddr, &pgt_pmd, &ptl);
1613	if (!start_pte)		/* mmap_lock + page lock should prevent this */
1614		goto abort;
1615	if (!pml)
1616		spin_lock(ptl);
1617	else if (ptl != pml)
1618		spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1619
1620	if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd))))
1621		goto abort;
1622
1623	/* step 2: clear page table and adjust rmap */
1624	for (i = 0, addr = haddr, pte = start_pte;
1625	     i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
1626		struct page *page;
1627		pte_t ptent = ptep_get(pte);
1628
1629		if (pte_none(ptent))
1630			continue;
1631		/*
1632		 * We dropped ptl after the first scan, to do the mmu_notifier:
1633		 * page lock stops more PTEs of the folio being faulted in, but
1634		 * does not stop write faults COWing anon copies from existing
1635		 * PTEs; and does not stop those being swapped out or migrated.
1636		 */
1637		if (!pte_present(ptent)) {
1638			result = SCAN_PTE_NON_PRESENT;
1639			goto abort;
1640		}
1641		page = vm_normal_page(vma, addr, ptent);
1642		if (folio_page(folio, i) != page)
1643			goto abort;
1644
1645		/*
1646		 * Must clear entry, or a racing truncate may re-remove it.
1647		 * TLB flush can be left until pmdp_collapse_flush() does it.
1648		 * PTE dirty? Shmem page is already dirty; file is read-only.
1649		 */
1650		ptep_clear(mm, addr, pte);
1651		folio_remove_rmap_pte(folio, page, vma);
1652		nr_ptes++;
1653	}
1654
1655	if (!pml)
1656		spin_unlock(ptl);
1657
1658	/* step 3: set proper refcount and mm_counters. */
1659	if (nr_ptes) {
1660		folio_ref_sub(folio, nr_ptes);
1661		add_mm_counter(mm, mm_counter_file(folio), -nr_ptes);
1662	}
1663
1664	/* step 4: remove empty page table */
1665	if (!pml) {
1666		pml = pmd_lock(mm, pmd);
1667		if (ptl != pml) {
1668			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1669			if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) {
1670				flush_tlb_mm(mm);
1671				goto unlock;
1672			}
1673		}
1674	}
1675	pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd);
1676	pmdp_get_lockless_sync();
1677	pte_unmap_unlock(start_pte, ptl);
1678	if (ptl != pml)
1679		spin_unlock(pml);
1680
1681	mmu_notifier_invalidate_range_end(&range);
1682
1683	mm_dec_nr_ptes(mm);
1684	page_table_check_pte_clear_range(mm, haddr, pgt_pmd);
1685	pte_free_defer(mm, pmd_pgtable(pgt_pmd));
1686
1687maybe_install_pmd:
1688	/* step 5: install pmd entry */
1689	result = install_pmd
1690			? set_huge_pmd(vma, haddr, pmd, &folio->page)
1691			: SCAN_SUCCEED;
1692	goto drop_folio;
1693abort:
1694	if (nr_ptes) {
1695		flush_tlb_mm(mm);
1696		folio_ref_sub(folio, nr_ptes);
1697		add_mm_counter(mm, mm_counter_file(folio), -nr_ptes);
1698	}
1699unlock:
1700	if (start_pte)
1701		pte_unmap_unlock(start_pte, ptl);
1702	if (pml && pml != ptl)
1703		spin_unlock(pml);
1704	if (notified)
1705		mmu_notifier_invalidate_range_end(&range);
1706drop_folio:
1707	folio_unlock(folio);
1708	folio_put(folio);
1709	return result;
1710}
1711
1712static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
1713{
1714	struct vm_area_struct *vma;
 
 
1715
1716	i_mmap_lock_read(mapping);
1717	vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
1718		struct mmu_notifier_range range;
1719		struct mm_struct *mm;
1720		unsigned long addr;
1721		pmd_t *pmd, pgt_pmd;
1722		spinlock_t *pml;
1723		spinlock_t *ptl;
1724		bool skipped_uffd = false;
1725
1726		/*
1727		 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
1728		 * got written to. These VMAs are likely not worth removing
1729		 * page tables from, as PMD-mapping is likely to be split later.
1730		 */
1731		if (READ_ONCE(vma->anon_vma))
1732			continue;
1733
1734		addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
1735		if (addr & ~HPAGE_PMD_MASK ||
1736		    vma->vm_end < addr + HPAGE_PMD_SIZE)
1737			continue;
1738
1739		mm = vma->vm_mm;
1740		if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED)
1741			continue;
1742
1743		if (hpage_collapse_test_exit(mm))
1744			continue;
1745		/*
1746		 * When a vma is registered with uffd-wp, we cannot recycle
1747		 * the page table because there may be pte markers installed.
1748		 * Other vmas can still have the same file mapped hugely, but
1749		 * skip this one: it will always be mapped in small page size
1750		 * for uffd-wp registered ranges.
1751		 */
1752		if (userfaultfd_wp(vma))
1753			continue;
1754
1755		/* PTEs were notified when unmapped; but now for the PMD? */
1756		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1757					addr, addr + HPAGE_PMD_SIZE);
1758		mmu_notifier_invalidate_range_start(&range);
1759
1760		pml = pmd_lock(mm, pmd);
1761		ptl = pte_lockptr(mm, pmd);
1762		if (ptl != pml)
1763			spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
1764
1765		/*
1766		 * Huge page lock is still held, so normally the page table
1767		 * must remain empty; and we have already skipped anon_vma
1768		 * and userfaultfd_wp() vmas.  But since the mmap_lock is not
1769		 * held, it is still possible for a racing userfaultfd_ioctl()
1770		 * to have inserted ptes or markers.  Now that we hold ptlock,
1771		 * repeating the anon_vma check protects from one category,
1772		 * and repeating the userfaultfd_wp() check from another.
1773		 */
1774		if (unlikely(vma->anon_vma || userfaultfd_wp(vma))) {
1775			skipped_uffd = true;
1776		} else {
1777			pgt_pmd = pmdp_collapse_flush(vma, addr, pmd);
1778			pmdp_get_lockless_sync();
1779		}
1780
1781		if (ptl != pml)
1782			spin_unlock(ptl);
1783		spin_unlock(pml);
1784
1785		mmu_notifier_invalidate_range_end(&range);
1786
1787		if (!skipped_uffd) {
1788			mm_dec_nr_ptes(mm);
1789			page_table_check_pte_clear_range(mm, addr, pgt_pmd);
1790			pte_free_defer(mm, pmd_pgtable(pgt_pmd));
1791		}
1792	}
1793	i_mmap_unlock_read(mapping);
1794}
1795
1796/**
1797 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
1798 *
1799 * @mm: process address space where collapse happens
1800 * @addr: virtual collapse start address
1801 * @file: file that collapse on
1802 * @start: collapse start address
1803 * @cc: collapse context and scratchpad
1804 *
1805 * Basic scheme is simple, details are more complex:
1806 *  - allocate and lock a new huge page;
1807 *  - scan page cache, locking old pages
1808 *    + swap/gup in pages if necessary;
1809 *  - copy data to new page
1810 *  - handle shmem holes
1811 *    + re-validate that holes weren't filled by someone else
1812 *    + check for userfaultfd
1813 *  - finalize updates to the page cache;
1814 *  - if replacing succeeds:
1815 *    + unlock huge page;
1816 *    + free old pages;
 
1817 *  - if replacing failed;
1818 *    + unlock old pages
1819 *    + unlock and free huge page;
 
1820 */
1821static int collapse_file(struct mm_struct *mm, unsigned long addr,
1822			 struct file *file, pgoff_t start,
1823			 struct collapse_control *cc)
1824{
1825	struct address_space *mapping = file->f_mapping;
1826	struct page *dst;
1827	struct folio *folio, *tmp, *new_folio;
1828	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
1829	LIST_HEAD(pagelist);
1830	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
 
1831	int nr_none = 0, result = SCAN_SUCCEED;
1832	bool is_shmem = shmem_file(file);
1833
1834	VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
1835	VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
1836
1837	result = alloc_charge_folio(&new_folio, mm, cc);
1838	if (result != SCAN_SUCCEED)
 
 
 
 
1839		goto out;
 
 
 
 
 
 
1840
1841	mapping_set_update(&xas, mapping);
 
 
 
 
1842
1843	__folio_set_locked(new_folio);
1844	if (is_shmem)
1845		__folio_set_swapbacked(new_folio);
1846	new_folio->index = start;
1847	new_folio->mapping = mapping;
1848
1849	/*
1850	 * Ensure we have slots for all the pages in the range.  This is
1851	 * almost certainly a no-op because most of the pages must be present
 
 
1852	 */
1853	do {
1854		xas_lock_irq(&xas);
1855		xas_create_range(&xas);
1856		if (!xas_error(&xas))
 
 
 
 
 
 
 
 
1857			break;
1858		xas_unlock_irq(&xas);
1859		if (!xas_nomem(&xas, GFP_KERNEL)) {
1860			result = SCAN_FAIL;
1861			goto rollback;
1862		}
1863	} while (1);
 
 
 
 
1864
1865	for (index = start; index < end;) {
1866		xas_set(&xas, index);
1867		folio = xas_load(&xas);
1868
1869		VM_BUG_ON(index != xas.xa_index);
1870		if (is_shmem) {
1871			if (!folio) {
1872				/*
1873				 * Stop if extent has been truncated or
1874				 * hole-punched, and is now completely
1875				 * empty.
1876				 */
1877				if (index == start) {
1878					if (!xas_next_entry(&xas, end - 1)) {
1879						result = SCAN_TRUNCATED;
1880						goto xa_locked;
1881					}
1882				}
1883				nr_none++;
1884				index++;
1885				continue;
1886			}
1887
1888			if (xa_is_value(folio) || !folio_test_uptodate(folio)) {
1889				xas_unlock_irq(&xas);
1890				/* swap in or instantiate fallocated page */
1891				if (shmem_get_folio(mapping->host, index, 0,
1892						&folio, SGP_NOALLOC)) {
1893					result = SCAN_FAIL;
1894					goto xa_unlocked;
1895				}
1896				/* drain lru cache to help folio_isolate_lru() */
1897				lru_add_drain();
1898			} else if (folio_trylock(folio)) {
1899				folio_get(folio);
1900				xas_unlock_irq(&xas);
1901			} else {
1902				result = SCAN_PAGE_LOCK;
1903				goto xa_locked;
1904			}
1905		} else {	/* !is_shmem */
1906			if (!folio || xa_is_value(folio)) {
1907				xas_unlock_irq(&xas);
1908				page_cache_sync_readahead(mapping, &file->f_ra,
1909							  file, index,
1910							  end - index);
1911				/* drain lru cache to help folio_isolate_lru() */
1912				lru_add_drain();
1913				folio = filemap_lock_folio(mapping, index);
1914				if (IS_ERR(folio)) {
1915					result = SCAN_FAIL;
1916					goto xa_unlocked;
1917				}
1918			} else if (folio_test_dirty(folio)) {
1919				/*
1920				 * khugepaged only works on read-only fd,
1921				 * so this page is dirty because it hasn't
1922				 * been flushed since first write. There
1923				 * won't be new dirty pages.
1924				 *
1925				 * Trigger async flush here and hope the
1926				 * writeback is done when khugepaged
1927				 * revisits this page.
1928				 *
1929				 * This is a one-off situation. We are not
1930				 * forcing writeback in loop.
1931				 */
1932				xas_unlock_irq(&xas);
1933				filemap_flush(mapping);
1934				result = SCAN_FAIL;
1935				goto xa_unlocked;
1936			} else if (folio_test_writeback(folio)) {
1937				xas_unlock_irq(&xas);
1938				result = SCAN_FAIL;
1939				goto xa_unlocked;
1940			} else if (folio_trylock(folio)) {
1941				folio_get(folio);
1942				xas_unlock_irq(&xas);
1943			} else {
1944				result = SCAN_PAGE_LOCK;
1945				goto xa_locked;
1946			}
 
 
 
 
 
 
1947		}
1948
1949		/*
1950		 * The folio must be locked, so we can drop the i_pages lock
1951		 * without racing with truncate.
1952		 */
1953		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 
 
1954
1955		/* make sure the folio is up to date */
1956		if (unlikely(!folio_test_uptodate(folio))) {
1957			result = SCAN_FAIL;
1958			goto out_unlock;
1959		}
1960
1961		/*
1962		 * If file was truncated then extended, or hole-punched, before
1963		 * we locked the first folio, then a THP might be there already.
1964		 * This will be discovered on the first iteration.
1965		 */
1966		if (folio_order(folio) == HPAGE_PMD_ORDER &&
1967		    folio->index == start) {
1968			/* Maybe PMD-mapped */
1969			result = SCAN_PTE_MAPPED_HUGEPAGE;
1970			goto out_unlock;
1971		}
1972
1973		if (folio_mapping(folio) != mapping) {
1974			result = SCAN_TRUNCATED;
1975			goto out_unlock;
1976		}
 
1977
1978		if (!is_shmem && (folio_test_dirty(folio) ||
1979				  folio_test_writeback(folio))) {
1980			/*
1981			 * khugepaged only works on read-only fd, so this
1982			 * folio is dirty because it hasn't been flushed
1983			 * since first write.
1984			 */
1985			result = SCAN_FAIL;
1986			goto out_unlock;
1987		}
1988
1989		if (!folio_isolate_lru(folio)) {
1990			result = SCAN_DEL_PAGE_LRU;
1991			goto out_unlock;
1992		}
1993
1994		if (!filemap_release_folio(folio, GFP_KERNEL)) {
1995			result = SCAN_PAGE_HAS_PRIVATE;
1996			folio_putback_lru(folio);
1997			goto out_unlock;
1998		}
1999
2000		if (folio_mapped(folio))
2001			try_to_unmap(folio,
2002					TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
2003
2004		xas_lock_irq(&xas);
2005
2006		VM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio);
 
 
 
2007
2008		/*
2009		 * We control 2 + nr_pages references to the folio:
2010		 *  - we hold a pin on it;
2011		 *  - nr_pages reference from page cache;
2012		 *  - one from lru_isolate_folio;
2013		 * If those are the only references, then any new usage
2014		 * of the folio will have to fetch it from the page
2015		 * cache. That requires locking the folio to handle
2016		 * truncate, so any new usage will be blocked until we
2017		 * unlock folio after collapse/during rollback.
2018		 */
2019		if (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) {
2020			result = SCAN_PAGE_COUNT;
2021			xas_unlock_irq(&xas);
2022			folio_putback_lru(folio);
2023			goto out_unlock;
2024		}
2025
2026		/*
2027		 * Accumulate the folios that are being collapsed.
 
2028		 */
2029		list_add_tail(&folio->lru, &pagelist);
2030		index += folio_nr_pages(folio);
 
 
 
 
 
 
2031		continue;
 
 
 
 
 
 
 
2032out_unlock:
2033		folio_unlock(folio);
2034		folio_put(folio);
2035		goto xa_unlocked;
2036	}
2037
2038	if (!is_shmem) {
2039		filemap_nr_thps_inc(mapping);
2040		/*
2041		 * Paired with the fence in do_dentry_open() -> get_write_access()
2042		 * to ensure i_writecount is up to date and the update to nr_thps
2043		 * is visible. Ensures the page cache will be truncated if the
2044		 * file is opened writable.
2045		 */
2046		smp_mb();
2047		if (inode_is_open_for_write(mapping->host)) {
2048			result = SCAN_FAIL;
2049			filemap_nr_thps_dec(mapping);
2050		}
2051	}
2052
2053xa_locked:
2054	xas_unlock_irq(&xas);
2055xa_unlocked:
2056
2057	/*
2058	 * If collapse is successful, flush must be done now before copying.
2059	 * If collapse is unsuccessful, does flush actually need to be done?
2060	 * Do it anyway, to clear the state.
2061	 */
2062	try_to_unmap_flush();
 
2063
2064	if (result == SCAN_SUCCEED && nr_none &&
2065	    !shmem_charge(mapping->host, nr_none))
2066		result = SCAN_FAIL;
2067	if (result != SCAN_SUCCEED) {
2068		nr_none = 0;
2069		goto rollback;
2070	}
2071
2072	/*
2073	 * The old folios are locked, so they won't change anymore.
2074	 */
2075	index = start;
2076	dst = folio_page(new_folio, 0);
2077	list_for_each_entry(folio, &pagelist, lru) {
2078		int i, nr_pages = folio_nr_pages(folio);
2079
2080		while (index < folio->index) {
2081			clear_highpage(dst);
2082			index++;
2083			dst++;
2084		}
2085
2086		for (i = 0; i < nr_pages; i++) {
2087			if (copy_mc_highpage(dst, folio_page(folio, i)) > 0) {
2088				result = SCAN_COPY_MC;
2089				goto rollback;
2090			}
2091			index++;
2092			dst++;
2093		}
2094	}
2095	while (index < end) {
2096		clear_highpage(dst);
2097		index++;
2098		dst++;
2099	}
2100
2101	if (nr_none) {
2102		struct vm_area_struct *vma;
2103		int nr_none_check = 0;
2104
2105		i_mmap_lock_read(mapping);
2106		xas_lock_irq(&xas);
2107
2108		xas_set(&xas, start);
2109		for (index = start; index < end; index++) {
2110			if (!xas_next(&xas)) {
2111				xas_store(&xas, XA_RETRY_ENTRY);
2112				if (xas_error(&xas)) {
2113					result = SCAN_STORE_FAILED;
2114					goto immap_locked;
2115				}
2116				nr_none_check++;
2117			}
2118		}
2119
2120		if (nr_none != nr_none_check) {
2121			result = SCAN_PAGE_FILLED;
2122			goto immap_locked;
2123		}
2124
2125		/*
2126		 * If userspace observed a missing page in a VMA with
2127		 * a MODE_MISSING userfaultfd, then it might expect a
2128		 * UFFD_EVENT_PAGEFAULT for that page. If so, we need to
2129		 * roll back to avoid suppressing such an event. Since
2130		 * wp/minor userfaultfds don't give userspace any
2131		 * guarantees that the kernel doesn't fill a missing
2132		 * page with a zero page, so they don't matter here.
2133		 *
2134		 * Any userfaultfds registered after this point will
2135		 * not be able to observe any missing pages due to the
2136		 * previously inserted retry entries.
2137		 */
2138		vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2139			if (userfaultfd_missing(vma)) {
2140				result = SCAN_EXCEED_NONE_PTE;
2141				goto immap_locked;
2142			}
 
 
 
 
 
2143		}
2144
2145immap_locked:
2146		i_mmap_unlock_read(mapping);
2147		if (result != SCAN_SUCCEED) {
2148			xas_set(&xas, start);
2149			for (index = start; index < end; index++) {
2150				if (xas_next(&xas) == XA_RETRY_ENTRY)
2151					xas_store(&xas, NULL);
2152			}
2153
2154			xas_unlock_irq(&xas);
2155			goto rollback;
2156		}
2157	} else {
2158		xas_lock_irq(&xas);
2159	}
2160
2161	if (is_shmem)
2162		__lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
2163	else
2164		__lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);
2165
2166	if (nr_none) {
2167		__lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, nr_none);
2168		/* nr_none is always 0 for non-shmem. */
2169		__lruvec_stat_mod_folio(new_folio, NR_SHMEM, nr_none);
2170	}
2171
2172	/*
2173	 * Mark new_folio as uptodate before inserting it into the
2174	 * page cache so that it isn't mistaken for an fallocated but
2175	 * unwritten page.
2176	 */
2177	folio_mark_uptodate(new_folio);
2178	folio_ref_add(new_folio, HPAGE_PMD_NR - 1);
2179
2180	if (is_shmem)
2181		folio_mark_dirty(new_folio);
2182	folio_add_lru(new_folio);
2183
2184	/* Join all the small entries into a single multi-index entry. */
2185	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2186	xas_store(&xas, new_folio);
2187	WARN_ON_ONCE(xas_error(&xas));
2188	xas_unlock_irq(&xas);
2189
2190	/*
2191	 * Remove pte page tables, so we can re-fault the page as huge.
2192	 * If MADV_COLLAPSE, adjust result to call collapse_pte_mapped_thp().
2193	 */
2194	retract_page_tables(mapping, start);
2195	if (cc && !cc->is_khugepaged)
2196		result = SCAN_PTE_MAPPED_HUGEPAGE;
2197	folio_unlock(new_folio);
2198
2199	/*
2200	 * The collapse has succeeded, so free the old folios.
2201	 */
2202	list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
2203		list_del(&folio->lru);
2204		folio->mapping = NULL;
2205		folio_clear_active(folio);
2206		folio_clear_unevictable(folio);
2207		folio_unlock(folio);
2208		folio_put_refs(folio, 2 + folio_nr_pages(folio));
2209	}
2210
2211	goto out;
2212
2213rollback:
2214	/* Something went wrong: roll back page cache changes */
2215	if (nr_none) {
2216		xas_lock_irq(&xas);
2217		mapping->nrpages -= nr_none;
2218		xas_unlock_irq(&xas);
2219		shmem_uncharge(mapping->host, nr_none);
2220	}
2221
2222	list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
2223		list_del(&folio->lru);
2224		folio_unlock(folio);
2225		folio_putback_lru(folio);
2226		folio_put(folio);
 
 
 
 
 
 
 
 
 
 
 
 
 
2227	}
2228	/*
2229	 * Undo the updates of filemap_nr_thps_inc for non-SHMEM
2230	 * file only. This undo is not needed unless failure is
2231	 * due to SCAN_COPY_MC.
2232	 */
2233	if (!is_shmem && result == SCAN_COPY_MC) {
2234		filemap_nr_thps_dec(mapping);
2235		/*
2236		 * Paired with the fence in do_dentry_open() -> get_write_access()
2237		 * to ensure the update to nr_thps is visible.
2238		 */
2239		smp_mb();
2240	}
2241
2242	new_folio->mapping = NULL;
2243
2244	folio_unlock(new_folio);
2245	folio_put(new_folio);
2246out:
2247	VM_BUG_ON(!list_empty(&pagelist));
2248	trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
2249	return result;
2250}
2251
2252static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2253				    struct file *file, pgoff_t start,
2254				    struct collapse_control *cc)
2255{
2256	struct folio *folio = NULL;
2257	struct address_space *mapping = file->f_mapping;
2258	XA_STATE(xas, &mapping->i_pages, start);
2259	int present, swap;
2260	int node = NUMA_NO_NODE;
2261	int result = SCAN_SUCCEED;
2262
2263	present = 0;
2264	swap = 0;
2265	memset(cc->node_load, 0, sizeof(cc->node_load));
2266	nodes_clear(cc->alloc_nmask);
2267	rcu_read_lock();
2268	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
2269		if (xas_retry(&xas, folio))
 
 
 
 
 
2270			continue;
 
2271
2272		if (xa_is_value(folio)) {
2273			swap += 1 << xas_get_order(&xas);
2274			if (cc->is_khugepaged &&
2275			    swap > khugepaged_max_ptes_swap) {
2276				result = SCAN_EXCEED_SWAP_PTE;
2277				count_vm_event(THP_SCAN_EXCEED_SWAP_PTE);
2278				break;
2279			}
2280			continue;
2281		}
2282
2283		if (folio_order(folio) == HPAGE_PMD_ORDER &&
2284		    folio->index == start) {
2285			/* Maybe PMD-mapped */
2286			result = SCAN_PTE_MAPPED_HUGEPAGE;
2287			/*
2288			 * For SCAN_PTE_MAPPED_HUGEPAGE, further processing
2289			 * by the caller won't touch the page cache, and so
2290			 * it's safe to skip LRU and refcount checks before
2291			 * returning.
2292			 */
2293			break;
2294		}
2295
2296		node = folio_nid(folio);
2297		if (hpage_collapse_scan_abort(node, cc)) {
2298			result = SCAN_SCAN_ABORT;
2299			break;
2300		}
2301		cc->node_load[node]++;
2302
2303		if (!folio_test_lru(folio)) {
2304			result = SCAN_PAGE_LRU;
2305			break;
2306		}
2307
2308		if (!is_refcount_suitable(folio)) {
2309			result = SCAN_PAGE_COUNT;
2310			break;
2311		}
2312
2313		/*
2314		 * We probably should check if the folio is referenced
2315		 * here, but nobody would transfer pte_young() to
2316		 * folio_test_referenced() for us.  And rmap walk here
2317		 * is just too costly...
2318		 */
2319
2320		present += folio_nr_pages(folio);
2321
2322		if (need_resched()) {
2323			xas_pause(&xas);
2324			cond_resched_rcu();
2325		}
2326	}
2327	rcu_read_unlock();
2328
2329	if (result == SCAN_SUCCEED) {
2330		if (cc->is_khugepaged &&
2331		    present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
2332			result = SCAN_EXCEED_NONE_PTE;
2333			count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
2334		} else {
2335			result = collapse_file(mm, addr, file, start, cc);
 
2336		}
2337	}
2338
2339	trace_mm_khugepaged_scan_file(mm, folio, file, present, swap, result);
2340	return result;
2341}
2342#else
2343static int hpage_collapse_scan_file(struct mm_struct *mm, unsigned long addr,
2344				    struct file *file, pgoff_t start,
2345				    struct collapse_control *cc)
2346{
2347	BUILD_BUG();
2348}
2349#endif
2350
2351static unsigned int khugepaged_scan_mm_slot(unsigned int pages, int *result,
2352					    struct collapse_control *cc)
2353	__releases(&khugepaged_mm_lock)
2354	__acquires(&khugepaged_mm_lock)
2355{
2356	struct vma_iterator vmi;
2357	struct khugepaged_mm_slot *mm_slot;
2358	struct mm_slot *slot;
2359	struct mm_struct *mm;
2360	struct vm_area_struct *vma;
2361	int progress = 0;
2362
2363	VM_BUG_ON(!pages);
2364	lockdep_assert_held(&khugepaged_mm_lock);
2365	*result = SCAN_FAIL;
2366
2367	if (khugepaged_scan.mm_slot) {
2368		mm_slot = khugepaged_scan.mm_slot;
2369		slot = &mm_slot->slot;
2370	} else {
2371		slot = list_entry(khugepaged_scan.mm_head.next,
2372				     struct mm_slot, mm_node);
2373		mm_slot = mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2374		khugepaged_scan.address = 0;
2375		khugepaged_scan.mm_slot = mm_slot;
2376	}
2377	spin_unlock(&khugepaged_mm_lock);
2378
2379	mm = slot->mm;
2380	/*
2381	 * Don't wait for semaphore (to avoid long wait times).  Just move to
2382	 * the next mm on the list.
2383	 */
2384	vma = NULL;
2385	if (unlikely(!mmap_read_trylock(mm)))
2386		goto breakouterloop_mmap_lock;
 
 
2387
2388	progress++;
2389	if (unlikely(hpage_collapse_test_exit_or_disable(mm)))
2390		goto breakouterloop;
2391
2392	vma_iter_init(&vmi, mm, khugepaged_scan.address);
2393	for_each_vma(vmi, vma) {
2394		unsigned long hstart, hend;
2395
2396		cond_resched();
2397		if (unlikely(hpage_collapse_test_exit_or_disable(mm))) {
2398			progress++;
2399			break;
2400		}
2401		if (!thp_vma_allowable_order(vma, vma->vm_flags,
2402					TVA_ENFORCE_SYSFS, PMD_ORDER)) {
2403skip:
2404			progress++;
2405			continue;
2406		}
2407		hstart = round_up(vma->vm_start, HPAGE_PMD_SIZE);
2408		hend = round_down(vma->vm_end, HPAGE_PMD_SIZE);
 
 
2409		if (khugepaged_scan.address > hend)
2410			goto skip;
2411		if (khugepaged_scan.address < hstart)
2412			khugepaged_scan.address = hstart;
2413		VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
2414
2415		while (khugepaged_scan.address < hend) {
2416			bool mmap_locked = true;
2417
2418			cond_resched();
2419			if (unlikely(hpage_collapse_test_exit_or_disable(mm)))
2420				goto breakouterloop;
2421
2422			VM_BUG_ON(khugepaged_scan.address < hstart ||
2423				  khugepaged_scan.address + HPAGE_PMD_SIZE >
2424				  hend);
2425			if (IS_ENABLED(CONFIG_SHMEM) && !vma_is_anonymous(vma)) {
2426				struct file *file = get_file(vma->vm_file);
2427				pgoff_t pgoff = linear_page_index(vma,
2428						khugepaged_scan.address);
2429
2430				mmap_read_unlock(mm);
2431				mmap_locked = false;
2432				*result = hpage_collapse_scan_file(mm,
2433					khugepaged_scan.address, file, pgoff, cc);
 
 
2434				fput(file);
2435				if (*result == SCAN_PTE_MAPPED_HUGEPAGE) {
2436					mmap_read_lock(mm);
2437					if (hpage_collapse_test_exit_or_disable(mm))
2438						goto breakouterloop;
2439					*result = collapse_pte_mapped_thp(mm,
2440						khugepaged_scan.address, false);
2441					if (*result == SCAN_PMD_MAPPED)
2442						*result = SCAN_SUCCEED;
2443					mmap_read_unlock(mm);
2444				}
2445			} else {
2446				*result = hpage_collapse_scan_pmd(mm, vma,
2447					khugepaged_scan.address, &mmap_locked, cc);
 
2448			}
2449
2450			if (*result == SCAN_SUCCEED)
2451				++khugepaged_pages_collapsed;
2452
2453			/* move to next address */
2454			khugepaged_scan.address += HPAGE_PMD_SIZE;
2455			progress += HPAGE_PMD_NR;
2456			if (!mmap_locked)
2457				/*
2458				 * We released mmap_lock so break loop.  Note
2459				 * that we drop mmap_lock before all hugepage
2460				 * allocations, so if allocation fails, we are
2461				 * guaranteed to break here and report the
2462				 * correct result back to caller.
2463				 */
2464				goto breakouterloop_mmap_lock;
2465			if (progress >= pages)
2466				goto breakouterloop;
2467		}
2468	}
2469breakouterloop:
2470	mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
2471breakouterloop_mmap_lock:
2472
2473	spin_lock(&khugepaged_mm_lock);
2474	VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
2475	/*
2476	 * Release the current mm_slot if this mm is about to die, or
2477	 * if we scanned all vmas of this mm.
2478	 */
2479	if (hpage_collapse_test_exit(mm) || !vma) {
2480		/*
2481		 * Make sure that if mm_users is reaching zero while
2482		 * khugepaged runs here, khugepaged_exit will find
2483		 * mm_slot not pointing to the exiting mm.
2484		 */
2485		if (slot->mm_node.next != &khugepaged_scan.mm_head) {
2486			slot = list_entry(slot->mm_node.next,
2487					  struct mm_slot, mm_node);
2488			khugepaged_scan.mm_slot =
2489				mm_slot_entry(slot, struct khugepaged_mm_slot, slot);
2490			khugepaged_scan.address = 0;
2491		} else {
2492			khugepaged_scan.mm_slot = NULL;
2493			khugepaged_full_scans++;
2494		}
2495
2496		collect_mm_slot(mm_slot);
2497	}
2498
2499	return progress;
2500}
2501
2502static int khugepaged_has_work(void)
2503{
2504	return !list_empty(&khugepaged_scan.mm_head) && hugepage_pmd_enabled();
 
2505}
2506
2507static int khugepaged_wait_event(void)
2508{
2509	return !list_empty(&khugepaged_scan.mm_head) ||
2510		kthread_should_stop();
2511}
2512
2513static void khugepaged_do_scan(struct collapse_control *cc)
2514{
 
2515	unsigned int progress = 0, pass_through_head = 0;
2516	unsigned int pages = READ_ONCE(khugepaged_pages_to_scan);
2517	bool wait = true;
2518	int result = SCAN_SUCCEED;
2519
2520	lru_add_drain_all();
 
 
 
 
2521
2522	while (true) {
2523		cond_resched();
2524
2525		if (unlikely(kthread_should_stop()))
2526			break;
2527
2528		spin_lock(&khugepaged_mm_lock);
2529		if (!khugepaged_scan.mm_slot)
2530			pass_through_head++;
2531		if (khugepaged_has_work() &&
2532		    pass_through_head < 2)
2533			progress += khugepaged_scan_mm_slot(pages - progress,
2534							    &result, cc);
2535		else
2536			progress = pages;
2537		spin_unlock(&khugepaged_mm_lock);
 
2538
2539		if (progress >= pages)
2540			break;
2541
2542		if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) {
2543			/*
2544			 * If fail to allocate the first time, try to sleep for
2545			 * a while.  When hit again, cancel the scan.
2546			 */
2547			if (!wait)
2548				break;
2549			wait = false;
2550			khugepaged_alloc_sleep();
2551		}
2552	}
2553}
2554
2555static bool khugepaged_should_wakeup(void)
2556{
2557	return kthread_should_stop() ||
2558	       time_after_eq(jiffies, khugepaged_sleep_expire);
2559}
2560
2561static void khugepaged_wait_work(void)
2562{
2563	if (khugepaged_has_work()) {
2564		const unsigned long scan_sleep_jiffies =
2565			msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
2566
2567		if (!scan_sleep_jiffies)
2568			return;
2569
2570		khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
2571		wait_event_freezable_timeout(khugepaged_wait,
2572					     khugepaged_should_wakeup(),
2573					     scan_sleep_jiffies);
2574		return;
2575	}
2576
2577	if (hugepage_pmd_enabled())
2578		wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
2579}
2580
2581static int khugepaged(void *none)
2582{
2583	struct khugepaged_mm_slot *mm_slot;
2584
2585	set_freezable();
2586	set_user_nice(current, MAX_NICE);
2587
2588	while (!kthread_should_stop()) {
2589		khugepaged_do_scan(&khugepaged_collapse_control);
2590		khugepaged_wait_work();
2591	}
2592
2593	spin_lock(&khugepaged_mm_lock);
2594	mm_slot = khugepaged_scan.mm_slot;
2595	khugepaged_scan.mm_slot = NULL;
2596	if (mm_slot)
2597		collect_mm_slot(mm_slot);
2598	spin_unlock(&khugepaged_mm_lock);
2599	return 0;
2600}
2601
2602static void set_recommended_min_free_kbytes(void)
2603{
2604	struct zone *zone;
2605	int nr_zones = 0;
2606	unsigned long recommended_min;
2607
2608	if (!hugepage_pmd_enabled()) {
2609		calculate_min_free_kbytes();
2610		goto update_wmarks;
2611	}
2612
2613	for_each_populated_zone(zone) {
2614		/*
2615		 * We don't need to worry about fragmentation of
2616		 * ZONE_MOVABLE since it only has movable pages.
2617		 */
2618		if (zone_idx(zone) > gfp_zone(GFP_USER))
2619			continue;
2620
2621		nr_zones++;
2622	}
2623
2624	/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
2625	recommended_min = pageblock_nr_pages * nr_zones * 2;
2626
2627	/*
2628	 * Make sure that on average at least two pageblocks are almost free
2629	 * of another type, one for a migratetype to fall back to and a
2630	 * second to avoid subsequent fallbacks of other types There are 3
2631	 * MIGRATE_TYPES we care about.
2632	 */
2633	recommended_min += pageblock_nr_pages * nr_zones *
2634			   MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
2635
2636	/* don't ever allow to reserve more than 5% of the lowmem */
2637	recommended_min = min(recommended_min,
2638			      (unsigned long) nr_free_buffer_pages() / 20);
2639	recommended_min <<= (PAGE_SHIFT-10);
2640
2641	if (recommended_min > min_free_kbytes) {
2642		if (user_min_free_kbytes >= 0)
2643			pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
2644				min_free_kbytes, recommended_min);
2645
2646		min_free_kbytes = recommended_min;
2647	}
2648
2649update_wmarks:
2650	setup_per_zone_wmarks();
2651}
2652
2653int start_stop_khugepaged(void)
2654{
 
 
2655	int err = 0;
2656
2657	mutex_lock(&khugepaged_mutex);
2658	if (hugepage_pmd_enabled()) {
2659		if (!khugepaged_thread)
2660			khugepaged_thread = kthread_run(khugepaged, NULL,
2661							"khugepaged");
2662		if (IS_ERR(khugepaged_thread)) {
2663			pr_err("khugepaged: kthread_run(khugepaged) failed\n");
2664			err = PTR_ERR(khugepaged_thread);
2665			khugepaged_thread = NULL;
2666			goto fail;
2667		}
2668
2669		if (!list_empty(&khugepaged_scan.mm_head))
2670			wake_up_interruptible(&khugepaged_wait);
 
 
2671	} else if (khugepaged_thread) {
2672		kthread_stop(khugepaged_thread);
2673		khugepaged_thread = NULL;
2674	}
2675	set_recommended_min_free_kbytes();
2676fail:
2677	mutex_unlock(&khugepaged_mutex);
2678	return err;
2679}
2680
2681void khugepaged_min_free_kbytes_update(void)
2682{
2683	mutex_lock(&khugepaged_mutex);
2684	if (hugepage_pmd_enabled() && khugepaged_thread)
2685		set_recommended_min_free_kbytes();
2686	mutex_unlock(&khugepaged_mutex);
2687}
2688
2689bool current_is_khugepaged(void)
2690{
2691	return kthread_func(current) == khugepaged;
2692}
2693
2694static int madvise_collapse_errno(enum scan_result r)
2695{
2696	/*
2697	 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide
2698	 * actionable feedback to caller, so they may take an appropriate
2699	 * fallback measure depending on the nature of the failure.
2700	 */
2701	switch (r) {
2702	case SCAN_ALLOC_HUGE_PAGE_FAIL:
2703		return -ENOMEM;
2704	case SCAN_CGROUP_CHARGE_FAIL:
2705	case SCAN_EXCEED_NONE_PTE:
2706		return -EBUSY;
2707	/* Resource temporary unavailable - trying again might succeed */
2708	case SCAN_PAGE_COUNT:
2709	case SCAN_PAGE_LOCK:
2710	case SCAN_PAGE_LRU:
2711	case SCAN_DEL_PAGE_LRU:
2712	case SCAN_PAGE_FILLED:
2713		return -EAGAIN;
2714	/*
2715	 * Other: Trying again likely not to succeed / error intrinsic to
2716	 * specified memory range. khugepaged likely won't be able to collapse
2717	 * either.
2718	 */
2719	default:
2720		return -EINVAL;
2721	}
2722}
2723
2724int madvise_collapse(struct vm_area_struct *vma, struct vm_area_struct **prev,
2725		     unsigned long start, unsigned long end)
2726{
2727	struct collapse_control *cc;
2728	struct mm_struct *mm = vma->vm_mm;
2729	unsigned long hstart, hend, addr;
2730	int thps = 0, last_fail = SCAN_FAIL;
2731	bool mmap_locked = true;
2732
2733	BUG_ON(vma->vm_start > start);
2734	BUG_ON(vma->vm_end < end);
2735
2736	*prev = vma;
2737
2738	if (!thp_vma_allowable_order(vma, vma->vm_flags, 0, PMD_ORDER))
2739		return -EINVAL;
2740
2741	cc = kmalloc(sizeof(*cc), GFP_KERNEL);
2742	if (!cc)
2743		return -ENOMEM;
2744	cc->is_khugepaged = false;
2745
2746	mmgrab(mm);
2747	lru_add_drain_all();
2748
2749	hstart = (start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
2750	hend = end & HPAGE_PMD_MASK;
2751
2752	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
2753		int result = SCAN_FAIL;
2754
2755		if (!mmap_locked) {
2756			cond_resched();
2757			mmap_read_lock(mm);
2758			mmap_locked = true;
2759			result = hugepage_vma_revalidate(mm, addr, false, &vma,
2760							 cc);
2761			if (result  != SCAN_SUCCEED) {
2762				last_fail = result;
2763				goto out_nolock;
2764			}
2765
2766			hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
2767		}
2768		mmap_assert_locked(mm);
2769		memset(cc->node_load, 0, sizeof(cc->node_load));
2770		nodes_clear(cc->alloc_nmask);
2771		if (IS_ENABLED(CONFIG_SHMEM) && !vma_is_anonymous(vma)) {
2772			struct file *file = get_file(vma->vm_file);
2773			pgoff_t pgoff = linear_page_index(vma, addr);
2774
2775			mmap_read_unlock(mm);
2776			mmap_locked = false;
2777			result = hpage_collapse_scan_file(mm, addr, file, pgoff,
2778							  cc);
2779			fput(file);
2780		} else {
2781			result = hpage_collapse_scan_pmd(mm, vma, addr,
2782							 &mmap_locked, cc);
2783		}
2784		if (!mmap_locked)
2785			*prev = NULL;  /* Tell caller we dropped mmap_lock */
2786
2787handle_result:
2788		switch (result) {
2789		case SCAN_SUCCEED:
2790		case SCAN_PMD_MAPPED:
2791			++thps;
2792			break;
2793		case SCAN_PTE_MAPPED_HUGEPAGE:
2794			BUG_ON(mmap_locked);
2795			BUG_ON(*prev);
2796			mmap_read_lock(mm);
2797			result = collapse_pte_mapped_thp(mm, addr, true);
2798			mmap_read_unlock(mm);
2799			goto handle_result;
2800		/* Whitelisted set of results where continuing OK */
2801		case SCAN_PMD_NULL:
2802		case SCAN_PTE_NON_PRESENT:
2803		case SCAN_PTE_UFFD_WP:
2804		case SCAN_PAGE_RO:
2805		case SCAN_LACK_REFERENCED_PAGE:
2806		case SCAN_PAGE_NULL:
2807		case SCAN_PAGE_COUNT:
2808		case SCAN_PAGE_LOCK:
2809		case SCAN_PAGE_COMPOUND:
2810		case SCAN_PAGE_LRU:
2811		case SCAN_DEL_PAGE_LRU:
2812			last_fail = result;
2813			break;
2814		default:
2815			last_fail = result;
2816			/* Other error, exit */
2817			goto out_maybelock;
2818		}
2819	}
2820
2821out_maybelock:
2822	/* Caller expects us to hold mmap_lock on return */
2823	if (!mmap_locked)
2824		mmap_read_lock(mm);
2825out_nolock:
2826	mmap_assert_locked(mm);
2827	mmdrop(mm);
2828	kfree(cc);
2829
2830	return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
2831			: madvise_collapse_errno(last_fail);
2832}