Skip to contentSkip to conversation

thp/khugepaged improvements and CoW semantics

PATCH Superseded Kirill A. Shutemov 4 participants 38 messages Mar 27, 2020 – Apr 1, 2020

Subsystems (5)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover thp/khugepaged improvements and CoW semantics

The patchset adds khugepaged selftest (anon-THP only for now), expands cases khugepaged can handle and switches anon-THP copy-on-write handling to 4k.

Please review and consider applying.

Kirill A. Shutemov (7):
khugepaged: Add self test
khugepaged: Do not stop collapse if less than half PTEs are referenced
khugepaged: Drain LRU add pagevec to get rid of extra pins
khugepaged: Allow to callapse a page shared across fork
khugepaged: Allow to collapse PTE-mapped compound pages
thp: Change CoW semantics for anon-THP
khugepaged: Introduce 'max_ptes_shared' tunable

 Documentation/admin-guide/mm/transhuge.rst |   7 +
 mm/huge_memory.c                           | 247 +-----
 mm/khugepaged.c                            | 124 ++-
 tools/testing/selftests/vm/Makefile        |   1 +
 tools/testing/selftests/vm/khugepaged.c    | 924 +++++++++++++++++++++
 5 files changed, 1057 insertions(+), 246 deletions(-)
 create mode 100644 tools/testing/selftests/vm/khugepaged.c
Signature · 1 line
2.26.0
#5 lore raw

PATCH 3/7 khugepaged: Drain LRU add pagevec to get rid of extra pins

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +8 -0
index 14d7afc90786..39e0994abeb8 100644
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		 * The page must only be referenced by the scanned process
 		 * and page swap cache.
 		 */
+		if (page_count(page) != 1 + PageSwapCache(page)) {
+			/*
+			 * Drain pagevec and retry just in case we can get rid
+			 * of the extra pin, like in swapin case.
+			 */
+			lru_add_drain();
+		}
 		if (page_count(page) != 1 + PageSwapCache(page)) {
 			unlock_page(page);
 			result = SCAN_PAGE_COUNT;
 			goto out;
 		}
+
 		if (pte_write(pteval)) {
 			writable = true;
 		} else {
Signature · 1 line
2.26.0
#12 lore raw

PATCH 4/7 khugepaged: Allow to callapse a page shared across fork

In reply to Kirill A. Shutemov

The page can be included into collapse as long as it doesn't have extra pins (from GUP or otherwise).

---
 mm/khugepaged.c | 28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)
mm/khugepaged.c +16 -12
index 39e0994abeb8..b47edfe57f7b 100644
@@ -581,18 +581,26 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		}
 
 		/*
-		 * cannot use mapcount: can't collapse if there's a gup pin.
-		 * The page must only be referenced by the scanned process
-		 * and page swap cache.
+		 * Check if the page has any GUP (or other external) pins.
+		 *
+		 * The page table that maps the page has been already unlinked
+		 * from the page table tree and this process cannot get
+		 * additinal pin on the page.
+		 *
+		 * New pins can come later if the page is shared across fork,
+		 * but not for the this process. It is fine. The other process
+		 * cannot write to the page, only trigger CoW.
 		 */
-		if (page_count(page) != 1 + PageSwapCache(page)) {
+		if (total_mapcount(page) + PageSwapCache(page) !=
+				page_count(page)) {
 			/*
 			 * Drain pagevec and retry just in case we can get rid
 			 * of the extra pin, like in swapin case.
 			 */
 			lru_add_drain();
 		}
-		if (page_count(page) != 1 + PageSwapCache(page)) {
+		if (total_mapcount(page) + PageSwapCache(page) !=
+				page_count(page)) {
 			unlock_page(page);
 			result = SCAN_PAGE_COUNT;
 			goto out;
@@ -680,7 +688,6 @@ static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
 		} else {
 			src_page = pte_page(pteval);
 			copy_user_highpage(page, src_page, address, vma);
-			VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);
 			release_pte_page(src_page);
 			/*
 			 * ptl mostly unnecessary, but preempt has to
@@ -1209,12 +1216,9 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		/*
-		 * cannot use mapcount: can't collapse if there's a gup pin.
-		 * The page must only be referenced by the scanned process
-		 * and page swap cache.
-		 */
-		if (page_count(page) != 1 + PageSwapCache(page)) {
+		/* Check if the page has any GUP (or other external) pins */
+		if (total_mapcount(page) + PageSwapCache(page) !=
+				page_count(page)) {
 			result = SCAN_PAGE_COUNT;
 			goto out_unmap;
 		}
Signature · 1 line
2.26.0
#2 lore raw

PATCH 2/7 khugepaged: Do not stop collapse if less than half PTEs are referenced

In reply to Kirill A. Shutemov

__collapse_huge_page_swapin() check number of referenced PTE to decide if the memory range is hot enough to justify swapin.

The problem is that it stops collapse altogether if there's not enough refereced pages, not only swappingin.

Fixes 0db501f7a34c ("mm, thp: convert from optimistic swapin collapsing to conservative")
---
 mm/khugepaged.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/khugepaged.c +2 -1
index 99bab7e4d05b..14d7afc90786 100644
@@ -905,7 +905,8 @@ static bool __collapse_huge_page_swapin(struct mm_struct *mm,
 	/* we only decide to swapin, if there is enough young ptes */
 	if (referenced < HPAGE_PMD_NR/2) {
 		trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
-		return false;
+		/* Do not block collapse, only skip swapping in */
+		return true;
 	}
 	vmf.pte = pte_offset_map(pmd, address);
 	for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
Signature · 1 line
2.26.0
#1 lore raw

PATCH 1/7 khugepaged: Add self test

In reply to Kirill A. Shutemov

The test checks if khugepaged is able to recover huge page where we expetect to do so. It only covers anon-THP for now.

Currenlty the test shows few failures. They are going to be addressed by the following patches.

---
 tools/testing/selftests/vm/Makefile     |   1 +
 tools/testing/selftests/vm/khugepaged.c | 841 ++++++++++++++++++++++++
 2 files changed, 842 insertions(+)
 create mode 100644 tools/testing/selftests/vm/khugepaged.c
tools/testing/selftests/vm/Makefile +1 -0
index 7f9a8a8c31da..981d0dc21f9e 100644
@@ -18,6 +18,7 @@ TEST_GEN_FILES += on-fault-limit
 TEST_GEN_FILES += thuge-gen
 TEST_GEN_FILES += transhuge-stress
 TEST_GEN_FILES += userfaultfd
+TEST_GEN_FILES += khugepaged
 
 ifneq (,$(filter $(ARCH),arm64 ia64 mips64 parisc64 ppc64 riscv64 s390x sh64 sparc64 x86_64))
 TEST_GEN_FILES += va_128TBswitch
tools/testing/selftests/vm/khugepaged.c new file +841 -0

841 lines not on this page · raw message

Signature · 1 line
2.26.0
#37 lore raw

PATCH 7/7 khugepaged: Introduce 'max_ptes_shared' tunable

In reply to Kirill A. Shutemov

``max_ptes_shared`` speicies how many pages can be shared across multiple processes. Exeeding the number woul block the collapse::

/sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_shared

A higher value may increase memory footprint for some workloads.

By default, at least half of pages has to be not shared.

---
 Documentation/admin-guide/mm/transhuge.rst |  7 ++
 mm/khugepaged.c                            | 52 ++++++++++++--
 tools/testing/selftests/vm/khugepaged.c    | 83 ++++++++++++++++++++++
 3 files changed, 138 insertions(+), 4 deletions(-)
Documentation/admin-guide/mm/transhuge.rst +7 -0
index bd5714547cee..d16e4f2bb70f 100644
@@ -220,6 +220,13 @@ memory. A lower value can prevent THPs from being
 collapsed, resulting fewer pages being collapsed into
 THPs, and lower memory access performance.
 
+``max_ptes_shared`` speicies how many pages can be shared across multiple
+processes. Exeeding the number woul block the collapse::
+
+	/sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_shared
+
+A higher value may increase memory footprint for some workloads.
+
 Boot parameter
 ==============
 
mm/khugepaged.c +48 -4

114 lines not on this page · raw message

tools/testing/selftests/vm/khugepaged.c +83 -0

125 lines not on this page · raw message

Signature · 1 line
2.26.0
#33 lore raw

PATCH 6/7 thp: Change CoW semantics for anon-THP

In reply to Kirill A. Shutemov

Currently we have different copy-on-write semantics for anon- and file-THP. For anon-THP we try to allocate huge page on the write fault, but on file-THP we split PMD and allocate 4k page.

Arguably, file-THP semantics is more desirable: we don't necessary want to unshare full PMD range from the parent on the first access. This is the primary reason THP is unusable for some workloads, like Redis.

The original THP refcounting didn't allow to have PTE-mapped compound pages, so we had no options, but to allocate huge page on CoW (with fallback to 512 4k pages).

The current refcounting doesn't have such limitations and we can cut a lot of complex code out of fault path.

khugepaged is now able to recover THP from such ranges if the configuration allows.

---
 mm/huge_memory.c | 247 +++++------------------------------------------
 1 file changed, 24 insertions(+), 223 deletions(-)
mm/huge_memory.c +24 -223
index ef6a6bcb291f..15b7a9c86b7c 100644
@@ -1206,262 +1206,63 @@ void huge_pmd_set_accessed(struct vm_fault *vmf, pmd_t orig_pmd)
 	spin_unlock(vmf->ptl);
 }
 
-static vm_fault_t do_huge_pmd_wp_page_fallback(struct vm_fault *vmf,
-			pmd_t orig_pmd, struct page *page)
-{
-	struct vm_area_struct *vma = vmf->vma;
-	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-	struct mem_cgroup *memcg;
-	pgtable_t pgtable;
-	pmd_t _pmd;
-	int i;
-	vm_fault_t ret = 0;
-	struct page **pages;
-	struct mmu_notifier_range range;
-
-	pages = kmalloc_array(HPAGE_PMD_NR, sizeof(struct page *),
-			      GFP_KERNEL);
-	if (unlikely(!pages)) {
-		ret |= VM_FAULT_OOM;
-		goto out;
-	}
-
-	for (i = 0; i < HPAGE_PMD_NR; i++) {
-		pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE, vma,
-					       vmf->address, page_to_nid(page));
-		if (unlikely(!pages[i] ||
-			     mem_cgroup_try_charge_delay(pages[i], vma->vm_mm,
-				     GFP_KERNEL, &memcg, false))) {
-			if (pages[i])
-				put_page(pages[i]);
-			while (--i >= 0) {
-				memcg = (void *)page_private(pages[i]);
-				set_page_private(pages[i], 0);
-				mem_cgroup_cancel_charge(pages[i], memcg,
-						false);
-				put_page(pages[i]);
-			}
-			kfree(pages);
-			ret |= VM_FAULT_OOM;
-			goto out;
-		}
-		set_page_private(pages[i], (unsigned long)memcg);
-	}
-
-	for (i = 0; i < HPAGE_PMD_NR; i++) {
-		copy_user_highpage(pages[i], page + i,
-				   haddr + PAGE_SIZE * i, vma);
-		__SetPageUptodate(pages[i]);
-		cond_resched();
-	}
-
-	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-				haddr, haddr + HPAGE_PMD_SIZE);
-	mmu_notifier_invalidate_range_start(&range);
-
-	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
-	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-		goto out_free_pages;
-	VM_BUG_ON_PAGE(!PageHead(page), page);
-
-	/*
-	 * Leave pmd empty until pte is filled note we must notify here as
-	 * concurrent CPU thread might write to new page before the call to
-	 * mmu_notifier_invalidate_range_end() happens which can lead to a
-	 * device seeing memory write in different order than CPU.
-	 *
-	 * See Documentation/vm/mmu_notifier.rst
-	 */
-	pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-
-	pgtable = pgtable_trans_huge_withdraw(vma->vm_mm, vmf->pmd);
-	pmd_populate(vma->vm_mm, &_pmd, pgtable);
-
-	for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
-		pte_t entry;
-		entry = mk_pte(pages[i], vma->vm_page_prot);
-		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
-		memcg = (void *)page_private(pages[i]);
-		set_page_private(pages[i], 0);
-		page_add_new_anon_rmap(pages[i], vmf->vma, haddr, false);
-		mem_cgroup_commit_charge(pages[i], memcg, false, false);
-		lru_cache_add_active_or_unevictable(pages[i], vma);
-		vmf->pte = pte_offset_map(&_pmd, haddr);
-		VM_BUG_ON(!pte_none(*vmf->pte));
-		set_pte_at(vma->vm_mm, haddr, vmf->pte, entry);
-		pte_unmap(vmf->pte);
-	}
-	kfree(pages);
-
-	smp_wmb(); /* make pte visible before pmd */
-	pmd_populate(vma->vm_mm, vmf->pmd, pgtable);
-	page_remove_rmap(page, true);
-	spin_unlock(vmf->ptl);
-
-	/*
-	 * No need to double call mmu_notifier->invalidate_range() callback as
-	 * the above pmdp_huge_clear_flush_notify() did already call it.
-	 */
-	mmu_notifier_invalidate_range_only_end(&range);
-
-	ret |= VM_FAULT_WRITE;
-	put_page(page);
-
-out:
-	return ret;
-
-out_free_pages:
-	spin_unlock(vmf->ptl);
-	mmu_notifier_invalidate_range_end(&range);
-	for (i = 0; i < HPAGE_PMD_NR; i++) {
-		memcg = (void *)page_private(pages[i]);
-		set_page_private(pages[i], 0);
-		mem_cgroup_cancel_charge(pages[i], memcg, false);
-		put_page(pages[i]);
-	}
-	kfree(pages);
-	goto out;
-}
-
 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf, pmd_t orig_pmd)
 {
 	struct vm_area_struct *vma = vmf->vma;
-	struct page *page = NULL, *new_page;
-	struct mem_cgroup *memcg;
+	struct page *page;
 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-	struct mmu_notifier_range range;
-	gfp_t huge_gfp;			/* for allocation and charge */
-	vm_fault_t ret = 0;
 
 	vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
 	VM_BUG_ON_VMA(!vma->anon_vma, vma);
+
 	if (is_huge_zero_pmd(orig_pmd))
-		goto alloc;
+		goto fallback;
+
 	spin_lock(vmf->ptl);
-	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-		goto out_unlock;
+
+	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+		spin_unlock(vmf->ptl);
+		return 0;
+	}
 
 	page = pmd_page(orig_pmd);
 	VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
-	/*
-	 * We can only reuse the page if nobody else maps the huge page or it's
-	 * part.
-	 */
+
+	/* Lock page for reuse_swap_page() */
 	if (!trylock_page(page)) {
 		get_page(page);
 		spin_unlock(vmf->ptl);
 		lock_page(page);
 		spin_lock(vmf->ptl);
 		if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+			spin_unlock(vmf->ptl);
 			unlock_page(page);
 			put_page(page);
-			goto out_unlock;
+			return 0;
 		}
 		put_page(page);
 	}
+
+	/*
+	 * We can only reuse the page if nobody else maps the huge page or it's
+	 * part.
+	 */
 	if (reuse_swap_page(page, NULL)) {
 		pmd_t entry;
 		entry = pmd_mkyoung(orig_pmd);
 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
 		if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry,  1))
 			update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-		ret |= VM_FAULT_WRITE;
 		unlock_page(page);
-		goto out_unlock;
-	}
-	unlock_page(page);
-	get_page(page);
-	spin_unlock(vmf->ptl);
-alloc:
-	if (__transparent_hugepage_enabled(vma) &&
-	    !transparent_hugepage_debug_cow()) {
-		huge_gfp = alloc_hugepage_direct_gfpmask(vma);
-		new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
-	} else
-		new_page = NULL;
-
-	if (likely(new_page)) {
-		prep_transhuge_page(new_page);
-	} else {
-		if (!page) {
-			split_huge_pmd(vma, vmf->pmd, vmf->address);
-			ret |= VM_FAULT_FALLBACK;
-		} else {
-			ret = do_huge_pmd_wp_page_fallback(vmf, orig_pmd, page);
-			if (ret & VM_FAULT_OOM) {
-				split_huge_pmd(vma, vmf->pmd, vmf->address);
-				ret |= VM_FAULT_FALLBACK;
-			}
-			put_page(page);
-		}
-		count_vm_event(THP_FAULT_FALLBACK);
-		goto out;
-	}
-
-	if (unlikely(mem_cgroup_try_charge_delay(new_page, vma->vm_mm,
-					huge_gfp, &memcg, true))) {
-		put_page(new_page);
-		split_huge_pmd(vma, vmf->pmd, vmf->address);
-		if (page)
-			put_page(page);
-		ret |= VM_FAULT_FALLBACK;
-		count_vm_event(THP_FAULT_FALLBACK);
-		goto out;
-	}
-
-	count_vm_event(THP_FAULT_ALLOC);
-	count_memcg_events(memcg, THP_FAULT_ALLOC, 1);
-
-	if (!page)
-		clear_huge_page(new_page, vmf->address, HPAGE_PMD_NR);
-	else
-		copy_user_huge_page(new_page, page, vmf->address,
-				    vma, HPAGE_PMD_NR);
-	__SetPageUptodate(new_page);
-
-	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-				haddr, haddr + HPAGE_PMD_SIZE);
-	mmu_notifier_invalidate_range_start(&range);
-
-	spin_lock(vmf->ptl);
-	if (page)
-		put_page(page);
-	if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
 		spin_unlock(vmf->ptl);
-		mem_cgroup_cancel_charge(new_page, memcg, true);
-		put_page(new_page);
-		goto out_mn;
-	} else {
-		pmd_t entry;
-		entry = mk_huge_pmd(new_page, vma->vm_page_prot);
-		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
-		pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-		page_add_new_anon_rmap(new_page, vma, haddr, true);
-		mem_cgroup_commit_charge(new_page, memcg, false, true);
-		lru_cache_add_active_or_unevictable(new_page, vma);
-		set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
-		update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-		if (!page) {
-			add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
-		} else {
-			VM_BUG_ON_PAGE(!PageHead(page), page);
-			page_remove_rmap(page, true);
-			put_page(page);
-		}
-		ret |= VM_FAULT_WRITE;
+		return VM_FAULT_WRITE;
 	}
+
+	unlock_page(page);
 	spin_unlock(vmf->ptl);
-out_mn:
-	/*
-	 * No need to double call mmu_notifier->invalidate_range() callback as
-	 * the above pmdp_huge_clear_flush_notify() did already call it.
-	 */
-	mmu_notifier_invalidate_range_only_end(&range);
-out:
-	return ret;
-out_unlock:
-	spin_unlock(vmf->ptl);
-	return ret;
+fallback:
+	__split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
+	return VM_FAULT_FALLBACK;
 }
 
 /*
Signature · 1 line
2.26.0
#16 lore raw

PATCH 5/7 khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +31 -10
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+	/*
+	 * We need to unlock and put compound page on LRU only once.
+	 * The rest of the pages have to be locked and not on LRU here.
+	 */
+	VM_BUG_ON_PAGE(!PageCompound(page) &&
+			(!PageLocked(page) && PageLRU(page)), page);
+
+	if (!PageLocked(page))
+		return;
+
+	page = compound_head(page);
 	dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
 	unlock_page(page);
 	putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 	pte_t *_pte;
 	int none_or_zero = 0, result = 0, referenced = 0;
 	bool writable = false;
+	LIST_HEAD(compound_pagelist);
 
 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
 	     _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 			goto out;
 		}
 
-		/* TODO: teach khugepaged to collapse THP mapped with pte */
+		VM_BUG_ON_PAGE(!PageAnon(page), page);
+
 		if (PageCompound(page)) {
-			result = SCAN_PAGE_COMPOUND;
-			goto out;
-		}
+			struct page *p;
+			page = compound_head(page);
 
-		VM_BUG_ON_PAGE(!PageAnon(page), page);
+			/*
+			 * Check if we have dealt with the compount page
+			 * already
+			 */
+			list_for_each_entry(p, &compound_pagelist, lru) {
+				if (page ==  p)
+					break;
+			}
+			if (page ==  p)
+				continue;
+		}
 
 		/*
 		 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		    page_is_young(page) || PageReferenced(page) ||
 		    mmu_notifier_test_young(vma->vm_mm, address))
 			referenced++;
+
+		if (PageCompound(page))
+			list_add_tail(&page->lru, &compound_pagelist);
 	}
 	if (likely(writable)) {
 		if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		/* TODO: teach khugepaged to collapse THP mapped with pte */
-		if (PageCompound(page)) {
-			result = SCAN_PAGE_COMPOUND;
-			goto out_unmap;
-		}
+		page = compound_head(page);
 
 		/*
 		 * Record which node the original page is from and save this
Signature · 1 line
2.26.0
reviewer Reviewed-by on v1 2/7
#3 lore raw

Re: [PATCH 2/7] khugepaged: Do not stop collapse if less than half PTEs are referenced

In reply to Kirill A. Shutemov
Quoted 28 lines · Kirill A. Shutemov

__collapse_huge_page_swapin() check number of referenced PTE to decide if the memory range is hot enough to justify swapin.

The problem is that it stops collapse altogether if there's not enough refereced pages, not only swappingin.

Fixes 0db501f7a34c ("mm, thp: convert from optimistic swapin collapsing to conservative")
---
 mm/khugepaged.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/khugepaged.c +2 -1
index 99bab7e4d05b..14d7afc90786 100644
@@ -905,7 +905,8 @@ static bool __collapse_huge_page_swapin(struct mm_struct *mm,
 	/* we only decide to swapin, if there is enough young ptes */
 	if (referenced < HPAGE_PMD_NR/2) {
 		trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
-		return false;
+		/* Do not block collapse, only skip swapping in */
+		return true;
 	}
 	vmf.pte = pte_offset_map(pmd, address);
 	for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
Signature · 1 line
2.26.0

Make sense.

—
Best Regards,
Yan Zi

reviewer Reviewed-by on v1 3/7
#6 lore raw

Re: [PATCH 3/7] khugepaged: Drain LRU add pagevec to get rid of extra pins

In reply to Kirill A. Shutemov
Quoted 35 lines · Kirill A. Shutemov

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +8 -0
index 14d7afc90786..39e0994abeb8 100644
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		 * The page must only be referenced by the scanned process
 		 * and page swap cache.
 		 */
+		if (page_count(page) != 1 + PageSwapCache(page)) {
+			/*
+			 * Drain pagevec and retry just in case we can get rid
+			 * of the extra pin, like in swapin case.
+			 */
+			lru_add_drain();
+		}
 		if (page_count(page) != 1 + PageSwapCache(page)) {
 			unlock_page(page);
 			result = SCAN_PAGE_COUNT;
 			goto out;
 		}
+
 		if (pte_write(pteval)) {
 			writable = true;
 		} else {
Signature · 1 line
2.26.0

Looks good to me. Is the added empty line intentional?

—
Best Regards,
Yan Zi

#4 lore raw

Re: [PATCH 2/7] khugepaged: Do not stop collapse if less than half PTEs are referenced

In reply to Kirill A. Shutemov
Quoted 6 lines · Kirill A. Shutemov

__collapse_huge_page_swapin() check number of referenced PTE to decide if the memory range is hot enough to justify swapin.

The problem is that it stops collapse altogether if there's not enough refereced pages, not only swappingin.

s/refereced/referenced

Quoted 25 lines
Fixes 0db501f7a34c ("mm, thp: convert from optimistic swapin collapsing to conservative")
---
 mm/khugepaged.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/khugepaged.c +2 -2
index 99bab7e4d05b..14d7afc90786 100644
@@ -905,7 +905,8 @@ static bool __collapse_huge_page_swapin(struct mm_struct *mm,
        /* we only decide to swapin, if there is enough young ptes */
        if (referenced < HPAGE_PMD_NR/2) {
                trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
-               return false;
+               /* Do not block collapse, only skip swapping in */
+               return true;
        }
        vmf.pte = pte_offset_map(pmd, address);
        for (; vmf.address < address + HPAGE_PMD_NR*PAGE_SIZE;
--

2.26.0

Reviewed-by on v1 3/7
#8 lore raw

Re: [PATCH 3/7] khugepaged: Drain LRU add pagevec to get rid of extra pins

In reply to Kirill A. Shutemov
Quoted 15 lines · Kirill A. Shutemov

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +0 -0
index 14d7afc90786..39e0994abeb8 100644

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 593

Quoted 9 lines
mm/khugepaged.c +6 -0
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                 * The page must only be referenced by the scanned process
                 * and page swap cache.
                 */
+               if (page_count(page) != 1 + PageSwapCache(page)) {
+                       /*
+                        * Drain pagevec and retry just in case we can get rid
+                        * of the extra pin, like in swapin case.
+                        */
+                       lru_add_drain();

This is definitely correct.

I'm wondering if we need one more lru_add_drain() before PageLRU check in khugepaged_scan_pmd() or not? The page might be in lru cache then get skipped. This would improve the success rate.

Quoted 14 lines
mm/khugepaged.c +2 -1
+               }
                if (page_count(page) != 1 + PageSwapCache(page)) {
                        unlock_page(page);
                        result = SCAN_PAGE_COUNT;
                        goto out;
                }
+
                if (pte_write(pteval)) {
                        writable = true;
                } else {
--

2.26.0

#13 lore raw

Re: [PATCH 4/7] khugepaged: Allow to callapse a page shared across fork

In reply to Kirill A. Shutemov
Quoted 22 lines · Kirill A. Shutemov

The page can be included into collapse as long as it doesn't have extra pins (from GUP or otherwise).

---
 mm/khugepaged.c | 28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)
mm/khugepaged.c +3 -3
index 39e0994abeb8..b47edfe57f7b 100644
@@ -581,18 +581,26 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		}
 
 		/*
-		 * cannot use mapcount: can't collapse if there's a gup pin.
-		 * The page must only be referenced by the scanned process
-		 * and page swap cache.
+		 * Check if the page has any GUP (or other external) pins.
+		 *
+		 * The page table that maps the page has been already unlinked

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 595

Quoted 10 lines
mm/khugepaged.c +8 -1
+		 * from the page table tree and this process cannot get
+		 * additinal pin on the page.
+		 *
+		 * New pins can come later if the page is shared across fork,
+		 * but not for the this process. It is fine. The other process
+		 * cannot write to the page, only trigger CoW.
 		 */
-		if (page_count(page) != 1 + PageSwapCache(page)) {
+		if (total_mapcount(page) + PageSwapCache(page) !=
+				page_count(page)) {

Do you think having a function for this check would be better? Since the check is used three times.

Quoted 13 lines
mm/khugepaged.c +2 -1
 			/*
 			 * Drain pagevec and retry just in case we can get rid
 			 * of the extra pin, like in swapin case.
 			 */
 			lru_add_drain();
 		}
-		if (page_count(page) != 1 + PageSwapCache(page)) {
+		if (total_mapcount(page) + PageSwapCache(page) !=
+				page_count(page)) {
 			unlock_page(page);
 			result = SCAN_PAGE_COUNT;
 			goto out;

mm/khugepaged.c static void __collapse_huge_page_copy(pte_t *pte, struct page *page, · line 683

Quoted 4 lines
mm/khugepaged.c +0 -1
@@ -680,7 +688,6 @@ static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
 		} else {
 			src_page = pte_page(pteval);
 			copy_user_highpage(page, src_page, address, vma);
-			VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);

Maybe replace it with this?

VM_BUG_ON_PAGE(page_mapcount(src_page) + PageSwapCache(src_page) != page_count(src_page), src_page);

Quoted 21 lines
mm/khugepaged.c +3 -6
 			release_pte_page(src_page);
 			/*
 			 * ptl mostly unnecessary, but preempt has to
@@ -1209,12 +1216,9 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		/*
-		 * cannot use mapcount: can't collapse if there's a gup pin.
-		 * The page must only be referenced by the scanned process
-		 * and page swap cache.
-		 */
-		if (page_count(page) != 1 + PageSwapCache(page)) {
+		/* Check if the page has any GUP (or other external) pins */
+		if (total_mapcount(page) + PageSwapCache(page) !=
+				page_count(page)) {
 			result = SCAN_PAGE_COUNT;
 			goto out_unmap;
 		}
Signature · 1 line
2.26.0

Thanks.

—
Best Regards,
Yan Zi

#17 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 21 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +2 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 529

Quoted 10 lines
mm/khugepaged.c +9 -0
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
+       if (!PageLocked(page))
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));

We need count in the number of base pages. The same counter is modified by vmscan in base page unit. Also need modify the inc path.

Quoted 17 lines
mm/khugepaged.c +3 -1
        unlock_page(page);
        putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
        pte_t *_pte;
        int none_or_zero = 0, result = 0, referenced = 0;
        bool writable = false;
+       LIST_HEAD(compound_pagelist);
 
        for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
             _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                        goto out;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
+               VM_BUG_ON_PAGE(!PageAnon(page), page);
+

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 583

Quoted 10 lines
mm/khugepaged.c +4 -4
                if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out;
-               }
+                       struct page *p;
+                       page = compound_head(page);
 
-               VM_BUG_ON_PAGE(!PageAnon(page), page);
+                       /*
+                        * Check if we have dealt with the compount page

s/compount/compound

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 591

Quoted 8 lines
mm/khugepaged.c +8 -0
+                        * already
+                        */
+                       list_for_each_entry(p, &compound_pagelist, lru) {
+                               if (page ==  p)
+                                       break;
+                       }
+                       if (page ==  p)
+                               continue;

I don't quite understand why we need the above check. My understanding is when we scan the ptes, once the first PTE mapped subpage is found, then the THP would be added into compound_pagelist, then the later loop would find the same THP on the list then just break the loop. Did I miss anything?

Quoted 31 lines
mm/khugepaged.c +5 -6
+               }
 
                /*
                 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    page_is_young(page) || PageReferenced(page) ||
                    mmu_notifier_test_young(vma->vm_mm, address))
                        referenced++;
+
+               if (PageCompound(page))
+                       list_add_tail(&page->lru, &compound_pagelist);
        }
        if (likely(writable)) {
                if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
-               if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out_unmap;
-               }
+               page = compound_head(page);
 
                /*
                 * Record which node the original page is from and save this
--

2.26.0

reviewer
#22 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 4 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

s/putpack/putback/

Quoted 11 lines
---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +0 -0
index b47edfe57f7b..c8c2c463095c 100644

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 523

Quoted 9 lines
mm/khugepaged.c +6 -0
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+	/*
+	 * We need to unlock and put compound page on LRU only once.
+	 * The rest of the pages have to be locked and not on LRU here.
+	 */
+	VM_BUG_ON_PAGE(!PageCompound(page) &&
+			(!PageLocked(page) && PageLRU(page)), page);

It only checks base pages.

Add

VM_BUG_ON_PAGE(PageCompound(page) && PageLocked(page) && PageLRU(page), page);

to check for compound pages.

Quoted 23 lines
mm/khugepaged.c +8 -1
+
+	if (!PageLocked(page))
+		return;
+
+	page = compound_head(page);
 	dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
 	unlock_page(page);
 	putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 	pte_t *_pte;
 	int none_or_zero = 0, result = 0, referenced = 0;
 	bool writable = false;
+	LIST_HEAD(compound_pagelist);
 
 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
 	     _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 			goto out;
 		}
 
-		/* TODO: teach khugepaged to collapse THP mapped with pte */
+		VM_BUG_ON_PAGE(!PageAnon(page), page);
+

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 583

Quoted 10 lines
mm/khugepaged.c +4 -4
 		if (PageCompound(page)) {
-			result = SCAN_PAGE_COMPOUND;
-			goto out;
-		}
+			struct page *p;
+			page = compound_head(page);
 
-		VM_BUG_ON_PAGE(!PageAnon(page), page);
+			/*
+			 * Check if we have dealt with the compount page

s/compount/compound/

Quoted 13 lines
mm/khugepaged.c +9 -0
+			 * already
+			 */
+			list_for_each_entry(p, &compound_pagelist, lru) {
+				if (page ==  p)
+					break;
+			}
+			if (page ==  p)
+				continue;
+		}
 
 		/*
 		 * We can do it before isolate_lru_page because the

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 670

Quoted 9 lines
mm/khugepaged.c +3 -0
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		    page_is_young(page) || PageReferenced(page) ||
 		    mmu_notifier_test_young(vma->vm_mm, address))
 			referenced++;
+
+		if (PageCompound(page))
+			list_add_tail(&page->lru, &compound_pagelist);
 	}
 	if (likely(writable)) {
 		if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

If a compound page is seen here, can we bail out the loop early? I guess not, because we can a partially mapped compound page at the beginning or the end of a VMA, right?

Quoted 15 lines
mm/khugepaged.c +1 -5
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		/* TODO: teach khugepaged to collapse THP mapped with pte */
-		if (PageCompound(page)) {
-			result = SCAN_PAGE_COMPOUND;
-			goto out_unmap;
-		}
+		page = compound_head(page);
 
 		/*
 		 * Record which node the original page is from and save this
Signature · 1 line
2.26.0

—
Best Regards,
Yan Zi

#34 lore raw

Re: [PATCH 6/7] thp: Change CoW semantics for anon-THP

In reply to Kirill A. Shutemov
Quoted 4 lines · Kirill A. Shutemov

Currently we have different copy-on-write semantics for anon- and file-THP. For anon-THP we try to allocate huge page on the write fault, but on file-THP we split PMD and allocate 4k page.

I agree this seems confusing.

Quoted 9 lines

Arguably, file-THP semantics is more desirable: we don't necessary want to unshare full PMD range from the parent on the first access. This is the primary reason THP is unusable for some workloads, like Redis.

The original THP refcounting didn't allow to have PTE-mapped compound pages, so we had no options, but to allocate huge page on CoW (with fallback to 512 4k pages).

Quoted 5 lines

The current refcounting doesn't have such limitations and we can cut a lot of complex code out of fault path.

khugepaged is now able to recover THP from such ranges if the configuration allows.

It looks this patch would just split the PMD then fallback to handle it on PTE level, it definitely simplify the code a lot. However it makes the use of THP depend on the productivity of khugepaged. And the success rate of THP allocation in khugepaged depends on defrag. But by default khugepaged runs at very low priority, so khugepaged defrag may result in priority inversion easily.

For example we saw THP split in reclaim path triggered by khugepaged held write anon_vma lock, but the other process which was doing reclaim too was blocked by anon_vma lock. Then the cond_resched() in rmap walk would make khugepaged preempted by all other processes easily so khugepaged may hold the anon_vma lock for indefinite time. Then we saw hung tasks.

So we have khugepaged defrag disabled for some workloads to workaround the priority inversion problem. So, I'm concerned some processes may never get THP for some our workloads with this patch applied.

The priority inversion caused by khugepaged was not very usual. Just my two cents.

Quoted 301 lines
---
 mm/huge_memory.c | 247 +++++------------------------------------------
 1 file changed, 24 insertions(+), 223 deletions(-)
mm/huge_memory.c +24 -224
index ef6a6bcb291f..15b7a9c86b7c 100644
@@ -1206,262 +1206,63 @@ void huge_pmd_set_accessed(struct vm_fault *vmf, pmd_t orig_pmd)
        spin_unlock(vmf->ptl);
 }
 
-static vm_fault_t do_huge_pmd_wp_page_fallback(struct vm_fault *vmf,
-                       pmd_t orig_pmd, struct page *page)
-{
-       struct vm_area_struct *vma = vmf->vma;
-       unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-       struct mem_cgroup *memcg;
-       pgtable_t pgtable;
-       pmd_t _pmd;
-       int i;
-       vm_fault_t ret = 0;
-       struct page **pages;
-       struct mmu_notifier_range range;
-
-       pages = kmalloc_array(HPAGE_PMD_NR, sizeof(struct page *),
-                             GFP_KERNEL);
-       if (unlikely(!pages)) {
-               ret |= VM_FAULT_OOM;
-               goto out;
-       }
-
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE, vma,
-                                              vmf->address, page_to_nid(page));
-               if (unlikely(!pages[i] ||
-                            mem_cgroup_try_charge_delay(pages[i], vma->vm_mm,
-                                    GFP_KERNEL, &memcg, false))) {
-                       if (pages[i])
-                               put_page(pages[i]);
-                       while (--i >= 0) {
-                               memcg = (void *)page_private(pages[i]);
-                               set_page_private(pages[i], 0);
-                               mem_cgroup_cancel_charge(pages[i], memcg,
-                                               false);
-                               put_page(pages[i]);
-                       }
-                       kfree(pages);
-                       ret |= VM_FAULT_OOM;
-                       goto out;
-               }
-               set_page_private(pages[i], (unsigned long)memcg);
-       }
-
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               copy_user_highpage(pages[i], page + i,
-                                  haddr + PAGE_SIZE * i, vma);
-               __SetPageUptodate(pages[i]);
-               cond_resched();
-       }
-
-       mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-                               haddr, haddr + HPAGE_PMD_SIZE);
-       mmu_notifier_invalidate_range_start(&range);
-
-       vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-               goto out_free_pages;
-       VM_BUG_ON_PAGE(!PageHead(page), page);
-
-       /*
-        * Leave pmd empty until pte is filled note we must notify here as
-        * concurrent CPU thread might write to new page before the call to
-        * mmu_notifier_invalidate_range_end() happens which can lead to a
-        * device seeing memory write in different order than CPU.
-        *
-        * See Documentation/vm/mmu_notifier.rst
-        */
-       pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-
-       pgtable = pgtable_trans_huge_withdraw(vma->vm_mm, vmf->pmd);
-       pmd_populate(vma->vm_mm, &_pmd, pgtable);
-
-       for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
-               pte_t entry;
-               entry = mk_pte(pages[i], vma->vm_page_prot);
-               entry = maybe_mkwrite(pte_mkdirty(entry), vma);
-               memcg = (void *)page_private(pages[i]);
-               set_page_private(pages[i], 0);
-               page_add_new_anon_rmap(pages[i], vmf->vma, haddr, false);
-               mem_cgroup_commit_charge(pages[i], memcg, false, false);
-               lru_cache_add_active_or_unevictable(pages[i], vma);
-               vmf->pte = pte_offset_map(&_pmd, haddr);
-               VM_BUG_ON(!pte_none(*vmf->pte));
-               set_pte_at(vma->vm_mm, haddr, vmf->pte, entry);
-               pte_unmap(vmf->pte);
-       }
-       kfree(pages);
-
-       smp_wmb(); /* make pte visible before pmd */
-       pmd_populate(vma->vm_mm, vmf->pmd, pgtable);
-       page_remove_rmap(page, true);
-       spin_unlock(vmf->ptl);
-
-       /*
-        * No need to double call mmu_notifier->invalidate_range() callback as
-        * the above pmdp_huge_clear_flush_notify() did already call it.
-        */
-       mmu_notifier_invalidate_range_only_end(&range);
-
-       ret |= VM_FAULT_WRITE;
-       put_page(page);
-
-out:
-       return ret;
-
-out_free_pages:
-       spin_unlock(vmf->ptl);
-       mmu_notifier_invalidate_range_end(&range);
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               memcg = (void *)page_private(pages[i]);
-               set_page_private(pages[i], 0);
-               mem_cgroup_cancel_charge(pages[i], memcg, false);
-               put_page(pages[i]);
-       }
-       kfree(pages);
-       goto out;
-}
-
 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf, pmd_t orig_pmd)
 {
        struct vm_area_struct *vma = vmf->vma;
-       struct page *page = NULL, *new_page;
-       struct mem_cgroup *memcg;
+       struct page *page;
        unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-       struct mmu_notifier_range range;
-       gfp_t huge_gfp;                 /* for allocation and charge */
-       vm_fault_t ret = 0;
 
        vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
        VM_BUG_ON_VMA(!vma->anon_vma, vma);
+
        if (is_huge_zero_pmd(orig_pmd))
-               goto alloc;
+               goto fallback;
+
        spin_lock(vmf->ptl);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-               goto out_unlock;
+
+       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+               spin_unlock(vmf->ptl);
+               return 0;
+       }
 
        page = pmd_page(orig_pmd);
        VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
-       /*
-        * We can only reuse the page if nobody else maps the huge page or it's
-        * part.
-        */
+
+       /* Lock page for reuse_swap_page() */
        if (!trylock_page(page)) {
                get_page(page);
                spin_unlock(vmf->ptl);
                lock_page(page);
                spin_lock(vmf->ptl);
                if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+                       spin_unlock(vmf->ptl);
                        unlock_page(page);
                        put_page(page);
-                       goto out_unlock;
+                       return 0;
                }
                put_page(page);
        }
+
+       /*
+        * We can only reuse the page if nobody else maps the huge page or it's
+        * part.
+        */
        if (reuse_swap_page(page, NULL)) {
                pmd_t entry;
                entry = pmd_mkyoung(orig_pmd);
                entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
                if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry,  1))
                        update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-               ret |= VM_FAULT_WRITE;
                unlock_page(page);
-               goto out_unlock;
-       }
-       unlock_page(page);
-       get_page(page);
-       spin_unlock(vmf->ptl);
-alloc:
-       if (__transparent_hugepage_enabled(vma) &&
-           !transparent_hugepage_debug_cow()) {
-               huge_gfp = alloc_hugepage_direct_gfpmask(vma);
-               new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
-       } else
-               new_page = NULL;
-
-       if (likely(new_page)) {
-               prep_transhuge_page(new_page);
-       } else {
-               if (!page) {
-                       split_huge_pmd(vma, vmf->pmd, vmf->address);
-                       ret |= VM_FAULT_FALLBACK;
-               } else {
-                       ret = do_huge_pmd_wp_page_fallback(vmf, orig_pmd, page);
-                       if (ret & VM_FAULT_OOM) {
-                               split_huge_pmd(vma, vmf->pmd, vmf->address);
-                               ret |= VM_FAULT_FALLBACK;
-                       }
-                       put_page(page);
-               }
-               count_vm_event(THP_FAULT_FALLBACK);
-               goto out;
-       }
-
-       if (unlikely(mem_cgroup_try_charge_delay(new_page, vma->vm_mm,
-                                       huge_gfp, &memcg, true))) {
-               put_page(new_page);
-               split_huge_pmd(vma, vmf->pmd, vmf->address);
-               if (page)
-                       put_page(page);
-               ret |= VM_FAULT_FALLBACK;
-               count_vm_event(THP_FAULT_FALLBACK);
-               goto out;
-       }
-
-       count_vm_event(THP_FAULT_ALLOC);
-       count_memcg_events(memcg, THP_FAULT_ALLOC, 1);
-
-       if (!page)
-               clear_huge_page(new_page, vmf->address, HPAGE_PMD_NR);
-       else
-               copy_user_huge_page(new_page, page, vmf->address,
-                                   vma, HPAGE_PMD_NR);
-       __SetPageUptodate(new_page);
-
-       mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-                               haddr, haddr + HPAGE_PMD_SIZE);
-       mmu_notifier_invalidate_range_start(&range);
-
-       spin_lock(vmf->ptl);
-       if (page)
-               put_page(page);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
                spin_unlock(vmf->ptl);
-               mem_cgroup_cancel_charge(new_page, memcg, true);
-               put_page(new_page);
-               goto out_mn;
-       } else {
-               pmd_t entry;
-               entry = mk_huge_pmd(new_page, vma->vm_page_prot);
-               entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
-               pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-               page_add_new_anon_rmap(new_page, vma, haddr, true);
-               mem_cgroup_commit_charge(new_page, memcg, false, true);
-               lru_cache_add_active_or_unevictable(new_page, vma);
-               set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
-               update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-               if (!page) {
-                       add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
-               } else {
-                       VM_BUG_ON_PAGE(!PageHead(page), page);
-                       page_remove_rmap(page, true);
-                       put_page(page);
-               }
-               ret |= VM_FAULT_WRITE;
+               return VM_FAULT_WRITE;
        }
+
+       unlock_page(page);
        spin_unlock(vmf->ptl);
-out_mn:
-       /*
-        * No need to double call mmu_notifier->invalidate_range() callback as
-        * the above pmdp_huge_clear_flush_notify() did already call it.
-        */
-       mmu_notifier_invalidate_range_only_end(&range);
-out:
-       return ret;
-out_unlock:
-       spin_unlock(vmf->ptl);
-       return ret;
+fallback:
+       __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
+       return VM_FAULT_FALLBACK;
 }
 
 /*
--

2.26.0

#30 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 23 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +4 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.
+        * The rest of the pages have to be locked and not on LRU here.
+        */

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 531

Quoted 10 lines
mm/khugepaged.c +7 -0
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
+       if (!PageLocked(page))
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
        unlock_page(page);
        putback_lru_page(page);

BTW, wouldn't this unlock the whole THP and put it back to LRU? Then we may copy the following PTE mapped pages with page unlocked and on LRU. I don't see critical problem, just the pages might be on and off LRU by others, i.e. vmscan, compaction, migration, etc. But no one could take the page away since try_to_unmap() would fail, but not very productive.

Quoted 64 lines
mm/khugepaged.c +20 -11
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
        pte_t *_pte;
        int none_or_zero = 0, result = 0, referenced = 0;
        bool writable = false;
+       LIST_HEAD(compound_pagelist);
 
        for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
             _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                        goto out;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
+               VM_BUG_ON_PAGE(!PageAnon(page), page);
+
                if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out;
-               }
+                       struct page *p;
+                       page = compound_head(page);
 
-               VM_BUG_ON_PAGE(!PageAnon(page), page);
+                       /*
+                        * Check if we have dealt with the compount page
+                        * already
+                        */
+                       list_for_each_entry(p, &compound_pagelist, lru) {
+                               if (page ==  p)
+                                       break;
+                       }
+                       if (page ==  p)
+                               continue;
+               }
 
                /*
                 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    page_is_young(page) || PageReferenced(page) ||
                    mmu_notifier_test_young(vma->vm_mm, address))
                        referenced++;
+
+               if (PageCompound(page))
+                       list_add_tail(&page->lru, &compound_pagelist);
        }
        if (likely(writable)) {
                if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
-               if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out_unmap;
-               }
+               page = compound_head(page);
 
                /*
                 * Record which node the original page is from and save this
--

2.26.0

#14 lore raw

Re: [PATCH 4/7] khugepaged: Allow to callapse a page shared across fork

In reply to Zi Yan
Quoted 58 lines · Zi Yan
Quoted 22 lines · Kirill A. Shutemov

The page can be included into collapse as long as it doesn't have extra pins (from GUP or otherwise).

---
 mm/khugepaged.c | 28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)
mm/khugepaged.c +3 -3
index 39e0994abeb8..b47edfe57f7b 100644
@@ -581,18 +581,26 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
              }
 
              /*
-              * cannot use mapcount: can't collapse if there's a gup pin.
-              * The page must only be referenced by the scanned process
-              * and page swap cache.
+              * Check if the page has any GUP (or other external) pins.
+              *
+              * The page table that maps the page has been already unlinked

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 595

Quoted 10 lines
mm/khugepaged.c +8 -1
+              * from the page table tree and this process cannot get
+              * additinal pin on the page.
+              *
+              * New pins can come later if the page is shared across fork,
+              * but not for the this process. It is fine. The other process
+              * cannot write to the page, only trigger CoW.
               */
-             if (page_count(page) != 1 + PageSwapCache(page)) {
+             if (total_mapcount(page) + PageSwapCache(page) !=
+                             page_count(page)) {

Do you think having a function for this check would be better? Since the check is used three times.

Quoted 13 lines
mm/khugepaged.c +2 -1
                      /*
                       * Drain pagevec and retry just in case we can get rid
                       * of the extra pin, like in swapin case.
                       */
                      lru_add_drain();
              }
-             if (page_count(page) != 1 + PageSwapCache(page)) {
+             if (total_mapcount(page) + PageSwapCache(page) !=
+                             page_count(page)) {
                      unlock_page(page);
                      result = SCAN_PAGE_COUNT;
                      goto out;

mm/khugepaged.c static void __collapse_huge_page_copy(pte_t *pte, struct page *page, · line 683

Quoted 4 lines
mm/khugepaged.c +0 -1
@@ -680,7 +688,6 @@ static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
              } else {
                      src_page = pte_page(pteval);
                      copy_user_highpage(page, src_page, address, vma);
-                     VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);

Maybe replace it with this?

Quoted 1 line

VM_BUG_ON_PAGE(page_mapcount(src_page) + PageSwapCache(src_page) != page_count(src_page), src_page);

I don't think this is correct either. If a THP is PTE mapped its refcount would be bumped by the number of PTE mapped subpages. But page_mapcount() would just return the mapcount of that specific subpage. So, total_mapcount() should be used, but the same check has been done before reaching here.

Quoted 29 lines
Quoted 22 lines
mm/khugepaged.c +3 -7
                      release_pte_page(src_page);
                      /*
                       * ptl mostly unnecessary, but preempt has to
@@ -1209,12 +1216,9 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                      goto out_unmap;
              }
 
-             /*
-              * cannot use mapcount: can't collapse if there's a gup pin.
-              * The page must only be referenced by the scanned process
-              * and page swap cache.
-              */
-             if (page_count(page) != 1 + PageSwapCache(page)) {
+             /* Check if the page has any GUP (or other external) pins */
+             if (total_mapcount(page) + PageSwapCache(page) !=
+                             page_count(page)) {
                      result = SCAN_PAGE_COUNT;
                      goto out_unmap;
              }
--
Quoted 1 line

2.26.0

Thanks.

—
Best Regards,
Yan Zi

reviewer
#15 lore raw

Re: [PATCH 4/7] khugepaged: Allow to callapse a page shared across fork

<snip>

Quoted 20 lines
Quoted 20 lines
Quoted 13 lines
                      /*
                       * Drain pagevec and retry just in case we can get rid
                       * of the extra pin, like in swapin case.
                       */
                      lru_add_drain();
              }
mm/khugepaged.c +2 -1
-             if (page_count(page) != 1 + PageSwapCache(page)) {
+             if (total_mapcount(page) + PageSwapCache(page) !=
+                             page_count(page)) {
                      unlock_page(page);
                      result = SCAN_PAGE_COUNT;
                      goto out;

mm/khugepaged.c static void __collapse_huge_page_copy(pte_t *pte, struct page *page, · line 683

Quoted 4 lines
mm/khugepaged.c +0 -1
@@ -680,7 +688,6 @@ static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
              } else {
                      src_page = pte_page(pteval);
                      copy_user_highpage(page, src_page, address, vma);
-                     VM_BUG_ON_PAGE(page_mapcount(src_page) != 1, src_page);

Maybe replace it with this?

Quoted 7 lines
Quoted 1 line

VM_BUG_ON_PAGE(page_mapcount(src_page) + PageSwapCache(src_page) != page_count(src_page), src_page);

I don't think this is correct either. If a THP is PTE mapped its refcount would be bumped by the number of PTE mapped subpages. But page_mapcount() would just return the mapcount of that specific subpage. So, total_mapcount() should be used, but the same check has been done before reaching here.

Yes, you are right. Thanks.

Please disregard this comment.

—
Best Regards,
Yan Zi

#7 lore raw

Re: [PATCH 3/7] khugepaged: Drain LRU add pagevec to get rid of extra pins

In reply to Zi Yan
Quoted 31 lines · Zi Yan
Quoted 29 lines · Kirill A. Shutemov

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +7 -0
index 14d7afc90786..39e0994abeb8 100644
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		 * The page must only be referenced by the scanned process
 		 * and page swap cache.
 		 */
+		if (page_count(page) != 1 + PageSwapCache(page)) {
+			/*
+			 * Drain pagevec and retry just in case we can get rid
+			 * of the extra pin, like in swapin case.
+			 */
+			lru_add_drain();
+		}
 		if (page_count(page) != 1 + PageSwapCache(page)) {
 			unlock_page(page);
 			result = SCAN_PAGE_COUNT;
 			goto out;
 		}
Quoted 8 lines
Quoted 6 lines
mm/khugepaged.c +1 -0
+
 		if (pte_write(pteval)) {
 			writable = true;
 		} else {
Signature · 1 line
2.26.0

Looks good to me. Is the added empty line intentional?

Yes. It groups try and retry together.

Signature · 1 line
 Kirill A. Shutemov
#18 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Yang Shi
Quoted 28 lines · Yang Shi
Quoted 26 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +7 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
Quoted 8 lines

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 529

Quoted 5 lines
mm/khugepaged.c +4 -0
+       if (!PageLocked(page))
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));

We need count in the number of base pages. The same counter is modified by vmscan in base page unit.

Is it though? Where?

Quoted 1 line

Also need modify the inc path.

Done already.

Quoted 24 lines
Quoted 24 lines
mm/khugepaged.c +5 -4
        unlock_page(page);
        putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
        pte_t *_pte;
        int none_or_zero = 0, result = 0, referenced = 0;
        bool writable = false;
+       LIST_HEAD(compound_pagelist);
 
        for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
             _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                        goto out;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
+               VM_BUG_ON_PAGE(!PageAnon(page), page);
+
                if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out;
-               }
+                       struct page *p;
+                       page = compound_head(page);
 
Quoted 5 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 583

Quoted 3 lines
mm/khugepaged.c +2 -1
-               VM_BUG_ON_PAGE(!PageAnon(page), page);
+                       /*
+                        * Check if we have dealt with the compount page

s/compount/compound

Thanks.

Quoted 9 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 591

Quoted 8 lines
mm/khugepaged.c +8 -0
+                        * already
+                        */
+                       list_for_each_entry(p, &compound_pagelist, lru) {
+                               if (page ==  p)
+                                       break;
+                       }
+                       if (page ==  p)
+                               continue;
Quoted 5 lines

I don't quite understand why we need the above check. My understanding is when we scan the ptes, once the first PTE mapped subpage is found, then the THP would be added into compound_pagelist, then the later loop would find the same THP on the list then just break the loop. Did I miss anything?

We skip the iteration and look at the next pte. We've already isolated the page. Nothing to do here.

Quoted 31 lines
Quoted 31 lines
mm/khugepaged.c +5 -6
+               }
 
                /*
                 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    page_is_young(page) || PageReferenced(page) ||
                    mmu_notifier_test_young(vma->vm_mm, address))
                        referenced++;
+
+               if (PageCompound(page))
+                       list_add_tail(&page->lru, &compound_pagelist);
        }
        if (likely(writable)) {
                if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
-               if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out_unmap;
-               }
+               page = compound_head(page);
 
                /*
                 * Record which node the original page is from and save this
--

2.26.0

Signature · 1 line
 Kirill A. Shutemov
#23 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Zi Yan
Quoted 21 lines · Zi Yan
Quoted 4 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

s/putpack/putback/

Quoted 12 lines
---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +0 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
Quoted 9 lines

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 523

Quoted 8 lines
mm/khugepaged.c +6 -0
 static void release_pte_page(struct page *page)
 {
+	/*
+	 * We need to unlock and put compound page on LRU only once.
+	 * The rest of the pages have to be locked and not on LRU here.
+	 */
+	VM_BUG_ON_PAGE(!PageCompound(page) &&
+			(!PageLocked(page) && PageLRU(page)), page);

It only checks base pages.

That's the point.

Quoted 5 lines

Add

VM_BUG_ON_PAGE(PageCompound(page) && PageLocked(page) && PageLRU(page), page);

to check for compound pages.

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

Quoted 30 lines
Quoted 30 lines
mm/khugepaged.c +10 -4
+
+	if (!PageLocked(page))
+		return;
+
+	page = compound_head(page);
 	dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
 	unlock_page(page);
 	putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 	pte_t *_pte;
 	int none_or_zero = 0, result = 0, referenced = 0;
 	bool writable = false;
+	LIST_HEAD(compound_pagelist);
 
 	for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
 	     _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 			goto out;
 		}
 
-		/* TODO: teach khugepaged to collapse THP mapped with pte */
+		VM_BUG_ON_PAGE(!PageAnon(page), page);
+
 		if (PageCompound(page)) {
-			result = SCAN_PAGE_COMPOUND;
-			goto out;
-		}
+			struct page *p;
+			page = compound_head(page);
 
Quoted 6 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 583

Quoted 3 lines
mm/khugepaged.c +2 -1
-		VM_BUG_ON_PAGE(!PageAnon(page), page);
+			/*
+			 * Check if we have dealt with the compount page

s/compount/compound/

Thanks.

Quoted 10 lines
Quoted 10 lines
mm/khugepaged.c +9 -0
+			 * already
+			 */
+			list_for_each_entry(p, &compound_pagelist, lru) {
+				if (page ==  p)
+					break;
+			}
+			if (page ==  p)
+				continue;
+		}
 
Quoted 14 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 670

Quoted 12 lines
mm/khugepaged.c +3 -0
 		/*
 		 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
 		    page_is_young(page) || PageReferenced(page) ||
 		    mmu_notifier_test_young(vma->vm_mm, address))
 			referenced++;
+
+		if (PageCompound(page))
+			list_add_tail(&page->lru, &compound_pagelist);
 	}
 	if (likely(writable)) {
 		if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Um? It's outside the pte loop. We get here once per PMD range.

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Quoted 24 lines

If a compound page is seen here, can we bail out the loop early? I guess not, because we can a partially mapped compound page at the beginning or the end of a VMA, right?

Quoted 15 lines
mm/khugepaged.c +1 -5
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
 			goto out_unmap;
 		}
 
-		/* TODO: teach khugepaged to collapse THP mapped with pte */
-		if (PageCompound(page)) {
-			result = SCAN_PAGE_COMPOUND;
-			goto out_unmap;
-		}
+		page = compound_head(page);
 
 		/*
 		 * Record which node the original page is from and save this
Signature · 1 line
2.26.0

—
Best Regards,
Yan Zi

Signature · 1 line
 Kirill A. Shutemov
#31 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Yang Shi
Quoted 29 lines · Yang Shi
Quoted 27 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +8 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
+       if (!PageLocked(page))
Quoted 8 lines

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 531

Quoted 6 lines
mm/khugepaged.c +3 -0
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
        unlock_page(page);
        putback_lru_page(page);

BTW, wouldn't this unlock the whole THP and put it back to LRU?

It is the intention.

Quoted 71 lines

Then we may copy the following PTE mapped pages with page unlocked and on LRU. I don't see critical problem, just the pages might be on and off LRU by others, i.e. vmscan, compaction, migration, etc. But no one could take the page away since try_to_unmap() would fail, but not very productive.

Quoted 64 lines
mm/khugepaged.c +20 -11
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
        pte_t *_pte;
        int none_or_zero = 0, result = 0, referenced = 0;
        bool writable = false;
+       LIST_HEAD(compound_pagelist);
 
        for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
             _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                        goto out;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
+               VM_BUG_ON_PAGE(!PageAnon(page), page);
+
                if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out;
-               }
+                       struct page *p;
+                       page = compound_head(page);
 
-               VM_BUG_ON_PAGE(!PageAnon(page), page);
+                       /*
+                        * Check if we have dealt with the compount page
+                        * already
+                        */
+                       list_for_each_entry(p, &compound_pagelist, lru) {
+                               if (page ==  p)
+                                       break;
+                       }
+                       if (page ==  p)
+                               continue;
+               }
 
                /*
                 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    page_is_young(page) || PageReferenced(page) ||
                    mmu_notifier_test_young(vma->vm_mm, address))
                        referenced++;
+
+               if (PageCompound(page))
+                       list_add_tail(&page->lru, &compound_pagelist);
        }
        if (likely(writable)) {
                if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
-               if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out_unmap;
-               }
+               page = compound_head(page);
 
                /*
                 * Record which node the original page is from and save this
--

2.26.0

Signature · 1 line
 Kirill A. Shutemov
#35 lore raw

Re: [PATCH 6/7] thp: Change CoW semantics for anon-THP

In reply to Yang Shi
Quoted 24 lines · Yang Shi
Quoted 4 lines · Kirill A. Shutemov

Currently we have different copy-on-write semantics for anon- and file-THP. For anon-THP we try to allocate huge page on the write fault, but on file-THP we split PMD and allocate 4k page.

I agree this seems confusing.

Quoted 9 lines

Arguably, file-THP semantics is more desirable: we don't necessary want to unshare full PMD range from the parent on the first access. This is the primary reason THP is unusable for some workloads, like Redis.

The original THP refcounting didn't allow to have PTE-mapped compound pages, so we had no options, but to allocate huge page on CoW (with fallback to 512 4k pages).

Quoted 5 lines

The current refcounting doesn't have such limitations and we can cut a lot of complex code out of fault path.

khugepaged is now able to recover THP from such ranges if the configuration allows.

Quoted 6 lines

It looks this patch would just split the PMD then fallback to handle it on PTE level, it definitely simplify the code a lot. However it makes the use of THP depend on the productivity of khugepaged. And the success rate of THP allocation in khugepaged depends on defrag. But by default khugepaged runs at very low priority, so khugepaged defrag may result in priority inversion easily.

If you have a workload that may be hurt by such change, please get some numbers. It would be interesting to see.

Quoted 6 lines

For example we saw THP split in reclaim path triggered by khugepaged held write anon_vma lock, but the other process which was doing reclaim too was blocked by anon_vma lock. Then the cond_resched() in rmap walk would make khugepaged preempted by all other processes easily so khugepaged may hold the anon_vma lock for indefinite time. Then we saw hung tasks.

Any chance you have a reproducer? I'm not sure I follow the problem, but it's almost 4AM, so I'm slow.

Quoted 308 lines

So we have khugepaged defrag disabled for some workloads to workaround the priority inversion problem. So, I'm concerned some processes may never get THP for some our workloads with this patch applied.

The priority inversion caused by khugepaged was not very usual. Just my two cents.

Quoted 301 lines
---
 mm/huge_memory.c | 247 +++++------------------------------------------
 1 file changed, 24 insertions(+), 223 deletions(-)
mm/huge_memory.c +24 -224
index ef6a6bcb291f..15b7a9c86b7c 100644
@@ -1206,262 +1206,63 @@ void huge_pmd_set_accessed(struct vm_fault *vmf, pmd_t orig_pmd)
        spin_unlock(vmf->ptl);
 }
 
-static vm_fault_t do_huge_pmd_wp_page_fallback(struct vm_fault *vmf,
-                       pmd_t orig_pmd, struct page *page)
-{
-       struct vm_area_struct *vma = vmf->vma;
-       unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-       struct mem_cgroup *memcg;
-       pgtable_t pgtable;
-       pmd_t _pmd;
-       int i;
-       vm_fault_t ret = 0;
-       struct page **pages;
-       struct mmu_notifier_range range;
-
-       pages = kmalloc_array(HPAGE_PMD_NR, sizeof(struct page *),
-                             GFP_KERNEL);
-       if (unlikely(!pages)) {
-               ret |= VM_FAULT_OOM;
-               goto out;
-       }
-
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE, vma,
-                                              vmf->address, page_to_nid(page));
-               if (unlikely(!pages[i] ||
-                            mem_cgroup_try_charge_delay(pages[i], vma->vm_mm,
-                                    GFP_KERNEL, &memcg, false))) {
-                       if (pages[i])
-                               put_page(pages[i]);
-                       while (--i >= 0) {
-                               memcg = (void *)page_private(pages[i]);
-                               set_page_private(pages[i], 0);
-                               mem_cgroup_cancel_charge(pages[i], memcg,
-                                               false);
-                               put_page(pages[i]);
-                       }
-                       kfree(pages);
-                       ret |= VM_FAULT_OOM;
-                       goto out;
-               }
-               set_page_private(pages[i], (unsigned long)memcg);
-       }
-
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               copy_user_highpage(pages[i], page + i,
-                                  haddr + PAGE_SIZE * i, vma);
-               __SetPageUptodate(pages[i]);
-               cond_resched();
-       }
-
-       mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-                               haddr, haddr + HPAGE_PMD_SIZE);
-       mmu_notifier_invalidate_range_start(&range);
-
-       vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-               goto out_free_pages;
-       VM_BUG_ON_PAGE(!PageHead(page), page);
-
-       /*
-        * Leave pmd empty until pte is filled note we must notify here as
-        * concurrent CPU thread might write to new page before the call to
-        * mmu_notifier_invalidate_range_end() happens which can lead to a
-        * device seeing memory write in different order than CPU.
-        *
-        * See Documentation/vm/mmu_notifier.rst
-        */
-       pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-
-       pgtable = pgtable_trans_huge_withdraw(vma->vm_mm, vmf->pmd);
-       pmd_populate(vma->vm_mm, &_pmd, pgtable);
-
-       for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
-               pte_t entry;
-               entry = mk_pte(pages[i], vma->vm_page_prot);
-               entry = maybe_mkwrite(pte_mkdirty(entry), vma);
-               memcg = (void *)page_private(pages[i]);
-               set_page_private(pages[i], 0);
-               page_add_new_anon_rmap(pages[i], vmf->vma, haddr, false);
-               mem_cgroup_commit_charge(pages[i], memcg, false, false);
-               lru_cache_add_active_or_unevictable(pages[i], vma);
-               vmf->pte = pte_offset_map(&_pmd, haddr);
-               VM_BUG_ON(!pte_none(*vmf->pte));
-               set_pte_at(vma->vm_mm, haddr, vmf->pte, entry);
-               pte_unmap(vmf->pte);
-       }
-       kfree(pages);
-
-       smp_wmb(); /* make pte visible before pmd */
-       pmd_populate(vma->vm_mm, vmf->pmd, pgtable);
-       page_remove_rmap(page, true);
-       spin_unlock(vmf->ptl);
-
-       /*
-        * No need to double call mmu_notifier->invalidate_range() callback as
-        * the above pmdp_huge_clear_flush_notify() did already call it.
-        */
-       mmu_notifier_invalidate_range_only_end(&range);
-
-       ret |= VM_FAULT_WRITE;
-       put_page(page);
-
-out:
-       return ret;
-
-out_free_pages:
-       spin_unlock(vmf->ptl);
-       mmu_notifier_invalidate_range_end(&range);
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               memcg = (void *)page_private(pages[i]);
-               set_page_private(pages[i], 0);
-               mem_cgroup_cancel_charge(pages[i], memcg, false);
-               put_page(pages[i]);
-       }
-       kfree(pages);
-       goto out;
-}
-
 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf, pmd_t orig_pmd)
 {
        struct vm_area_struct *vma = vmf->vma;
-       struct page *page = NULL, *new_page;
-       struct mem_cgroup *memcg;
+       struct page *page;
        unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-       struct mmu_notifier_range range;
-       gfp_t huge_gfp;                 /* for allocation and charge */
-       vm_fault_t ret = 0;
 
        vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
        VM_BUG_ON_VMA(!vma->anon_vma, vma);
+
        if (is_huge_zero_pmd(orig_pmd))
-               goto alloc;
+               goto fallback;
+
        spin_lock(vmf->ptl);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-               goto out_unlock;
+
+       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+               spin_unlock(vmf->ptl);
+               return 0;
+       }
 
        page = pmd_page(orig_pmd);
        VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
-       /*
-        * We can only reuse the page if nobody else maps the huge page or it's
-        * part.
-        */
+
+       /* Lock page for reuse_swap_page() */
        if (!trylock_page(page)) {
                get_page(page);
                spin_unlock(vmf->ptl);
                lock_page(page);
                spin_lock(vmf->ptl);
                if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+                       spin_unlock(vmf->ptl);
                        unlock_page(page);
                        put_page(page);
-                       goto out_unlock;
+                       return 0;
                }
                put_page(page);
        }
+
+       /*
+        * We can only reuse the page if nobody else maps the huge page or it's
+        * part.
+        */
        if (reuse_swap_page(page, NULL)) {
                pmd_t entry;
                entry = pmd_mkyoung(orig_pmd);
                entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
                if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry,  1))
                        update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-               ret |= VM_FAULT_WRITE;
                unlock_page(page);
-               goto out_unlock;
-       }
-       unlock_page(page);
-       get_page(page);
-       spin_unlock(vmf->ptl);
-alloc:
-       if (__transparent_hugepage_enabled(vma) &&
-           !transparent_hugepage_debug_cow()) {
-               huge_gfp = alloc_hugepage_direct_gfpmask(vma);
-               new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
-       } else
-               new_page = NULL;
-
-       if (likely(new_page)) {
-               prep_transhuge_page(new_page);
-       } else {
-               if (!page) {
-                       split_huge_pmd(vma, vmf->pmd, vmf->address);
-                       ret |= VM_FAULT_FALLBACK;
-               } else {
-                       ret = do_huge_pmd_wp_page_fallback(vmf, orig_pmd, page);
-                       if (ret & VM_FAULT_OOM) {
-                               split_huge_pmd(vma, vmf->pmd, vmf->address);
-                               ret |= VM_FAULT_FALLBACK;
-                       }
-                       put_page(page);
-               }
-               count_vm_event(THP_FAULT_FALLBACK);
-               goto out;
-       }
-
-       if (unlikely(mem_cgroup_try_charge_delay(new_page, vma->vm_mm,
-                                       huge_gfp, &memcg, true))) {
-               put_page(new_page);
-               split_huge_pmd(vma, vmf->pmd, vmf->address);
-               if (page)
-                       put_page(page);
-               ret |= VM_FAULT_FALLBACK;
-               count_vm_event(THP_FAULT_FALLBACK);
-               goto out;
-       }
-
-       count_vm_event(THP_FAULT_ALLOC);
-       count_memcg_events(memcg, THP_FAULT_ALLOC, 1);
-
-       if (!page)
-               clear_huge_page(new_page, vmf->address, HPAGE_PMD_NR);
-       else
-               copy_user_huge_page(new_page, page, vmf->address,
-                                   vma, HPAGE_PMD_NR);
-       __SetPageUptodate(new_page);
-
-       mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-                               haddr, haddr + HPAGE_PMD_SIZE);
-       mmu_notifier_invalidate_range_start(&range);
-
-       spin_lock(vmf->ptl);
-       if (page)
-               put_page(page);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
                spin_unlock(vmf->ptl);
-               mem_cgroup_cancel_charge(new_page, memcg, true);
-               put_page(new_page);
-               goto out_mn;
-       } else {
-               pmd_t entry;
-               entry = mk_huge_pmd(new_page, vma->vm_page_prot);
-               entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
-               pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-               page_add_new_anon_rmap(new_page, vma, haddr, true);
-               mem_cgroup_commit_charge(new_page, memcg, false, true);
-               lru_cache_add_active_or_unevictable(new_page, vma);
-               set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
-               update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-               if (!page) {
-                       add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
-               } else {
-                       VM_BUG_ON_PAGE(!PageHead(page), page);
-                       page_remove_rmap(page, true);
-                       put_page(page);
-               }
-               ret |= VM_FAULT_WRITE;
+               return VM_FAULT_WRITE;
        }
+
+       unlock_page(page);
        spin_unlock(vmf->ptl);
-out_mn:
-       /*
-        * No need to double call mmu_notifier->invalidate_range() callback as
-        * the above pmdp_huge_clear_flush_notify() did already call it.
-        */
-       mmu_notifier_invalidate_range_only_end(&range);
-out:
-       return ret;
-out_unlock:
-       spin_unlock(vmf->ptl);
-       return ret;
+fallback:
+       __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
+       return VM_FAULT_FALLBACK;
 }
 
 /*
--

2.26.0

Signature · 1 line
 Kirill A. Shutemov
#19 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 39 lines · Kirill A. Shutemov
Quoted 28 lines · Yang Shi
Quoted 26 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +7 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
Quoted 8 lines

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 529

Quoted 5 lines
mm/khugepaged.c +4 -0
+       if (!PageLocked(page))
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));

We need count in the number of base pages. The same counter is modified by vmscan in base page unit.

Quoted 1 line

Is it though? Where?

__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken) in vmscan.c, here nr_taken is nr_compound(page), so if it is THP the number would be 512.

So in both inc and dec path of collapse PTE mapped THP, we should mod nr_compound(page) too.

Quoted 46 lines
Quoted 2 lines

Also need modify the inc path.

Done already.

Quoted 24 lines
Quoted 24 lines
mm/khugepaged.c +5 -4
        unlock_page(page);
        putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
        pte_t *_pte;
        int none_or_zero = 0, result = 0, referenced = 0;
        bool writable = false;
+       LIST_HEAD(compound_pagelist);
 
        for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
             _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                        goto out;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
+               VM_BUG_ON_PAGE(!PageAnon(page), page);
+
                if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out;
-               }
+                       struct page *p;
+                       page = compound_head(page);
 
Quoted 5 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 583

Quoted 3 lines
mm/khugepaged.c +2 -1
-               VM_BUG_ON_PAGE(!PageAnon(page), page);
+                       /*
+                        * Check if we have dealt with the compount page

s/compount/compound

Thanks.

Quoted 9 lines
Quoted 8 lines
mm/khugepaged.c +8 -0
+                        * already
+                        */
+                       list_for_each_entry(p, &compound_pagelist, lru) {
+                               if (page ==  p)
+                                       break;
+                       }
+                       if (page ==  p)
+                               continue;
Quoted 8 lines
Quoted 5 lines

I don't quite understand why we need the above check. My understanding is when we scan the ptes, once the first PTE mapped subpage is found, then the THP would be added into compound_pagelist, then the later loop would find the same THP on the list then just break the loop. Did I miss anything?

We skip the iteration and look at the next pte. We've already isolated the page. Nothing to do here.

I got your point. Thanks.

Quoted 35 lines
Quoted 26 lines
Quoted 26 lines
mm/khugepaged.c +5 -5
+               }
 
                /*
                 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    page_is_young(page) || PageReferenced(page) ||
                    mmu_notifier_test_young(vma->vm_mm, address))
                        referenced++;
+
+               if (PageCompound(page))
+                       list_add_tail(&page->lru, &compound_pagelist);
        }
        if (likely(writable)) {
                if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
-               if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out_unmap;
-               }
+               page = compound_head(page);
 
Quoted 6 lines
Quoted 6 lines
mm/khugepaged.c +0 -1
                /*
                 * Record which node the original page is from and save this
--

2.26.0

--
Kirill A. Shutemov

#32 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 40 lines · Kirill A. Shutemov
Quoted 29 lines · Yang Shi
Quoted 27 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +8 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
+       if (!PageLocked(page))
Quoted 8 lines

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 531

Quoted 6 lines
mm/khugepaged.c +3 -0
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
        unlock_page(page);
        putback_lru_page(page);

BTW, wouldn't this unlock the whole THP and put it back to LRU?

Quoted 1 line

It is the intention.

Yes, understood. Considering the below case:

Subpages 0, 1, 2, 3 are PTE mapped. Once subpage 0 is copied release_pte_page() would be called then the whole THP would be unlocked and putback to lru, then the loop would iterate to subpage 1, 2 and 3, but the page is not locked and on lru already. Is it intentional?

Quoted 75 lines
Quoted 66 lines

Then we may copy the following PTE mapped pages with page unlocked and on LRU. I don't see critical problem, just the pages might be on and off LRU by others, i.e. vmscan, compaction, migration, etc. But no one could take the page away since try_to_unmap() would fail, but not very productive.

Quoted 58 lines
mm/khugepaged.c +20 -10
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
        pte_t *_pte;
        int none_or_zero = 0, result = 0, referenced = 0;
        bool writable = false;
+       LIST_HEAD(compound_pagelist);
 
        for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
             _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                        goto out;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
+               VM_BUG_ON_PAGE(!PageAnon(page), page);
+
                if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out;
-               }
+                       struct page *p;
+                       page = compound_head(page);
 
-               VM_BUG_ON_PAGE(!PageAnon(page), page);
+                       /*
+                        * Check if we have dealt with the compount page
+                        * already
+                        */
+                       list_for_each_entry(p, &compound_pagelist, lru) {
+                               if (page ==  p)
+                                       break;
+                       }
+                       if (page ==  p)
+                               continue;
+               }
 
                /*
                 * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    page_is_young(page) || PageReferenced(page) ||
                    mmu_notifier_test_young(vma->vm_mm, address))
                        referenced++;
+
+               if (PageCompound(page))
+                       list_add_tail(&page->lru, &compound_pagelist);
        }
        if (likely(writable)) {
                if (likely(referenced)) {
@@ -1185,11 +1210,7 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
 
-               /* TODO: teach khugepaged to collapse THP mapped with pte */
-               if (PageCompound(page)) {
-                       result = SCAN_PAGE_COMPOUND;
-                       goto out_unmap;
-               }
+               page = compound_head(page);
 
Quoted 6 lines
Quoted 6 lines
mm/khugepaged.c +0 -1
                /*
                 * Record which node the original page is from and save this
--

2.26.0

--
Kirill A. Shutemov

reviewer
#24 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 39 lines · Kirill A. Shutemov

External email: Use caution opening links or attachments

Quoted 21 lines · Zi Yan
Quoted 4 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

s/putpack/putback/

Quoted 12 lines
---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +0 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
Quoted 9 lines

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 523

Quoted 8 lines
mm/khugepaged.c +6 -0
 static void release_pte_page(struct page *page)
 {
+   /*
+    * We need to unlock and put compound page on LRU only once.
+    * The rest of the pages have to be locked and not on LRU here.
+    */
+   VM_BUG_ON_PAGE(!PageCompound(page) &&
+                   (!PageLocked(page) && PageLRU(page)), page);

It only checks base pages.

That's the point.

Quoted 2 lines

Add

Quoted 8 lines
Quoted 3 lines

VM_BUG_ON_PAGE(PageCompound(page) && PageLocked(page) && PageLRU(page), page);

to check for compound pages.

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

For the first time, the compound page is locked and not on LRU, so this VM_BUG_ON passes. For the second time and so on, the compound page is unlocked and on the LRU, so this VM_BUG_ON still passes.

For base page, VM_BUG_ON passes.

Other unexpected situation (a compound page is locked and on LRU) triggers the VM_BU_ON, but your VM_BUG_ON will not detect this situation, right?

Quoted 64 lines
Quoted 30 lines
Quoted 30 lines
mm/khugepaged.c +10 -4
+
+   if (!PageLocked(page))
+           return;
+
+   page = compound_head(page);
    dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));
    unlock_page(page);
    putback_lru_page(page);
@@ -537,6 +548,7 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
    pte_t *_pte;
    int none_or_zero = 0, result = 0, referenced = 0;
    bool writable = false;
+   LIST_HEAD(compound_pagelist);
 
    for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
         _pte++, address += PAGE_SIZE) {
@@ -561,13 +573,23 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                    goto out;
            }
 
-           /* TODO: teach khugepaged to collapse THP mapped with pte */
+           VM_BUG_ON_PAGE(!PageAnon(page), page);
+
            if (PageCompound(page)) {
-                   result = SCAN_PAGE_COMPOUND;
-                   goto out;
-           }
+                   struct page *p;
+                   page = compound_head(page);
 
Quoted 6 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 583

Quoted 3 lines
mm/khugepaged.c +2 -1
-           VM_BUG_ON_PAGE(!PageAnon(page), page);
+                   /*
+                    * Check if we have dealt with the compount page

s/compount/compound/

Thanks.

Quoted 10 lines
Quoted 10 lines
mm/khugepaged.c +9 -0
+                    * already
+                    */
+                   list_for_each_entry(p, &compound_pagelist, lru) {
+                           if (page ==  p)
+                                   break;
+                   }
+                   if (page ==  p)
+                           continue;
+           }
 
Quoted 14 lines

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 670

Quoted 12 lines
mm/khugepaged.c +3 -0
            /*
             * We can do it before isolate_lru_page because the
@@ -640,6 +662,9 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                page_is_young(page) || PageReferenced(page) ||
                mmu_notifier_test_young(vma->vm_mm, address))
                    referenced++;
+
+           if (PageCompound(page))
+                   list_add_tail(&page->lru, &compound_pagelist);
    }
    if (likely(writable)) {
            if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Quoted 5 lines

Um? It's outside the pte loop. We get here once per PMD range.

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Throughout the pte loop, we should only see at most one compound page, right?

If that is the case, we do not need a list to store that single compound page but can use a struct page pointer that is initialized to NULL and later assigned to the discovered compound page, right? I am not saying I want to change the code in this way, but just try to make sure I understand the code correctly.

Thanks.

—
Best Regards,
Yan Zi

#36 lore raw

Re: [PATCH 6/7] thp: Change CoW semantics for anon-THP

In reply to Kirill A. Shutemov
Quoted 33 lines · Kirill A. Shutemov
Quoted 24 lines · Yang Shi
Quoted 4 lines · Kirill A. Shutemov

Currently we have different copy-on-write semantics for anon- and file-THP. For anon-THP we try to allocate huge page on the write fault, but on file-THP we split PMD and allocate 4k page.

I agree this seems confusing.

Quoted 9 lines

Arguably, file-THP semantics is more desirable: we don't necessary want to unshare full PMD range from the parent on the first access. This is the primary reason THP is unusable for some workloads, like Redis.

The original THP refcounting didn't allow to have PTE-mapped compound pages, so we had no options, but to allocate huge page on CoW (with fallback to 512 4k pages).

Quoted 5 lines

The current refcounting doesn't have such limitations and we can cut a lot of complex code out of fault path.

khugepaged is now able to recover THP from such ranges if the configuration allows.

Quoted 6 lines

It looks this patch would just split the PMD then fallback to handle it on PTE level, it definitely simplify the code a lot. However it makes the use of THP depend on the productivity of khugepaged. And the success rate of THP allocation in khugepaged depends on defrag. But by default khugepaged runs at very low priority, so khugepaged defrag may result in priority inversion easily.

Quoted 2 lines

If you have a workload that may be hurt by such change, please get some numbers. It would be interesting to see.

Please see the below splat:

[ 7417.871422] INFO: task /home/staragent:9088 blocked for more than
1200 seconds.
[ 7417.880501]       Tainted: G        W         4.19.91 #1
[ 7417.889015] "echo 0 > /proc/sys/kernel/hung_task_timeout_secs"
disables this message.
[ 7417.897373] /home/staragent D    0  9088      1 0x00000000
[ 7417.905017] Call Trace:
[ 7417.907898]  ? __schedule+0x3cf/0x660
[ 7417.911988]  ? core_sys_select+0x1d2/0x270
[ 7417.916562]  schedule+0x33/0xc0
[ 7417.920205]  rwsem_down_read_failed+0x130/0x190
[ 7417.925153]  ? call_rwsem_down_read_failed+0x14/0x30
[ 7417.930648]  call_rwsem_down_read_failed+0x14/0x30
[ 7417.935894]  down_read+0x1c/0x30
[ 7417.939603]  __do_page_fault+0x435/0x4d0
[ 7417.943984]  do_page_fault+0x32/0x110
[ 7417.949315]  ? page_fault+0x8/0x30
[ 7417.953189]  page_fault+0x1e/0x30
[ 7417.956974] RIP: 0033:0x8063b0
[ 7417.960582] Code: Bad RIP value.

*** the task got current->mm->mmap_sem: 0xffff88a65ed02f80 crash> bt ffff88a65ed02f80
PID: 102341 TASK: ffff88a65ed02f80 CPU: 64 COMMAND: "/home/staragent"
#0 [ffffc90021bd73e8] __schedule at ffffffff818436af
#1 [ffffc90021bd7480] schedule at ffffffff81843973
#2 [ffffc90021bd7498] rwsem_down_read_failed at ffffffff818472b0 #3 [ffffc90021bd7540] call_rwsem_down_read_failed at ffffffff818393d4 #4 [ffffc90021bd7588] down_read at ffffffff8184662c
#5 [ffffc90021bd7598] page_lock_anon_vma_read at ffffffff81242d9c #6 [ffffc90021bd75c0] rmap_walk_anon at ffffffff8124154f
#7 [ffffc90021bd7620] page_referenced at ffffffff8124350e #8 [ffffc90021bd7690] shrink_page_list at ffffffff8120b2f4 #9 [ffffc90021bd7760] shrink_inactive_list at ffffffff8120c4c6
#10 [ffffc90021bd7808] shrink_node_memcg at ffffffff8120cffa #11 [ffffc90021bd7910] shrink_node at ffffffff8120d534
#12 [ffffc90021bd79a8] do_try_to_free_pages at ffffffff8120dac4 #13 [ffffc90021bd7a10] try_to_free_pages at ffffffff8120dec4 #14 [ffffc90021bd7aa8] __alloc_pages_slowpath at ffffffff811fa367 #15 [ffffc90021bd7bd0] __alloc_pages_nodemask at ffffffff811fb116 #16 [ffffc90021bd7c30] __do_page_cache_readahead at ffffffff812013c4 #17 [ffffc90021bd7cc8] filemap_fault at ffffffff811ef652
#18 [ffffc90021bd7d98] ext4_filemap_fault at ffffffffc030c48c [ext4] #19 [ffffc90021bd7db0] __do_fault at ffffffff81234cf0
#20 [ffffc90021bd7dd0] __handle_mm_fault at ffffffff812337d8 #21 [ffffc90021bd7e80] handle_mm_fault at ffffffff81233adc #22 [ffffc90021bd7eb0] __do_page_fault at ffffffff8106f084 #23 [ffffc90021bd7f20] do_page_fault at ffffffff8106f342
#24 [ffffc90021bd7f50] page_fault at ffffffff81a0112e

    RIP: 00007f67de084e72  RSP: 00007f67677fddb8  RFLAGS: 00010206
    RAX: 00007f67de084e72  RBX: 0000000002802310  RCX: 0000000000080000
    RDX: 00007f67680008c0  RSI: 0000000000080000  RDI: 00007f67680008c0
    RBP: 00007f67677fddf0   R8: 0000000000000000   R9: 00007f6768086460
    R10: 00007f67677fdde0  R11: 00000000009b3ca8  R12: 0000000002802120
    R13: 0000000002802768  R14: 0000000000000003  R15: 00007f67677fe700
    ORIG_RAX: ffffffffffffffff  CS: 0033  SS: 002b

*** staragent held mmap_sem and was doing memory reclaim, and was trying to acquire anon_vma lock.

*** the anon_vma->root->rwsem is held by khugepaged crash> struct task_struct 0xffff88fe6f5dc740
comm = “khugepaged\000\000\000\000\000”
crash> bt 0xffff88fe6f5dc740
PID: 504 TASK: ffff88fe6f5dc740 CPU: 34 COMMAND: "khugepaged"
#0 [ffffc9000da2f630] __schedule at ffffffff818436af #1 [ffffc9000da2f6c8] _cond_resched at ffffffff81843c0d #2 [ffffc9000da2f6d8] rmap_walk_anon at ffffffff81241465 #3 [ffffc9000da2f738] remove_migration_ptes at ffffffff8127129d #4 [ffffc9000da2f770] remap_page at ffffffff8127504f #5 [ffffc9000da2f788] split_huge_page_to_list at ffffffff8127a82a #6 [ffffc9000da2f810] shrink_page_list at ffffffff8120b3fc #7 [ffffc9000da2f8e0] shrink_inactive_list at ffffffff8120c4c6 #8 [ffffc9000da2f988] shrink_node_memcg at ffffffff8120cffa #9 [ffffc9000da2fa90] shrink_node at ffffffff8120d534
#10 [ffffc9000da2fb28] do_try_to_free_pages at ffffffff8120dac4 #11 [ffffc9000da2fb90] try_to_free_pages at ffffffff8120dec4 #12 [ffffc9000da2fc28] __alloc_pages_slowpath at ffffffff811fa367 #13 [ffffc9000da2fd50] __alloc_pages_nodemask at ffffffff811fb116 #14 [ffffc9000da2fdb0] khugepaged at ffffffff8127e478 #15 [ffffc9000da2ff10] kthread at ffffffff810bcb75
#16 [ffffc9000da2ff50] ret_from_fork at ffffffff81a001cf

The system was overloaded and experiencing memory pressure. Releasing mmap_sem before doing any blocking operations could mitigate the problem, but the underlying priority inversion caused by khugepaged still exists.

Quoted 9 lines
Quoted 6 lines

For example we saw THP split in reclaim path triggered by khugepaged held write anon_vma lock, but the other process which was doing reclaim too was blocked by anon_vma lock. Then the cond_resched() in rmap walk would make khugepaged preempted by all other processes easily so khugepaged may hold the anon_vma lock for indefinite time. Then we saw hung tasks.

Any chance you have a reproducer? I'm not sure I follow the problem, but it's almost 4AM, so I'm slow.

I don't have a stable reproducer.

Quoted 312 lines
Quoted 304 lines

So we have khugepaged defrag disabled for some workloads to workaround the priority inversion problem. So, I'm concerned some processes may never get THP for some our workloads with this patch applied.

The priority inversion caused by khugepaged was not very usual. Just my two cents.

Quoted 296 lines
---
 mm/huge_memory.c | 247 +++++------------------------------------------
 1 file changed, 24 insertions(+), 223 deletions(-)
mm/huge_memory.c +24 -223
index ef6a6bcb291f..15b7a9c86b7c 100644
@@ -1206,262 +1206,63 @@ void huge_pmd_set_accessed(struct vm_fault *vmf, pmd_t orig_pmd)
        spin_unlock(vmf->ptl);
 }
 
-static vm_fault_t do_huge_pmd_wp_page_fallback(struct vm_fault *vmf,
-                       pmd_t orig_pmd, struct page *page)
-{
-       struct vm_area_struct *vma = vmf->vma;
-       unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-       struct mem_cgroup *memcg;
-       pgtable_t pgtable;
-       pmd_t _pmd;
-       int i;
-       vm_fault_t ret = 0;
-       struct page **pages;
-       struct mmu_notifier_range range;
-
-       pages = kmalloc_array(HPAGE_PMD_NR, sizeof(struct page *),
-                             GFP_KERNEL);
-       if (unlikely(!pages)) {
-               ret |= VM_FAULT_OOM;
-               goto out;
-       }
-
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE, vma,
-                                              vmf->address, page_to_nid(page));
-               if (unlikely(!pages[i] ||
-                            mem_cgroup_try_charge_delay(pages[i], vma->vm_mm,
-                                    GFP_KERNEL, &memcg, false))) {
-                       if (pages[i])
-                               put_page(pages[i]);
-                       while (--i >= 0) {
-                               memcg = (void *)page_private(pages[i]);
-                               set_page_private(pages[i], 0);
-                               mem_cgroup_cancel_charge(pages[i], memcg,
-                                               false);
-                               put_page(pages[i]);
-                       }
-                       kfree(pages);
-                       ret |= VM_FAULT_OOM;
-                       goto out;
-               }
-               set_page_private(pages[i], (unsigned long)memcg);
-       }
-
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               copy_user_highpage(pages[i], page + i,
-                                  haddr + PAGE_SIZE * i, vma);
-               __SetPageUptodate(pages[i]);
-               cond_resched();
-       }
-
-       mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-                               haddr, haddr + HPAGE_PMD_SIZE);
-       mmu_notifier_invalidate_range_start(&range);
-
-       vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-               goto out_free_pages;
-       VM_BUG_ON_PAGE(!PageHead(page), page);
-
-       /*
-        * Leave pmd empty until pte is filled note we must notify here as
-        * concurrent CPU thread might write to new page before the call to
-        * mmu_notifier_invalidate_range_end() happens which can lead to a
-        * device seeing memory write in different order than CPU.
-        *
-        * See Documentation/vm/mmu_notifier.rst
-        */
-       pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-
-       pgtable = pgtable_trans_huge_withdraw(vma->vm_mm, vmf->pmd);
-       pmd_populate(vma->vm_mm, &_pmd, pgtable);
-
-       for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) {
-               pte_t entry;
-               entry = mk_pte(pages[i], vma->vm_page_prot);
-               entry = maybe_mkwrite(pte_mkdirty(entry), vma);
-               memcg = (void *)page_private(pages[i]);
-               set_page_private(pages[i], 0);
-               page_add_new_anon_rmap(pages[i], vmf->vma, haddr, false);
-               mem_cgroup_commit_charge(pages[i], memcg, false, false);
-               lru_cache_add_active_or_unevictable(pages[i], vma);
-               vmf->pte = pte_offset_map(&_pmd, haddr);
-               VM_BUG_ON(!pte_none(*vmf->pte));
-               set_pte_at(vma->vm_mm, haddr, vmf->pte, entry);
-               pte_unmap(vmf->pte);
-       }
-       kfree(pages);
-
-       smp_wmb(); /* make pte visible before pmd */
-       pmd_populate(vma->vm_mm, vmf->pmd, pgtable);
-       page_remove_rmap(page, true);
-       spin_unlock(vmf->ptl);
-
-       /*
-        * No need to double call mmu_notifier->invalidate_range() callback as
-        * the above pmdp_huge_clear_flush_notify() did already call it.
-        */
-       mmu_notifier_invalidate_range_only_end(&range);
-
-       ret |= VM_FAULT_WRITE;
-       put_page(page);
-
-out:
-       return ret;
-
-out_free_pages:
-       spin_unlock(vmf->ptl);
-       mmu_notifier_invalidate_range_end(&range);
-       for (i = 0; i < HPAGE_PMD_NR; i++) {
-               memcg = (void *)page_private(pages[i]);
-               set_page_private(pages[i], 0);
-               mem_cgroup_cancel_charge(pages[i], memcg, false);
-               put_page(pages[i]);
-       }
-       kfree(pages);
-       goto out;
-}
-
 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf, pmd_t orig_pmd)
 {
        struct vm_area_struct *vma = vmf->vma;
-       struct page *page = NULL, *new_page;
-       struct mem_cgroup *memcg;
+       struct page *page;
        unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
-       struct mmu_notifier_range range;
-       gfp_t huge_gfp;                 /* for allocation and charge */
-       vm_fault_t ret = 0;
 
        vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd);
        VM_BUG_ON_VMA(!vma->anon_vma, vma);
+
        if (is_huge_zero_pmd(orig_pmd))
-               goto alloc;
+               goto fallback;
+
        spin_lock(vmf->ptl);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd)))
-               goto out_unlock;
+
+       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+               spin_unlock(vmf->ptl);
+               return 0;
+       }
 
        page = pmd_page(orig_pmd);
        VM_BUG_ON_PAGE(!PageCompound(page) || !PageHead(page), page);
-       /*
-        * We can only reuse the page if nobody else maps the huge page or it's
-        * part.
-        */
+
+       /* Lock page for reuse_swap_page() */
        if (!trylock_page(page)) {
                get_page(page);
                spin_unlock(vmf->ptl);
                lock_page(page);
                spin_lock(vmf->ptl);
                if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
+                       spin_unlock(vmf->ptl);
                        unlock_page(page);
                        put_page(page);
-                       goto out_unlock;
+                       return 0;
                }
                put_page(page);
        }
+
+       /*
+        * We can only reuse the page if nobody else maps the huge page or it's
+        * part.
+        */
        if (reuse_swap_page(page, NULL)) {
                pmd_t entry;
                entry = pmd_mkyoung(orig_pmd);
                entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
                if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry,  1))
                        update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-               ret |= VM_FAULT_WRITE;
                unlock_page(page);
-               goto out_unlock;
-       }
-       unlock_page(page);
-       get_page(page);
-       spin_unlock(vmf->ptl);
-alloc:
-       if (__transparent_hugepage_enabled(vma) &&
-           !transparent_hugepage_debug_cow()) {
-               huge_gfp = alloc_hugepage_direct_gfpmask(vma);
-               new_page = alloc_hugepage_vma(huge_gfp, vma, haddr, HPAGE_PMD_ORDER);
-       } else
-               new_page = NULL;
-
-       if (likely(new_page)) {
-               prep_transhuge_page(new_page);
-       } else {
-               if (!page) {
-                       split_huge_pmd(vma, vmf->pmd, vmf->address);
-                       ret |= VM_FAULT_FALLBACK;
-               } else {
-                       ret = do_huge_pmd_wp_page_fallback(vmf, orig_pmd, page);
-                       if (ret & VM_FAULT_OOM) {
-                               split_huge_pmd(vma, vmf->pmd, vmf->address);
-                               ret |= VM_FAULT_FALLBACK;
-                       }
-                       put_page(page);
-               }
-               count_vm_event(THP_FAULT_FALLBACK);
-               goto out;
-       }
-
-       if (unlikely(mem_cgroup_try_charge_delay(new_page, vma->vm_mm,
-                                       huge_gfp, &memcg, true))) {
-               put_page(new_page);
-               split_huge_pmd(vma, vmf->pmd, vmf->address);
-               if (page)
-                       put_page(page);
-               ret |= VM_FAULT_FALLBACK;
-               count_vm_event(THP_FAULT_FALLBACK);
-               goto out;
-       }
-
-       count_vm_event(THP_FAULT_ALLOC);
-       count_memcg_events(memcg, THP_FAULT_ALLOC, 1);
-
-       if (!page)
-               clear_huge_page(new_page, vmf->address, HPAGE_PMD_NR);
-       else
-               copy_user_huge_page(new_page, page, vmf->address,
-                                   vma, HPAGE_PMD_NR);
-       __SetPageUptodate(new_page);
-
-       mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
-                               haddr, haddr + HPAGE_PMD_SIZE);
-       mmu_notifier_invalidate_range_start(&range);
-
-       spin_lock(vmf->ptl);
-       if (page)
-               put_page(page);
-       if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) {
                spin_unlock(vmf->ptl);
-               mem_cgroup_cancel_charge(new_page, memcg, true);
-               put_page(new_page);
-               goto out_mn;
-       } else {
-               pmd_t entry;
-               entry = mk_huge_pmd(new_page, vma->vm_page_prot);
-               entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
-               pmdp_huge_clear_flush_notify(vma, haddr, vmf->pmd);
-               page_add_new_anon_rmap(new_page, vma, haddr, true);
-               mem_cgroup_commit_charge(new_page, memcg, false, true);
-               lru_cache_add_active_or_unevictable(new_page, vma);
-               set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
-               update_mmu_cache_pmd(vma, vmf->address, vmf->pmd);
-               if (!page) {
-                       add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
-               } else {
-                       VM_BUG_ON_PAGE(!PageHead(page), page);
-                       page_remove_rmap(page, true);
-                       put_page(page);
-               }
-               ret |= VM_FAULT_WRITE;
+               return VM_FAULT_WRITE;
        }
+
+       unlock_page(page);
        spin_unlock(vmf->ptl);
-out_mn:
-       /*
-        * No need to double call mmu_notifier->invalidate_range() callback as
-        * the above pmdp_huge_clear_flush_notify() did already call it.
-        */
-       mmu_notifier_invalidate_range_only_end(&range);
-out:
-       return ret;
-out_unlock:
-       spin_unlock(vmf->ptl);
-       return ret;
+fallback:
+       __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
+       return VM_FAULT_FALLBACK;
 }
 
Quoted 5 lines
Quoted 5 lines
mm/huge_memory.c +0 -1
 /*
--

2.26.0

--
Kirill A. Shutemov

#9 lore raw

Re: [PATCH 3/7] khugepaged: Drain LRU add pagevec to get rid of extra pins

In reply to Yang Shi
Quoted 29 lines · Yang Shi
Quoted 15 lines · Kirill A. Shutemov

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +0 -0
index 14d7afc90786..39e0994abeb8 100644

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 593

Quoted 9 lines
mm/khugepaged.c +6 -0
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                 * The page must only be referenced by the scanned process
                 * and page swap cache.
                 */
+               if (page_count(page) != 1 + PageSwapCache(page)) {
+                       /*
+                        * Drain pagevec and retry just in case we can get rid
+                        * of the extra pin, like in swapin case.
+                        */
+                       lru_add_drain();

This is definitely correct.

Quoted 3 lines

I'm wondering if we need one more lru_add_drain() before PageLRU check in khugepaged_scan_pmd() or not? The page might be in lru cache then get skipped. This would improve the success rate.

Could you elaborate on the scenario, I don't follow.

Signature · 1 line
 Kirill A. Shutemov
#20 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Yang Shi
Quoted 40 lines · Yang Shi
Quoted 39 lines · Kirill A. Shutemov
Quoted 36 lines · Yang Shi
Quoted 21 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +2 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 529

Quoted 10 lines
mm/khugepaged.c +9 -0
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
+       if (!PageLocked(page))
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));

We need count in the number of base pages. The same counter is modified by vmscan in base page unit.

Quoted 5 lines
Quoted 1 line

Is it though? Where?

__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken) in vmscan.c, here nr_taken is nr_compound(page), so if it is THP the number would be 512.

Could you point a particular codepath?

Quoted 2 lines

So in both inc and dec path of collapse PTE mapped THP, we should mod nr_compound(page) too.

I disagree. Compound page is represented by single entry on LRU, so it has to be counted once.

Signature · 1 line
 Kirill A. Shutemov
#25 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Zi Yan
Quoted 5 lines · Zi Yan
Quoted 4 lines

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

Quoted 8 lines

For the first time, the compound page is locked and not on LRU, so this VM_BUG_ON passes. For the second time and so on, the compound page is unlocked and on the LRU, so this VM_BUG_ON still passes.

For base page, VM_BUG_ON passes.

Other unexpected situation (a compound page is locked and on LRU) triggers the VM_BU_ON, but your VM_BUG_ON will not detect this situation, right?

Right. I will rework this code. I've just realized it is racy: after unlock and putback on LRU the page can be locked by somebody else and this code can unlock it which completely borken.

I'll pass down compound_pagelist to release_pte_pages() and handle the situation there.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 2 lines
    if (likely(writable)) {
            if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Quoted 7 lines
Quoted 5 lines

Um? It's outside the pte loop. We get here once per PMD range.

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Throughout the pte loop, we should only see at most one compound page, right?

No. mremap(2) opens a possibility for HPAGE_PMD_NR compound pages for single PMD range.

Signature · 1 line
 Kirill A. Shutemov
#10 lore raw

Re: [PATCH 3/7] khugepaged: Drain LRU add pagevec to get rid of extra pins

In reply to Kirill A. Shutemov
Quoted 31 lines · Kirill A. Shutemov
Quoted 29 lines · Yang Shi
Quoted 15 lines · Kirill A. Shutemov

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +0 -0
index 14d7afc90786..39e0994abeb8 100644

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 593

Quoted 9 lines
mm/khugepaged.c +6 -0
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                 * The page must only be referenced by the scanned process
                 * and page swap cache.
                 */
+               if (page_count(page) != 1 + PageSwapCache(page)) {
+                       /*
+                        * Drain pagevec and retry just in case we can get rid
+                        * of the extra pin, like in swapin case.
+                        */
+                       lru_add_drain();

This is definitely correct.

Quoted 5 lines
Quoted 3 lines

I'm wondering if we need one more lru_add_drain() before PageLRU check in khugepaged_scan_pmd() or not? The page might be in lru cache then get skipped. This would improve the success rate.

Could you elaborate on the scenario, I don't follow.

I mean the below change:

mm/khugepaged.c +3 -0
@@ -1195,6 +1195,9 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
                khugepaged_node_load[node]++;
+               if (!PageLRU(page))
+                       /* Flush the page out of lru cache */
+                       lru_add_drain();
                if (!PageLRU(page)) {
                        result = SCAN_PAGE_LRU;
                        goto out_unmap;

If the page is not on LRU we even can't reach collapse_huge_page(), right?

Quoted 4 lines

--
Kirill A. Shutemov

#21 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 42 lines · Kirill A. Shutemov
Quoted 40 lines · Yang Shi
Quoted 39 lines · Kirill A. Shutemov
Quoted 36 lines · Yang Shi
Quoted 21 lines · Kirill A. Shutemov

We can collapse PTE-mapped compound pages. We only need to avoid handling them more than once: lock/unlock page only once if it's present in the PMD range multiple times as it handled on compound level. The same goes for LRU isolation and putpack.

---
 mm/khugepaged.c | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)
mm/khugepaged.c +2 -0
index b47edfe57f7b..c8c2c463095c 100644
@@ -515,6 +515,17 @@ void __khugepaged_exit(struct mm_struct *mm)
 
 static void release_pte_page(struct page *page)
 {
+       /*
+        * We need to unlock and put compound page on LRU only once.

mm/khugepaged.c void __khugepaged_exit(struct mm_struct *mm) · line 529

Quoted 10 lines
mm/khugepaged.c +9 -0
+        * The rest of the pages have to be locked and not on LRU here.
+        */
+       VM_BUG_ON_PAGE(!PageCompound(page) &&
+                       (!PageLocked(page) && PageLRU(page)), page);
+
+       if (!PageLocked(page))
+               return;
+
+       page = compound_head(page);
        dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page));

We need count in the number of base pages. The same counter is modified by vmscan in base page unit.

Quoted 7 lines
Quoted 5 lines
Quoted 1 line

Is it though? Where?

__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken) in vmscan.c, here nr_taken is nr_compound(page), so if it is THP the number would be 512.

Could you point a particular codepath?

shrink_inactive_list ->
nr_taken = isolate_lru_pages() __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);

Then in isolate_lru_pages() :

        nr_pages = compound_nr(page);
        ...
        switch (__isolate_lru_page(page, mode)) {
                case 0:
                        nr_taken += nr_pages;
Quoted 6 lines
Quoted 3 lines

So in both inc and dec path of collapse PTE mapped THP, we should mod nr_compound(page) too.

I disagree. Compound page is represented by single entry on LRU, so it has to be counted once.

It was not a problem without THP swap. But with THP swap we saw pgsteal_{kswapd|direct} may be greater than pgscan_{kswapd|direct} if we count THP as one page.

Please refer to the below commit:

commit 98879b3b9edc1604f2d1a6686576ef4d08ed3310

Author: Yang Shi <[email protected]>
Date:   Thu Jul 11 20:59:30 2019 -0700

mm: vmscan: correct some vmscan counters for THP swapout

Commit bd4c82c22c36 ("mm, THP, swap: delay splitting THP after swapped out"), THP can be swapped out in a whole. But, nr_reclaimed and some other vm counters still get inc'ed by one even though a whole THP (512 pages) gets swapped out.

This doesn't make too much sense to memory reclaim.

For example, direct reclaim may just need reclaim SWAP_CLUSTER_MAX pages, reclaiming one THP could fulfill it. But, if nr_reclaimed is not increased correctly, direct reclaim may just waste time to reclaim more pages, SWAP_CLUSTER_MAX * 512 pages in worst case.

And, it may cause pgsteal_{kswapd|direct} is greater than pgscan_{kswapd|direct}, like the below:

pgsteal_kswapd 122933
pgsteal_direct 26600225
pgscan_kswapd 174153
pgscan_direct 14678312

nr_reclaimed and nr_scanned must be fixed in parallel otherwise it would break some page reclaim logic, e.g.

vmpressure: this looks at the scanned/reclaimed ratio so it won't change semantics as long as scanned & reclaimed are fixed in parallel.

compaction/reclaim: compaction wants a certain number of physical pages freed up before going back to compacting.

kswapd priority raising: kswapd raises priority if we scan fewer pages than the reclaim target (which itself is obviously expressed in order-0 pages). As a result, kswapd can falsely raise its aggressiveness even when it's making great progress.

Other than nr_scanned and nr_reclaimed, some other counters, e.g. pgactivate, nr_skipped, nr_ref_keep and nr_unmap_fail need to be fixed too since they are user visible via cgroup, /proc/vmstat or trace points, otherwise they would be underreported.

When isolating pages from LRUs, nr_taken has been accounted in base page, but nr_scanned and nr_skipped are still accounted in THP. It doesn't make too much sense too since this may cause trace point underreport the numbers as well.

So accounting those counters in base page instead of accounting THP as one page.

nr_dirty, nr_unqueued_dirty, nr_congested and nr_writeback are used by file cache, so they are not impacted by THP swap.

This change may result in lower steal/scan ratio in some cases since THP may get split during page reclaim, then a part of tail pages get reclaimed instead of the whole 512 pages, but nr_scanned is accounted by 512, particularly for direct reclaim. But, this should be not a significant issue.

So, since we count THP in base page unit in vmscan path, so the same counter should be updated in base page unit in other path as well IMHO.

Quoted 3 lines

--
Kirill A. Shutemov

#26 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 11 lines · Kirill A. Shutemov
Quoted 9 lines · Zi Yan
Quoted 4 lines

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

For the first time, the compound page is locked and not on LRU, so this VM_BUG_ON passes. For the second time and so on, the compound page is unlocked and on the LRU, so this VM_BUG_ON still passes.

Quoted 8 lines
Quoted 4 lines

For base page, VM_BUG_ON passes.

Other unexpected situation (a compound page is locked and on LRU) triggers the VM_BU_ON, but your VM_BUG_ON will not detect this situation, right?

Right. I will rework this code. I've just realized it is racy: after unlock and putback on LRU the page can be locked by somebody else and this code can unlock it which completely borken.

I'm wondering if we shall skip putting the page back to LRU. Since the page is about to be freed soon, so as I mentioned in the other patch it sounds not very productive to put it back to LRU again.

Quoted 24 lines

I'll pass down compound_pagelist to release_pte_pages() and handle the situation there.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 2 lines
    if (likely(writable)) {
            if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Quoted 7 lines
Quoted 5 lines

Um? It's outside the pte loop. We get here once per PMD range.

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Throughout the pte loop, we should only see at most one compound page, right?

No. mremap(2) opens a possibility for HPAGE_PMD_NR compound pages for single PMD range.

--
Kirill A. Shutemov

#27 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Kirill A. Shutemov
Quoted 30 lines · Kirill A. Shutemov
Quoted 5 lines · Zi Yan
Quoted 4 lines

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

Quoted 8 lines

For the first time, the compound page is locked and not on LRU, so this VM_BUG_ON passes. For the second time and so on, the compound page is unlocked and on the LRU, so this VM_BUG_ON still passes.

For base page, VM_BUG_ON passes.

Other unexpected situation (a compound page is locked and on LRU) triggers the VM_BU_ON, but your VM_BUG_ON will not detect this situation, right?

Right. I will rework this code. I've just realized it is racy: after unlock and putback on LRU the page can be locked by somebody else and this code can unlock it which completely borken.

I'll pass down compound_pagelist to release_pte_pages() and handle the situation there.

Quoted 7 lines
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
    if (likely(writable)) {
            if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Um? It's outside the pte loop. We get here once per PMD range.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Throughout the pte loop, we should only see at most one compound page, right?

No. mremap(2) opens a possibility for HPAGE_PMD_NR compound pages for single PMD range.

Do you mean every PTE in the PMD is mapped by a sub page from different THPs?

Quoted 5 lines

--
Kirill A. Shutemov

#11 lore raw

Re: [PATCH 3/7] khugepaged: Drain LRU add pagevec to get rid of extra pins

In reply to Yang Shi
Quoted 53 lines · Yang Shi
Quoted 31 lines · Kirill A. Shutemov
Quoted 29 lines · Yang Shi
Quoted 15 lines · Kirill A. Shutemov

__collapse_huge_page_isolate() may fail due to extra pin in the LRU add pagevec. It's petty common for swapin case: we swap in pages just to fail due to the extra pin.

---
 mm/khugepaged.c | 8 ++++++++
 1 file changed, 8 insertions(+)
mm/khugepaged.c +0 -0
index 14d7afc90786..39e0994abeb8 100644

mm/khugepaged.c static int __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 593

Quoted 9 lines
mm/khugepaged.c +6 -0
@@ -585,11 +585,19 @@ static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
                 * The page must only be referenced by the scanned process
                 * and page swap cache.
                 */
+               if (page_count(page) != 1 + PageSwapCache(page)) {
+                       /*
+                        * Drain pagevec and retry just in case we can get rid
+                        * of the extra pin, like in swapin case.
+                        */
+                       lru_add_drain();

This is definitely correct.

Quoted 5 lines
Quoted 3 lines

I'm wondering if we need one more lru_add_drain() before PageLRU check in khugepaged_scan_pmd() or not? The page might be in lru cache then get skipped. This would improve the success rate.

Could you elaborate on the scenario, I don't follow.

I mean the below change:

mm/khugepaged.c +3 -0
@@ -1195,6 +1195,9 @@ static int khugepaged_scan_pmd(struct mm_struct *mm,
                        goto out_unmap;
                }
                khugepaged_node_load[node]++;
+               if (!PageLRU(page))
+                       /* Flush the page out of lru cache */
+                       lru_add_drain();
                if (!PageLRU(page)) {
                        result = SCAN_PAGE_LRU;
                        goto out_unmap;
Quoted 1 line

If the page is not on LRU we even can't reach collapse_huge_page(), right?

Yeah, I've archived the same by doing lru_add_drain_all() once per khugepaged_do_scan(). It is more effective than lru_add_drain() inside khugepaged_scan_pmd() and should have too much overhead.

The lru_add_drain() from this patch moved into swapin routine and called only on success.

Signature · 1 line
 Kirill A. Shutemov
#28 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

In reply to Yang Shi
Quoted 35 lines · Yang Shi
Quoted 34 lines · Kirill A. Shutemov
Quoted 5 lines · Zi Yan
Quoted 4 lines

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

Quoted 8 lines

For the first time, the compound page is locked and not on LRU, so this VM_BUG_ON passes. For the second time and so on, the compound page is unlocked and on the LRU, so this VM_BUG_ON still passes.

For base page, VM_BUG_ON passes.

Other unexpected situation (a compound page is locked and on LRU) triggers the VM_BU_ON, but your VM_BUG_ON will not detect this situation, right?

Right. I will rework this code. I've just realized it is racy: after unlock and putback on LRU the page can be locked by somebody else and this code can unlock it which completely borken.

I'll pass down compound_pagelist to release_pte_pages() and handle the situation there.

Quoted 11 lines
Quoted 10 lines
Quoted 4 lines
Quoted 2 lines
    if (likely(writable)) {
            if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Um? It's outside the pte loop. We get here once per PMD range.

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Throughout the pte loop, we should only see at most one compound page, right?

No. mremap(2) opens a possibility for HPAGE_PMD_NR compound pages for single PMD range.

Do you mean every PTE in the PMD is mapped by a sub page from different THPs?

Yes.

Well, it was harder to archive than I expected, but below is a test case, I've come up with. It maps 512 head pages within single PMD range.

tools/testing/selftests/vm/khugepaged.c +58 -0
index 3a98d5b2d6d8..9ae119234a39 100644
@@ -703,6 +703,63 @@ static void collapse_full_of_compound(void)
 	munmap(p, hpage_pmd_size);
 }
 
+static void collapse_compound_extreme(void)
+{
+	void *p;
+	int i;
+
+	p = alloc_mapping();
+	for (i = 0; i < hpage_pmd_nr; i++) {
+		printf("\rConstruct PTE page table full of different PTE-mapped compound pages %3d/%d...",
+				i + 1, hpage_pmd_nr);
+
+		madvise(BASE_ADDR, hpage_pmd_size, MADV_HUGEPAGE);
+		fill_memory(BASE_ADDR, 0, hpage_pmd_size);
+		if (!check_huge(BASE_ADDR)) {
+			printf("Failed to allocate huge page\n");
+			exit(EXIT_FAILURE);
+		}
+		madvise(BASE_ADDR, hpage_pmd_size, MADV_NOHUGEPAGE);
+
+		p = mremap(BASE_ADDR - i * page_size,
+				i * page_size + hpage_pmd_size,
+				(i + 1) * page_size,
+				MREMAP_MAYMOVE | MREMAP_FIXED,
+				BASE_ADDR + 2 * hpage_pmd_size);
+		if (p == MAP_FAILED) {
+			perror("mremap+unmap");
+			exit(EXIT_FAILURE);
+		}
+
+		p = mremap(BASE_ADDR + 2 * hpage_pmd_size,
+				(i + 1) * page_size,
+				(i + 1) * page_size + hpage_pmd_size,
+				MREMAP_MAYMOVE | MREMAP_FIXED,
+				BASE_ADDR - (i + 1) * page_size);
+		if (p == MAP_FAILED) {
+			perror("mremap+alloc");
+			exit(EXIT_FAILURE);
+		}
+	}
+
+	munmap(BASE_ADDR, hpage_pmd_size);
+	fill_memory(p, 0, hpage_pmd_size);
+	if (!check_huge(p))
+		success("OK");
+	else
+		fail("Fail");
+
+	if (wait_for_scan("Collapse PTE table full of different compound pages", p))
+		fail("Timeout");
+	else if (check_huge(p))
+		success("OK");
+	else
+		fail("Fail");
+
+	validate_memory(p, 0, hpage_pmd_size);
+	munmap(p, hpage_pmd_size);
+}
+
 static void collapse_fork(void)
 {
 	int wstatus;
@@ -916,6 +973,7 @@ int main(void)
 	collapse_max_ptes_swap();
 	collapse_signle_pte_entry_compound();
 	collapse_full_of_compound();
+	collapse_compound_extreme();
 	collapse_fork();
 	collapse_fork_compound();
 	collapse_max_ptes_shared();
Signature · 1 line
 Kirill A. Shutemov
#29 lore raw

Re: [PATCH 5/7] khugepaged: Allow to collapse PTE-mapped compound pages

Quoted 42 lines · Kirill A. Shutemov
Quoted 40 lines · Yang Shi
Quoted 38 lines · Kirill A. Shutemov
Quoted 5 lines · Zi Yan
Quoted 4 lines

The compound page may be locked here if the function called for the first time for the page and not locked after that (becouse we've unlocked it we saw it the first time). The same with LRU.

Quoted 8 lines

For the first time, the compound page is locked and not on LRU, so this VM_BUG_ON passes. For the second time and so on, the compound page is unlocked and on the LRU, so this VM_BUG_ON still passes.

For base page, VM_BUG_ON passes.

Other unexpected situation (a compound page is locked and on LRU) triggers the VM_BU_ON, but your VM_BUG_ON will not detect this situation, right?

Right. I will rework this code. I've just realized it is racy: after unlock and putback on LRU the page can be locked by somebody else and this code can unlock it which completely borken.

I'll pass down compound_pagelist to release_pte_pages() and handle the situation there.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 2 lines
    if (likely(writable)) {
            if (likely(referenced)) {

Do we need a list here? There should be at most one compound page we will see here, right?

Quoted 7 lines
Quoted 5 lines

Um? It's outside the pte loop. We get here once per PMD range.

'page' argument to trace_mm_collapse_huge_page_isolate() is misleading:
it's just the last page handled in the loop.

Throughout the pte loop, we should only see at most one compound page, right?

No. mremap(2) opens a possibility for HPAGE_PMD_NR compound pages for single PMD range.

Quoted 6 lines
Quoted 1 line

Do you mean every PTE in the PMD is mapped by a sub page from different THPs?

Yes.

Well, it was harder to archive than I expected, but below is a test case, I've come up with. It maps 512 head pages within single PMD range.

Thanks, this is very helpful.

Quoted 79 lines
tools/testing/selftests/vm/khugepaged.c +58 -1
index 3a98d5b2d6d8..9ae119234a39 100644
@@ -703,6 +703,63 @@ static void collapse_full_of_compound(void)
        munmap(p, hpage_pmd_size);
 }
 
+static void collapse_compound_extreme(void)
+{
+       void *p;
+       int i;
+
+       p = alloc_mapping();
+       for (i = 0; i < hpage_pmd_nr; i++) {
+               printf("\rConstruct PTE page table full of different PTE-mapped compound pages %3d/%d...",
+                               i + 1, hpage_pmd_nr);
+
+               madvise(BASE_ADDR, hpage_pmd_size, MADV_HUGEPAGE);
+               fill_memory(BASE_ADDR, 0, hpage_pmd_size);
+               if (!check_huge(BASE_ADDR)) {
+                       printf("Failed to allocate huge page\n");
+                       exit(EXIT_FAILURE);
+               }
+               madvise(BASE_ADDR, hpage_pmd_size, MADV_NOHUGEPAGE);
+
+               p = mremap(BASE_ADDR - i * page_size,
+                               i * page_size + hpage_pmd_size,
+                               (i + 1) * page_size,
+                               MREMAP_MAYMOVE | MREMAP_FIXED,
+                               BASE_ADDR + 2 * hpage_pmd_size);
+               if (p == MAP_FAILED) {
+                       perror("mremap+unmap");
+                       exit(EXIT_FAILURE);
+               }
+
+               p = mremap(BASE_ADDR + 2 * hpage_pmd_size,
+                               (i + 1) * page_size,
+                               (i + 1) * page_size + hpage_pmd_size,
+                               MREMAP_MAYMOVE | MREMAP_FIXED,
+                               BASE_ADDR - (i + 1) * page_size);
+               if (p == MAP_FAILED) {
+                       perror("mremap+alloc");
+                       exit(EXIT_FAILURE);
+               }
+       }
+
+       munmap(BASE_ADDR, hpage_pmd_size);
+       fill_memory(p, 0, hpage_pmd_size);
+       if (!check_huge(p))
+               success("OK");
+       else
+               fail("Fail");
+
+       if (wait_for_scan("Collapse PTE table full of different compound pages", p))
+               fail("Timeout");
+       else if (check_huge(p))
+               success("OK");
+       else
+               fail("Fail");
+
+       validate_memory(p, 0, hpage_pmd_size);
+       munmap(p, hpage_pmd_size);
+}
+
 static void collapse_fork(void)
 {
        int wstatus;
@@ -916,6 +973,7 @@ int main(void)
        collapse_max_ptes_swap();
        collapse_signle_pte_entry_compound();
        collapse_full_of_compound();
+       collapse_compound_extreme();
        collapse_fork();
        collapse_fork_compound();
        collapse_max_ptes_shared();
--
 Kirill A. Shutemov