Skip to contentSkip to conversation

1G page support for guest_memfd

RFC PATCH NAK Ackerley Tng 18 participants 272 messages May 14, 2025 – Jan 24 1 message not in the archive Page 2 of 3

Subsystems (22)
lore
Share & tools
lore
#106 lore raw

Re: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status

In reply to Yan Zhao
Quoted 48 lines · Yan Zhao
Quoted 47 lines · Ackerley Tng

Query guest_memfd for private/shared status if those guest_memfds track private/shared status.

With this patch, Coco VMs can use guest_memfd for both shared and private memory. If Coco VMs choose to use guest_memfd for both shared and private memory, by creating guest_memfd with the GUEST_MEMFD_FLAG_SUPPORT_SHARED flag, guest_memfd will be used to provide the private/shared status of the memory, instead of kvm->mem_attr_array.

Change-Id I8f23d7995c12242aa4e09ccf5ec19360e9c9ed83
---
  include/linux/kvm_host.h | 19 ++++++++++++-------
  virt/kvm/guest_memfd.c   | 22 ++++++++++++++++++++++
  2 files changed, 34 insertions(+), 7 deletions(-)
include/linux/kvm_host.h +10 -0
index b317392453a5..91279e05e010 100644
@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu,
  }
 
  #ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
  bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot);
+bool kvm_gmem_is_private(struct kvm_memory_slot *slot, gfn_t gfn);
+
  #else
+
  static inline bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot)
  {
  	return false;
  }
+
+static inline bool kvm_gmem_is_private(struct kvm_memory_slot *slot, gfn_t gfn)
+{
+	return false;
+}
+
  #endif /* CONFIG_KVM_GMEM_SHARED_MEM */
 
  #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
@@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
  		return false;
 
Quoted 12 lines

include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2558

Quoted 10 lines
include/linux/kvm_host.h +2 -7
  	slot = gfn_to_memslot(kvm, gfn);
-	if (kvm_slot_has_gmem(slot) && kvm_gmem_memslot_supports_shared(slot)) {
-		/*
-		 * For now, memslots only support in-place shared memory if the
-		 * host is allowed to mmap memory (i.e., non-Coco VMs).
-		 */
-		return false;
-	}
+	if (kvm_slot_has_gmem(slot) && kvm_gmem_memslot_supports_shared(slot))
+		return kvm_gmem_is_private(slot, gfn);

When userspace gets an exit reason KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?

IIUC, when userspace sets flag GUEST_MEMFD_FLAG_SUPPORT_SHARED to create the guest_memfd, the check for memory attribute will go through the guest_memfd way, the information in kvm->mem_attr_array will not be used.

So if userspace sets GUEST_MEMFD_FLAG_SUPPORT_SHARED, it uses KVM_GMEM_CONVERT_SHARED/PRIVATE to update gmem shareability. If userspace doesn't set GUEST_MEMFD_FLAG_SUPPORT_SHARED, it still uses KVM_SET_MEMORY_ATTRIBUTES to update KVM memory attribute tracking.

Quoted 4 lines
Quoted 4 lines
include/linux/kvm_host.h +0 -0
  	return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;
  }
#123 lore raw

Re: [RFC PATCH v2 16/51] mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()

In reply to Ackerley Tng
Quoted 20 lines · Ackerley Tng

Previously, gbl_chg was passed from alloc_hugetlb_folio() into dequeue_hugetlb_folio_vma(), leaking the concept of gbl_chg into dequeue_hugetlb_folio_vma().

This patch consolidates the interpretation of gbl_chg into alloc_hugetlb_folio(), also renaming dequeue_hugetlb_folio_vma() to dequeue_hugetlb_folio() so dequeue_hugetlb_folio() can just focus on dequeuing a folio.

Change-Id I31bf48af2400b6e13b44d03c8be22ce1a9092a9c
---
  mm/hugetlb.c | 28 +++++++++++-----------------
  1 file changed, 11 insertions(+), 17 deletions(-)
mm/hugetlb.c +0 -0
index 6ea1be71aa42..b843e869496f 100644

mm/hugetlb.c static unsigned long available_huge_pages(struct hstate *h) · line 1369

Quoted 9 lines
mm/hugetlb.c +3 -3
@@ -1364,9 +1364,9 @@ static unsigned long available_huge_pages(struct hstate *h)
  	return h->free_huge_pages - h->resv_huge_pages;
  }
 
-static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
-				struct vm_area_struct *vma,
-				unsigned long address, long gbl_chg)
+static struct folio *dequeue_hugetlb_folio(struct hstate *h,
+					   struct vm_area_struct *vma,
+					   unsigned long address)

The rename seems not needed in this patch, since the function still takes vma and uses it. May be better to move the rename to a later patch.

Quoted 48 lines
mm/hugetlb.c +8 -14
  {
  	struct folio *folio = NULL;
  	struct mempolicy *mpol;
@@ -1374,13 +1374,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
  	nodemask_t *nodemask;
  	int nid;
 
-	/*
-	 * gbl_chg==1 means the allocation requires a new page that was not
-	 * reserved before.  Making sure there's at least one free page.
-	 */
-	if (gbl_chg && !available_huge_pages(h))
-		goto err;
-
  	gfp_mask = htlb_alloc_mask(h);
  	nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
 
@@ -1398,9 +1391,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
 
  	mpol_cond_put(mpol);
  	return folio;
-
-err:
-	return NULL;
  }
 
  /*
@@ -3074,12 +3064,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
  		goto out_uncharge_cgroup_reservation;
 
  	spin_lock_irq(&hugetlb_lock);
+
  	/*
-	 * glb_chg is passed to indicate whether or not a page must be taken
-	 * from the global free pool (global change).  gbl_chg == 0 indicates
-	 * a reservation exists for the allocation.
+	 * gbl_chg == 0 indicates a reservation exists for the allocation - so
+	 * try dequeuing a page. If there are available_huge_pages(), try using
+	 * them!
  	 */
-	folio = dequeue_hugetlb_folio_vma(h, vma, addr, gbl_chg);
+	folio = NULL;
+	if (!gbl_chg || available_huge_pages(h))
+		folio = dequeue_hugetlb_folio(h, vma, addr);
+
  	if (!folio) {
  		spin_unlock_irq(&hugetlb_lock);
  		folio = alloc_buddy_hugetlb_folio_with_mpol(h, vma, addr);
#107 lore raw

Re: [RFC PATCH v2 06/51] KVM: Query guest_memfd for private/shared status

In reply to Binbin Wu
Quoted 60 lines · Binbin Wu
Quoted 49 lines · Yan Zhao
Quoted 48 lines · Ackerley Tng

Query guest_memfd for private/shared status if those guest_memfds track private/shared status.

With this patch, Coco VMs can use guest_memfd for both shared and private memory. If Coco VMs choose to use guest_memfd for both shared and private memory, by creating guest_memfd with the GUEST_MEMFD_FLAG_SUPPORT_SHARED flag, guest_memfd will be used to provide the private/shared status of the memory, instead of kvm->mem_attr_array.

Change-Id I8f23d7995c12242aa4e09ccf5ec19360e9c9ed83
---
  include/linux/kvm_host.h | 19 ++++++++++++-------
  virt/kvm/guest_memfd.c   | 22 ++++++++++++++++++++++
  2 files changed, 34 insertions(+), 7 deletions(-)
include/linux/kvm_host.h +10 -3
index b317392453a5..91279e05e010 100644
@@ -2508,12 +2508,22 @@ static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu,
  }
  #ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
  bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot);
+bool kvm_gmem_is_private(struct kvm_memory_slot *slot, gfn_t gfn);
+
  #else
+
  static inline bool kvm_gmem_memslot_supports_shared(const struct kvm_memory_slot *slot)
  {
  	return false;
  }
+
+static inline bool kvm_gmem_is_private(struct kvm_memory_slot *slot, gfn_t gfn)
+{
+	return false;
+}
+
  #endif /* CONFIG_KVM_GMEM_SHARED_MEM */
  #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
@@ -2544,13 +2554,8 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
  		return false;
  	slot = gfn_to_memslot(kvm, gfn);
-	if (kvm_slot_has_gmem(slot) && kvm_gmem_memslot_supports_shared(slot)) {
-		/*
-		 * For now, memslots only support in-place shared memory if the
Quoted 8 lines

include/linux/kvm_host.h static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn) · line 2558

Quoted 6 lines
include/linux/kvm_host.h +2 -4
-		 * host is allowed to mmap memory (i.e., non-Coco VMs).
-		 */
-		return false;
-	}
+	if (kvm_slot_has_gmem(slot) && kvm_gmem_memslot_supports_shared(slot))
+		return kvm_gmem_is_private(slot, gfn);

When userspace gets an exit reason KVM_EXIT_MEMORY_FAULT, looks it needs to update both KVM memory attribute and gmem shareability, via two separate ioctls?

Quoted 8 lines

IIUC, when userspace sets flag GUEST_MEMFD_FLAG_SUPPORT_SHARED to create the guest_memfd, the check for memory attribute will go through the guest_memfd way, the information in kvm->mem_attr_array will not be used.

So if userspace sets GUEST_MEMFD_FLAG_SUPPORT_SHARED, it uses KVM_GMEM_CONVERT_SHARED/PRIVATE to update gmem shareability. If userspace doesn't set GUEST_MEMFD_FLAG_SUPPORT_SHARED, it still uses KVM_SET_MEMORY_ATTRIBUTES to update KVM memory attribute tracking.

Ok, so the user needs to search the memory region and guest_memfd to choose the right ioctl.

For slots with guest_memfd of flag GUEST_MEMFD_FLAG_SUPPORT_SHARED, the KVM_LPAGE_MIXED_FLAG bit in the lpage_info cannot reflect the truth and a false value there may also prevent KVM from installing a huge page.

Quoted 6 lines
Quoted 4 lines
Quoted 4 lines
include/linux/kvm_host.h +0 -0
  	return kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;
  }
#160 lore raw

Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator

In reply to Ackerley Tng
Quoted 109 lines · Ackerley Tng

If a custom allocator is requested at guest_memfd creation time, pages from the custom allocator will be used to back guest_memfd.

Change-Id I59df960b3273790f42fe5bea54a234f40962eb75
---
 mm/memory.c            |   1 +
 virt/kvm/guest_memfd.c | 142 +++++++++++++++++++++++++++++++++++++----
 2 files changed, 132 insertions(+), 11 deletions(-)
mm/memory.c +1 -0
index ba3ea0a82f7f..3af45e96913c 100644
@@ -7249,6 +7249,7 @@ void folio_zero_user(struct folio *folio, unsigned long addr_hint)
 	else
 		process_huge_page(addr_hint, nr_pages, clear_subpage, folio);
 }
+EXPORT_SYMBOL_GPL(folio_zero_user);
 
 static int copy_user_gigantic_page(struct folio *dst, struct folio *src,
 				   unsigned long addr_hint,
virt/kvm/guest_memfd.c +38 -7
index c65d93c5a443..24d270b9b725 100644
@@ -478,15 +478,13 @@ static inline void kvm_gmem_mark_prepared(struct folio *folio)
  * leaking host data and the up-to-date flag is set.
  */
 static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
-				  gfn_t gfn, struct folio *folio)
+				  gfn_t gfn, struct folio *folio,
+				  unsigned long addr_hint)
 {
-	unsigned long nr_pages, i;
 	pgoff_t index;
 	int r;
 
-	nr_pages = folio_nr_pages(folio);
-	for (i = 0; i < nr_pages; i++)
-		clear_highpage(folio_page(folio, i));
+	folio_zero_user(folio, addr_hint);
 
 	/*
 	 * Preparing huge folios should always be safe, since it should
@@ -554,7 +552,9 @@ static int kvm_gmem_filemap_add_folio(struct address_space *mapping,
  */
 static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
 {
+	size_t allocated_size;
 	struct folio *folio;
+	pgoff_t index_floor;
 	int ret;
 
 repeat:
@@ -581,8 +581,10 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
 			return ERR_PTR(ret);
 		}
 	}
+	allocated_size = folio_size(folio);
 
-	ret = kvm_gmem_filemap_add_folio(inode->i_mapping, folio, index);
+	index_floor = round_down(index, folio_nr_pages(folio));
+	ret = kvm_gmem_filemap_add_folio(inode->i_mapping, folio, index_floor);
 	if (ret) {
 		folio_put(folio);
 
@@ -598,7 +600,17 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
 		return ERR_PTR(ret);
 	}
 
-	__folio_set_locked(folio);
+	spin_lock(&inode->i_lock);
+	inode->i_blocks += allocated_size / 512;
+	spin_unlock(&inode->i_lock);
+
+	/*
+	 * folio is the one that is allocated, this gets the folio at the
+	 * requested index.
+	 */
+	folio = page_folio(folio_file_page(folio, index));
+	folio_lock(folio);
+
 	return folio;
 }
 
@@ -736,6 +748,92 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 	spin_unlock(&inode->i_lock);
 }
 
+/**
+ * kvm_gmem_zero_range() - Zeroes all sub-pages in range [@start, @end).
+ *
+ * @mapping: the filemap to remove this range from.
+ * @start: index in filemap for start of range (inclusive).
+ * @end: index in filemap for end of range (exclusive).
+ *
+ * The pages in range may be split. truncate_inode_pages_range() isn't the right
+ * function because it removes pages from the page cache; this function only
+ * zeroes the pages.
+ */
+static void kvm_gmem_zero_range(struct address_space *mapping,
+				pgoff_t start, pgoff_t end)
+{
+	struct folio_batch fbatch;
+
+	folio_batch_init(&fbatch);
+	while (filemap_get_folios(mapping, &start, end - 1, &fbatch)) {
+		unsigned int i;

virt/kvm/guest_memfd.c static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode, · line 779

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+
+		for (i = 0; i < folio_batch_count(&fbatch); ++i) {
+			struct folio *f;
+			size_t nr_bytes;
+
+			f = fbatch.folios[i];
+			nr_bytes = offset_in_folio(f, end << PAGE_SHIFT);
+			if (nr_bytes == 0)
+				nr_bytes = folio_size(f);
+

Is folio_lock() required here?

Quoted 61 lines
virt/kvm/guest_memfd.c +57 -0
+			folio_zero_segment(f, 0, nr_bytes);
+		}
+
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+}
+
+/**
+ * kvm_gmem_truncate_inode_range() - Truncate pages in range [@lstart, @lend).
+ *
+ * @inode: inode to truncate from.
+ * @lstart: offset in inode for start of range (inclusive).
+ * @lend: offset in inode for end of range (exclusive).
+ *
+ * Removes full (huge)pages from the filemap and zeroing incomplete
+ * (huge)pages. The pages in the range may be split.
+ */
+static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
+					  loff_t lend)
+{
+	pgoff_t full_hpage_start;
+	size_t nr_per_huge_page;
+	pgoff_t full_hpage_end;
+	size_t nr_pages;
+	pgoff_t start;
+	pgoff_t end;
+	void *priv;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	start = lstart >> PAGE_SHIFT;
+	end = min(lend, i_size_read(inode)) >> PAGE_SHIFT;
+
+	full_hpage_start = round_up(start, nr_per_huge_page);
+	full_hpage_end = round_down(end, nr_per_huge_page);
+
+	if (start < full_hpage_start) {
+		pgoff_t zero_end = min(full_hpage_start, end);
+
+		kvm_gmem_zero_range(inode->i_mapping, start, zero_end);
+	}
+
+	if (full_hpage_end > full_hpage_start) {
+		nr_pages = full_hpage_end - full_hpage_start;
+		kvm_gmem_truncate_inode_aligned_pages(inode, full_hpage_start,
+						      nr_pages);
+	}
+
+	if (end > full_hpage_end && end > full_hpage_start) {
+		pgoff_t zero_start = max(full_hpage_end, start);
+
+		kvm_gmem_zero_range(inode->i_mapping, zero_start, end);
+	}
+}
+
 static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 {
 	struct list_head *gmem_list = &inode->i_mapping->i_private_list;

virt/kvm/guest_memfd.c static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len) · line 851

Quoted 2 lines
virt/kvm/guest_memfd.c +0 -0
@@ -752,7 +850,12 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	list_for_each_entry(gmem, gmem_list, entry)
 		kvm_gmem_invalidate_begin(gmem, start, end);

The kvm_gmem_punch_hole() can be triggered by user's madvise() operation, e.g.,

mem = mmap(NULL, test_page_size, PROT_READ | PROT_WRITE, MAP_SHARED, guest_memfd, 0); madvise(mem, test_page_size, MADV_REMOVE);

As the mmap'ed VA is only for shared memory, it seems that the madvise() on a VA range should only affect the shared memory. However, kvm_gmem_punch_hole() indiscriminately truncates or zeros any memory.

Quoted 57 lines
virt/kvm/guest_memfd.c +26 -4
-	truncate_inode_pages_range(inode->i_mapping, offset, offset + len - 1);
+	if (kvm_gmem_has_custom_allocator(inode)) {
+		kvm_gmem_truncate_inode_range(inode, offset, offset + len);
+	} else {
+		/* Page size is PAGE_SIZE, so use optimized truncation function. */
+		truncate_inode_pages_range(inode->i_mapping, offset, offset + len - 1);
+	}
 
 	list_for_each_entry(gmem, gmem_list, entry)
 		kvm_gmem_invalidate_end(gmem, start, end);
@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
 
 	start = offset >> PAGE_SHIFT;
 	end = (offset + len) >> PAGE_SHIFT;
+	if (kvm_gmem_has_custom_allocator(inode)) {
+		size_t nr_pages;
+		void *p;
+
+		p = kvm_gmem_allocator_private(inode);
+		nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(p);
+
+		start = round_down(start, nr_pages);
+		end = round_down(end, nr_pages);
+	}
 
 	r = 0;
 	for (index = start; index < end; ) {
@@ -1570,7 +1683,7 @@ static struct folio *__kvm_gmem_get_pfn(struct file *file,
 
 	*pfn = folio_file_pfn(folio, index);
 	if (max_order)
-		*max_order = 0;
+		*max_order = folio_order(folio);
 
 	*is_prepared = folio_test_uptodate(folio);
 	return folio;
@@ -1597,8 +1710,15 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		goto out;
 	}
 
-	if (!is_prepared)
-		r = kvm_gmem_prepare_folio(kvm, slot, gfn, folio);
+	if (!is_prepared) {
+		/*
+		 * Use the same address as hugetlb for zeroing private pages
+		 * that won't be mapped to userspace anyway.
+		 */
+		unsigned long addr_hint = folio->index << PAGE_SHIFT;
+
+		r = kvm_gmem_prepare_folio(kvm, slot, gfn, folio, addr_hint);
+	}
 
 	folio_unlock(folio);
 
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#189 lore raw

Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)

In reply to Ackerley Tng
Quoted 17 lines · Ackerley Tng

Merge and truncate on fallocate(PUNCH_HOLE), but if the file is being closed, defer merging to folio_put() callback.

Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0d
---
 virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++-----
 1 file changed, 68 insertions(+), 8 deletions(-)
virt/kvm/guest_memfd.c +0 -0
index cb426c1dfef8..04b1513c2998 100644
@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
 	return ret;
 }
 

virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,
+					   size_t nr_pages)
+{
+	struct folio *f;
+	pgoff_t unused;
+	long num_freed;
+
+	unmap_mapping_pages(inode->i_mapping, index, nr_pages, false);
+
+	if (!kvm_gmem_has_safe_refcount(inode->i_mapping, index, nr_pages, &unused))

Why is kvm_gmem_has_safe_refcount() checked here, but not in kvm_gmem_zero_range() within kvm_gmem_truncate_inode_range() in patch 33?

virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873

Quoted 2 lines
virt/kvm/guest_memfd.c +2 -0
+		return -EAGAIN;
+

Rather than merging the folios, could we simply call kvm_gmem_truncate_indices() instead?

num_freed = kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); return num_freed;

Quoted 156 lines
virt/kvm/guest_memfd.c +56 -8
+	f = filemap_get_folio(inode->i_mapping, index);
+	if (IS_ERR(f))
+		return 0;
+
+	/* Leave just filemap's refcounts on the folio. */
+	folio_put(f);
+
+	WARN_ON(kvm_gmem_merge_folio_in_filemap(inode, f));
+
+	num_freed = folio_nr_pages(f);
+	folio_lock(f);
+	truncate_inode_folio(inode->i_mapping, f);
+	folio_unlock(f);
+
+	return num_freed;
+}
+
 #else
 
 static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
 	return 0;
 }
 
+static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,
+					   size_t nr_pages)
+{
+	return 0;
+}
+
 #endif
 
 #else
@@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,
  *
  * Removes folios beginning @index for @nr_pages from filemap in @inode, updates
  * inode metadata.
+ *
+ * Return: 0 on success and negative error otherwise.
  */
-static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
+static long kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 						  pgoff_t index,
 						  size_t nr_pages)
 {
@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 	long num_freed;
 	pgoff_t idx;
 	void *priv;
+	long ret;
 
 	priv = kvm_gmem_allocator_private(inode);
 	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
 
+	ret = 0;
 	num_freed = 0;
 	for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) {
-		num_freed += kvm_gmem_truncate_indices(
-			inode->i_mapping, idx, nr_per_huge_page);
+		if (mapping_exiting(inode->i_mapping) ||
+		    !kvm_gmem_has_some_shared(inode, idx, nr_per_huge_page)) {
+			num_freed += kvm_gmem_truncate_indices(
+				inode->i_mapping, idx, nr_per_huge_page);
+		} else {
+			ret = kvm_gmem_merge_truncate_indices(inode, idx,
+							      nr_per_huge_page);
+			if (ret < 0)
+				break;
+
+			num_freed += ret;
+			ret = 0;
+		}
 	}
 
 	spin_lock(&inode->i_lock);
 	inode->i_blocks -= (num_freed << PAGE_SHIFT) / 512;
 	spin_unlock(&inode->i_lock);
+
+	return ret;
 }
 
 /**
@@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,
  *
  * Removes full (huge)pages from the filemap and zeroing incomplete
  * (huge)pages. The pages in the range may be split.
+ *
+ * Return: 0 on success and negative error otherwise.
  */
-static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
+static long kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 					  loff_t lend)
 {
 	pgoff_t full_hpage_start;
@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 	pgoff_t start;
 	pgoff_t end;
 	void *priv;
+	long ret;
 
 	priv = kvm_gmem_allocator_private(inode);
 	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 		kvm_gmem_zero_range(inode->i_mapping, start, zero_end);
 	}
 
+	ret = 0;
 	if (full_hpage_end > full_hpage_start) {
 		nr_pages = full_hpage_end - full_hpage_start;
-		kvm_gmem_truncate_inode_aligned_pages(inode, full_hpage_start,
-						      nr_pages);
+		ret = kvm_gmem_truncate_inode_aligned_pages(
+			inode, full_hpage_start, nr_pages);
 	}
 
 	if (end > full_hpage_end && end > full_hpage_start) {
@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 
 		kvm_gmem_zero_range(inode->i_mapping, zero_start, end);
 	}
+
+	return ret;
 }
 
 static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	pgoff_t start = offset >> PAGE_SHIFT;
 	pgoff_t end = (offset + len) >> PAGE_SHIFT;
 	struct kvm_gmem *gmem;
+	long ret;
 
 	/*
 	 * Bindings must be stable across invalidation to ensure the start+end
@@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	list_for_each_entry(gmem, gmem_list, entry)
 		kvm_gmem_invalidate_begin_and_zap(gmem, start, end);
 
+	ret = 0;
 	if (kvm_gmem_has_custom_allocator(inode)) {
-		kvm_gmem_truncate_inode_range(inode, offset, offset + len);
+		ret = kvm_gmem_truncate_inode_range(inode, offset, offset + len);
 	} else {
 		/* Page size is PAGE_SIZE, so use optimized truncation function. */
 		truncate_inode_pages_range(inode->i_mapping, offset, offset + len - 1);
@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 
 	filemap_invalidate_unlock(inode->i_mapping);
 
-	return 0;
+	return ret;
 }
 
 static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#190 lore raw

Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)

Quoted 18 lines · Yan Zhao
Quoted 17 lines · Ackerley Tng

Merge and truncate on fallocate(PUNCH_HOLE), but if the file is being closed, defer merging to folio_put() callback.

Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0d
---
 virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++-----
 1 file changed, 68 insertions(+), 8 deletions(-)
virt/kvm/guest_memfd.c +0 -0
index cb426c1dfef8..04b1513c2998 100644
@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
 	return ret;
 }
 
Quoted 10 lines

virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,
+					   size_t nr_pages)
+{
+	struct folio *f;
+	pgoff_t unused;
+	long num_freed;
+
+	unmap_mapping_pages(inode->i_mapping, index, nr_pages, false);
+
+	if (!kvm_gmem_has_safe_refcount(inode->i_mapping, index, nr_pages, &unused))

Yan, thank you for your reviews!

Quoted 3 lines

Why is kvm_gmem_has_safe_refcount() checked here, but not in kvm_gmem_zero_range() within kvm_gmem_truncate_inode_range() in patch 33?

The contract for guest_memfd with HugeTLB pages is that if holes are punched in any ranges less than a full huge page, no pages are removed from the filemap. Those ranges are only zeroed.

In kvm_gmem_zero_range(), we never remove any folios, and so there is no need to merge. If there's no need to merge, then we don't need to check for a safe refcount, and can just proceed to zero.

kvm_gmem_merge_truncate_indices() is only used during hole punching and not when the file is closed. Hole punch vs file closure is checked using mapping_exiting(inode->i_mapping).

During a hole punch, we will only allow truncation if there are no unexpected refcounts on any subpages, hence this kvm_gmem_has_safe_refcount() check.

Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873

Quoted 2 lines
virt/kvm/guest_memfd.c +2 -0
+		return -EAGAIN;
+

Rather than merging the folios, could we simply call kvm_gmem_truncate_indices() instead?

num_freed = kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); return num_freed;

We could do this too, but then that would be deferring the huge page merging to the folio_put() callback and eventually the kernel worker thread.

My goal here is to try to not to defer merging and freeing as much as possible so that most of the page/memory operations are synchronous, because synchronous operations are more predictable.

As an example of improving predictability, in one of the selftests, I do a hole punch and then try to allocate again. Because the merging and freeing of the HugeTLB page sometimes takes too long, the allocation sometimes fails: the guest_memfd's subpool hadn't yet received the freed page back. With a synchronous truncation, the truncation may take longer, but the selftest predictably passes.

Quoted 156 lines
Quoted 156 lines
virt/kvm/guest_memfd.c +56 -8
+	f = filemap_get_folio(inode->i_mapping, index);
+	if (IS_ERR(f))
+		return 0;
+
+	/* Leave just filemap's refcounts on the folio. */
+	folio_put(f);
+
+	WARN_ON(kvm_gmem_merge_folio_in_filemap(inode, f));
+
+	num_freed = folio_nr_pages(f);
+	folio_lock(f);
+	truncate_inode_folio(inode->i_mapping, f);
+	folio_unlock(f);
+
+	return num_freed;
+}
+
 #else
 
 static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
 	return 0;
 }
 
+static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,
+					   size_t nr_pages)
+{
+	return 0;
+}
+
 #endif
 
 #else
@@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,
  *
  * Removes folios beginning @index for @nr_pages from filemap in @inode, updates
  * inode metadata.
+ *
+ * Return: 0 on success and negative error otherwise.
  */
-static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
+static long kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 						  pgoff_t index,
 						  size_t nr_pages)
 {
@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 	long num_freed;
 	pgoff_t idx;
 	void *priv;
+	long ret;
 
 	priv = kvm_gmem_allocator_private(inode);
 	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
 
+	ret = 0;
 	num_freed = 0;
 	for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) {
-		num_freed += kvm_gmem_truncate_indices(
-			inode->i_mapping, idx, nr_per_huge_page);
+		if (mapping_exiting(inode->i_mapping) ||
+		    !kvm_gmem_has_some_shared(inode, idx, nr_per_huge_page)) {
+			num_freed += kvm_gmem_truncate_indices(
+				inode->i_mapping, idx, nr_per_huge_page);
+		} else {
+			ret = kvm_gmem_merge_truncate_indices(inode, idx,
+							      nr_per_huge_page);
+			if (ret < 0)
+				break;
+
+			num_freed += ret;
+			ret = 0;
+		}
 	}
 
 	spin_lock(&inode->i_lock);
 	inode->i_blocks -= (num_freed << PAGE_SHIFT) / 512;
 	spin_unlock(&inode->i_lock);
+
+	return ret;
 }
 
 /**
@@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,
  *
  * Removes full (huge)pages from the filemap and zeroing incomplete
  * (huge)pages. The pages in the range may be split.
+ *
+ * Return: 0 on success and negative error otherwise.
  */
-static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
+static long kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 					  loff_t lend)
 {
 	pgoff_t full_hpage_start;
@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 	pgoff_t start;
 	pgoff_t end;
 	void *priv;
+	long ret;
 
 	priv = kvm_gmem_allocator_private(inode);
 	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 		kvm_gmem_zero_range(inode->i_mapping, start, zero_end);
 	}
 
+	ret = 0;
 	if (full_hpage_end > full_hpage_start) {
 		nr_pages = full_hpage_end - full_hpage_start;
-		kvm_gmem_truncate_inode_aligned_pages(inode, full_hpage_start,
-						      nr_pages);
+		ret = kvm_gmem_truncate_inode_aligned_pages(
+			inode, full_hpage_start, nr_pages);
 	}
 
 	if (end > full_hpage_end && end > full_hpage_start) {
@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 
 		kvm_gmem_zero_range(inode->i_mapping, zero_start, end);
 	}
+
+	return ret;
 }
 
 static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	pgoff_t start = offset >> PAGE_SHIFT;
 	pgoff_t end = (offset + len) >> PAGE_SHIFT;
 	struct kvm_gmem *gmem;
+	long ret;
 
 	/*
 	 * Bindings must be stable across invalidation to ensure the start+end
@@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	list_for_each_entry(gmem, gmem_list, entry)
 		kvm_gmem_invalidate_begin_and_zap(gmem, start, end);
 
+	ret = 0;
 	if (kvm_gmem_has_custom_allocator(inode)) {
-		kvm_gmem_truncate_inode_range(inode, offset, offset + len);
+		ret = kvm_gmem_truncate_inode_range(inode, offset, offset + len);
 	} else {
 		/* Page size is PAGE_SIZE, so use optimized truncation function. */
 		truncate_inode_pages_range(inode->i_mapping, offset, offset + len - 1);
@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 
 	filemap_invalidate_unlock(inode->i_mapping);
 
-	return 0;
+	return ret;
 }
 
 static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#191 lore raw

Re: [RFC PATCH v2 39/51] KVM: guest_memfd: Merge and truncate on fallocate(PUNCH_HOLE)

Quoted 37 lines · Ackerley Tng
Quoted 18 lines · Yan Zhao
Quoted 17 lines · Ackerley Tng

Merge and truncate on fallocate(PUNCH_HOLE), but if the file is being closed, defer merging to folio_put() callback.

Change-Id Iae26987756e70c83f3b121edbc0ed0bc105eec0d
---
 virt/kvm/guest_memfd.c | 76 +++++++++++++++++++++++++++++++++++++-----
 1 file changed, 68 insertions(+), 8 deletions(-)
virt/kvm/guest_memfd.c +0 -0
index cb426c1dfef8..04b1513c2998 100644
@@ -859,6 +859,35 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
 	return ret;
 }
 
Quoted 10 lines

virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 871

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,
+					   size_t nr_pages)
+{
+	struct folio *f;
+	pgoff_t unused;
+	long num_freed;
+
+	unmap_mapping_pages(inode->i_mapping, index, nr_pages, false);
+
+	if (!kvm_gmem_has_safe_refcount(inode->i_mapping, index, nr_pages, &unused))

Yan, thank you for your reviews!

Quoted 3 lines

Why is kvm_gmem_has_safe_refcount() checked here, but not in kvm_gmem_zero_range() within kvm_gmem_truncate_inode_range() in patch 33?

Quoted 7 lines

The contract for guest_memfd with HugeTLB pages is that if holes are punched in any ranges less than a full huge page, no pages are removed from the filemap. Those ranges are only zeroed.

In kvm_gmem_zero_range(), we never remove any folios, and so there is no need to merge. If there's no need to merge, then we don't need to check for a safe refcount, and can just proceed to zero.

However, if there are still extra ref count to a shared page, its content will be zeroed out.

Quoted 8 lines

kvm_gmem_merge_truncate_indices() is only used during hole punching and not when the file is closed. Hole punch vs file closure is checked using mapping_exiting(inode->i_mapping).

During a hole punch, we will only allow truncation if there are no unexpected refcounts on any subpages, hence this kvm_gmem_has_safe_refcount() check.

Hmm, I couldn't find a similar refcount check in hugetlbfs_punch_hole(). Did I overlook it?

So, why does guest_memfd require this check when punching a hole?

Quoted 6 lines
Quoted 6 lines

virt/kvm/guest_memfd.c static int kvm_gmem_restructure_folios_in_range(struct inode *inode, · line 873

Quoted 2 lines
virt/kvm/guest_memfd.c +2 -0
+		return -EAGAIN;
+

Rather than merging the folios, could we simply call kvm_gmem_truncate_indices() instead?

Quoted 7 lines
Quoted 3 lines

num_freed = kvm_gmem_truncate_indices(inode->i_mapping, index, nr_pages); return num_freed;

We could do this too, but then that would be deferring the huge page merging to the folio_put() callback and eventually the kernel worker thread.

With deferring the huge page merging to folio_put(), a benefit is that __kvm_gmem_filemap_add_folio() can be saved for the merged folio. This function is possible to fail and is unnecessary for punch hole as the folio will be removed immediately from the filemap in truncate_inode_folio().

Quoted 10 lines

My goal here is to try to not to defer merging and freeing as much as possible so that most of the page/memory operations are synchronous, because synchronous operations are more predictable.

As an example of improving predictability, in one of the selftests, I do a hole punch and then try to allocate again. Because the merging and freeing of the HugeTLB page sometimes takes too long, the allocation sometimes fails: the guest_memfd's subpool hadn't yet received the freed page back. With a synchronous truncation, the truncation may take longer, but the selftest predictably passes.

Maybe check if guestmem_hugetlb_handle_folio_put() is invoked in the interrupt context, and, if not, invoke the guestmem_hugetlb_cleanup_folio() synchronously?

Quoted 157 lines
Quoted 156 lines
Quoted 156 lines
virt/kvm/guest_memfd.c +56 -8
+	f = filemap_get_folio(inode->i_mapping, index);
+	if (IS_ERR(f))
+		return 0;
+
+	/* Leave just filemap's refcounts on the folio. */
+	folio_put(f);
+
+	WARN_ON(kvm_gmem_merge_folio_in_filemap(inode, f));
+
+	num_freed = folio_nr_pages(f);
+	folio_lock(f);
+	truncate_inode_folio(inode->i_mapping, f);
+	folio_unlock(f);
+
+	return num_freed;
+}
+
 #else
 
 static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
@@ -874,6 +903,12 @@ static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
 	return 0;
 }
 
+static long kvm_gmem_merge_truncate_indices(struct inode *inode, pgoff_t index,
+					   size_t nr_pages)
+{
+	return 0;
+}
+
 #endif
 
 #else
@@ -1182,8 +1217,10 @@ static long kvm_gmem_truncate_indices(struct address_space *mapping,
  *
  * Removes folios beginning @index for @nr_pages from filemap in @inode, updates
  * inode metadata.
+ *
+ * Return: 0 on success and negative error otherwise.
  */
-static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
+static long kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 						  pgoff_t index,
 						  size_t nr_pages)
 {
@@ -1191,19 +1228,34 @@ static void kvm_gmem_truncate_inode_aligned_pages(struct inode *inode,
 	long num_freed;
 	pgoff_t idx;
 	void *priv;
+	long ret;
 
 	priv = kvm_gmem_allocator_private(inode);
 	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
 
+	ret = 0;
 	num_freed = 0;
 	for (idx = index; idx < index + nr_pages; idx += nr_per_huge_page) {
-		num_freed += kvm_gmem_truncate_indices(
-			inode->i_mapping, idx, nr_per_huge_page);
+		if (mapping_exiting(inode->i_mapping) ||
+		    !kvm_gmem_has_some_shared(inode, idx, nr_per_huge_page)) {
+			num_freed += kvm_gmem_truncate_indices(
+				inode->i_mapping, idx, nr_per_huge_page);
+		} else {
+			ret = kvm_gmem_merge_truncate_indices(inode, idx,
+							      nr_per_huge_page);
+			if (ret < 0)
+				break;
+
+			num_freed += ret;
+			ret = 0;
+		}
 	}
 
 	spin_lock(&inode->i_lock);
 	inode->i_blocks -= (num_freed << PAGE_SHIFT) / 512;
 	spin_unlock(&inode->i_lock);
+
+	return ret;
 }
 
 /**
@@ -1252,8 +1304,10 @@ static void kvm_gmem_zero_range(struct address_space *mapping,
  *
  * Removes full (huge)pages from the filemap and zeroing incomplete
  * (huge)pages. The pages in the range may be split.
+ *
+ * Return: 0 on success and negative error otherwise.
  */
-static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
+static long kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 					  loff_t lend)
 {
 	pgoff_t full_hpage_start;
@@ -1263,6 +1317,7 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 	pgoff_t start;
 	pgoff_t end;
 	void *priv;
+	long ret;
 
 	priv = kvm_gmem_allocator_private(inode);
 	nr_per_huge_page = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
@@ -1279,10 +1334,11 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 		kvm_gmem_zero_range(inode->i_mapping, start, zero_end);
 	}
 
+	ret = 0;
 	if (full_hpage_end > full_hpage_start) {
 		nr_pages = full_hpage_end - full_hpage_start;
-		kvm_gmem_truncate_inode_aligned_pages(inode, full_hpage_start,
-						      nr_pages);
+		ret = kvm_gmem_truncate_inode_aligned_pages(
+			inode, full_hpage_start, nr_pages);
 	}
 
 	if (end > full_hpage_end && end > full_hpage_start) {
@@ -1290,6 +1346,8 @@ static void kvm_gmem_truncate_inode_range(struct inode *inode, loff_t lstart,
 
 		kvm_gmem_zero_range(inode->i_mapping, zero_start, end);
 	}
+
+	return ret;
 }
 
 static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
@@ -1298,6 +1356,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	pgoff_t start = offset >> PAGE_SHIFT;
 	pgoff_t end = (offset + len) >> PAGE_SHIFT;
 	struct kvm_gmem *gmem;
+	long ret;
 
 	/*
 	 * Bindings must be stable across invalidation to ensure the start+end
@@ -1308,8 +1367,9 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 	list_for_each_entry(gmem, gmem_list, entry)
 		kvm_gmem_invalidate_begin_and_zap(gmem, start, end);
 
+	ret = 0;
 	if (kvm_gmem_has_custom_allocator(inode)) {
-		kvm_gmem_truncate_inode_range(inode, offset, offset + len);
+		ret = kvm_gmem_truncate_inode_range(inode, offset, offset + len);
 	} else {
 		/* Page size is PAGE_SIZE, so use optimized truncation function. */
 		truncate_inode_pages_range(inode->i_mapping, offset, offset + len - 1);
@@ -1320,7 +1380,7 @@ static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 
 	filemap_invalidate_unlock(inode->i_mapping);
 
-	return 0;
+	return ret;
 }
 
 static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#12 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Ackerley Tng
Quoted 37 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 8 lines
Documentation/virt/kvm/api.rst +5 -0
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Quoted 61 lines
Documentation/virt/kvm/api.rst +0 -0
 See KVM_SET_USER_MEMORY_REGION2 for additional details.
 
 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
index 4cc824a3a7c9..d7df312479aa 100644
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {
 #define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
 
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
+
 #define GUEST_MEMFD_FLAG_SUPPORT_SHARED	(1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE	(1UL << 1)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
virt/kvm/guest_memfd.c +22 -0
index 239d0f13dcc1..590932499eba 100644
@@ -4,6 +4,7 @@
 #include <linux/falloc.h>
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
+#include <linux/maple_tree.h>
 #include <linux/pseudo_fs.h>
 #include <linux/pagemap.h>
 
@@ -17,6 +18,24 @@ struct kvm_gmem {
 	struct list_head entry;
 };
 
+struct kvm_gmem_inode_private {
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	struct maple_tree shareability;
+#endif
+};
+
+enum shareability {
+	SHAREABILITY_GUEST = 1,	/* Only the guest can map (fault) folios in this range. */
+	SHAREABILITY_ALL = 2,	/* Both guest and host can fault folios in this range. */
+};
+
+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index);
+
+static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)
+{
+	return inode->i_mapping->i_private_data;
+}
+
 /**
  * folio_file_pfn - like folio_file_page, but return a pfn.
  * @folio: The folio which contains this index.
@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
 	return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
 }
 
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+				      loff_t size, u64 flags)
+{
+	enum shareability m;
+	pgoff_t last;
+
+	last = (size >> PAGE_SHIFT) - 1;
+	m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+						    SHAREABILITY_ALL;
+	return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+				 GFP_KERNEL);

One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via KVM_SET_MEMORY_ATTRIBUTES (which is the current QEMU default behavior).

I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.

Maybe it would make sense for KVM memory attributes too?

Quoted 135 lines
virt/kvm/guest_memfd.c +87 -1
+}
+
+static enum shareability kvm_gmem_shareability_get(struct inode *inode,
+						 pgoff_t index)
+{
+	struct maple_tree *mt;
+	void *entry;
+
+	mt = &kvm_gmem_private(inode)->shareability;
+	entry = mtree_load(mt, index);
+	WARN(!entry,
+	     "Shareability should always be defined for all indices in inode.");
+
+	return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+		return ERR_PTR(-EACCES);
+
+	return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+	return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	WARN_ONCE("Unexpected call to get shared folio.")
+	return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
 				    pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
 	filemap_invalidate_lock_shared(inode->i_mapping);
 
-	folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+	folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
 	if (IS_ERR(folio)) {
 		int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
 	.fallocate	= kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+	kfree(private);
+
+	free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	/*
+	 * mtree_destroy() can't be used within rcu callback, hence can't be
+	 * done in ->free_inode().
+	 */
+	if (private)
+		mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
 	.statfs		= simple_statfs,
+	.destroy_inode	= kvm_gmem_destroy_inode,
+	.free_inode	= kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 						      loff_t size, u64 flags)
 {
+	struct kvm_gmem_inode_private *private;
 	struct inode *inode;
+	int err;
 
 	inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
 	if (IS_ERR(inode))
 		return inode;
 
+	err = -ENOMEM;
+	private = kzalloc(sizeof(*private), GFP_KERNEL);
+	if (!private)
+		goto out;
+
+	mt_init(&private->shareability);
+	inode->i_mapping->i_private_data = private;
+
+	err = kvm_gmem_shareability_setup(private, size, flags);
+	if (err)
+		goto out;
+
 	inode->i_private = (void *)(unsigned long)flags;
 	inode->i_op = &kvm_gmem_iops;
 	inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
 	return inode;
+
+out:
+	iput(inode);
+
+	return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
 	if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
 		valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+	if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+		valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
 	if (flags & ~valid_flags)
 		return -EINVAL;
 

virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964

Quoted 5 lines
virt/kvm/guest_memfd.c +2 -0
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 	if (!file)
 		return -EFAULT;
 
+	filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+

I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new SHAREABILITY_GUEST_PREPARED state) the SHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPARED transition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.

I was originally planning on introducing a new rw_semaphore with similar semantics to the rw_lock that Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle setting SHAREABILITY_GUEST_PREPARED within fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.

They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.

I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:

KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes

but figured I'd mention it here in case there are other things to consider on the locking front.

Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.

-Mike

[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/

Quoted 16 lines
virt/kvm/guest_memfd.c +1 -1
 	folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
 	if (IS_ERR(folio)) {
 		r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		*page = folio_file_page(folio, index);
 	else
 		folio_put(folio);
-
 out:
+	filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
 	fput(file);
 	return r;
 }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#4 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Yan Zhao
Quoted 146 lines · Yan Zhao
Quoted 118 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +5 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+
 See KVM_SET_USER_MEMORY_REGION2 for additional details.
 
 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
index 4cc824a3a7c9..d7df312479aa 100644
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {
 #define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
 
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
+
 #define GUEST_MEMFD_FLAG_SUPPORT_SHARED	(1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE	(1UL << 1)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
virt/kvm/guest_memfd.c +34 -0
index 239d0f13dcc1..590932499eba 100644
@@ -4,6 +4,7 @@
 #include <linux/falloc.h>
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
+#include <linux/maple_tree.h>
 #include <linux/pseudo_fs.h>
 #include <linux/pagemap.h>
 
@@ -17,6 +18,24 @@ struct kvm_gmem {
 	struct list_head entry;
 };
 
+struct kvm_gmem_inode_private {
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	struct maple_tree shareability;
+#endif
+};
+
+enum shareability {
+	SHAREABILITY_GUEST = 1,	/* Only the guest can map (fault) folios in this range. */
+	SHAREABILITY_ALL = 2,	/* Both guest and host can fault folios in this range. */
+};
+
+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index);
+
+static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)
+{
+	return inode->i_mapping->i_private_data;
+}
+
 /**
  * folio_file_pfn - like folio_file_page, but return a pfn.
  * @folio: The folio which contains this index.
@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
 	return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
 }
 
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,
+				      loff_t size, u64 flags)
+{
+	enum shareability m;
+	pgoff_t last;
+
+	last = (size >> PAGE_SHIFT) - 1;
+	m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+						    SHAREABILITY_ALL;
+	return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+				 GFP_KERNEL);
+}
+

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 75

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+static enum shareability kvm_gmem_shareability_get(struct inode *inode,
+						 pgoff_t index)
+{
+	struct maple_tree *mt;
+	void *entry;
+
+	mt = &kvm_gmem_private(inode)->shareability;
+	entry = mtree_load(mt, index);
+	WARN(!entry,
+	     "Shareability should always be defined for all indices in inode.");

I noticed that in [1], the kvm_gmem_mmap() does not check the range. So, the WARN() here can be hit when userspace mmap() an area larger than the inode size and accesses the out of band HVA.

Maybe limit the mmap() range?

(quoted diff) +3 -0
@@ -1609,6 +1620,10 @@ static int kvm_gmem_mmap(struct file *file, struct vm_area_struct *vma)
        if (!kvm_gmem_supports_shared(file_inode(file)))
                return -ENODEV;
 
+       if (vma->vm_end - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT) > i_size_read(file_inode(file)))
+               return -EINVAL;
+
        if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) !=
            (VM_SHARED | VM_MAYSHARE)) {
                return -EINVAL;
Quoted 2 lines

[1] https://lore.kernel.org/all/[email protected]/

This is a good idea. Thanks! I also think it is a good idea to include this with the guest_memfd mmap base series that Fuad is working on [1], maybe in v11.

[1] https://lore.kernel.org/all/[email protected]/

Quoted 84 lines
Quoted 84 lines
virt/kvm/guest_memfd.c +54 -1
+	return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+		return ERR_PTR(-EACCES);
+
+	return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+	return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	WARN_ONCE("Unexpected call to get shared folio.")
+	return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
 				    pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
 	filemap_invalidate_lock_shared(inode->i_mapping);
 
-	folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+	folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
 	if (IS_ERR(folio)) {
 		int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
 	.fallocate	= kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+	kfree(private);
+
+	free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	/*
+	 * mtree_destroy() can't be used within rcu callback, hence can't be
+	 * done in ->free_inode().
+	 */
+	if (private)
+		mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
 	.statfs		= simple_statfs,
+	.destroy_inode	= kvm_gmem_destroy_inode,
+	.free_inode	= kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 						      loff_t size, u64 flags)
 {
+	struct kvm_gmem_inode_private *private;
 	struct inode *inode;
+	int err;
 
 	inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
 	if (IS_ERR(inode))
 		return inode;
 
Quoted 8 lines

virt/kvm/guest_memfd.c static const struct inode_operations kvm_gmem_iops = { · line 661

Quoted 6 lines
virt/kvm/guest_memfd.c +6 -0
+	err = -ENOMEM;
+	private = kzalloc(sizeof(*private), GFP_KERNEL);
+	if (!private)
+		goto out;
+
+	mt_init(&private->shareability);

Wrap the mt_init() inside "#ifdef CONFIG_KVM_GMEM_SHARED_MEM" ?

Will fix this in the next revision. Will also update this to only initialize shareability if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED).

Quoted 54 lines
Quoted 54 lines
virt/kvm/guest_memfd.c +17 -1
+	inode->i_mapping->i_private_data = private;
+
+	err = kvm_gmem_shareability_setup(private, size, flags);
+	if (err)
+		goto out;
+
 	inode->i_private = (void *)(unsigned long)flags;
 	inode->i_op = &kvm_gmem_iops;
 	inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
 	return inode;
+
+out:
+	iput(inode);
+
+	return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
 	if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
 		valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+	if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+		valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
 	if (flags & ~valid_flags)
 		return -EINVAL;
 
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 	if (!file)
 		return -EFAULT;
 
+	filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+
 	folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
 	if (IS_ERR(folio)) {
 		r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		*page = folio_file_page(folio, index);
 	else
 		folio_put(folio);
-
 out:
+	filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
 	fput(file);
 	return r;
 }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#10 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Binbin Wu
Quoted 41 lines · Binbin Wu
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
  Documentation/virt/kvm/api.rst |   5 ++
  include/uapi/linux/kvm.h       |   2 +
  virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
  3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
  The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
  This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 6 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6412

Quoted 2 lines
Documentation/virt/kvm/api.rst +2 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.

It seems that the sentence is stale?
Didn't find the definition of KVM_CAP_GMEM_CONVERSIONS.

Thanks. This should read

If the capability KVM_CAP_GMEM_SHARED_MEM is supported, and GUEST_MEMFD_FLAG_SUPPORT_SHARED is specified, then the 'flags' field supports GUEST_MEMFD_FLAG_INIT_PRIVATE.

Quoted 19 lines
Quoted 4 lines

Setting GUEST_MEMFD_FLAG_INIT_PRIVATE

Documentation/virt/kvm/api.rst +3 -0
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

[...]

Quoted 14 lines

static int kvm_gmem_init_fs_context(struct fs_context *fc)

Documentation/virt/kvm/api.rst +2 -0
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
  static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
  						      loff_t size, u64 flags)
  {
+	struct kvm_gmem_inode_private *private;
  	struct inode *inode;
+	int err;
 
  	inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
  	if (IS_ERR(inode))
  		return inode;
 
Quoted 10 lines

Documentation/virt/kvm/api.rst static const struct inode_operations kvm_gmem_iops = { · line 661

Quoted 6 lines
Documentation/virt/kvm/api.rst +6 -0
+	err = -ENOMEM;
+	private = kzalloc(sizeof(*private), GFP_KERNEL);
+	if (!private)
+		goto out;
+
+	mt_init(&private->shareability);

shareability is defined only when CONFIG_KVM_GMEM_SHARED_MEM enabled, should be done within CONFIG_KVM_GMEM_SHARED_MEM .

Yes, thank you! Will also update this to only initialize shareability if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED).

Quoted 22 lines
Quoted 21 lines
Documentation/virt/kvm/api.rst +11 -0
+	inode->i_mapping->i_private_data = private;
+
+	err = kvm_gmem_shareability_setup(private, size, flags);
+	if (err)
+		goto out;
+
  	inode->i_private = (void *)(unsigned long)flags;
  	inode->i_op = &kvm_gmem_iops;
  	inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
  	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
  	return inode;
+
+out:
+	iput(inode);
+
+	return ERR_PTR(err);
  }
 
 

[...]

#11 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 50 lines · Ackerley Tng
Quoted 41 lines · Binbin Wu
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
  Documentation/virt/kvm/api.rst |   5 ++
  include/uapi/linux/kvm.h       |   2 +
  virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
  3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
  The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
  This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 6 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6412

Quoted 2 lines
Documentation/virt/kvm/api.rst +2 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.

It seems that the sentence is stale?
Didn't find the definition of KVM_CAP_GMEM_CONVERSIONS.

Quoted 6 lines

Thanks. This should read

If the capability KVM_CAP_GMEM_SHARED_MEM is supported, and GUEST_MEMFD_FLAG_SUPPORT_SHARED is specified, then the 'flags' field supports GUEST_MEMFD_FLAG_INIT_PRIVATE.

My bad, saw your other email. Fixing the above:

If the capability KVM_CAP_GMEM_CONVERSION is supported, and GUEST_MEMFD_FLAG_SUPPORT_SHARED is specified, then the 'flags' field supports GUEST_MEMFD_FLAG_INIT_PRIVATE.

Quoted 55 lines
Quoted 19 lines
Quoted 4 lines

Setting GUEST_MEMFD_FLAG_INIT_PRIVATE

Documentation/virt/kvm/api.rst +3 -0
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

[...]

Quoted 14 lines

static int kvm_gmem_init_fs_context(struct fs_context *fc)

Documentation/virt/kvm/api.rst +2 -0
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
  static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
  						      loff_t size, u64 flags)
  {
+	struct kvm_gmem_inode_private *private;
  	struct inode *inode;
+	int err;
 
  	inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
  	if (IS_ERR(inode))
  		return inode;
 
Quoted 10 lines

Documentation/virt/kvm/api.rst static const struct inode_operations kvm_gmem_iops = { · line 661

Quoted 6 lines
Documentation/virt/kvm/api.rst +6 -0
+	err = -ENOMEM;
+	private = kzalloc(sizeof(*private), GFP_KERNEL);
+	if (!private)
+		goto out;
+
+	mt_init(&private->shareability);

shareability is defined only when CONFIG_KVM_GMEM_SHARED_MEM enabled, should be done within CONFIG_KVM_GMEM_SHARED_MEM .

Yes, thank you! Will also update this to only initialize shareability if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED).

Quoted 22 lines
Quoted 21 lines
Documentation/virt/kvm/api.rst +11 -0
+	inode->i_mapping->i_private_data = private;
+
+	err = kvm_gmem_shareability_setup(private, size, flags);
+	if (err)
+		goto out;
+
  	inode->i_private = (void *)(unsigned long)flags;
  	inode->i_op = &kvm_gmem_iops;
  	inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
  	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
  	return inode;
+
+out:
+	iput(inode);
+
+	return ERR_PTR(err);
  }
 
 

[...]

#5 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Yan Zhao

Hi,

.. snip..

Quoted 17 lines

I noticed that in [1], the kvm_gmem_mmap() does not check the range. So, the WARN() here can be hit when userspace mmap() an area larger than the inode size and accesses the out of band HVA.

Maybe limit the mmap() range?

(quoted diff) +3 -0
@@ -1609,6 +1620,10 @@ static int kvm_gmem_mmap(struct file *file, struct vm_area_struct *vma)
        if (!kvm_gmem_supports_shared(file_inode(file)))
                return -ENODEV;
 
+       if (vma->vm_end - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT) > i_size_read(file_inode(file)))
+               return -EINVAL;
+
        if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) !=
            (VM_SHARED | VM_MAYSHARE)) {
                return -EINVAL;
Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

I don't think we want to do that for a couple of reasons. We catch such invalid accesses on faulting, and, by analogy, afaikt, neither secretmem nor memfd perform a similar check on mmap (nor do memory-mapped files in general).

There are also valid reasons why a user would want to deliberately mmap more memory than the backing store, knowing that it's only going to fault what it's going to use, e.g., alignment.

Cheers,
/fuad

Quoted 146 lines
Quoted 80 lines
virt/kvm/guest_memfd.c +54 -1
+     return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+     if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+             return ERR_PTR(-EACCES);
+
+     return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+     return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+     WARN_ONCE("Unexpected call to get shared folio.")
+     return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
                                  pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
      filemap_invalidate_lock_shared(inode->i_mapping);
 
-     folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+     folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
      if (IS_ERR(folio)) {
              int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
      .fallocate      = kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+     struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+     kfree(private);
+
+     free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+     struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+     /*
+      * mtree_destroy() can't be used within rcu callback, hence can't be
+      * done in ->free_inode().
+      */
+     if (private)
+             mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
      .statfs         = simple_statfs,
+     .destroy_inode  = kvm_gmem_destroy_inode,
+     .free_inode     = kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
                                                    loff_t size, u64 flags)
 {
+     struct kvm_gmem_inode_private *private;
      struct inode *inode;
+     int err;
 

virt/kvm/guest_memfd.c static const struct inode_operations kvm_gmem_iops = { · line 661

Quoted 10 lines
virt/kvm/guest_memfd.c +6 -0
      inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
      if (IS_ERR(inode))
              return inode;
 
+     err = -ENOMEM;
+     private = kzalloc(sizeof(*private), GFP_KERNEL);
+     if (!private)
+             goto out;
+
+     mt_init(&private->shareability);

Wrap the mt_init() inside "#ifdef CONFIG_KVM_GMEM_SHARED_MEM" ?

Quoted 54 lines
virt/kvm/guest_memfd.c +17 -2
+     inode->i_mapping->i_private_data = private;
+
+     err = kvm_gmem_shareability_setup(private, size, flags);
+     if (err)
+             goto out;
+
      inode->i_private = (void *)(unsigned long)flags;
      inode->i_op = &kvm_gmem_iops;
      inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
      WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
      return inode;
+
+out:
+     iput(inode);
+
+     return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
      if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
              valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+     if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+             valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
      if (flags & ~valid_flags)
              return -EINVAL;
 
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
      if (!file)
              return -EFAULT;
 
+     filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+
      folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
      if (IS_ERR(folio)) {
              r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
              *page = folio_file_page(folio, index);
      else
              folio_put(folio);
-
 out:
+     filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
      fput(file);
      return r;
 }
--

2.49.0.1045.g170613ef41-goog

#6 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 28 lines · Fuad Tabba

Hi,

.. snip..

Quoted 17 lines

I noticed that in [1], the kvm_gmem_mmap() does not check the range. So, the WARN() here can be hit when userspace mmap() an area larger than the inode size and accesses the out of band HVA.

Maybe limit the mmap() range?

(quoted diff) +3 -0
@@ -1609,6 +1620,10 @@ static int kvm_gmem_mmap(struct file *file, struct vm_area_struct *vma)
        if (!kvm_gmem_supports_shared(file_inode(file)))
                return -ENODEV;
 
+       if (vma->vm_end - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT) > i_size_read(file_inode(file)))
+               return -EINVAL;
+
        if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) !=
            (VM_SHARED | VM_MAYSHARE)) {
                return -EINVAL;
Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

I don't think we want to do that for a couple of reasons. We catch such invalid accesses on faulting, and, by analogy, afaikt, neither secretmem nor memfd perform a similar check on mmap (nor do memory-mapped files in general).

Quoted 4 lines

There are also valid reasons why a user would want to deliberately mmap more memory than the backing store, knowing that it's only going to fault what it's going to use, e.g., alignment.

This is a good point.

I think there's no check against the inode size on faulting now though? v10's [1] kvm_gmem_fault_shared() calls kvm_gmem_get_folio() straightaway.

We should add a check like [2] to kvm_gmem_fault_shared().

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/torvalds/linux/blob/8477ab143069c6b05d6da4a8184ded8b969240f5/mm/filemap.c#L3373

Quoted 150 lines

Cheers,
/fuad

Quoted 146 lines
Quoted 80 lines
virt/kvm/guest_memfd.c +54 -1
+     return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+     if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+             return ERR_PTR(-EACCES);
+
+     return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+     return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+     WARN_ONCE("Unexpected call to get shared folio.")
+     return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
                                  pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
      filemap_invalidate_lock_shared(inode->i_mapping);
 
-     folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+     folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
      if (IS_ERR(folio)) {
              int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
      .fallocate      = kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+     struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+     kfree(private);
+
+     free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+     struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+     /*
+      * mtree_destroy() can't be used within rcu callback, hence can't be
+      * done in ->free_inode().
+      */
+     if (private)
+             mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
      .statfs         = simple_statfs,
+     .destroy_inode  = kvm_gmem_destroy_inode,
+     .free_inode     = kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
                                                    loff_t size, u64 flags)
 {
+     struct kvm_gmem_inode_private *private;
      struct inode *inode;
+     int err;
 

virt/kvm/guest_memfd.c static const struct inode_operations kvm_gmem_iops = { · line 661

Quoted 10 lines
virt/kvm/guest_memfd.c +6 -0
      inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
      if (IS_ERR(inode))
              return inode;
 
+     err = -ENOMEM;
+     private = kzalloc(sizeof(*private), GFP_KERNEL);
+     if (!private)
+             goto out;
+
+     mt_init(&private->shareability);

Wrap the mt_init() inside "#ifdef CONFIG_KVM_GMEM_SHARED_MEM" ?

Quoted 54 lines
virt/kvm/guest_memfd.c +17 -2
+     inode->i_mapping->i_private_data = private;
+
+     err = kvm_gmem_shareability_setup(private, size, flags);
+     if (err)
+             goto out;
+
      inode->i_private = (void *)(unsigned long)flags;
      inode->i_op = &kvm_gmem_iops;
      inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
      WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
      return inode;
+
+out:
+     iput(inode);
+
+     return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
      if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
              valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+     if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+             valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
      if (flags & ~valid_flags)
              return -EINVAL;
 
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
      if (!file)
              return -EFAULT;
 
+     filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+
      folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
      if (IS_ERR(folio)) {
              r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
              *page = folio_file_page(folio, index);
      else
              folio_put(folio);
-
 out:
+     filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
      fput(file);
      return r;
 }
--

2.49.0.1045.g170613ef41-goog

#47 lore raw

Re: [RFC PATCH v2 03/51] KVM: selftests: Update guest_memfd_test for INIT_PRIVATE flag

In reply to Binbin Wu
Quoted 86 lines · Binbin Wu
Quoted 85 lines · Ackerley Tng
Quoted 70 lines · Ira Weiny
Quoted 56 lines · Ackerley Tng

Test that GUEST_MEMFD_FLAG_INIT_PRIVATE is only valid when GUEST_MEMFD_FLAG_SUPPORT_SHARED is set.

Change-Id I506e236a232047cfaee17bcaed02ee14c8d25bbb
---
  .../testing/selftests/kvm/guest_memfd_test.c  | 36 ++++++++++++-------
  1 file changed, 24 insertions(+), 12 deletions(-)
tools/testing/selftests/kvm/guest_memfd_test.c +21 -5
index 60aaba5808a5..bf2876cbd711 100644
@@ -401,13 +401,31 @@ static void test_with_type(unsigned long vm_type, uint64_t guest_memfd_flags,
  	kvm_vm_release(vm);
  }
 
+static void test_vm_with_gmem_flag(struct kvm_vm *vm, uint64_t flag,
+				   bool expect_valid)
+{
+	size_t page_size = getpagesize();
+	int fd;
+
+	fd = __vm_create_guest_memfd(vm, page_size, flag);
+
+	if (expect_valid) {
+		TEST_ASSERT(fd > 0,
+			    "guest_memfd() with flag '0x%lx' should be valid",
+			    flag);
+		close(fd);
+	} else {
+		TEST_ASSERT(fd == -1 && errno == EINVAL,
+			    "guest_memfd() with flag '0x%lx' should fail with EINVAL",
+			    flag);
+	}
+}
+
  static void test_vm_type_gmem_flag_validity(unsigned long vm_type,
  					    uint64_t expected_valid_flags)
  {
-	size_t page_size = getpagesize();
  	struct kvm_vm *vm;
  	uint64_t flag = 0;
-	int fd;
 
  	if (!(kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(vm_type)))
  		return;
@@ -415,17 +433,11 @@ static void test_vm_type_gmem_flag_validity(unsigned long vm_type,
  	vm = vm_create_barebones_type(vm_type);
 
  	for (flag = BIT(0); flag; flag <<= 1) {
-		fd = __vm_create_guest_memfd(vm, page_size, flag);
+		test_vm_with_gmem_flag(vm, flag, flag & expected_valid_flags);
 
-		if (flag & expected_valid_flags) {
-			TEST_ASSERT(fd > 0,

tools/testing/selftests/kvm/guest_memfd_test.c static void test_vm_type_gmem_flag_validity(unsigned long vm_type, · line 440

Quoted 10 lines
tools/testing/selftests/kvm/guest_memfd_test.c +3 -7
-				    "guest_memfd() with flag '0x%lx' should be valid",
-				    flag);
-			close(fd);
-		} else {
-			TEST_ASSERT(fd == -1 && errno == EINVAL,
-				    "guest_memfd() with flag '0x%lx' should fail with EINVAL",
-				    flag);
+		if (flag == GUEST_MEMFD_FLAG_SUPPORT_SHARED) {
+			test_vm_with_gmem_flag(
+				vm, flag | GUEST_MEMFD_FLAG_INIT_PRIVATE, true);

I don't understand the point of this check. In 2/51 we set GUEST_MEMFD_FLAG_INIT_PRIVATE when GUEST_MEMFD_FLAG_SUPPORT_SHARED is set.

Quoted 3 lines

When can this check ever fail?

Ira

In 02/51, GUEST_MEMFD_FLAG_INIT_PRIVATE is not set by default, GUEST_MEMFD_FLAG_INIT_PRIVATE is set as one of the valid_flags.

The intention is that GUEST_MEMFD_FLAG_INIT_PRIVATE is only valid if GUEST_MEMFD_FLAG_SUPPORT_SHARED is requested by userspace.

In this test, the earlier part before the if block calls test_vm_with_gmem_flag() all valid flags, and that already tests GUEST_MEMFD_FLAG_SUPPORT_SHARED individually.

Quoted 6 lines
Quoted 4 lines

Specifically if GUEST_MEMFD_FLAG_SUPPORT_SHARED is set, this if block adds a test for when both GUEST_MEMFD_FLAG_SUPPORT_SHARED and GUEST_MEMFD_FLAG_INIT_PRIVATE are set, and sets that expect_valid is true.

Maybe it's more clear to move this case out of the loop?

Will try that in the next revision. Thanks!

Quoted 3 lines
Quoted 3 lines

This second test doesn't fail, it is meant to check that the kernel allows the pair of flags to be set. Hope that makes sense.

#98 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Binbin Wu
Quoted 27 lines · Binbin Wu

On 5/15/2025 7:41 AM, Ackerley Tng wrote:

[...]

Quoted 24 lines
virt/kvm/guest_memfd.c +24 -0
+
+static int kvm_gmem_convert_range(struct file *file, pgoff_t start,
+				  size_t nr_pages, bool shared,
+				  pgoff_t *error_index)
+{
+	struct conversion_work *work, *tmp, *rollback_stop_item;
+	LIST_HEAD(work_list);
+	struct inode *inode;
+	enum shareability m;
+	int ret;
+
+	inode = file_inode(file);
+
+	filemap_invalidate_lock(inode->i_mapping);
+
+	m = shared ? SHAREABILITY_ALL : SHAREABILITY_GUEST;
+	ret = kvm_gmem_convert_compute_work(inode, start, nr_pages, m, &work_list);
+	if (ret || list_empty(&work_list))
+		goto out;
+
+	list_for_each_entry(work, &work_list, list)
+		kvm_gmem_convert_invalidate_begin(inode, work);
+
+	list_for_each_entry(work, &work_list, list) {
Quoted 9 lines

virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 322

Quoted 2 lines
virt/kvm/guest_memfd.c +2 -0
+		ret = kvm_gmem_convert_should_proceed(inode, work, shared,
+						      error_index);

Since kvm_gmem_invalidate_begin() begins to handle shared memory, kvm_gmem_convert_invalidate_begin() will zap the table.
The shared mapping could be zapped in kvm_gmem_convert_invalidate_begin() even when kvm_gmem_convert_should_proceed() returns error.
The sequence is a bit confusing to me, at least in this patch so far.

It is true that zapping of pages from the guest page table will happen before we figure out whether conversion is allowed.

For a shared-to-private conversion, we will definitely unmap from the host before checking if conversion is allowed, and there's no choice there since conversion is allowed if there are no unexpected refcounts, and the way to eliminate expected refcounts is to unmap from the host.

Since we're unmapping before checking if conversion is allowed, I thought it would be fine to also zap from guest page tables before checking if conversion is allowed.

Conversion is not meant to happen very regularly, and even if it is unmapped or zapped, the next access will fault in the page anyway, so there is a performance but not a functionality impact.

Hope that helps. Is it still odd to zap before checking if conversion should proceed?

Quoted 70 lines
Quoted 35 lines
virt/kvm/guest_memfd.c +35 -0
+		if (ret)
+			goto invalidate_end;
+	}
+
+	list_for_each_entry(work, &work_list, list) {
+		rollback_stop_item = work;
+		ret = kvm_gmem_shareability_apply(inode, work, m);
+		if (ret)
+			break;
+	}
+
+	if (ret) {
+		m = shared ? SHAREABILITY_GUEST : SHAREABILITY_ALL;
+		list_for_each_entry(work, &work_list, list) {
+			if (work == rollback_stop_item)
+				break;
+
+			WARN_ON(kvm_gmem_shareability_apply(inode, work, m));
+		}
+	}
+
+invalidate_end:
+	list_for_each_entry(work, &work_list, list)
+		kvm_gmem_convert_invalidate_end(inode, work);
+out:
+	filemap_invalidate_unlock(inode->i_mapping);
+
+	list_for_each_entry_safe(work, tmp, &work_list, list) {
+		list_del(&work->list);
+		kfree(work);
+	}
+
+	return ret;
+}
+

[...]

Quoted 33 lines
virt/kvm/guest_memfd.c +13 -2
@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,
  	unsigned long index;
 
  	xa_for_each_range(&gmem->bindings, index, slot, start, end - 1) {
+		enum kvm_gfn_range_filter filter;
  		pgoff_t pgoff = slot->gmem.pgoff;
 
+		filter = KVM_FILTER_PRIVATE;
+		if (kvm_gmem_memslot_supports_shared(slot)) {
+			/*
+			 * Unmapping would also cause invalidation, but cannot
+			 * rely on mmu_notifiers to do invalidation via
+			 * unmapping, since memory may not be mapped to
+			 * userspace.
+			 */
+			filter |= KVM_FILTER_SHARED;
+		}
+
  		struct kvm_gfn_range gfn_range = {
  			.start = slot->base_gfn + max(pgoff, start) - pgoff,
  			.end = slot->base_gfn + min(pgoff + slot->npages, end) - pgoff,
  			.slot = slot,
  			.may_block = true,
-			/* guest memfd is relevant to only private mappings. */
-			.attr_filter = KVM_FILTER_PRIVATE,
+			.attr_filter = filter,
  		};
 
  		if (!found_memslot) {
@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);
  #define kvm_gmem_mmap NULL
  #endif /* CONFIG_KVM_GMEM_SHARED_MEM */
 

[...]

#102 lore raw

Re: [RFC PATCH v2 05/51] KVM: guest_memfd: Skip LRU for guest_memfd folios

In reply to Binbin Wu
Quoted 10 lines · Binbin Wu
Quoted 6 lines · Ackerley Tng

filemap_add_folio(), called from filemap_grab_folio(), adds the folio onto some LRU list, which is not necessary for guest_memfd since guest_memfd folios don't participate in any swapping.

This patch reimplements part of filemap_add_folio() to avoid adding allocated guest_memfd folios to the filemap.

filemap -> LRU list?

Yes, thank you. Will fix this in the next revision.

Quoted 51 lines
Quoted 14 lines

With shared to private conversions dependent on refcounts, avoiding usage of LRU ensures that LRU lists no longer take any refcounts on guest_memfd folios and significantly reduces the chance of elevated refcounts during conversion.

Change-Id Ia2540d9fc132d46219e6e714fd42bc82a62a27fa
---
  mm/filemap.c           |  1 +
  mm/memcontrol.c        |  2 +
  virt/kvm/guest_memfd.c | 91 ++++++++++++++++++++++++++++++++++++++----
  3 files changed, 86 insertions(+), 8 deletions(-)

[...]

Quoted 36 lines

/*
* Returns a locked folio on success. The caller is responsible for
* setting the up-to-date flag before the memory is mapped into the guest.

virt/kvm/guest_memfd.c +27 -1
@@ -477,8 +509,46 @@ static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
   */
  static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  {
+	struct folio *folio;
+	gfp_t gfp;
+	int ret;
+
+repeat:
+	folio = filemap_lock_folio(inode->i_mapping, index);
+	if (!IS_ERR(folio))
+		return folio;
+
+	gfp = mapping_gfp_mask(inode->i_mapping);
+
  	/* TODO: Support huge pages. */
-	return filemap_grab_folio(inode->i_mapping, index);
+	folio = filemap_alloc_folio(gfp, 0);
+	if (!folio)
+		return ERR_PTR(-ENOMEM);
+
+	ret = mem_cgroup_charge(folio, NULL, gfp);
+	if (ret) {
+		folio_put(folio);
+		return ERR_PTR(ret);
+	}
+
+	ret = kvm_gmem_filemap_add_folio(inode->i_mapping, folio, index);
+	if (ret) {
+		folio_put(folio);
+
+		/*
+		 * There was a race, two threads tried to get a folio indexing
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot, · line 542

Quoted 3 lines
virt/kvm/guest_memfd.c +3 -0
+		 * to the same location in the filemap. The losing thread should
+		 * free the allocated folio, then lock the folio added to the
+		 * filemap by the winning thread.

How about changing
“then lock the folio added to the filemap by the winning thread” to
"the winning thread locks the folio added to the filemap"?

How about:

There was a race. Threads tried to get a folio indexing to the same location in the filemap. The winning thread allocated and locked the folio at the requested index. The losing threads should free the extra allocated folio, then wait to lock the same folio allocated (and locked) by the winning thread.

Quoted 15 lines
Quoted 15 lines
virt/kvm/guest_memfd.c +9 -0
+		 */
+		if (ret == -EEXIST)
+			goto repeat;
+
+		return ERR_PTR(ret);
+	}
+
+	__folio_set_locked(folio);
+	return folio;
  }
 
  static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,
@@ -956,23 +1026,28 @@ static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol
  }
 
Quoted 12 lines

virt/kvm/guest_memfd.c static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *fol · line 1036

Quoted 9 lines
virt/kvm/guest_memfd.c +8 -0
  #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
+static void kvm_gmem_invalidate(struct folio *folio)
+{
+	kvm_pfn_t pfn = folio_pfn(folio);
+
+	kvm_arch_gmem_invalidate(pfn, pfn + folio_nr_pages(folio));
+}
+#else
+static inline void kvm_gmem_invalidate(struct folio *folio) {}

No need to tag a local static function with "inline".

Will fix in the next revision.

Quoted 3 lines
Quoted 2 lines
virt/kvm/guest_memfd.c +2 -0
+#endif
+

[...]

#132 lore raw

Re: [RFC PATCH v2 22/51] mm: hugetlb: Refactor hugetlb allocation functions

In reply to Ackerley Tng
Quoted 10 lines · Ackerley Tng

Refactor dequeue_hugetlb_folio() and alloc_surplus_hugetlb_folio() to take mpol, nid and nodemask. This decouples allocation of a folio from a vma.

Change-Id I890fb46fe8c6349383d8cf89befc68a4994eb416
---
 mm/hugetlb.c | 64 ++++++++++++++++++++++++----------------------------
 1 file changed, 30 insertions(+), 34 deletions(-)

[snip]

Quoted 22 lines
mm/hugetlb.c +5 -1
@@ -2993,6 +2974,11 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 	int ret, idx;
 	struct hugetlb_cgroup *h_cg = NULL;
 	gfp_t gfp = htlb_alloc_mask(h) | __GFP_RETRY_MAYFAIL;
+	struct mempolicy *mpol;
+	nodemask_t *nodemask;
+	gfp_t gfp_mask;
+	pgoff_t ilx;
+	int nid;
 
 	idx = hstate_index(h);
 
@@ -3032,7 +3018,6 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 
 		subpool_reservation_exists = npages_req == 0;
 	}
-
 	reservation_exists = vma_reservation_exists || subpool_reservation_exists;
 
 	/*

mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3036

Quoted 4 lines
mm/hugetlb.c +1 -0
@@ -3048,21 +3033,30 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 			goto out_subpool_put;
 	}
 
+	mpol = get_vma_policy(vma, addr, h->order, &ilx);

Why does the memory policy need to be acquired here instead of after the cgroup charge? AFAICT this is not needed and would at least eliminate 1 of the error conditions puts.

mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3040

Quoted 5 lines
mm/hugetlb.c +3 -1
+
 	ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
-	if (ret)
+	if (ret) {
+		mpol_cond_put(mpol);
                ^^^^
		here

All that said I think the use of some new cleanup macros could really help a lot of this code.

What do folks in this area of the kernel think of those?

Ira

[snip]

#135 lore raw

Re: [RFC PATCH v2 23/51] mm: hugetlb: Refactor out hugetlb_alloc_folio()

In reply to Ackerley Tng
Quoted 31 lines · Ackerley Tng

Refactor out hugetlb_alloc_folio() from alloc_hugetlb_folio(), which handles allocation of a folio and cgroup charging.

Other than flags to control charging in the allocation process, hugetlb_alloc_folio() also has parameters for memory policy.

This refactoring as a whole decouples the hugetlb page allocation from hugetlbfs, (1) where the subpool is stored at the fs mount, (2) reservations are made during mmap and stored in the vma, and (3) mpol must be stored at vma->vm_policy (4) a vma must be used for allocation even if the pages are not meant to be used by host process.

This decoupling will allow hugetlb_alloc_folio() to be used by guest_memfd in later patches. In guest_memfd, (1) a subpool is created per-fd and is stored on the inode, (2) no vma-related reservations are used (3) mpol may not be associated with a vma since (4) for private pages, the pages will not be mappable to userspace and hence have to associated vmas.

This could hopefully also open hugetlb up as a more generic source of hugetlb pages that are not bound to hugetlbfs, with the complexities of userspace/mmap/vma-related reservations contained just to hugetlbfs.

Change-Id I60528f246341268acbf0ed5de7752ae2cacbef93
---
 include/linux/hugetlb.h |  12 +++
 mm/hugetlb.c            | 192 ++++++++++++++++++++++------------------
 2 files changed, 118 insertions(+), 86 deletions(-)

[snip]

Quoted 24 lines
mm/hugetlb.c +23 -0
+/**
+ * hugetlb_alloc_folio() - Allocates a hugetlb folio.
+ *
+ * @h: struct hstate to allocate from.
+ * @mpol: struct mempolicy to apply for this folio allocation.
+ * @ilx: Interleave index for interpretation of @mpol.
+ * @charge_cgroup_rsvd: Set to true to charge cgroup reservation.
+ * @use_existing_reservation: Set to true if this allocation should use an
+ *                            existing hstate reservation.
+ *
+ * This function handles cgroup and global hstate reservations. VMA-related
+ * reservations and subpool debiting must be handled by the caller if necessary.
+ *
+ * Return: folio on success or negated error otherwise.
+ */
+struct folio *hugetlb_alloc_folio(struct hstate *h, struct mempolicy *mpol,
+				  pgoff_t ilx, bool charge_cgroup_rsvd,
+				  bool use_existing_reservation)
+{
+	unsigned int nr_pages = pages_per_huge_page(h);
+	struct hugetlb_cgroup *h_cg = NULL;
+	struct folio *folio = NULL;
+	nodemask_t *nodemask;

mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 2989

Quoted 10 lines
mm/hugetlb.c +10 -0
+	gfp_t gfp_mask;
+	int nid;
+	int idx;
+	int ret;
+
+	idx = hstate_index(h);
+
+	if (charge_cgroup_rsvd) {
+		if (hugetlb_cgroup_charge_cgroup_rsvd(idx, nr_pages, &h_cg))
+			goto out;

Why not just return here?

			return ERR_PTR(-ENOSPC);
Quoted 47 lines
mm/hugetlb.c +47 -0
+	}
+
+	if (hugetlb_cgroup_charge_cgroup(idx, nr_pages, &h_cg))
+		goto out_uncharge_cgroup_reservation;
+
+	gfp_mask = htlb_alloc_mask(h);
+	nid = policy_node_nodemask(mpol, gfp_mask, ilx, &nodemask);
+
+	spin_lock_irq(&hugetlb_lock);
+
+	if (use_existing_reservation || available_huge_pages(h))
+		folio = dequeue_hugetlb_folio(h, gfp_mask, mpol, nid, nodemask);
+
+	if (!folio) {
+		spin_unlock_irq(&hugetlb_lock);
+		folio = alloc_surplus_hugetlb_folio(h, gfp_mask, mpol, nid, nodemask);
+		if (!folio)
+			goto out_uncharge_cgroup;
+		spin_lock_irq(&hugetlb_lock);
+		list_add(&folio->lru, &h->hugepage_activelist);
+		folio_ref_unfreeze(folio, 1);
+		/* Fall through */
+	}
+
+	if (use_existing_reservation) {
+		folio_set_hugetlb_restore_reserve(folio);
+		h->resv_huge_pages--;
+	}
+
+	hugetlb_cgroup_commit_charge(idx, nr_pages, h_cg, folio);
+
+	if (charge_cgroup_rsvd)
+		hugetlb_cgroup_commit_charge_rsvd(idx, nr_pages, h_cg, folio);
+
+	spin_unlock_irq(&hugetlb_lock);
+
+	gfp_mask = htlb_alloc_mask(h) | __GFP_RETRY_MAYFAIL;
+	ret = mem_cgroup_charge_hugetlb(folio, gfp_mask);
+	/*
+	 * Unconditionally increment NR_HUGETLB here. If it turns out that
+	 * mem_cgroup_charge_hugetlb failed, then immediately free the page and
+	 * decrement NR_HUGETLB.
+	 */
+	lruvec_stat_mod_folio(folio, NR_HUGETLB, pages_per_huge_page(h));
+
+	if (ret == -ENOMEM) {
+		free_huge_folio(folio);

mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3046

Quoted 10 lines
mm/hugetlb.c +10 -0
+		return ERR_PTR(-ENOMEM);
+	}
+
+	return folio;
+
+out_uncharge_cgroup:
+	hugetlb_cgroup_uncharge_cgroup(idx, nr_pages, h_cg);
+out_uncharge_cgroup_reservation:
+	if (charge_cgroup_rsvd)
+		hugetlb_cgroup_uncharge_cgroup_rsvd(idx, nr_pages, h_cg);

I find the direct copy of the unwind logic from alloc_hugetlb_folio() cumbersome and it seems like a good opportunity to clean it up.

mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3049

Quoted 3 lines
mm/hugetlb.c +3 -0
+out:
+	folio = ERR_PTR(-ENOSPC);
+	goto out;

Endless loop?

Ira

[snip]

#7 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Ackerley Tng

Hi Ackerley,

Quoted 36 lines · Ackerley Tng
Quoted 28 lines · Fuad Tabba

Hi,

.. snip..

Quoted 17 lines

I noticed that in [1], the kvm_gmem_mmap() does not check the range. So, the WARN() here can be hit when userspace mmap() an area larger than the inode size and accesses the out of band HVA.

Maybe limit the mmap() range?

(quoted diff) +3 -0
@@ -1609,6 +1620,10 @@ static int kvm_gmem_mmap(struct file *file, struct vm_area_struct *vma)
        if (!kvm_gmem_supports_shared(file_inode(file)))
                return -ENODEV;
 
+       if (vma->vm_end - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT) > i_size_read(file_inode(file)))
+               return -EINVAL;
+
        if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) !=
            (VM_SHARED | VM_MAYSHARE)) {
                return -EINVAL;
Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

I don't think we want to do that for a couple of reasons. We catch such invalid accesses on faulting, and, by analogy, afaikt, neither secretmem nor memfd perform a similar check on mmap (nor do memory-mapped files in general).

Quoted 4 lines

There are also valid reasons why a user would want to deliberately mmap more memory than the backing store, knowing that it's only going to fault what it's going to use, e.g., alignment.

Quoted 7 lines

This is a good point.

I think there's no check against the inode size on faulting now though? v10's [1] kvm_gmem_fault_shared() calls kvm_gmem_get_folio() straightaway.

We should add a check like [2] to kvm_gmem_fault_shared().

Yes! I mistakenly thought that kvm_gmem_get_folio() had such a check, I just verified that it doesn't. I have added the check, as well as a new selftest to make sure we don't miss it in the future.

Thanks!
/fuad

Quoted 153 lines

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/torvalds/linux/blob/8477ab143069c6b05d6da4a8184ded8b969240f5/mm/filemap.c#L3373

Quoted 150 lines

Cheers,
/fuad

Quoted 146 lines
Quoted 80 lines
virt/kvm/guest_memfd.c +54 -1
+     return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+     if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+             return ERR_PTR(-EACCES);
+
+     return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+     return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+     WARN_ONCE("Unexpected call to get shared folio.")
+     return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
                                  pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
      filemap_invalidate_lock_shared(inode->i_mapping);
 
-     folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+     folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
      if (IS_ERR(folio)) {
              int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
      .fallocate      = kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+     struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+     kfree(private);
+
+     free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+     struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+     /*
+      * mtree_destroy() can't be used within rcu callback, hence can't be
+      * done in ->free_inode().
+      */
+     if (private)
+             mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
      .statfs         = simple_statfs,
+     .destroy_inode  = kvm_gmem_destroy_inode,
+     .free_inode     = kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
                                                    loff_t size, u64 flags)
 {
+     struct kvm_gmem_inode_private *private;
      struct inode *inode;
+     int err;
 

virt/kvm/guest_memfd.c static const struct inode_operations kvm_gmem_iops = { · line 661

Quoted 10 lines
virt/kvm/guest_memfd.c +6 -0
      inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
      if (IS_ERR(inode))
              return inode;
 
+     err = -ENOMEM;
+     private = kzalloc(sizeof(*private), GFP_KERNEL);
+     if (!private)
+             goto out;
+
+     mt_init(&private->shareability);

Wrap the mt_init() inside "#ifdef CONFIG_KVM_GMEM_SHARED_MEM" ?

Quoted 54 lines
virt/kvm/guest_memfd.c +17 -2
+     inode->i_mapping->i_private_data = private;
+
+     err = kvm_gmem_shareability_setup(private, size, flags);
+     if (err)
+             goto out;
+
      inode->i_private = (void *)(unsigned long)flags;
      inode->i_op = &kvm_gmem_iops;
      inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
      WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
      return inode;
+
+out:
+     iput(inode);
+
+     return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
      if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
              valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+     if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+             valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
      if (flags & ~valid_flags)
              return -EINVAL;
 
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
      if (!file)
              return -EFAULT;
 
+     filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+
      folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
      if (IS_ERR(folio)) {
              r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
              *page = folio_file_page(folio, index);
      else
              folio_put(folio);
-
 out:
+     filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
      fput(file);
      return r;
 }
--

2.49.0.1045.g170613ef41-goog

#99 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Ackerley Tng
Quoted 45 lines · Ackerley Tng
Quoted 26 lines · Binbin Wu

On 5/15/2025 7:41 AM, Ackerley Tng wrote:

[...]

Quoted 23 lines
virt/kvm/guest_memfd.c +23 -0
+
+static int kvm_gmem_convert_range(struct file *file, pgoff_t start,
+				  size_t nr_pages, bool shared,
+				  pgoff_t *error_index)
+{
+	struct conversion_work *work, *tmp, *rollback_stop_item;
+	LIST_HEAD(work_list);
+	struct inode *inode;
+	enum shareability m;
+	int ret;
+
+	inode = file_inode(file);
+
+	filemap_invalidate_lock(inode->i_mapping);
+
+	m = shared ? SHAREABILITY_ALL : SHAREABILITY_GUEST;
+	ret = kvm_gmem_convert_compute_work(inode, start, nr_pages, m, &work_list);
+	if (ret || list_empty(&work_list))
+		goto out;
+
+	list_for_each_entry(work, &work_list, list)
+		kvm_gmem_convert_invalidate_begin(inode, work);
+
Quoted 9 lines

virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t inde · line 322

Quoted 3 lines
virt/kvm/guest_memfd.c +3 -0
+	list_for_each_entry(work, &work_list, list) {
+		ret = kvm_gmem_convert_should_proceed(inode, work, shared,
+						      error_index);

Since kvm_gmem_invalidate_begin() begins to handle shared memory, kvm_gmem_convert_invalidate_begin() will zap the table.
The shared mapping could be zapped in kvm_gmem_convert_invalidate_begin() even when kvm_gmem_convert_should_proceed() returns error.
The sequence is a bit confusing to me, at least in this patch so far.

It is true that zapping of pages from the guest page table will happen before we figure out whether conversion is allowed.

For a shared-to-private conversion, we will definitely unmap from the host before checking if conversion is allowed, and there's no choice there since conversion is allowed if there are no unexpected refcounts, and the way to eliminate expected refcounts is to unmap from the host.

Quoted 7 lines

Since we're unmapping before checking if conversion is allowed, I thought it would be fine to also zap from guest page tables before checking if conversion is allowed.

Conversion is not meant to happen very regularly, and even if it is unmapped or zapped, the next access will fault in the page anyway, so there is a performance but not a functionality impact.

Yes, it's OK for shared mapping.

Quoted 2 lines

Hope that helps.

It helped, thanks!

Quoted 73 lines

Is it still odd to zap before checking if conversion should proceed?

Quoted 70 lines
Quoted 35 lines
virt/kvm/guest_memfd.c +35 -0
+		if (ret)
+			goto invalidate_end;
+	}
+
+	list_for_each_entry(work, &work_list, list) {
+		rollback_stop_item = work;
+		ret = kvm_gmem_shareability_apply(inode, work, m);
+		if (ret)
+			break;
+	}
+
+	if (ret) {
+		m = shared ? SHAREABILITY_GUEST : SHAREABILITY_ALL;
+		list_for_each_entry(work, &work_list, list) {
+			if (work == rollback_stop_item)
+				break;
+
+			WARN_ON(kvm_gmem_shareability_apply(inode, work, m));
+		}
+	}
+
+invalidate_end:
+	list_for_each_entry(work, &work_list, list)
+		kvm_gmem_convert_invalidate_end(inode, work);
+out:
+	filemap_invalidate_unlock(inode->i_mapping);
+
+	list_for_each_entry_safe(work, tmp, &work_list, list) {
+		list_del(&work->list);
+		kfree(work);
+	}
+
+	return ret;
+}
+

[...]

Quoted 33 lines
virt/kvm/guest_memfd.c +13 -2
@@ -186,15 +490,26 @@ static void kvm_gmem_invalidate_begin(struct kvm_gmem *gmem, pgoff_t start,
   	unsigned long index;
 
   	xa_for_each_range(&gmem->bindings, index, slot, start, end - 1) {
+		enum kvm_gfn_range_filter filter;
   		pgoff_t pgoff = slot->gmem.pgoff;
 
+		filter = KVM_FILTER_PRIVATE;
+		if (kvm_gmem_memslot_supports_shared(slot)) {
+			/*
+			 * Unmapping would also cause invalidation, but cannot
+			 * rely on mmu_notifiers to do invalidation via
+			 * unmapping, since memory may not be mapped to
+			 * userspace.
+			 */
+			filter |= KVM_FILTER_SHARED;
+		}
+
   		struct kvm_gfn_range gfn_range = {
   			.start = slot->base_gfn + max(pgoff, start) - pgoff,
   			.end = slot->base_gfn + min(pgoff + slot->npages, end) - pgoff,
   			.slot = slot,
   			.may_block = true,
-			/* guest memfd is relevant to only private mappings. */
-			.attr_filter = KVM_FILTER_PRIVATE,
+			.attr_filter = filter,
   		};
 
   		if (!found_memslot) {
@@ -484,11 +799,49 @@ EXPORT_SYMBOL_GPL(kvm_gmem_memslot_supports_shared);
   #define kvm_gmem_mmap NULL
   #endif /* CONFIG_KVM_GMEM_SHARED_MEM */
 

[...]

#161 lore raw

Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator

In reply to Ackerley Tng

On 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]

Quoted 6 lines
  
  	list_for_each_entry(gmem, gmem_list, entry)
  		kvm_gmem_invalidate_end(gmem, start, end);
virt/kvm/guest_memfd.c +0 -0
@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
 
  	start = offset >> PAGE_SHIFT;

virt/kvm/guest_memfd.c static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) · line 890

Quoted 10 lines
virt/kvm/guest_memfd.c +9 -0
  	end = (offset + len) >> PAGE_SHIFT;
+	if (kvm_gmem_has_custom_allocator(inode)) {
+		size_t nr_pages;
+		void *p;
+
+		p = kvm_gmem_allocator_private(inode);
+		nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(p);
+
+		start = round_down(start, nr_pages);
+		end = round_down(end, nr_pages);

It's weird here.
Should the end be round_up()?

Quoted 5 lines
virt/kvm/guest_memfd.c +1 -0
+	}
 
  	r = 0;
  	for (index = start; index < end; ) {

[...]

#186 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Ackerley Tng

On 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]

Quoted 4 lines
virt/kvm/guest_memfd.c +4 -0
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+	size_t to_nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_page(priv);
+
+	if (kvm_gmem_has_some_shared(inode, folio->index, to_nr_pages))

What if a huge page whose attribute is shared?

Quoted 5 lines
virt/kvm/guest_memfd.c +5 -0
+		return kvm_gmem_split_folio_in_filemap(inode, folio);
+
+	return 0;
+}
+

[...]

Quoted 34 lines

static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)

virt/kvm/guest_memfd.c +8 -2
@@ -563,11 +1005,16 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  		return folio;
 
  	if (kvm_gmem_has_custom_allocator(inode)) {
-		void *p = kvm_gmem_allocator_private(inode);
+		size_t nr_pages;
+		void *p;
 
+		p = kvm_gmem_allocator_private(inode);
  		folio = kvm_gmem_allocator_ops(inode)->alloc_folio(p);
  		if (IS_ERR(folio))
  			return folio;
+
+		nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(p);
+		index_floor = round_down(index, nr_pages);
  	} else {
  		gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
 
@@ -580,10 +1027,11 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  			folio_put(folio);
  			return ERR_PTR(ret);
  		}
+
+		index_floor = index;
  	}
  	allocated_size = folio_size(folio);
 
-	index_floor = round_down(index, folio_nr_pages(folio));
  	ret = kvm_gmem_filemap_add_folio(inode->i_mapping, folio, index_floor);
  	if (ret) {
  		folio_put(folio);

virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 1054

Quoted 7 lines
virt/kvm/guest_memfd.c +4 -0
@@ -600,6 +1048,13 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  		return ERR_PTR(ret);
  	}
 
+	/* Leave just filemap's refcounts on folio. */
+	folio_put(folio);
+
+	ret = kvm_gmem_try_split_folio_in_filemap(inode, folio);

When !CONFIG_KVM_GMEM_SHARED_MEM, kvm_gmem_try_split_folio_in_filemap() is undefined.

Quoted 7 lines
virt/kvm/guest_memfd.c +3 -0
+	if (ret)
+		goto err;
+
  	spin_lock(&inode->i_lock);
  	inode->i_blocks += allocated_size / 512;
  	spin_unlock(&inode->i_lock);

[...]

#174 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Edgecombe, Rick P
Quoted 15 lines · Rick P

virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349

Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8 -0
+
+static pgoff_t kvm_gmem_compute_invalidate_bound(struct inode *inode,
+						 pgoff_t bound, bool start)
+{
+	size_t nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))

General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.

Quoted 3 lines

Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators?

I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.

I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.

Quoted 4 lines

If it
didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?

This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.

Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23 -0
+		return bound;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (start)
+		return round_down(bound, nr_pages);
+	else
+		return round_up(bound, nr_pages);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_start(struct inode *inode,
+						 pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, true);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_end(struct inode *inode,
+					       pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, false);
+}
+
#176 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Edgecombe, Rick P
Quoted 15 lines · Rick P

virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349

Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8 -0
+
+static pgoff_t kvm_gmem_compute_invalidate_bound(struct inode *inode,
+						 pgoff_t bound, bool start)
+{
+	size_t nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))

General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.

Quoted 3 lines

Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators?

I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.

I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.

Quoted 4 lines

If it
didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?

This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.

Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23 -0
+		return bound;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (start)
+		return round_down(bound, nr_pages);
+	else
+		return round_up(bound, nr_pages);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_start(struct inode *inode,
+						 pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, true);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_end(struct inode *inode,
+					       pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, false);
+}
+
#177 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Edgecombe, Rick P
Quoted 15 lines · Rick P

virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349

Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8 -0
+
+static pgoff_t kvm_gmem_compute_invalidate_bound(struct inode *inode,
+						 pgoff_t bound, bool start)
+{
+	size_t nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))

General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.

Quoted 3 lines

Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators?

I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.

I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.

Quoted 4 lines

If it
didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?

This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.

Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23 -0
+		return bound;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (start)
+		return round_down(bound, nr_pages);
+	else
+		return round_up(bound, nr_pages);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_start(struct inode *inode,
+						 pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, true);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_end(struct inode *inode,
+					       pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, false);
+}
+
#178 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Edgecombe, Rick P
Quoted 15 lines · Rick P

virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349

Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8 -0
+
+static pgoff_t kvm_gmem_compute_invalidate_bound(struct inode *inode,
+						 pgoff_t bound, bool start)
+{
+	size_t nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))

General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.

Quoted 3 lines

Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators?

I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.

I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.

Quoted 4 lines

If it
didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?

This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.

Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23 -0
+		return bound;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (start)
+		return round_down(bound, nr_pages);
+	else
+		return round_up(bound, nr_pages);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_start(struct inode *inode,
+						 pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, true);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_end(struct inode *inode,
+					       pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, false);
+}
+
#179 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Edgecombe, Rick P
Quoted 15 lines · Rick P

virt/kvm/guest_memfd.c static bool kvm_gmem_has_safe_refcount(struct address_space *mapping, pgoff_t st · line 349

Quoted 8 lines · Ackerley Tng
virt/kvm/guest_memfd.c +8 -0
+
+static pgoff_t kvm_gmem_compute_invalidate_bound(struct inode *inode,
+						 pgoff_t bound, bool start)
+{
+	size_t nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))

General comment - It's a bit unfortunate how kvm_gmem_has_custom_allocator() is checked all over the place across this series. There are only two allocators after this, right? So one is implemented with callbacks presumably designed to fit other allocators, and one has special case logic in guest_memfd.c.

Quoted 3 lines

Did you consider designing struct guestmem_allocator_operations so that it could encapsulate the special logic for both the existing and new allocators?

I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.

I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.

Quoted 4 lines

If it
didn't work well, could we expect that a next allocator would actually fit struct guestmem_allocator_operations?

This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.

Quoted 23 lines
Quoted 23 lines
virt/kvm/guest_memfd.c +23 -0
+		return bound;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (start)
+		return round_down(bound, nr_pages);
+	else
+		return round_up(bound, nr_pages);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_start(struct inode *inode,
+						 pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, true);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_end(struct inode *inode,
+					       pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, false);
+}
+
#182 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Yan Zhao
Quoted 1 line · Yan Zhao

On Wed, May 14, 2025 at 04:42:17PM -0700, Ackerley Tng wrote:

[...]

Quoted 43 lines
Quoted 43 lines
virt/kvm/guest_memfd.c +33 -1
+static pgoff_t kvm_gmem_compute_invalidate_bound(struct inode *inode,
+						 pgoff_t bound, bool start)
+{
+	size_t nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return bound;
+
+	priv = kvm_gmem_allocator_private(inode);
+	nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (start)
+		return round_down(bound, nr_pages);
+	else
+		return round_up(bound, nr_pages);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_start(struct inode *inode,
+						 pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, true);
+}
+
+static pgoff_t kvm_gmem_compute_invalidate_end(struct inode *inode,
+					       pgoff_t bound)
+{
+	return kvm_gmem_compute_invalidate_bound(inode, bound, false);
+}
+
 static int kvm_gmem_shareability_apply(struct inode *inode,
 				       struct conversion_work *work,
 				       enum shareability m)
@@ -299,35 +428,53 @@ static void kvm_gmem_convert_invalidate_begin(struct inode *inode,
 					      struct conversion_work *work)
 {
 	struct list_head *gmem_list;
+	pgoff_t invalidate_start;
+	pgoff_t invalidate_end;
 	struct kvm_gmem *gmem;
-	pgoff_t end;
+	pgoff_t work_end;
 
Quoted 4 lines

virt/kvm/guest_memfd.c static void kvm_gmem_convert_invalidate_begin(struct inode *inode, · line 438

Quoted 4 lines
virt/kvm/guest_memfd.c +3 -1
-	end = work->start + work->nr_pages;
+	work_end = work->start + work->nr_pages;
+	invalidate_start = kvm_gmem_compute_invalidate_start(inode, work->start);
+	invalidate_end = kvm_gmem_compute_invalidate_end(inode, work_end);

The invalidation range is broadened to include the full range to take care of this race [1] reported for the conversion flow that uses KVM_SET_MEMORY_ATTRIBUTES ioctl, so I also repeated the broadening for this guest_memfd conversion ioctl.

Quoted 3 lines

Could we just notify the exact gfn range and let KVM adjust the invalidate range?

How do we get KVM to adjust the invalidate range?

Quoted 4 lines

Then kvm_gmem_invalidate_begin() can asks KVM to do EPT splitting before any kvm_mmu_unmap_gfn_range() is performed.

In this snapshot of my WIP of putting this HugeTLB support with TDX huge page EPT support [2], I was thinking to combine EPT splitting together with unmap, and leaving the invalidate to be a separate part. (See kvm_gmem_unmap_private().) I did it this way so that the EPT splitting is range is the unmapping range, and only the invalidation range is broadened.

What do you think of that?

Quoted 216 lines
Quoted 216 lines
virt/kvm/guest_memfd.c +159 -9
 	gmem_list = &inode->i_mapping->i_private_list;
 	list_for_each_entry(gmem, gmem_list, entry)
-		kvm_gmem_invalidate_begin(gmem, work->start, end);
+		kvm_gmem_invalidate_begin(gmem, invalidate_start, invalidate_end);
 }
 
 static void kvm_gmem_convert_invalidate_end(struct inode *inode,
 					    struct conversion_work *work)
 {
 	struct list_head *gmem_list;
+	pgoff_t invalidate_start;
+	pgoff_t invalidate_end;
 	struct kvm_gmem *gmem;
-	pgoff_t end;
+	pgoff_t work_end;
 
-	end = work->start + work->nr_pages;
+	work_end = work->start + work->nr_pages;
+	invalidate_start = kvm_gmem_compute_invalidate_start(inode, work->start);
+	invalidate_end = kvm_gmem_compute_invalidate_end(inode, work_end);
 
 	gmem_list = &inode->i_mapping->i_private_list;
 	list_for_each_entry(gmem, gmem_list, entry)
-		kvm_gmem_invalidate_end(gmem, work->start, end);
+		kvm_gmem_invalidate_end(gmem, invalidate_start, invalidate_end);
 }
 
 static int kvm_gmem_convert_should_proceed(struct inode *inode,
 					   struct conversion_work *work,
 					   bool to_shared, pgoff_t *error_index)
 {
-	if (!to_shared) {
+	if (to_shared) {
+		struct list_head *gmem_list;
+		struct kvm_gmem *gmem;
+		pgoff_t work_end;
+
+		work_end = work->start + work->nr_pages;
+
+		gmem_list = &inode->i_mapping->i_private_list;
+		list_for_each_entry(gmem, gmem_list, entry)
+			kvm_gmem_unmap_private(gmem, work->start, work_end);
+	} else {
 		unmap_mapping_pages(inode->i_mapping, work->start,
 				    work->nr_pages, false);
 
@@ -340,6 +487,27 @@ static int kvm_gmem_convert_should_proceed(struct inode *inode,
 	return 0;
 }
 
+static int kvm_gmem_convert_execute_work(struct inode *inode,
+					 struct conversion_work *work,
+					 bool to_shared)
+{
+	enum shareability m;
+	int ret;
+
+	m = to_shared ? SHAREABILITY_ALL : SHAREABILITY_GUEST;
+	ret = kvm_gmem_shareability_apply(inode, work, m);
+	if (ret)
+		return ret;
+	/*
+	 * Apply shareability first so split/merge can operate on new
+	 * shareability state.
+	 */
+	ret = kvm_gmem_restructure_folios_in_range(
+		inode, work->start, work->nr_pages, to_shared);
+
+	return ret;
+}
+
 static int kvm_gmem_convert_range(struct file *file, pgoff_t start,
 				  size_t nr_pages, bool shared,
 				  pgoff_t *error_index)
@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,
 
 	list_for_each_entry(work, &work_list, list) {
 		rollback_stop_item = work;
-		ret = kvm_gmem_shareability_apply(inode, work, m);
+
+		ret = kvm_gmem_convert_execute_work(inode, work, shared);
 		if (ret)
 			break;
 	}
 
 	if (ret) {
-		m = shared ? SHAREABILITY_GUEST : SHAREABILITY_ALL;
 		list_for_each_entry(work, &work_list, list) {
+			int r;
+
+			r = kvm_gmem_convert_execute_work(inode, work, !shared);
+			WARN_ON(r);
+
 			if (work == rollback_stop_item)
 				break;
-
-			WARN_ON(kvm_gmem_shareability_apply(inode, work, m));
 		}
 	}
 
@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,
 	return ret;
 }
 
+#ifdef CONFIG_KVM_GMEM_HUGETLB
+
+static inline void __filemap_remove_folio_for_restructuring(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+
+	spin_lock(&mapping->host->i_lock);
+	xa_lock_irq(&mapping->i_pages);
+
+	__filemap_remove_folio(folio, NULL);
+
+	xa_unlock_irq(&mapping->i_pages);
+	spin_unlock(&mapping->host->i_lock);
+}
+
+/**
+ * filemap_remove_folio_for_restructuring() - Remove @folio from filemap for
+ * split/merge.
+ *
+ * @folio: the folio to be removed.
+ *
+ * Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless
+ * for guest_memfd), and skips call to ->free_folio() to maintain folio flags.
+ *
+ * Context: Expects only the filemap's refcounts to be left on the folio. Will
+ *          freeze these refcounts away so that no other users will interfere
+ *          with restructuring.
+ */
+static inline void filemap_remove_folio_for_restructuring(struct folio *folio)
+{
+	int filemap_refcount;
+
+	filemap_refcount = folio_nr_pages(folio);
+	while (!folio_ref_freeze(folio, filemap_refcount)) {
+		/*
+		 * At this point only filemap refcounts are expected, hence okay
+		 * to spin until speculative refcounts go away.
+		 */
+		WARN_ONCE(1, "Spinning on folio=%p refcount=%d", folio, folio_ref_count(folio));
+	}
+
+	folio_lock(folio);
+	__filemap_remove_folio_for_restructuring(folio);
+	folio_unlock(folio);
+}
+
+/**
+ * kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode.
+ *
+ * @inode: inode containing the folio.
+ * @folio: folio to be split.
+ *
+ * Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap
+ * and add back the split folios.
+ *
+ * Context: Expects that before this call, folio's refcount is just the
+ *          filemap's refcounts. After this function returns, the split folios'
+ *          refcounts will also be filemap's refcounts.
+ * Return: 0 on success or negative error otherwise.
+ */
+static int kvm_gmem_split_folio_in_filemap(struct inode *inode, struct folio *folio)
+{
+	size_t orig_nr_pages;
+	pgoff_t orig_index;
+	size_t i, j;
+	int ret;
+
+	orig_nr_pages = folio_nr_pages(folio);
+	if (orig_nr_pages == 1)
+		return 0;
+
+	orig_index = folio->index;
+
+	filemap_remove_folio_for_restructuring(folio);
+
+	ret = kvm_gmem_allocator_ops(inode)->split_folio(folio);
+	if (ret)
+		goto err;
+
+	for (i = 0; i < orig_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(folio, i));
+
+		ret = __kvm_gmem_filemap_add_folio(inode->i_mapping, f,
+						   orig_index + i);
+		if (ret)
+			goto rollback;
+	}
+
+	return ret;
+
+rollback:
+	for (j = 0; j < i; ++j) {
+		struct folio *f = page_folio(folio_page(folio, j));
+
+		filemap_remove_folio_for_restructuring(f);
+	}
+
+	kvm_gmem_allocator_ops(inode)->merge_folio(folio);
+err:
+	WARN_ON(__kvm_gmem_filemap_add_folio(inode->i_mapping, folio, orig_index));
+
+	return ret;
+}
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{
+	size_t to_nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724

Quoted 5 lines
virt/kvm/guest_memfd.c +5 -0
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_page(priv);
+
+	if (kvm_gmem_has_some_shared(inode, folio->index, to_nr_pages))

If the guest_memfd is configured with GUESTMEM_HUGETLB_FLAG_1GB, it seems that whenever there's a shared page within a 1GB range, the folio will always be split into 4KB folios. Is it good?

It is not the best, but okay as an initial step.

We want to work on splitting 1G to 2M (as many 2M pages as possible) then to 4K. I believe the agreement with the community is that the 1G->2M->4K splitting is an optimization for the patch series after this one.

Quoted 112 lines
Quoted 99 lines
virt/kvm/guest_memfd.c +99 -0
+		return kvm_gmem_split_folio_in_filemap(inode, folio);
+
+	return 0;
+}
+
+/**
+ * kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in
+ * @inode.
+ *
+ * @inode: inode containing the folio.
+ * @first_folio: first folio among folios to be merged.
+ *
+ * Will clean up subfolios from filemap and add back the merged folio.
+ *
+ * Context: Expects that before this call, all subfolios only have filemap
+ *          refcounts. After this function returns, the merged folio will only
+ *          have filemap refcounts.
+ * Return: 0 on success or negative error otherwise.
+ */
+static int kvm_gmem_merge_folio_in_filemap(struct inode *inode,
+					   struct folio *first_folio)
+{
+	size_t to_nr_pages;
+	pgoff_t index;
+	void *priv;
+	size_t i;
+	int ret;
+
+	index = first_folio->index;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+	if (folio_nr_pages(first_folio) == to_nr_pages)
+		return 0;
+
+	for (i = 0; i < to_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(first_folio, i));
+
+		filemap_remove_folio_for_restructuring(f);
+	}
+
+	kvm_gmem_allocator_ops(inode)->merge_folio(first_folio);
+
+	ret = __kvm_gmem_filemap_add_folio(inode->i_mapping, first_folio, index);
+	if (ret)
+		goto err_split;
+
+	return ret;
+
+err_split:
+	WARN_ON(kvm_gmem_allocator_ops(inode)->split_folio(first_folio));
+	for (i = 0; i < to_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(first_folio, i));
+
+		WARN_ON(__kvm_gmem_filemap_add_folio(inode->i_mapping, f, index + i));
+	}
+
+	return ret;
+}
+
+static inline int kvm_gmem_try_merge_folio_in_filemap(struct inode *inode,
+						      struct folio *first_folio)
+{
+	size_t to_nr_pages;
+	void *priv;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (kvm_gmem_has_some_shared(inode, first_folio->index, to_nr_pages))
+		return 0;
+
+	return kvm_gmem_merge_folio_in_filemap(inode, first_folio);
+}
+
+static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
+						pgoff_t start, size_t nr_pages,
+						bool is_split_operation)
+{
+	size_t to_nr_pages;
+	pgoff_t index;
+	pgoff_t end;
+	void *priv;
+	int ret;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	end = start + nr_pages;
+
+	/* Round to allocator page size, to check all (huge) pages in range. */
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	start = round_down(start, to_nr_pages);
+	end = round_up(end, to_nr_pages);
+
+	for (index = start; index < end; index += to_nr_pages) {
+		struct folio *f;

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+
+		f = filemap_get_folio(inode->i_mapping, index);
+		if (IS_ERR(f))
+			continue;
+
+		/* Leave just filemap's refcounts on the folio. */
+		folio_put(f);
+
+		if (is_split_operation)
+			ret = kvm_gmem_split_folio_in_filemap(inode, f);

The split operation is performed after kvm_gmem_unmap_private() within kvm_gmem_convert_should_proceed(), right?

Quoted 4 lines

So, it seems that that it's not necessary for TDX to avoid holding private page references, as TDX must have released the page refs after kvm_gmem_unmap_private() (except when there's TDX module or KVM bug).

I agree with your assessment in the follow up email.

We don't want to unmap more than the requested conversion range to avoid extra churn. If TDX holds refcounts on mapped pages, the subpages that are still mapped will contribute to the refcount of the huge page, and we can't split a page that has refcounts because we don't know how the refcounts are distributed over the subpages.

I guess technically if the refcounts are divisible across nr_pages, we could still split, but if we have a 1G page, but only some of the 1G subpages are mapped into TDX EPTs, then we would have a refcount that we don't know how to divide out.

Quoted 22 lines
Quoted 22 lines
virt/kvm/guest_memfd.c +22 -0
+		else
+			ret = kvm_gmem_try_merge_folio_in_filemap(inode, f);
+
+		if (ret)
+			goto rollback;
+	}
+	return ret;
+
+rollback:
+	for (index -= to_nr_pages; index >= start; index -= to_nr_pages) {
+		struct folio *f;
+
+		f = filemap_get_folio(inode->i_mapping, index);
+		if (IS_ERR(f))
+			continue;
+
+		/* Leave just filemap's refcounts on the folio. */
+		folio_put(f);
+
+		if (is_split_operation)
+			WARN_ON(kvm_gmem_merge_folio_in_filemap(inode, f));
+		else
Quoted 8 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 863

Quoted 8 lines
virt/kvm/guest_memfd.c +8 -0
+			WARN_ON(kvm_gmem_split_folio_in_filemap(inode, f));
+	}
+
+	return ret;
+}
+
+#else
+

[...]

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/googleprodkernel/linux-cc/commits/wip-tdx-gmem-conversions-hugetlb-2mept/

#175 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Ackerley Tng
Quoted 10 lines · Ackerley Tng
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

Did you consider designing struct guestmem_allocator_operations so that > > > > it > > could
encapsulate the special logic for both the existing and new allocators?

I did, yes. I believe it is definitely possible to make standard 4K pages become another allocator too.

I would love to clean this up. Not sure if that will be a new series after this one, or part of this one though.

Usually new work should handle the refactor first, then build on top of it. The code today bolts on a new thing in a dirty way leaving cleanup.

Towards also expedient reviewability, a better order could be:
1. Add allocator callbacks one at a time (or in whatever granularity is possible), moving 4k allocator to callbacks at the same time. Basically a code move. Don't factor out common code between the planned allocators. Will be dirt simple to review.
2. Introduce changes to hugelbfs, explaining why each will be used by guestmemfd
3. Add hugetlbsfs/1GB custom allocator to guestmemfd code, a callback at a time. Have any necessary factoring out of 4k page allocator bits out of the callback implementation come in a separate preceding patch. Explain the commonality.

What do you think?

Also, for (2) do you think you could move some of these pure cleanup patches out of the series to go up ahead of time? And for any hugetlb changes that 1GB guestmemfd depends on, explain why in the log? I'm not clear what is required and what is opportunistic cleanup.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

If it
didn't work well, could we expect that a next allocator would actually > > > > fit
struct guestmem_allocator_operations?

This was definitely designed to support allocators beyond guestmem_hugetlb, though I won't promise that it will be a perfect fit for future allocators. This is internal to the kernel and this interface can be updated for future allocators though.

Makes sense. This was probing on whether the interface didn't fit the 4k allocator. It makes sense to have the interface target the existing 2 allocators, and no future ideas.

#184 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Yan Zhao
Quoted 14 lines · Yan Zhao
Quoted 13 lines · Ackerley Tng
virt/kvm/guest_memfd.c +13 -0
+static int kvm_gmem_convert_execute_work(struct inode *inode,
+					 struct conversion_work *work,
+					 bool to_shared)
+{
+	enum shareability m;
+	int ret;
+
+	m = to_shared ? SHAREABILITY_ALL : SHAREABILITY_GUEST;
+	ret = kvm_gmem_shareability_apply(inode, work, m);
+	if (ret)
+		return ret;
+	/*
+	 * Apply shareability first so split/merge can operate on new
Quoted 8 lines

virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 510

Quoted 8 lines
virt/kvm/guest_memfd.c +8 -0
+	 * shareability state.
+	 */
+	ret = kvm_gmem_restructure_folios_in_range(
+		inode, work->start, work->nr_pages, to_shared);
+
+	return ret;
+}
+

Hi Yan,

Thanks for your thorough reviews and your alternative suggestion in the other discussion at [1]! I'll try to bring the conversion-related parts of that discussion over here.

Quoted 3 lines

virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 513

Quoted 3 lines

static int kvm_gmem_convert_range(struct file *file, pgoff_t start,

virt/kvm/guest_memfd.c +0 -0
 				  size_t nr_pages, bool shared,
 				  pgoff_t *error_index)

The guiding principle I was using for the conversion ioctls is

* Have the shareability updates and any necessary page restructuring (aka splitting/merging) either fully complete for not at all by the time the conversion ioctl returns.
* Any unmapping (from host or guest page tables) will not be re-mapped on errors.
* Rollback undoes changes if conversion failed, and in those cases any errors are turned into WARNings.

The rationale is that we want page sizes to be in sync with shareability so that any faults after the (successful or failed) conversion will not wrongly map in a larger page than allowed and cause any host crashes.

We considered 3 places where the memory can be mapped for conversions:

1. Host page tables
2. Guest page tables
3. IOMMU page tables

Unmapping from host page tables is the simplest case. We unmap any shared ranges from the host page tables. Any accesses after the failed conversion would just fault the memory back in and proceed as usual.

guest_memfd memory is not unmapped from IOMMUs in conversions. This case is handled because IOMMU mappings hold refcounts. After unmapping from the host, we check for unexpected refcounts and fail if there are unexpected refcounts.

We also unmap from guest page tables. Considering failed conversions, if the pages are shared, we're good since the next time the guest accesses the page, the page will be faulted in as before.

If the pages are private, on the next guest access, the pages will be faulted in again as well. This is fine for software-protected VMs IIUC.

For TDX (and SNP) IIUC the memory would have been cleared, and the memory would also need to be re-accepted. I was thinking that this is by design, since when a TDX guest requests a conversion it knows that the contents is not to be used again.

The userspace VMM is obligated to keep trying convert and if it gives up, userspace VMM should inform the guest that the conversion failed. The guest should handle conversion failures too and not assume that conversion always succeeds.

Putting TDX aside for a moment, so far, there are a few ways this conversion could fail:

a. Unexpected refcounts. Userspace should clear up the unexpected
refcounts and report failure to the guest if it can't for whatever reason.
b. ENOMEM because (i) we ran out of memory updating the shareability
maple_tree or (ii) since splitting involves allocating more memory for struct pages and we ran out of memory there. In this case the userspace VMM gets -ENOMEM and can make more memory available and then retry, or if it can't, also report failure to the guest.

TDX introduces TDX-specific conversion failures (see discussion at [1]), which this series doesn't handle, but I think we still have a line of sight to handle new errors.

In the other thread [1], I was proposing to have guest_memfd decide what to do on errors, but I think that might be baking more TDX-specific details into guest_memfd/KVM, and perhaps this is better:

We could return the errors to userspace and let userspace determine what to do. For retryable errors (as determined by userspace), it should do what it needs to do, and retry. For errors like TDX being unable to reclaim the memory, it could tell guest_memfd to leak that memory.

If userspace gives up, it should report conversion failure to the guest if userspace thinks the guest can continue (to a clean shutdown or otherwise). If something terrible happened during conversion, then userspace might have to exit itself or shutdown the host.

In [2], for TDX-specific conversion failures, you proposed prepping to eliminate errors and exiting early on failure, then actually unmapping. I think that could work too.

I'm a little concerned that prepping could be complicated, since the nature of conversion depends on the current state of shareability, and there's a lot to prepare, everything from counting memory required for maple_tree allocation (and merging ranges in the maple_tree), and counting the number of pages required for undoing vmemmap optimization in the case of splitting...

And even after doing all the prep to eliminate errors, the unmapping could fail in TDX-specific cases anyway, which still needs to be handled.

Hence I'm hoping you'll consider to let TDX-specific failures be built-in and handled alongside other failures by getting help from the userspace VMM, and in the worst case letting the guest know the conversion failed.

I also appreciate comments or suggestions from anyone else!

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Quoted 11 lines
Quoted 11 lines
virt/kvm/guest_memfd.c +2 -1
@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,
 
 	list_for_each_entry(work, &work_list, list) {
 		rollback_stop_item = work;
-		ret = kvm_gmem_shareability_apply(inode, work, m);
+
+		ret = kvm_gmem_convert_execute_work(inode, work, shared);
 		if (ret)
 			break;
 	}
 
Quoted 14 lines

virt/kvm/guest_memfd.c static int kvm_gmem_convert_range(struct file *file, pgoff_t start, · line 385

Quoted 12 lines
virt/kvm/guest_memfd.c +5 -3
 	if (ret) {
-		m = shared ? SHAREABILITY_GUEST : SHAREABILITY_ALL;
 		list_for_each_entry(work, &work_list, list) {
+			int r;
+
+			r = kvm_gmem_convert_execute_work(inode, work, !shared);
+			WARN_ON(r);
+
 			if (work == rollback_stop_item)
 				break;
-
-			WARN_ON(kvm_gmem_shareability_apply(inode, work, m));

Could kvm_gmem_shareability_apply() fail here?

Yes, it could. If shareability cannot be updated, then we probably ran out of memory. Userspace VMM will probably get -ENOMEM set on some earlier ret and should handle that accordingly.

On -ENOMEM in a rollback, the host is in a very tough spot anyway, and a clean guest shutdown may be the only way out, hence this is a WARN and not returned to userspace.

Quoted 85 lines
Quoted 85 lines
virt/kvm/guest_memfd.c +78 -0
 		}
 	}
 
@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,
 	return ret;
 }
 
+#ifdef CONFIG_KVM_GMEM_HUGETLB
+
+static inline void __filemap_remove_folio_for_restructuring(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+
+	spin_lock(&mapping->host->i_lock);
+	xa_lock_irq(&mapping->i_pages);
+
+	__filemap_remove_folio(folio, NULL);
+
+	xa_unlock_irq(&mapping->i_pages);
+	spin_unlock(&mapping->host->i_lock);
+}
+
+/**
+ * filemap_remove_folio_for_restructuring() - Remove @folio from filemap for
+ * split/merge.
+ *
+ * @folio: the folio to be removed.
+ *
+ * Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless
+ * for guest_memfd), and skips call to ->free_folio() to maintain folio flags.
+ *
+ * Context: Expects only the filemap's refcounts to be left on the folio. Will
+ *          freeze these refcounts away so that no other users will interfere
+ *          with restructuring.
+ */
+static inline void filemap_remove_folio_for_restructuring(struct folio *folio)
+{
+	int filemap_refcount;
+
+	filemap_refcount = folio_nr_pages(folio);
+	while (!folio_ref_freeze(folio, filemap_refcount)) {
+		/*
+		 * At this point only filemap refcounts are expected, hence okay
+		 * to spin until speculative refcounts go away.
+		 */
+		WARN_ONCE(1, "Spinning on folio=%p refcount=%d", folio, folio_ref_count(folio));
+	}
+
+	folio_lock(folio);
+	__filemap_remove_folio_for_restructuring(folio);
+	folio_unlock(folio);
+}
+
+/**
+ * kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode.
+ *
+ * @inode: inode containing the folio.
+ * @folio: folio to be split.
+ *
+ * Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap
+ * and add back the split folios.
+ *
+ * Context: Expects that before this call, folio's refcount is just the
+ *          filemap's refcounts. After this function returns, the split folios'
+ *          refcounts will also be filemap's refcounts.
+ * Return: 0 on success or negative error otherwise.
+ */
+static int kvm_gmem_split_folio_in_filemap(struct inode *inode, struct folio *folio)
+{
+	size_t orig_nr_pages;
+	pgoff_t orig_index;
+	size_t i, j;
+	int ret;
+
+	orig_nr_pages = folio_nr_pages(folio);
+	if (orig_nr_pages == 1)
+		return 0;
+
+	orig_index = folio->index;
+
+	filemap_remove_folio_for_restructuring(folio);
+
+	ret = kvm_gmem_allocator_ops(inode)->split_folio(folio);
+	if (ret)
+		goto err;
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 691

Quoted 6 lines
virt/kvm/guest_memfd.c +6 -0
+
+	for (i = 0; i < orig_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(folio, i));
+
+		ret = __kvm_gmem_filemap_add_folio(inode->i_mapping, f,
+						   orig_index + i);

Why does the failure of __kvm_gmem_filemap_add_folio() here lead to rollback, while the failure of the one under rollback only triggers WARN_ON()?

Mostly because I don't really have a choice on rollback. On rollback we try to restore the merged folio back into the filemap, and if we couldn't, the host is probably in rather bad shape in terms of memory availability and there may not be many options for the userspace VMM.

Perhaps the different possible errors from __kvm_gmem_filemap_add_folio() in both should be handled differently. Do you have any suggestions on that?

Quoted 81 lines
Quoted 81 lines
virt/kvm/guest_memfd.c +81 -0
+		if (ret)
+			goto rollback;
+	}
+
+	return ret;
+
+rollback:
+	for (j = 0; j < i; ++j) {
+		struct folio *f = page_folio(folio_page(folio, j));
+
+		filemap_remove_folio_for_restructuring(f);
+	}
+
+	kvm_gmem_allocator_ops(inode)->merge_folio(folio);
+err:
+	WARN_ON(__kvm_gmem_filemap_add_folio(inode->i_mapping, folio, orig_index));
+
+	return ret;
+}
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{
+	size_t to_nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_page(priv);
+
+	if (kvm_gmem_has_some_shared(inode, folio->index, to_nr_pages))
+		return kvm_gmem_split_folio_in_filemap(inode, folio);
+
+	return 0;
+}
+
+/**
+ * kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in
+ * @inode.
+ *
+ * @inode: inode containing the folio.
+ * @first_folio: first folio among folios to be merged.
+ *
+ * Will clean up subfolios from filemap and add back the merged folio.
+ *
+ * Context: Expects that before this call, all subfolios only have filemap
+ *          refcounts. After this function returns, the merged folio will only
+ *          have filemap refcounts.
+ * Return: 0 on success or negative error otherwise.
+ */
+static int kvm_gmem_merge_folio_in_filemap(struct inode *inode,
+					   struct folio *first_folio)
+{
+	size_t to_nr_pages;
+	pgoff_t index;
+	void *priv;
+	size_t i;
+	int ret;
+
+	index = first_folio->index;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+	if (folio_nr_pages(first_folio) == to_nr_pages)
+		return 0;
+
+	for (i = 0; i < to_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(first_folio, i));
+
+		filemap_remove_folio_for_restructuring(f);
+	}
+
+	kvm_gmem_allocator_ops(inode)->merge_folio(first_folio);
+
+	ret = __kvm_gmem_filemap_add_folio(inode->i_mapping, first_folio, index);
+	if (ret)
+		goto err_split;
+
+	return ret;
Quoted 10 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 775

Quoted 3 lines
virt/kvm/guest_memfd.c +3 -0
+
+err_split:
+	WARN_ON(kvm_gmem_allocator_ops(inode)->split_folio(first_folio));

guestmem_hugetlb_split_folio() is possible to fail. e.g.
After the stash is freed by guestmem_hugetlb_unstash_free_metadata() in guestmem_hugetlb_merge_folio(), it's possible to get -ENOMEM for the stash allocation in guestmem_hugetlb_stash_metadata() in guestmem_hugetlb_split_folio().

Yes. This is also on the error path. In line with all the other error and rollback paths, I don't really have other options at this point, since on error, I probably ran out of memory, so I try my best to restore the original state but give up with a WARN otherwise.

Quoted 51 lines
Quoted 51 lines
virt/kvm/guest_memfd.c +51 -0
+	for (i = 0; i < to_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(first_folio, i));
+
+		WARN_ON(__kvm_gmem_filemap_add_folio(inode->i_mapping, f, index + i));
+	}
+
+	return ret;
+}
+
+static inline int kvm_gmem_try_merge_folio_in_filemap(struct inode *inode,
+						      struct folio *first_folio)
+{
+	size_t to_nr_pages;
+	void *priv;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (kvm_gmem_has_some_shared(inode, first_folio->index, to_nr_pages))
+		return 0;
+
+	return kvm_gmem_merge_folio_in_filemap(inode, first_folio);
+}
+
+static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
+						pgoff_t start, size_t nr_pages,
+						bool is_split_operation)
+{
+	size_t to_nr_pages;
+	pgoff_t index;
+	pgoff_t end;
+	void *priv;
+	int ret;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	end = start + nr_pages;
+
+	/* Round to allocator page size, to check all (huge) pages in range. */
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	start = round_down(start, to_nr_pages);
+	end = round_up(end, to_nr_pages);
+
+	for (index = start; index < end; index += to_nr_pages) {
+		struct folio *f;
+
+		f = filemap_get_folio(inode->i_mapping, index);
+		if (IS_ERR(f))
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833

Quoted 7 lines
virt/kvm/guest_memfd.c +7 -0
+			continue;
+
+		/* Leave just filemap's refcounts on the folio. */
+		folio_put(f);
+
+		if (is_split_operation)
+			ret = kvm_gmem_split_folio_in_filemap(inode, f);

kvm_gmem_try_split_folio_in_filemap()?

Here we know for sure that this was a private-to-shared conversion. Hence, we know that there are at least some shared parts in this huge page and we can skip checking that.

Quoted 3 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 836

Quoted 3 lines
virt/kvm/guest_memfd.c +3 -0
+		else
+			ret = kvm_gmem_try_merge_folio_in_filemap(inode, f);
+

For merge, we don't know if the entire huge page might perhaps contain some other shared subpages, hence we "try" to merge by first checking against shareability to find shared subpages.

Quoted 7 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 843

Quoted 7 lines
virt/kvm/guest_memfd.c +7 -0
+		if (ret)
+			goto rollback;
+	}
+	return ret;
+
+rollback:
+	for (index -= to_nr_pages; index >= start; index -= to_nr_pages) {

Note to self: the first index -= to_nr_pages was meant to skip the index that caused the failure, but this could cause an underflow if index = 0 when entering rollback. Need to fix this in the next revision.

Quoted 6 lines
Quoted 6 lines
virt/kvm/guest_memfd.c +6 -0
+		struct folio *f;
+
+		f = filemap_get_folio(inode->i_mapping, index);
+		if (IS_ERR(f))
+			continue;
+
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 856

Quoted 7 lines
virt/kvm/guest_memfd.c +7 -0
+		/* Leave just filemap's refcounts on the folio. */
+		folio_put(f);
+
+		if (is_split_operation)
+			WARN_ON(kvm_gmem_merge_folio_in_filemap(inode, f));
+		else
+			WARN_ON(kvm_gmem_split_folio_in_filemap(inode, f));

Is it safe to just leave WARN_ON()s in the rollback case?

Same as above. I don't think we have much of a choice.

Quoted 5 lines

Besides, are the kvm_gmem_merge_folio_in_filemap() and kvm_gmem_split_folio_in_filemap() here duplicated with the kvm_gmem_split_folio_in_filemap() and kvm_gmem_try_merge_folio_in_filemap() in the following "r = kvm_gmem_convert_execute_work(inode, work, !shared)"?

This handles the case where some pages in the range [start, start + nr_pages) were split and the failure was halfway through. I could call kvm_gmem_convert_execute_work() with !shared but that would go over all the folios again from the start.

Quoted 23 lines
Quoted 22 lines
virt/kvm/guest_memfd.c +22 -0
+	}
+
+	return ret;
+}
+
+#else
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{
+	return 0;
+}
+
+static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
+						pgoff_t start, size_t nr_pages,
+						bool is_split_operation)
+{
+	return 0;
+}
+
+#endif
+
#187 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Binbin Wu
Quoted 19 lines · Binbin Wu

On 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]

Quoted 4 lines
virt/kvm/guest_memfd.c +4 -0
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 724

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+	size_t to_nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_page(priv);
+
+	if (kvm_gmem_has_some_shared(inode, folio->index, to_nr_pages))

What if a huge page whose attribute is shared?

This checks if there are any shared pages in the range [folio->index, folio->index + to_nr_pages), so if the entire huge page is shared this function should also return true.

folio->index is the start of the merged huge page, and to_nr_pages is the number of pages in the merged huge page, so this should be querying exactly the entire huge page.

Note to self: rename kvm_gmem_has_some_shared() to kvm_gmem_has_any_shared() in the next revision.

Hope I answered your question! Let me know if I misunderstood your question.

Quoted 43 lines
Quoted 5 lines
virt/kvm/guest_memfd.c +5 -0
+		return kvm_gmem_split_folio_in_filemap(inode, folio);
+
+	return 0;
+}
+

[...]

Quoted 37 lines

static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)

virt/kvm/guest_memfd.c +8 -2
@@ -563,11 +1005,16 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  		return folio;
 
  	if (kvm_gmem_has_custom_allocator(inode)) {
-		void *p = kvm_gmem_allocator_private(inode);
+		size_t nr_pages;
+		void *p;
 
+		p = kvm_gmem_allocator_private(inode);
  		folio = kvm_gmem_allocator_ops(inode)->alloc_folio(p);
  		if (IS_ERR(folio))
  			return folio;
+
+		nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(p);
+		index_floor = round_down(index, nr_pages);
  	} else {
  		gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
 
@@ -580,10 +1027,11 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  			folio_put(folio);
  			return ERR_PTR(ret);
  		}
+
+		index_floor = index;
  	}
  	allocated_size = folio_size(folio);
 
-	index_floor = round_down(index, folio_nr_pages(folio));
  	ret = kvm_gmem_filemap_add_folio(inode->i_mapping, folio, index_floor);
  	if (ret) {
  		folio_put(folio);
@@ -600,6 +1048,13 @@ static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
  		return ERR_PTR(ret);
  	}
 
Quoted 8 lines

virt/kvm/guest_memfd.c static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index) · line 1054

Quoted 4 lines
virt/kvm/guest_memfd.c +4 -0
+	/* Leave just filemap's refcounts on folio. */
+	folio_put(folio);
+
+	ret = kvm_gmem_try_split_folio_in_filemap(inode, folio);

When !CONFIG_KVM_GMEM_SHARED_MEM, kvm_gmem_try_split_folio_in_filemap() is undefined.

Will fix this in the next revision. Thanks!

Quoted 8 lines
Quoted 7 lines
virt/kvm/guest_memfd.c +3 -0
+	if (ret)
+		goto err;
+
  	spin_lock(&inode->i_lock);
  	inode->i_blocks += allocated_size / 512;
  	spin_unlock(&inode->i_lock);

[...]

#13 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Michael Roth
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 11 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

I can move this change to the later patch. Thanks! Will fix in the next revision.

Quoted 9 lines

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

I guess we could also have userspace be careful not to do any allocation before converting.

Quoted 293 lines
Quoted 61 lines
Documentation/virt/kvm/api.rst +0 -0
 See KVM_SET_USER_MEMORY_REGION2 for additional details.
 
 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
index 4cc824a3a7c9..d7df312479aa 100644
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {
 #define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
 
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
+
 #define GUEST_MEMFD_FLAG_SUPPORT_SHARED	(1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE	(1UL << 1)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
virt/kvm/guest_memfd.c +22 -0
index 239d0f13dcc1..590932499eba 100644
@@ -4,6 +4,7 @@
 #include <linux/falloc.h>
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
+#include <linux/maple_tree.h>
 #include <linux/pseudo_fs.h>
 #include <linux/pagemap.h>
 
@@ -17,6 +18,24 @@ struct kvm_gmem {
 	struct list_head entry;
 };
 
+struct kvm_gmem_inode_private {
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	struct maple_tree shareability;
+#endif
+};
+
+enum shareability {
+	SHAREABILITY_GUEST = 1,	/* Only the guest can map (fault) folios in this range. */
+	SHAREABILITY_ALL = 2,	/* Both guest and host can fault folios in this range. */
+};
+
+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index);
+
+static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)
+{
+	return inode->i_mapping->i_private_data;
+}
+
 /**
  * folio_file_pfn - like folio_file_page, but return a pfn.
  * @folio: The folio which contains this index.
@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
 	return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
 }
 
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+				      loff_t size, u64 flags)
+{
+	enum shareability m;
+	pgoff_t last;
+
+	last = (size >> PAGE_SHIFT) - 1;
+	m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+						    SHAREABILITY_ALL;
+	return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+				 GFP_KERNEL);

One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via KVM_SET_MEMORY_ATTRIBUTES (which is the current QEMU default behavior).

I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.

Maybe it would make sense for KVM memory attributes too?

Quoted 135 lines
virt/kvm/guest_memfd.c +87 -1
+}
+
+static enum shareability kvm_gmem_shareability_get(struct inode *inode,
+						 pgoff_t index)
+{
+	struct maple_tree *mt;
+	void *entry;
+
+	mt = &kvm_gmem_private(inode)->shareability;
+	entry = mtree_load(mt, index);
+	WARN(!entry,
+	     "Shareability should always be defined for all indices in inode.");
+
+	return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+		return ERR_PTR(-EACCES);
+
+	return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+	return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	WARN_ONCE("Unexpected call to get shared folio.")
+	return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
 				    pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
 	filemap_invalidate_lock_shared(inode->i_mapping);
 
-	folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+	folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
 	if (IS_ERR(folio)) {
 		int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
 	.fallocate	= kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+	kfree(private);
+
+	free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	/*
+	 * mtree_destroy() can't be used within rcu callback, hence can't be
+	 * done in ->free_inode().
+	 */
+	if (private)
+		mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
 	.statfs		= simple_statfs,
+	.destroy_inode	= kvm_gmem_destroy_inode,
+	.free_inode	= kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 						      loff_t size, u64 flags)
 {
+	struct kvm_gmem_inode_private *private;
 	struct inode *inode;
+	int err;
 
 	inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
 	if (IS_ERR(inode))
 		return inode;
 
+	err = -ENOMEM;
+	private = kzalloc(sizeof(*private), GFP_KERNEL);
+	if (!private)
+		goto out;
+
+	mt_init(&private->shareability);
+	inode->i_mapping->i_private_data = private;
+
+	err = kvm_gmem_shareability_setup(private, size, flags);
+	if (err)
+		goto out;
+
 	inode->i_private = (void *)(unsigned long)flags;
 	inode->i_op = &kvm_gmem_iops;
 	inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
 	return inode;
+
+out:
+	iput(inode);
+
+	return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
 	if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
 		valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+	if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+		valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
 	if (flags & ~valid_flags)
 		return -EINVAL;
 

virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964

Quoted 5 lines
virt/kvm/guest_memfd.c +2 -0
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 	if (!file)
 		return -EFAULT;
 
+	filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+

I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new SHAREABILITY_GUEST_PREPARED state) the SHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPARED transition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.

I was originally planning on introducing a new rw_semaphore with similar semantics to the rw_lock that Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle setting SHAREABILITY_GUEST_PREPARED within fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.

They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.

I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:

KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes

but figured I'd mention it here in case there are other things to consider on the locking front.

Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.

-Mike

[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/

Quoted 16 lines
virt/kvm/guest_memfd.c +1 -1
 	folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
 	if (IS_ERR(folio)) {
 		r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		*page = folio_file_page(folio, index);
 	else
 		folio_put(folio);
-
 out:
+	filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
 	fput(file);
 	return r;
 }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#25 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Michael Roth
Quoted 1 line · Michael Roth

On Wed, May 14, 2025 at 04:41:41PM -0700, Ackerley Tng wrote:

Missed out responses on the second two comments!

[...]

Quoted 19 lines

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63

Quoted 13 lines
virt/kvm/guest_memfd.c +13 -0
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,
+				      loff_t size, u64 flags)
+{
+	enum shareability m;
+	pgoff_t last;
+
+	last = (size >> PAGE_SHIFT) - 1;
+	m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+						    SHAREABILITY_ALL;
+	return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+				 GFP_KERNEL);

One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via KVM_SET_MEMORY_ATTRIBUTES (which is the current QEMU default behavior).

Quoted 4 lines

I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.

We discussed this at the guest_memfd upstream call, and I believe the current position is to go with maple_trees. Thanks for bringing this up!

Quoted 2 lines

Maybe it would make sense for KVM memory attributes too?

I think so, but I haven't had the chance to work on that.

Quoted 2 lines
Quoted 2 lines
(quoted diff) +2 -0
+}
+

[...]

Quoted 6 lines

virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964

Quoted 6 lines
virt/kvm/guest_memfd.c +2 -0
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 	if (!file)
 		return -EFAULT;
 
+	filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+

In this RFC, the filemap_invalidate_lock() was basically used to serialize everything that could modify shareability.

Quoted 41 lines

I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new SHAREABILITY_GUEST_PREPARED state) the SHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPARED transition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.

I was originally planning on introducing a new rw_semaphore with similar semantics to the rw_lock that Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle setting SHAREABILITY_GUEST_PREPARED within fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.

They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.

I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:

KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes

Quoted 2 lines

but figured I'd mention it here in case there are other things to consider on the locking front.

We discussed this a little at the last guest_memfd call: I'll summarize the question I raised during the call here in text. :)

Today in guest_memfd the "prepared" and "zeroed" concepts are tracked with the folio's uptodate flag.

Preparation is only used by SNP today and TDX does the somewhat equivalent "preparation" at time of mapping into the guest page table.

Can we do SNP's preparation at some other point in time and not let the "prepared" state be handled by guest_memfd at all?

This might simplify locking too, so preparedness would be locked whenever SNP needs to, independently of shareability tracking.

Also, this might simplify the routines that use kvm_gmem_populate(), perhaps remove the need for kvm_gmem_populate()? The current callers are basically using kvm_gmem_populate() to allocate pages, why not call kvm_gmem_get_folio() to do the allocation?

Another tangential point: it's hard to use the uptodate flag for tracking preparedness, since when there are huge pages, the uptodate flag can only indicate if the entire folio is prepared, but a user of the memory might only have part of the folio prepared.

Quoted 27 lines

Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.

-Mike

[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/

Quoted 16 lines
virt/kvm/guest_memfd.c +1 -1
 	folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
 	if (IS_ERR(folio)) {
 		r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		*page = folio_file_page(folio, index);
 	else
 		folio_put(folio);
-
 out:
+	filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
 	fput(file);
 	return r;
 }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#133 lore raw

Re: [RFC PATCH v2 22/51] mm: hugetlb: Refactor hugetlb allocation functions

In reply to Ira Weiny
Quoted 39 lines · Ira Weiny
Quoted 10 lines · Ackerley Tng

Refactor dequeue_hugetlb_folio() and alloc_surplus_hugetlb_folio() to take mpol, nid and nodemask. This decouples allocation of a folio from a vma.

Change-Id I890fb46fe8c6349383d8cf89befc68a4994eb416
---
 mm/hugetlb.c | 64 ++++++++++++++++++++++++----------------------------
 1 file changed, 30 insertions(+), 34 deletions(-)

[snip]

Quoted 25 lines
mm/hugetlb.c +5 -1
@@ -2993,6 +2974,11 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 	int ret, idx;
 	struct hugetlb_cgroup *h_cg = NULL;
 	gfp_t gfp = htlb_alloc_mask(h) | __GFP_RETRY_MAYFAIL;
+	struct mempolicy *mpol;
+	nodemask_t *nodemask;
+	gfp_t gfp_mask;
+	pgoff_t ilx;
+	int nid;
 
 	idx = hstate_index(h);
 
@@ -3032,7 +3018,6 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 
 		subpool_reservation_exists = npages_req == 0;
 	}
-
 	reservation_exists = vma_reservation_exists || subpool_reservation_exists;
 
 	/*
@@ -3048,21 +3033,30 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 			goto out_subpool_put;
 	}
 
Quoted 6 lines

mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3036

Quoted 1 line
mm/hugetlb.c +1 -0
+	mpol = get_vma_policy(vma, addr, h->order, &ilx);

Why does the memory policy need to be acquired here instead of after the cgroup charge? AFAICT this is not needed and would at least eliminate 1 of the error conditions puts.

I was hoping that by taking this early, the upcoming refactoring out of hugetlb_alloc_folio() will look like a nice, clean removal of the middle of this function, leaving acquiring of the mpol and mpol_cond_put() in-place.

In the next revision I'm splitting up the refactoring in this patch further so if this is still an issue in some number of revisions' time, I can fix this.

Quoted 11 lines

mm/hugetlb.c struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, · line 3040

Quoted 5 lines
mm/hugetlb.c +3 -1
+
 	ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
-	if (ret)
+	if (ret) {
+		mpol_cond_put(mpol);
                ^^^^
		here

All that said I think the use of some new cleanup macros could really help a lot of this code.

I'm happy to try that out...

Quoted 2 lines

What do folks in this area of the kernel think of those?

not sure though.

Quoted 3 lines

Ira

[snip]

#136 lore raw

Re: [RFC PATCH v2 23/51] mm: hugetlb: Refactor out hugetlb_alloc_folio()

In reply to Ira Weiny
Quoted 71 lines · Ira Weiny
Quoted 31 lines · Ackerley Tng

Refactor out hugetlb_alloc_folio() from alloc_hugetlb_folio(), which handles allocation of a folio and cgroup charging.

Other than flags to control charging in the allocation process, hugetlb_alloc_folio() also has parameters for memory policy.

This refactoring as a whole decouples the hugetlb page allocation from hugetlbfs, (1) where the subpool is stored at the fs mount, (2) reservations are made during mmap and stored in the vma, and (3) mpol must be stored at vma->vm_policy (4) a vma must be used for allocation even if the pages are not meant to be used by host process.

This decoupling will allow hugetlb_alloc_folio() to be used by guest_memfd in later patches. In guest_memfd, (1) a subpool is created per-fd and is stored on the inode, (2) no vma-related reservations are used (3) mpol may not be associated with a vma since (4) for private pages, the pages will not be mappable to userspace and hence have to associated vmas.

This could hopefully also open hugetlb up as a more generic source of hugetlb pages that are not bound to hugetlbfs, with the complexities of userspace/mmap/vma-related reservations contained just to hugetlbfs.

Change-Id I60528f246341268acbf0ed5de7752ae2cacbef93
---
 include/linux/hugetlb.h |  12 +++
 mm/hugetlb.c            | 192 ++++++++++++++++++++++------------------
 2 files changed, 118 insertions(+), 86 deletions(-)

[snip]

Quoted 24 lines
mm/hugetlb.c +23 -0
+/**
+ * hugetlb_alloc_folio() - Allocates a hugetlb folio.
+ *
+ * @h: struct hstate to allocate from.
+ * @mpol: struct mempolicy to apply for this folio allocation.
+ * @ilx: Interleave index for interpretation of @mpol.
+ * @charge_cgroup_rsvd: Set to true to charge cgroup reservation.
+ * @use_existing_reservation: Set to true if this allocation should use an
+ *                            existing hstate reservation.
+ *
+ * This function handles cgroup and global hstate reservations. VMA-related
+ * reservations and subpool debiting must be handled by the caller if necessary.
+ *
+ * Return: folio on success or negated error otherwise.
+ */
+struct folio *hugetlb_alloc_folio(struct hstate *h, struct mempolicy *mpol,
+				  pgoff_t ilx, bool charge_cgroup_rsvd,
+				  bool use_existing_reservation)
+{
+	unsigned int nr_pages = pages_per_huge_page(h);
+	struct hugetlb_cgroup *h_cg = NULL;
+	struct folio *folio = NULL;
+	nodemask_t *nodemask;

mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 2989

Quoted 10 lines
mm/hugetlb.c +10 -0
+	gfp_t gfp_mask;
+	int nid;
+	int idx;
+	int ret;
+
+	idx = hstate_index(h);
+
+	if (charge_cgroup_rsvd) {
+		if (hugetlb_cgroup_charge_cgroup_rsvd(idx, nr_pages, &h_cg))
+			goto out;

Why not just return here?

Quoted 2 lines
			return ERR_PTR(-ENOSPC);

I wanted to consistently exit the function on errors at the same place, and also make this refactoring look like I just took the middle of alloc_hugetlb_folio() out as much as possible.

Quoted 52 lines
Quoted 52 lines
mm/hugetlb.c +52 -0
+	}
+
+	if (hugetlb_cgroup_charge_cgroup(idx, nr_pages, &h_cg))
+		goto out_uncharge_cgroup_reservation;
+
+	gfp_mask = htlb_alloc_mask(h);
+	nid = policy_node_nodemask(mpol, gfp_mask, ilx, &nodemask);
+
+	spin_lock_irq(&hugetlb_lock);
+
+	if (use_existing_reservation || available_huge_pages(h))
+		folio = dequeue_hugetlb_folio(h, gfp_mask, mpol, nid, nodemask);
+
+	if (!folio) {
+		spin_unlock_irq(&hugetlb_lock);
+		folio = alloc_surplus_hugetlb_folio(h, gfp_mask, mpol, nid, nodemask);
+		if (!folio)
+			goto out_uncharge_cgroup;
+		spin_lock_irq(&hugetlb_lock);
+		list_add(&folio->lru, &h->hugepage_activelist);
+		folio_ref_unfreeze(folio, 1);
+		/* Fall through */
+	}
+
+	if (use_existing_reservation) {
+		folio_set_hugetlb_restore_reserve(folio);
+		h->resv_huge_pages--;
+	}
+
+	hugetlb_cgroup_commit_charge(idx, nr_pages, h_cg, folio);
+
+	if (charge_cgroup_rsvd)
+		hugetlb_cgroup_commit_charge_rsvd(idx, nr_pages, h_cg, folio);
+
+	spin_unlock_irq(&hugetlb_lock);
+
+	gfp_mask = htlb_alloc_mask(h) | __GFP_RETRY_MAYFAIL;
+	ret = mem_cgroup_charge_hugetlb(folio, gfp_mask);
+	/*
+	 * Unconditionally increment NR_HUGETLB here. If it turns out that
+	 * mem_cgroup_charge_hugetlb failed, then immediately free the page and
+	 * decrement NR_HUGETLB.
+	 */
+	lruvec_stat_mod_folio(folio, NR_HUGETLB, pages_per_huge_page(h));
+
+	if (ret == -ENOMEM) {
+		free_huge_folio(folio);
+		return ERR_PTR(-ENOMEM);
+	}
+
+	return folio;
+
Quoted 9 lines

mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3046

Quoted 5 lines
mm/hugetlb.c +5 -0
+out_uncharge_cgroup:
+	hugetlb_cgroup_uncharge_cgroup(idx, nr_pages, h_cg);
+out_uncharge_cgroup_reservation:
+	if (charge_cgroup_rsvd)
+		hugetlb_cgroup_uncharge_cgroup_rsvd(idx, nr_pages, h_cg);

I find the direct copy of the unwind logic from alloc_hugetlb_folio() cumbersome and it seems like a good opportunity to clean it up.

I really wanted to make this refactoring look like I just took the middle of alloc_hugetlb_folio() out as much as possible, to make it obvious and understandable. I think the cleanup can be a separate patch (series?)

Quoted 6 lines

mm/hugetlb.c void wait_for_freed_hugetlb_folios(void) · line 3049

Quoted 3 lines
mm/hugetlb.c +3 -0
+out:
+	folio = ERR_PTR(-ENOSPC);
+	goto out;

Endless loop?

Thanks, this should have been

return folio;

Quoted 3 lines

Ira

[snip]

#185 lore raw

Re: [RFC PATCH v2 38/51] KVM: guest_memfd: Split allocator pages for guest_memfd use

In reply to Ackerley Tng
Quoted 68 lines · Ackerley Tng
Quoted 14 lines · Yan Zhao
Quoted 13 lines · Ackerley Tng
virt/kvm/guest_memfd.c +13 -0
+static int kvm_gmem_convert_execute_work(struct inode *inode,
+					 struct conversion_work *work,
+					 bool to_shared)
+{
+	enum shareability m;
+	int ret;
+
+	m = to_shared ? SHAREABILITY_ALL : SHAREABILITY_GUEST;
+	ret = kvm_gmem_shareability_apply(inode, work, m);
+	if (ret)
+		return ret;
+	/*
+	 * Apply shareability first so split/merge can operate on new
Quoted 8 lines

virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 510

Quoted 8 lines
virt/kvm/guest_memfd.c +8 -0
+	 * shareability state.
+	 */
+	ret = kvm_gmem_restructure_folios_in_range(
+		inode, work->start, work->nr_pages, to_shared);
+
+	return ret;
+}
+

Hi Yan,

Thanks for your thorough reviews and your alternative suggestion in the other discussion at [1]! I'll try to bring the conversion-related parts of that discussion over here.

Quoted 3 lines

virt/kvm/guest_memfd.c static int kvm_gmem_convert_should_proceed(struct inode *inode, · line 513

Quoted 3 lines

static int kvm_gmem_convert_range(struct file *file, pgoff_t start,

virt/kvm/guest_memfd.c +0 -0
 				  size_t nr_pages, bool shared,
 				  pgoff_t *error_index)

The guiding principle I was using for the conversion ioctls is

* Have the shareability updates and any necessary page restructuring (aka splitting/merging) either fully complete for not at all by the time the conversion ioctl returns.
* Any unmapping (from host or guest page tables) will not be re-mapped on errors.
* Rollback undoes changes if conversion failed, and in those cases any errors are turned into WARNings.

The rationale is that we want page sizes to be in sync with shareability so that any faults after the (successful or failed) conversion will not wrongly map in a larger page than allowed and cause any host crashes.

We considered 3 places where the memory can be mapped for conversions:

1. Host page tables
2. Guest page tables
3. IOMMU page tables

Unmapping from host page tables is the simplest case. We unmap any shared ranges from the host page tables. Any accesses after the failed conversion would just fault the memory back in and proceed as usual.

guest_memfd memory is not unmapped from IOMMUs in conversions. This case is handled because IOMMU mappings hold refcounts. After unmapping from the host, we check for unexpected refcounts and fail if there are unexpected refcounts.

We also unmap from guest page tables. Considering failed conversions, if the pages are shared, we're good since the next time the guest accesses the page, the page will be faulted in as before.

Quoted 7 lines

If the pages are private, on the next guest access, the pages will be faulted in again as well. This is fine for software-protected VMs IIUC.

For TDX (and SNP) IIUC the memory would have been cleared, and the memory would also need to be re-accepted. I was thinking that this is by design, since when a TDX guest requests a conversion it knows that the contents is not to be used again.

This is not guaranteed.

On private-to-shared conversion failure, the guest may leak the page or release the page. If the guest chooses the latter (e.g. in kvmclock_init_mem(), kvm_arch_ptp_init()), the page is regarded as private by the guest OS. Re-acceptance then will not happen before the guest access.

So, it's better for host to keep the original SEPT if private-to-shared conversion fails.

Quoted 4 lines

The userspace VMM is obligated to keep trying convert and if it gives up, userspace VMM should inform the guest that the conversion failed. The guest should handle conversion failures too and not assume that conversion always succeeds.

I don't think relying userspace to keep trying convert endlessly is a good design.

Quoted 7 lines

Putting TDX aside for a moment, so far, there are a few ways this conversion could fail:

a. Unexpected refcounts. Userspace should clear up the unexpected
refcounts and report failure to the guest if it can't for whatever reason.

This is acceptable. Unmapping shared mappings in the primary MMU or shared EPT is harmless.

Quoted 5 lines

b. ENOMEM because (i) we ran out of memory updating the shareability
maple_tree or (ii) since splitting involves allocating more memory for struct pages and we ran out of memory there. In this case the userspace VMM gets -ENOMEM and can make more memory available and then retry, or if it can't, also report failure to the guest.

This is unacceptable. Why not reserve the memory before determining to start the real conversion? If -ENOMEM is returned before executing the conversion, we don't need to handle the restore error, which is impossible to be handled gracefully.

Quoted 3 lines

TDX introduces TDX-specific conversion failures (see discussion at [1]), which this series doesn't handle, but I think we still have a line of sight to handle new errors.

The errors can be divided into two categories:
(1) errors due to kernel bugs
(2) errors that could occur in normal or bad conditions (e.g. the -ENOMEM)

We can't handle (1), so BUG_ON or leaking memory is allowed. However, we should try to avoid (2) especially in the rollback path.

Quoted 3 lines

In the other thread [1], I was proposing to have guest_memfd decide what to do on errors, but I think that might be baking more TDX-specific details into guest_memfd/KVM, and perhaps this is better:

The TDX-specific errors in the unmapping path is of category (1). So, we hope to resolve it by BUG_ON and leaking the memory.

The other conversion error for TDX is for splitting memory. We hope to do the splitting before executing the real conversion.

Please check the proposal details at
https://lore.kernel.org/all/aE%[email protected].

Quoted 164 lines

We could return the errors to userspace and let userspace determine what to do. For retryable errors (as determined by userspace), it should do what it needs to do, and retry. For errors like TDX being unable to reclaim the memory, it could tell guest_memfd to leak that memory.

If userspace gives up, it should report conversion failure to the guest if userspace thinks the guest can continue (to a clean shutdown or otherwise). If something terrible happened during conversion, then userspace might have to exit itself or shutdown the host.

In [2], for TDX-specific conversion failures, you proposed prepping to eliminate errors and exiting early on failure, then actually unmapping. I think that could work too.

I'm a little concerned that prepping could be complicated, since the nature of conversion depends on the current state of shareability, and there's a lot to prepare, everything from counting memory required for maple_tree allocation (and merging ranges in the maple_tree), and counting the number of pages required for undoing vmemmap optimization in the case of splitting...

And even after doing all the prep to eliminate errors, the unmapping could fail in TDX-specific cases anyway, which still needs to be handled.

Hence I'm hoping you'll consider to let TDX-specific failures be built-in and handled alongside other failures by getting help from the userspace VMM, and in the worst case letting the guest know the conversion failed.

I also appreciate comments or suggestions from anyone else!

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Quoted 11 lines
Quoted 11 lines
virt/kvm/guest_memfd.c +2 -1
@@ -371,18 +539,21 @@ static int kvm_gmem_convert_range(struct file *file, pgoff_t start,
 
 	list_for_each_entry(work, &work_list, list) {
 		rollback_stop_item = work;
-		ret = kvm_gmem_shareability_apply(inode, work, m);
+
+		ret = kvm_gmem_convert_execute_work(inode, work, shared);
 		if (ret)
 			break;
 	}
 
Quoted 14 lines

virt/kvm/guest_memfd.c static int kvm_gmem_convert_range(struct file *file, pgoff_t start, · line 385

Quoted 12 lines
virt/kvm/guest_memfd.c +5 -3
 	if (ret) {
-		m = shared ? SHAREABILITY_GUEST : SHAREABILITY_ALL;
 		list_for_each_entry(work, &work_list, list) {
+			int r;
+
+			r = kvm_gmem_convert_execute_work(inode, work, !shared);
+			WARN_ON(r);
+
 			if (work == rollback_stop_item)
 				break;
-
-			WARN_ON(kvm_gmem_shareability_apply(inode, work, m));

Could kvm_gmem_shareability_apply() fail here?

Yes, it could. If shareability cannot be updated, then we probably ran out of memory. Userspace VMM will probably get -ENOMEM set on some earlier ret and should handle that accordingly.

On -ENOMEM in a rollback, the host is in a very tough spot anyway, and a clean guest shutdown may be the only way out, hence this is a WARN and not returned to userspace.

Quoted 85 lines
Quoted 85 lines
virt/kvm/guest_memfd.c +78 -0
 		}
 	}
 
@@ -434,6 +605,277 @@ static int kvm_gmem_ioctl_convert_range(struct file *file,
 	return ret;
 }
 
+#ifdef CONFIG_KVM_GMEM_HUGETLB
+
+static inline void __filemap_remove_folio_for_restructuring(struct folio *folio)
+{
+	struct address_space *mapping = folio->mapping;
+
+	spin_lock(&mapping->host->i_lock);
+	xa_lock_irq(&mapping->i_pages);
+
+	__filemap_remove_folio(folio, NULL);
+
+	xa_unlock_irq(&mapping->i_pages);
+	spin_unlock(&mapping->host->i_lock);
+}
+
+/**
+ * filemap_remove_folio_for_restructuring() - Remove @folio from filemap for
+ * split/merge.
+ *
+ * @folio: the folio to be removed.
+ *
+ * Similar to filemap_remove_folio(), but skips LRU-related calls (meaningless
+ * for guest_memfd), and skips call to ->free_folio() to maintain folio flags.
+ *
+ * Context: Expects only the filemap's refcounts to be left on the folio. Will
+ *          freeze these refcounts away so that no other users will interfere
+ *          with restructuring.
+ */
+static inline void filemap_remove_folio_for_restructuring(struct folio *folio)
+{
+	int filemap_refcount;
+
+	filemap_refcount = folio_nr_pages(folio);
+	while (!folio_ref_freeze(folio, filemap_refcount)) {
+		/*
+		 * At this point only filemap refcounts are expected, hence okay
+		 * to spin until speculative refcounts go away.
+		 */
+		WARN_ONCE(1, "Spinning on folio=%p refcount=%d", folio, folio_ref_count(folio));
+	}
+
+	folio_lock(folio);
+	__filemap_remove_folio_for_restructuring(folio);
+	folio_unlock(folio);
+}
+
+/**
+ * kvm_gmem_split_folio_in_filemap() - Split @folio within filemap in @inode.
+ *
+ * @inode: inode containing the folio.
+ * @folio: folio to be split.
+ *
+ * Split a folio into folios of size PAGE_SIZE. Will clean up folio from filemap
+ * and add back the split folios.
+ *
+ * Context: Expects that before this call, folio's refcount is just the
+ *          filemap's refcounts. After this function returns, the split folios'
+ *          refcounts will also be filemap's refcounts.
+ * Return: 0 on success or negative error otherwise.
+ */
+static int kvm_gmem_split_folio_in_filemap(struct inode *inode, struct folio *folio)
+{
+	size_t orig_nr_pages;
+	pgoff_t orig_index;
+	size_t i, j;
+	int ret;
+
+	orig_nr_pages = folio_nr_pages(folio);
+	if (orig_nr_pages == 1)
+		return 0;
+
+	orig_index = folio->index;
+
+	filemap_remove_folio_for_restructuring(folio);
+
+	ret = kvm_gmem_allocator_ops(inode)->split_folio(folio);
+	if (ret)
+		goto err;
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 691

Quoted 6 lines
virt/kvm/guest_memfd.c +6 -0
+
+	for (i = 0; i < orig_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(folio, i));
+
+		ret = __kvm_gmem_filemap_add_folio(inode->i_mapping, f,
+						   orig_index + i);

Why does the failure of __kvm_gmem_filemap_add_folio() here lead to rollback, while the failure of the one under rollback only triggers WARN_ON()?

Quoted 4 lines

Mostly because I don't really have a choice on rollback. On rollback we try to restore the merged folio back into the filemap, and if we couldn't, the host is probably in rather bad shape in terms of memory availability and there may not be many options for the userspace VMM.

Out of memory is not a good excuse for rollback error.

Quoted 3 lines

Perhaps the different possible errors from __kvm_gmem_filemap_add_folio() in both should be handled differently. Do you have any suggestions on that?

Maybe reserving the memory or ruling out other factors that could lead to conversion failure before executing the conversion?
Then BUG_ON the if the failure is cause by a bug.

Quoted 158 lines
Quoted 81 lines
Quoted 81 lines
virt/kvm/guest_memfd.c +81 -0
+		if (ret)
+			goto rollback;
+	}
+
+	return ret;
+
+rollback:
+	for (j = 0; j < i; ++j) {
+		struct folio *f = page_folio(folio_page(folio, j));
+
+		filemap_remove_folio_for_restructuring(f);
+	}
+
+	kvm_gmem_allocator_ops(inode)->merge_folio(folio);
+err:
+	WARN_ON(__kvm_gmem_filemap_add_folio(inode->i_mapping, folio, orig_index));
+
+	return ret;
+}
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{
+	size_t to_nr_pages;
+	void *priv;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_page(priv);
+
+	if (kvm_gmem_has_some_shared(inode, folio->index, to_nr_pages))
+		return kvm_gmem_split_folio_in_filemap(inode, folio);
+
+	return 0;
+}
+
+/**
+ * kvm_gmem_merge_folio_in_filemap() - Merge @first_folio within filemap in
+ * @inode.
+ *
+ * @inode: inode containing the folio.
+ * @first_folio: first folio among folios to be merged.
+ *
+ * Will clean up subfolios from filemap and add back the merged folio.
+ *
+ * Context: Expects that before this call, all subfolios only have filemap
+ *          refcounts. After this function returns, the merged folio will only
+ *          have filemap refcounts.
+ * Return: 0 on success or negative error otherwise.
+ */
+static int kvm_gmem_merge_folio_in_filemap(struct inode *inode,
+					   struct folio *first_folio)
+{
+	size_t to_nr_pages;
+	pgoff_t index;
+	void *priv;
+	size_t i;
+	int ret;
+
+	index = first_folio->index;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+	if (folio_nr_pages(first_folio) == to_nr_pages)
+		return 0;
+
+	for (i = 0; i < to_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(first_folio, i));
+
+		filemap_remove_folio_for_restructuring(f);
+	}
+
+	kvm_gmem_allocator_ops(inode)->merge_folio(first_folio);
+
+	ret = __kvm_gmem_filemap_add_folio(inode->i_mapping, first_folio, index);
+	if (ret)
+		goto err_split;
+
+	return ret;
Quoted 10 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 775

Quoted 3 lines
virt/kvm/guest_memfd.c +3 -0
+
+err_split:
+	WARN_ON(kvm_gmem_allocator_ops(inode)->split_folio(first_folio));

guestmem_hugetlb_split_folio() is possible to fail. e.g.
After the stash is freed by guestmem_hugetlb_unstash_free_metadata() in guestmem_hugetlb_merge_folio(), it's possible to get -ENOMEM for the stash allocation in guestmem_hugetlb_stash_metadata() in guestmem_hugetlb_split_folio().

Yes. This is also on the error path. In line with all the other error and rollback paths, I don't really have other options at this point, since on error, I probably ran out of memory, so I try my best to restore the original state but give up with a WARN otherwise.

Quoted 51 lines
Quoted 51 lines
virt/kvm/guest_memfd.c +51 -0
+	for (i = 0; i < to_nr_pages; ++i) {
+		struct folio *f = page_folio(folio_page(first_folio, i));
+
+		WARN_ON(__kvm_gmem_filemap_add_folio(inode->i_mapping, f, index + i));
+	}
+
+	return ret;
+}
+
+static inline int kvm_gmem_try_merge_folio_in_filemap(struct inode *inode,
+						      struct folio *first_folio)
+{
+	size_t to_nr_pages;
+	void *priv;
+
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	if (kvm_gmem_has_some_shared(inode, first_folio->index, to_nr_pages))
+		return 0;
+
+	return kvm_gmem_merge_folio_in_filemap(inode, first_folio);
+}
+
+static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
+						pgoff_t start, size_t nr_pages,
+						bool is_split_operation)
+{
+	size_t to_nr_pages;
+	pgoff_t index;
+	pgoff_t end;
+	void *priv;
+	int ret;
+
+	if (!kvm_gmem_has_custom_allocator(inode))
+		return 0;
+
+	end = start + nr_pages;
+
+	/* Round to allocator page size, to check all (huge) pages in range. */
+	priv = kvm_gmem_allocator_private(inode);
+	to_nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(priv);
+
+	start = round_down(start, to_nr_pages);
+	end = round_up(end, to_nr_pages);
+
+	for (index = start; index < end; index += to_nr_pages) {
+		struct folio *f;
+
+		f = filemap_get_folio(inode->i_mapping, index);
+		if (IS_ERR(f))
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 833

Quoted 7 lines
virt/kvm/guest_memfd.c +7 -0
+			continue;
+
+		/* Leave just filemap's refcounts on the folio. */
+		folio_put(f);
+
+		if (is_split_operation)
+			ret = kvm_gmem_split_folio_in_filemap(inode, f);

kvm_gmem_try_split_folio_in_filemap()?

Quoted 3 lines

Here we know for sure that this was a private-to-shared conversion. Hence, we know that there are at least some shared parts in this huge page and we can skip checking that.

Ok.

Quoted 7 lines
Quoted 3 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 836

Quoted 3 lines
virt/kvm/guest_memfd.c +3 -0
+		else
+			ret = kvm_gmem_try_merge_folio_in_filemap(inode, f);
+

For merge, we don't know if the entire huge page might perhaps contain some other shared subpages, hence we "try" to merge by first checking against shareability to find shared subpages.

Makes sense.

Quoted 11 lines
Quoted 7 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 843

Quoted 7 lines
virt/kvm/guest_memfd.c +7 -0
+		if (ret)
+			goto rollback;
+	}
+	return ret;
+
+rollback:
+	for (index -= to_nr_pages; index >= start; index -= to_nr_pages) {

Note to self: the first index -= to_nr_pages was meant to skip the index that caused the failure, but this could cause an underflow if index = 0 when entering rollback. Need to fix this in the next revision.

Yes :)

Quoted 52 lines
Quoted 6 lines
Quoted 6 lines
virt/kvm/guest_memfd.c +6 -0
+		struct folio *f;
+
+		f = filemap_get_folio(inode->i_mapping, index);
+		if (IS_ERR(f))
+			continue;
+
Quoted 9 lines

virt/kvm/guest_memfd.c static int kvm_gmem_ioctl_convert_range(struct file *file, · line 856

Quoted 7 lines
virt/kvm/guest_memfd.c +7 -0
+		/* Leave just filemap's refcounts on the folio. */
+		folio_put(f);
+
+		if (is_split_operation)
+			WARN_ON(kvm_gmem_merge_folio_in_filemap(inode, f));
+		else
+			WARN_ON(kvm_gmem_split_folio_in_filemap(inode, f));

Is it safe to just leave WARN_ON()s in the rollback case?

Same as above. I don't think we have much of a choice.

Quoted 5 lines

Besides, are the kvm_gmem_merge_folio_in_filemap() and kvm_gmem_split_folio_in_filemap() here duplicated with the kvm_gmem_split_folio_in_filemap() and kvm_gmem_try_merge_folio_in_filemap() in the following "r = kvm_gmem_convert_execute_work(inode, work, !shared)"?

This handles the case where some pages in the range [start, start + nr_pages) were split and the failure was halfway through. I could call kvm_gmem_convert_execute_work() with !shared but that would go over all the folios again from the start.

Quoted 23 lines
Quoted 22 lines
virt/kvm/guest_memfd.c +22 -0
+	}
+
+	return ret;
+}
+
+#else
+
+static inline int kvm_gmem_try_split_folio_in_filemap(struct inode *inode,
+						      struct folio *folio)
+{
+	return 0;
+}
+
+static int kvm_gmem_restructure_folios_in_range(struct inode *inode,
+						pgoff_t start, size_t nr_pages,
+						bool is_split_operation)
+{
+	return 0;
+}
+
+#endif
+
#223 lore raw
In reply to Ackerley Tng
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Currently, we tested the initial memory region using the in-place conversion version of guest_memfd as backend by modifying QEMU to add an extra anonymous backend to hold the source initial content in shared memory. The extra anonymous backend is freed after finishing ading the initial memory region.

This issue is benign for TDX, as the initial memory region can also utilize the traditional guest_memfd, which only allows 4KB mappings. This is acceptable for now, as the initial memory region typically involves a small amount of memory, and we may not enable huge pages for ranges covered by the initial memory region in the near future.

#224 lore raw
Quoted 20 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

Quoted 10 lines

Currently, we tested the initial memory region using the in-place conversion version of guest_memfd as backend by modifying QEMU to add an extra anonymous backend to hold the source initial content in shared memory. The extra anonymous backend is freed after finishing ading the initial memory region.

This issue is benign for TDX, as the initial memory region can also utilize the traditional guest_memfd, which only allows 4KB mappings. This is acceptable for now, as the initial memory region typically involves a small amount of memory, and we may not enable huge pages for ranges covered by the initial memory region in the near future.

#225 lore raw
Quoted 26 lines · Xiaoyao Li
Quoted 19 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page- support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Quoted 7 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.

#226 lore raw
Quoted 35 lines · Xiaoyao Li
Quoted 34 lines · Xiaoyao Li
Quoted 32 lines · Yan Zhao
Quoted 6 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

Quoted 7 lines

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at
https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-
support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build
time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory
and private target memory.

Therefore, userspace cannot store the initial content in shared memory at the
mmap-ed VA of a guest_memfd that performs in-place conversion between shared and
private memory. This is because the guest_memfd will first unmap a PFN in shared
page tables and then check for any extra refcount held for the shared PFN before
converting it to private.

Quoted 5 lines
Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

However, whenever there's a GUP in TDX to get the source page, there will be an extra page refcount.

Quoted 4 lines
Quoted 4 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

The conversion request here will be declined therefore.

Quoted 9 lines
Quoted 3 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.

#227 lore raw
Quoted 36 lines · Yan Zhao
Quoted 35 lines · Xiaoyao Li
Quoted 34 lines · Xiaoyao Li
Quoted 32 lines · Yan Zhao
Quoted 6 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

Quoted 7 lines

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at
https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-
support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build
time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory
and private target memory.

Therefore, userspace cannot store the initial content in shared memory at the
mmap-ed VA of a guest_memfd that performs in-place conversion between shared and
private memory. This is because the guest_memfd will first unmap a PFN in shared
page tables and then check for any extra refcount held for the shared PFN before
converting it to private.

Quoted 7 lines
Quoted 5 lines
Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

However, whenever there's a GUP in TDX to get the source page, there will be an extra page refcount.

The GUP in TDX happens after the gmem converts the page to private.

In the view of TDX, the physical page is converted to private already and it contains the initial content. But the content is not usable for TDX until TDX calls in-place PAGE.ADD

Quoted 16 lines
Quoted 4 lines
Quoted 4 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

The conversion request here will be declined therefore.

Quoted 9 lines
Quoted 3 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.

#228 lore raw
Quoted 39 lines · Xiaoyao Li
Quoted 38 lines · Yan Zhao
Quoted 37 lines · Xiaoyao Li
Quoted 36 lines · Xiaoyao Li
Quoted 23 lines · Yan Zhao
Quoted 6 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

Quoted 7 lines

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at
https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-
support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build
time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory
and private target memory.

Quoted 9 lines

Therefore, userspace cannot store the initial content in shared memory at the
mmap-ed VA of a guest_memfd that performs in-place conversion between shared and
private memory. This is because the guest_memfd will first unmap a PFN in shared
page tables and then check for any extra refcount held for the shared PFN before
converting it to private.

I have an idea.

Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
Quoted 3 lines

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

However, whenever there's a GUP in TDX to get the source page, there will be an extra page refcount.

The GUP in TDX happens after the gmem converts the page to private.

May it's not GUP since the page has been unmapped from userspace? (Sorry that I'm not familiar with the terminology)

Quoted 20 lines

In the view of TDX, the physical page is converted to private already and it contains the initial content. But the content is not usable for TDX until TDX calls in-place PAGE.ADD

Quoted 16 lines
Quoted 4 lines
Quoted 4 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

The conversion request here will be declined therefore.

Quoted 9 lines
Quoted 3 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to explicitly request that the page range is converted to private and the content needs to be retained. So that TDX can identify which case needs to call in-place TDH.PAGE.ADD.

#70 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Vishal Annapurve
Quoted 110 lines · Vishal Annapurve
Quoted 63 lines · Fuad Tabba

Hi Vishal,

Quoted 55 lines · Vishal Annapurve
Quoted 46 lines · Fuad Tabba

Hi Ackerley,

Quoted 4 lines · Ackerley Tng

The two new guest_memfd ioctls KVM_GMEM_CONVERT_SHARED and KVM_GMEM_CONVERT_PRIVATE convert the requested memory ranges to shared and private respectively.

I have a high level question about this particular patch and this approach for conversion: why do we need IOCTLs to manage conversion between private and shared?

In the presentations I gave at LPC [1, 2], and in my latest patch series that performs in-place conversion [3] and the associated (by now outdated) state diagram [4], I didn't see the need to have a userspace-facing interface to manage that. KVM has all the information it needs to handle conversions, which are triggered by the guest. To me this seems like it adds additional complexity, as well as a user facing interface that we would need to maintain.

There are various ways we could handle conversion without explicit interference from userspace. What I had in mind is the following (as an example, details can vary according to VM type). I will use use the case of conversion from shared to private because that is the more complicated (interesting) case:

- Guest issues a hypercall to request that a shared folio become private.

- The hypervisor receives the call, and passes it to KVM.

- KVM unmaps the folio from the guest stage-2 (EPT I think in x86 parlance), and unmaps it from the host. The host however, could still have references (e.g., GUP).

- KVM exits to the host (hypervisor call exit), with the information that the folio has been unshared from it.

- A well behaving host would now get rid of all of its references (e.g., release GUPs), perform a VCPU run, and the guest continues running as normal. I expect this to be the common case.

But to handle the more interesting situation, let's say that the host doesn't do it immediately, and for some reason it holds on to some references to that folio.

Quoted 6 lines

- Even if that's the case, the guest can still run *. If the guest tries to access the folio, KVM detects that access when it tries to fault it into the guest, sees that the host still has references to that folio, and exits back to the host with a memory fault exit. At this point, the VCPU that has tried to fault in that particular folio cannot continue running as long as it cannot fault in that folio.

Quoted 3 lines

Are you talking about the following scheme?
1) guest_memfd checks shareability on each get pfn and if there is a mismatch exit to the host.

Quoted 5 lines

I think we are not really on the same page here (no pun intended :) ). I'll try to answer your questions anyway...

Which get_pfn? Are you referring to get_pfn when faulting the page into the guest or into the host?

I am referring to guest fault handling in KVM.

Quoted 23 lines
Quoted 3 lines

2) host user space has to guess whether it's a pending refcount or whether it's an actual mismatch.

No need to guess. VCPU run will let it know exactly why it's exiting.

Quoted 6 lines

3) guest_memfd will maintain a third state "pending_private_conversion" or equivalent which will transition to private upon the last refcount drop of each page.

If conversion is triggered by userspace (in case of pKVM, it will be triggered from within the KVM (?)):

Why would conversion be triggered by userspace? As far as I know, it's the guest that triggers the conversion.

Quoted 6 lines

* Conversion will just fail if there are extra refcounts and userspace can try to get rid of extra refcounts on the range while it has enough context without hitting any ambiguity with memory fault exit.
* guest_memfd will not have to deal with this extra state from 3 above and overall guest_memfd conversion handling becomes relatively simpler.

Quoted 2 lines

That's not really related. The extra state isn't necessary any more once we agreed in the previous discussion that we will retry instead.

Who is *we* here? Which entity will retry conversion?

Quoted 9 lines
Quoted 4 lines

Note that for x86 CoCo cases, memory conversion is already triggered by userspace using KVM ioctl, this series is proposing to use guest_memfd ioctl to do the same.

The reason why for x86 CoCo cases conversion is already triggered by userspace using KVM ioctl is that it has to, since shared memory and private memory are two separate pages, and userspace needs to manage that. Sharing memory in place removes the need for that.

Quoted 5 lines

Userspace still needs to clean up memory usage before conversion is successful. e.g. remove IOMMU mappings for shared to private conversion. I would think that memory conversion should not succeed before all existing users let go of the guest_memfd pages for the range being converted.

Ah about that. Actually IOMMU mappings can remain the same in a case like mine TSM+VFIO RFC based on the Fuad's older patches, here in particular:

https://lore.kernel.org/r/[email protected]

which works nicely - mapped it once and forgot.

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

For now (and for fun^wexperiment) I disabled kvm_gmem_has_safe_refcount() (04/51 adds it) and it seems to have no effect untiiil memfd is closed - folios_put_refs() crashes in list_del(&folio->lru). I wonder now what direction to go from here.

My TSM+VFIO RFC uses the hw ability to DMA to/from Coco VM (==AMD SEV SNP VM), both private and shared DMA at the same time is going to be allowed. Thanks,

Quoted 35 lines

In x86 CoCo usecases, userspace can also decide to not allow conversion for scenarios where ranges are still under active use by the host and guest is erroneously trying to take away memory. Both SNP/TDX spec allow failure of conversion due to in use memory.

Quoted 4 lines

This series isn't using the same ioctl, it's introducing new ones to perform a task that as far as I can tell so far, KVM can handle by itself.

I would like to understand this better. How will KVM handle the conversion process for guest_memfd pages? Can you help walk an example sequence for shared to private conversion specifically around guest_memfd offset states?

Quoted 20 lines
Quoted 3 lines

- Allows not having to keep track of separate shared/private range
information in KVM.

This patch series is already tracking shared/private range information in KVM.

Quoted 9 lines

- Simpler handling of the conversion process done per guest_memfd
rather than for full range.
- Userspace can handle the rollback as needed, simplifying error
handling in guest_memfd.
- guest_memfd is single source of truth and notifies the users of
shareability change.
- e.g. IOMMU, userspace, KVM MMU all can be registered for
getting notifications from guest_memfd directly and will get notified for invalidation upon shareability attribute updates.

All of these can still be done without introducing a new ioctl.

Cheers,
/fuad

Signature · 1 line
Alexey
#71 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 9 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

Jason

#72 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 10 lines · Jason Gunthorpe
Quoted 7 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack
2) Directly query pfns from guest_memfd for both shared/private ranges
3) Implement an invalidation callback that guest_memfd can invoke on conversions.

Current flow:
Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range

         -> KVM has the concept of invalidation_begin() and end(),

which effectively ensures that between these function calls, no new EPT/NPT entries can be added for the range.
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges
* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

    -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.
* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

           -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

         -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

There should be a way to block external IOMMU pagetable updates while guest_memfd is performing conversion e.g. something like kvm_invalidate_begin()/end().

Quoted 4 lines
Quoted 2 lines

is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should

+1.

Quoted 7 lines

be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

Quoted 6 lines

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

+1.

Quoted 2 lines

Jason

#263 lore raw
In reply to Ackerley Tng
Quoted 7 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

[...]

At the guest_memfd upstream call today (2025-06-26), we talked about when to merge folios with respect to conversions.

Just want to call out that in this RFCv2, we managed to get conversions working with merges happening as soon as possible.

"As soon as possible" means merges happen as long as shareability is all private (or all meaningless) within an aligned hugepage range. We try to merge after every conversion request and on truncation. On truncation, shareability becomes meaningless.

On explicit truncation (e.g. fallocate(PUNCH_HOLE)), truncation can fail if there are unexpected refcounts (because we can't merge with unexpected refcounts). Explicit truncation will succeed only if refcounts are expected, and merge is performed before finally removing from filemap.

On truncation caused by file close or inode release, guest_memfd may not hold the last refcount on the folio. Only in this case, we defer merging to the folio_put() callback, and because the callback can be called from atomic context, the merge is further deferred to be performed by a kernel worker.

Deferment of merging is already minimized so that most of the restructuring is synchronous with some userspace-initiated action (conversion or explicit truncation). The only deferred merge is when the file is closed, and in that case there's no way to reject/fail this file close.

(There are possible optimizations here - Yan suggested [1] checking if the folio_put() was called from interrupt context - I have not tried implementing that yet)

I did propose an explicit guest_memfd merge ioctl, but since RFCv2 works, I was thinking to to have the merge ioctl be a separate optimization/project/patch series if it turns out that merging as-soon-as-possible is an inefficient strategy, or if some VM use cases prefer to have an explicit merge ioctl.

During the call, Michael also brought up that SNP adds some constraints with respect to guest accepting pages/levels.

Could you please expand on that? Suppose for an SNP guest,

1. Guest accepted a page at 2M level
2. Guest converts a 4K sub page to shared
3. guest_memfd requests unmapping of the guest-requested 4K range (the rest of the 2M remains mapped into stage 2 page tables)
4. guest_memfd splits the huge page to 4K pages (the 4K is set to SHAREABILITY_ALL, the rest of the 2M is still SHAREABILITY_GUEST)

Can the SNP guest continue to use the rest of the 2M page or must it re-accept all the pages at 4K?

And for the reverse:

1. Guest accepted a 2M range at 4K
2. guest_memfd merges the full 2M range to a single 2M page

Must the SNP guest re-accept at 2M for the guest to continue functioning, or will the SNP guest continue to work (just with poorer performance than if the memory was accepted at 2M)?

[1] https://lore.kernel.org/all/aDfT35EsYP%[email protected]/

#73 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Vishal Annapurve
Quoted 40 lines · Vishal Annapurve
Quoted 10 lines · Jason Gunthorpe
Quoted 7 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack
2) Directly query pfns from guest_memfd for both shared/private ranges
3) Implement an invalidation callback that guest_memfd can invoke on conversions.

Current flow:
Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range

          -> KVM has the concept of invalidation_begin() and end(),

which effectively ensures that between these function calls, no new EPT/NPT entries can be added for the range.
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.

Quoted 5 lines

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges

Done that.

Quoted 2 lines

* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

This API imho should drop the confusing kvm_ prefix.

Quoted 4 lines
     -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.

Right now I cutnpasted kvm_gmem_get_folio() (which essentially is filemap_lock_folio()/filemap_alloc_folio()/__filemap_add_folio()) to avoid new links between iommufd.ko and kvm.ko. It is probably unavoidable though.

Quoted 21 lines

* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

            -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

Quoted 5 lines
          -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

Alright (although this zap+map is not necessary on the AMD hw).

Quoted 10 lines

There should be a way to block external IOMMU pagetable updates while guest_memfd is performing conversion e.g. something like kvm_invalidate_begin()/end().

Quoted 4 lines
Quoted 2 lines

is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should

+1.

Yeah, not doing this already, because I physically cannot map gmemfd's memory in IOMMU via VMA (which allocates memory via gup() so wrong memory is mapped in IOMMU). Thanks,

Quoted 7 lines
Quoted 7 lines

be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

Quoted 8 lines
Quoted 6 lines

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

+1.

Alright. Thanks for the comments.

Quoted 3 lines
Quoted 3 lines

Jason

Signature · 1 line
Alexey
#74 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 16 lines · Alexey Kardashevskiy
Quoted 12 lines · Vishal Annapurve
Quoted 10 lines · Jason Gunthorpe
Quoted 7 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

Quoted 6 lines
Quoted 6 lines

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack
2) Directly query pfns from guest_memfd for both shared/private ranges
3) Implement an invalidation callback that guest_memfd can invoke on conversions.

Conversions and truncations both.

Quoted 33 lines
Quoted 22 lines

Current flow:
Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range

          -> KVM has the concept of invalidation_begin() and end(),

which effectively ensures that between these function calls, no new EPT/NPT entries can be added for the range.
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.

Quoted 5 lines

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges

Done that.

Quoted 2 lines

* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

Quoted 8 lines

This API imho should drop the confusing kvm_ prefix.

Quoted 4 lines
     -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.

Right now I cutnpasted kvm_gmem_get_folio() (which essentially is filemap_lock_folio()/filemap_alloc_folio()/__filemap_add_folio()) to avoid new links between iommufd.ko and kvm.ko. It is probably unavoidable though.

I don't think that's the way to avoid links between iommufd.ko and kvm.ko. Cleaner way probably is to have gmem logic built-in and allow runtime registration of invalidation callbacks from KVM/IOMMU backends. Need to think about this more.

Quoted 30 lines
Quoted 23 lines

* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

            -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

Quoted 5 lines
          -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

Quoted 1 line

Alright (although this zap+map is not necessary on the AMD hw).

IMO guest_memfd ideally should not directly interact or cater to arch specific needs, it should implement a mechanism that works for all archs. KVM/IOMMU implement invalidation callbacks and have all the architecture specific knowledge to take the right decisions.

Quoted 41 lines
Quoted 6 lines

There should be a way to block external IOMMU pagetable updates while guest_memfd is performing conversion e.g. something like kvm_invalidate_begin()/end().

Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should

+1.

Yeah, not doing this already, because I physically cannot map gmemfd's memory in IOMMU via VMA (which allocates memory via gup() so wrong memory is mapped in IOMMU). Thanks,

Quoted 7 lines
Quoted 7 lines

be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

Quoted 8 lines
Quoted 6 lines

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

+1.

Alright. Thanks for the comments.

Quoted 3 lines
Quoted 3 lines

Jason

--
Alexey

#229 lore raw
In reply to Xiaoyao Li
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

That's correct.

Quoted 5 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.

Quoted 4 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

I think this scheme will be cleaner:
1) Userspace marks the guest_memfd ranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts those guest_memfd ranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.

i.e. for TDX VMs, KVM_TDX_INIT_MEM_REGION still does the in-place TDH.PAGE.ADD.

Since we need to support VMs that will/won't use in-place conversion, I think operations like KVM_TDX_INIT_MEM_REGION can introduce explicit flags to allow userspace to indicate whether to assume in-place conversion or not. Maybe kvm_tdx_init_mem_region.source_addr/kvm_sev_snp_launch_update.uaddr can be null in the scenarios where in-place conversion is used.

#75 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Vishal Annapurve
Quoted 66 lines · Vishal Annapurve
Quoted 16 lines · Alexey Kardashevskiy
Quoted 12 lines · Vishal Annapurve
Quoted 10 lines · Jason Gunthorpe
Quoted 7 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

Quoted 6 lines
Quoted 6 lines

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack
2) Directly query pfns from guest_memfd for both shared/private ranges
3) Implement an invalidation callback that guest_memfd can invoke on conversions.

Conversions and truncations both.

Quoted 40 lines
Quoted 22 lines

Current flow:
Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range

           -> KVM has the concept of invalidation_begin() and end(),

which effectively ensures that between these function calls, no new EPT/NPT entries can be added for the range.
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.

Quoted 5 lines

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges

Done that.

Quoted 2 lines

* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

This API imho should drop the confusing kvm_ prefix.

Quoted 4 lines
      -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.

Quoted 6 lines
Quoted 1 line

Right now I cutnpasted kvm_gmem_get_folio() (which essentially is filemap_lock_folio()/filemap_alloc_folio()/__filemap_add_folio()) to avoid new links between iommufd.ko and kvm.ko. It is probably unavoidable though.

I don't think that's the way to avoid links between iommufd.ko and kvm.ko. Cleaner way probably is to have gmem logic built-in and allow runtime registration of invalidation callbacks from KVM/IOMMU backends. Need to think about this more.

Yeah, otherwise iommufd.ko will have to install a hook in guest_memfd (==kvm.ko) in run time so more beloved symbol_get() :)

Quoted 31 lines
Quoted 31 lines
Quoted 29 lines

* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

             -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

           -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

Quoted 6 lines
Quoted 1 line

Alright (although this zap+map is not necessary on the AMD hw).

IMO guest_memfd ideally should not directly interact or cater to arch specific needs, it should implement a mechanism that works for all archs. KVM/IOMMU implement invalidation callbacks and have all the architecture specific knowledge to take the right decisions.

Every page conversion will go through:

kvm-amd.ko -1-> guest_memfd (kvm.ko) -2-> iommufd.ko -3-> amd-iommu (build-in).

Which one decides on IOMMU not needing (un)mapping? Got to be (1) but then it need to propagate the decision to amd-iommu (and we do not have (3) at the moment in that path).

Or we just always do unmap+map (and trigger unwanted page huge page smashing)? All is doable and neither particularly horrible, I'm trying to see where the consensus is now. Thanks,

Quoted 40 lines
Quoted 40 lines
Quoted 11 lines

There should be a way to block external IOMMU pagetable updates while guest_memfd is performing conversion e.g. something like kvm_invalidate_begin()/end().

Quoted 4 lines
Quoted 2 lines

is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should

+1.

Yeah, not doing this already, because I physically cannot map gmemfd's memory in IOMMU via VMA (which allocates memory via gup() so wrong memory is mapped in IOMMU). Thanks,

Quoted 7 lines
Quoted 7 lines

be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

Quoted 8 lines
Quoted 6 lines

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

+1.

Alright. Thanks for the comments.

Quoted 3 lines
Quoted 3 lines

Jason

--
Alexey

Signature · 1 line
Alexey
#230 lore raw
In reply to Vishal Annapurve
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

That's correct.

Quoted 5 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.

Quoted 4 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

Quoted 13 lines

I think this scheme will be cleaner:
1) Userspace marks the guest_memfd ranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts those guest_memfd ranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.

One caveat:

when TDX populates the mirror root, kvm_gmem_get_pfn() is invoked. Then kvm_gmem_prepare_folio() is further invoked to zero the folio.

Quoted 1 line

i.e. for TDX VMs, KVM_TDX_INIT_MEM_REGION still does the in-place TDH.PAGE.ADD.

So, upon here, the pages should not contain the original content?

Quoted 6 lines

Since we need to support VMs that will/won't use in-place conversion, I think operations like KVM_TDX_INIT_MEM_REGION can introduce explicit flags to allow userspace to indicate whether to assume in-place conversion or not. Maybe kvm_tdx_init_mem_region.source_addr/kvm_sev_snp_launch_update.uaddr can be null in the scenarios where in-place conversion is used.

#231 lore raw
Quoted 67 lines · Yan Zhao
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

That's correct.

Quoted 5 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.

Quoted 4 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

Quoted 13 lines

I think this scheme will be cleaner:
1) Userspace marks the guest_memfd ranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts those guest_memfd ranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.

Quoted 4 lines

One caveat:

when TDX populates the mirror root, kvm_gmem_get_pfn() is invoked. Then kvm_gmem_prepare_folio() is further invoked to zero the folio.

Given that confidential VMs have their own way of initializing private memory, I think zeroing makes sense for only shared memory ranges. i.e. something like below:
1) Don't zero at allocation time.
2) If faulting in a shared page and its not uptodate, then zero the page and set the page as uptodate.
3) Clear uptodate flag on private to shared conversion.
4) For faults on private ranges, don't zero the memory.

There might be some other considerations here e.g. pKVM needs non-destructive conversion operation, which might need a way to enable zeroing at allocation time only.

On a TDX specific note, IIUC, KVM TDX logic doesn't need to clear pages on future platforms [1].

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 4 lines
Quoted 2 lines

i.e. for TDX VMs, KVM_TDX_INIT_MEM_REGION still does the in-place TDH.PAGE.ADD.

So, upon here, the pages should not contain the original content?

Pages should contain the original content. Michael is already experimenting with similar logic [2] for SNP.

[2] https://lore.kernel.org/lkml/[email protected]/

#76 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Alexey Kardashevskiy
Quoted 67 lines · Alexey Kardashevskiy

...

Quoted 18 lines
Quoted 18 lines
Quoted 5 lines

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges

Done that.

Quoted 2 lines

* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

This API imho should drop the confusing kvm_ prefix.

Quoted 4 lines
      -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.

Quoted 6 lines
Quoted 1 line

Right now I cutnpasted kvm_gmem_get_folio() (which essentially is filemap_lock_folio()/filemap_alloc_folio()/__filemap_add_folio()) to avoid new links between iommufd.ko and kvm.ko. It is probably unavoidable though.

I don't think that's the way to avoid links between iommufd.ko and kvm.ko. Cleaner way probably is to have gmem logic built-in and allow runtime registration of invalidation callbacks from KVM/IOMMU backends. Need to think about this more.

Yeah, otherwise iommufd.ko will have to install a hook in guest_memfd (==kvm.ko) in run time so more beloved symbol_get() :)

Quoted 31 lines
Quoted 31 lines
Quoted 29 lines

* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

             -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

           -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

Quoted 6 lines
Quoted 1 line

Alright (although this zap+map is not necessary on the AMD hw).

IMO guest_memfd ideally should not directly interact or cater to arch specific needs, it should implement a mechanism that works for all archs. KVM/IOMMU implement invalidation callbacks and have all the architecture specific knowledge to take the right decisions.

Quoted 5 lines

Every page conversion will go through:

kvm-amd.ko -1-> guest_memfd (kvm.ko) -2-> iommufd.ko -3-> amd-iommu (build-in).

Which one decides on IOMMU not needing (un)mapping? Got to be (1) but then it need to propagate the decision to amd-iommu (and we do not have (3) at the moment in that path).

If there is a need, guest_memfd can support two different callbacks:
1) Conversion notifier/callback invoked by guest_memfd during conversion handling.
2) Invalidation notifier/callback invoked by guest_memfd during truncation.

Iommufd/kvm can handle conversion callback/notifier as per the needs of underlying architecture. e.g. for TDX connect do the unmapping vs for SEV Trusted IO skip the unmapping.

Invalidation callback/notifier will need to be handled by unmapping page tables.

Quoted 3 lines

Or we just always do unmap+map (and trigger unwanted page huge page smashing)? All is doable and neither particularly horrible, I'm trying to see where the consensus is now. Thanks,

I assume when you say huge page smashing, it means huge page NPT mapping getting split.

AFAIR, based on discussion with Michael during guest_memfd calls, stage2 NPT entries need to be of the same granularity as RMP tables for AMD SNP guests. i.e. huge page NPT mappings need to be smashed on the KVM side during conversion. So today guest_memfd sends invalidation notification to KVM for both conversion and truncation. Doesn't the same constraint for keeping IOMMU page tables at the same granularity as RMP tables hold for trusted IO?

#232 lore raw
In reply to Vishal Annapurve
Quoted 82 lines · Vishal Annapurve
Quoted 67 lines · Yan Zhao
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

That's correct.

Quoted 5 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.

Quoted 4 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

Quoted 13 lines

I think this scheme will be cleaner:
1) Userspace marks the guest_memfd ranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts those guest_memfd ranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.

Quoted 4 lines

One caveat:

when TDX populates the mirror root, kvm_gmem_get_pfn() is invoked. Then kvm_gmem_prepare_folio() is further invoked to zero the folio.

Given that confidential VMs have their own way of initializing private memory, I think zeroing makes sense for only shared memory ranges. i.e. something like below:
1) Don't zero at allocation time.
2) If faulting in a shared page and its not uptodate, then zero the page and set the page as uptodate.
3) Clear uptodate flag on private to shared conversion.
4) For faults on private ranges, don't zero the memory.

Quoted 6 lines

There might be some other considerations here e.g. pKVM needs non-destructive conversion operation, which might need a way to enable zeroing at allocation time only.

On a TDX specific note, IIUC, KVM TDX logic doesn't need to clear pages on future platforms [1].

Yes, TDX does not need to clear pages on private page allocation. But current kvm_gmem_prepare_folio() clears private pages in the common path for both TDX and SEV-SNP.

I just wanted to point out that it's a kind of obstacle that need to be removed to implement the proposed approach.

Quoted 11 lines

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 4 lines
Quoted 2 lines

i.e. for TDX VMs, KVM_TDX_INIT_MEM_REGION still does the in-place TDH.PAGE.ADD.

So, upon here, the pages should not contain the original content?

Pages should contain the original content. Michael is already experimenting with similar logic [2] for SNP.

[2] https://lore.kernel.org/lkml/[email protected]/

#233 lore raw
Quoted 88 lines · Yan Zhao
Quoted 86 lines · Vishal Annapurve
Quoted 67 lines · Yan Zhao
Quoted 52 lines · Vishal Annapurve
Quoted 28 lines · Xiaoyao Li
Quoted 20 lines · Yan Zhao
Quoted 11 lines · Ackerley Tng

Hello,

This patchset builds upon discussion at LPC 2024 and many guest_memfd upstream calls to provide 1G page support for guest_memfd by taking pages from HugeTLB.

This patchset is based on Linux v6.15-rc6, and requires the mmap support for guest_memfd patchset (Thanks Fuad!) [1].

For ease of testing, this series is also available, stitched together, at https://github.com/googleprodkernel/linux-cc/tree/gmem-1g-page-support-rfc-v2

Just to record a found issue -- not one that must be fixed.

In TDX, the initial memory region is added as private memory during TD's build time, with its initial content copied from source pages in shared memory. The copy operation requires simultaneous access to both shared source memory and private target memory.

Quoted 5 lines

Therefore, userspace cannot store the initial content in shared memory at the mmap-ed VA of a guest_memfd that performs in-place conversion between shared and private memory. This is because the guest_memfd will first unmap a PFN in shared page tables and then check for any extra refcount held for the shared PFN before converting it to private.

Quoted 5 lines

I have an idea.

If I understand correctly, the KVM_GMEM_CONVERT_PRIVATE of in-place conversion unmap the PFN in shared page tables while keeping the content of the page unchanged, right?

That's correct.

Quoted 5 lines

So KVM_GMEM_CONVERT_PRIVATE can be used to initialize the private memory actually for non-CoCo case actually, that userspace first mmap() it and ensure it's shared and writes the initial content to it, after it userspace convert it to private with KVM_GMEM_CONVERT_PRIVATE.

I think you mean pKVM by non-coco VMs that care about private memory. Yes, initial memory regions can start as shared which userspace can populate and then convert the ranges to private.

Quoted 4 lines

For CoCo case, like TDX, it can hook to KVM_GMEM_CONVERT_PRIVATE if it wants the private memory to be initialized with initial content, and just do in-place TDH.PAGE.ADD in the hook.

Quoted 13 lines

I think this scheme will be cleaner:
1) Userspace marks the guest_memfd ranges corresponding to initial payload as shared.
2) Userspace mmaps and populates the ranges.
3) Userspace converts those guest_memfd ranges to private.
4) For both SNP and TDX, userspace continues to invoke corresponding initial payload preparation operations via existing KVM ioctls e.g. KVM_SEV_SNP_LAUNCH_UPDATE/KVM_TDX_INIT_MEM_REGION.
- SNP/TDX KVM logic fetches the right pfns for the target gfns
using the normal paths supported by KVM and passes those pfns directly to the right trusted module to initialize the "encrypted" memory contents.
- Avoiding any GUP or memcpy from source addresses.

Quoted 4 lines

One caveat:

when TDX populates the mirror root, kvm_gmem_get_pfn() is invoked. Then kvm_gmem_prepare_folio() is further invoked to zero the folio.

Given that confidential VMs have their own way of initializing private memory, I think zeroing makes sense for only shared memory ranges. i.e. something like below:
1) Don't zero at allocation time.
2) If faulting in a shared page and its not uptodate, then zero the page and set the page as uptodate.
3) Clear uptodate flag on private to shared conversion.
4) For faults on private ranges, don't zero the memory.

There might be some other considerations here e.g. pKVM needs non-destructive conversion operation, which might need a way to enable zeroing at allocation time only.

Quoted 9 lines
Quoted 2 lines

On a TDX specific note, IIUC, KVM TDX logic doesn't need to clear pages on future platforms [1].

Yes, TDX does not need to clear pages on private page allocation. But current kvm_gmem_prepare_folio() clears private pages in the common path for both TDX and SEV-SNP.

I just wanted to point out that it's a kind of obstacle that need to be removed to implement the proposed approach.

Proposed approach will work with 4K pages without any additional changes. For huge pages it's easy to prototype this approach by just disabling zeroing logic in guest mem on faulting and instead always doing zeroing on allocation.

I would be curious to understand if we need zeroing on conversion for Confidential VMs. If not, then the simple rule of zeroing on allocation only will work for all usecases.

#79 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Vishal Annapurve
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so guest_memfd can reject the request before attempting the actual unmap. Otherwise, the unmap of TD-DMA-pinned pages will fail.

Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.

Quoted 39 lines

2) Directly query pfns from guest_memfd for both shared/private ranges
3) Implement an invalidation callback that guest_memfd can invoke on conversions.

Current flow:
Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range

         -> KVM has the concept of invalidation_begin() and end(),

which effectively ensures that between these function calls, no new EPT/NPT entries can be added for the range.
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges
* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

    -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.
* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Quoted 7 lines

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

           -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.

If guest_memfd could determine if a page is used by DMA purposes before attempting the actual unmaps, it could reject and fail the conversion earlier, thereby keeping IOMMU/S-EPT mappings intact.

This could prevent the conversion from partially failing.

Quoted 47 lines

3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

         -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

There should be a way to block external IOMMU pagetable updates while guest_memfd is performing conversion e.g. something like kvm_invalidate_begin()/end().

Quoted 4 lines
Quoted 2 lines

is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should

+1.

Quoted 7 lines

be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

Quoted 6 lines

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

+1.

Quoted 2 lines

Jason

#80 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 17 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

Quoted 8 lines

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so guest_memfd can reject the request before attempting the actual unmap.

So it looks like guest_memfd will need an interface with KVM/IOMMU backends to check if unmapping can succeed. And if unmapping still fails, there should be a way for KVM/IOMMU backends to kill the TD and any TDIs bound to that TD.

Quoted 5 lines

Otherwise, the unmap of TD-DMA-pinned pages will fail.

Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.

#81 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 15 lines · Vishal Annapurve
Quoted 14 lines · Yan Zhao
Quoted 12 lines · Vishal Annapurve
Quoted 10 lines · Jason Gunthorpe
Quoted 7 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

Quoted 7 lines
Quoted 7 lines
Quoted 3 lines

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

I don't see this as having much to do with iommufd.

iommufd will somehow support the T=1 iommu inside the TDX module but it won't have an IOAS for it since the VMM does not control the translation.

The discussion here is for the T=0 iommu which is controlled by iommufd and does have an IOAS. It should be popoulated with all the shared pages from the guestmemfd.

Quoted 3 lines
Quoted 3 lines

If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so guest_memfd can reject the request before attempting the actual unmap.

This has to be delt with between the TDX module and KVM. When KVM gives pages to become secure it may not be able to get them back..

This problem has nothing to do with iommufd.

But generally I expect that the T=1 iommu follows the S-EPT entirely and there is no notion of pages "locked for dma". If DMA is ongoing and a page is made non-secure then the DMA fails.

Obviously in a mode where there is a vPCI device we will need all the pages to be pinned in the guestmemfd to prevent any kind of migrations. Only shared/private conversions should change the page around.

Maybe this needs to be an integral functionality in guestmemfd?

Jason

#82 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 44 lines · Jason Gunthorpe
Quoted 15 lines · Vishal Annapurve
Quoted 14 lines · Yan Zhao
Quoted 12 lines · Vishal Annapurve
Quoted 10 lines · Jason Gunthorpe
Quoted 7 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

Quoted 7 lines
Quoted 7 lines
Quoted 3 lines

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

I don't see this as having much to do with iommufd.

iommufd will somehow support the T=1 iommu inside the TDX module but it won't have an IOAS for it since the VMM does not control the translation.

The discussion here is for the T=0 iommu which is controlled by iommufd and does have an IOAS. It should be popoulated with all the shared pages from the guestmemfd.

Quoted 3 lines
Quoted 3 lines

If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so guest_memfd can reject the request before attempting the actual unmap.

This has to be delt with between the TDX module and KVM. When KVM gives pages to become secure it may not be able to get them back..

This problem has nothing to do with iommufd.

Quoted 8 lines

But generally I expect that the T=1 iommu follows the S-EPT entirely and there is no notion of pages "locked for dma". If DMA is ongoing and a page is made non-secure then the DMA fails.

Obviously in a mode where there is a vPCI device we will need all the pages to be pinned in the guestmemfd to prevent any kind of migrations. Only shared/private conversions should change the page around.

Yes, guest_memfd ensures that all the faulted-in pages (irrespective of shared or private ranges) are not migratable. We already have a similar restriction with CPU accesses to encrypted memory ranges that need arch specific protocols to migrate memory contents.

Quoted 4 lines

Maybe this needs to be an integral functionality in guestmemfd?

Jason

#14 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Ackerley Tng
Quoted 68 lines · Ackerley Tng
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 11 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

I can move this change to the later patch. Thanks! Will fix in the next revision.

Quoted 9 lines

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Quoted 7 lines

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

I guess we could also have userspace be careful not to do any allocation before converting.

I assume we do want to support things like preallocating guest memory so not sure this approach is feasible to avoid splits.

But I feel like we might be working around a deeper issue here, which is that we are pre-emptively splitting anything that *could* be mapped into userspace (i.e. allocated+shared/mixed), rather than splitting when necessary.

I know that was the plan laid out in the guest_memfd calls, but I've run into a couple instances that have me thinking we should revisit this.

1) Some of the recent guest_memfd seems to be gravitating towards having userspace populate/initialize guest memory payload prior to boot via mmap()'ing the shared guest_memfd pages so things work the same as they would for initialized normal VM memory payload (rather than relying on back-channels in the kernel to user data into guest_memfd pages).

When you do this though, for an SNP guest at least, that memory acceptance is done in chunks of 4MB (with accept_memory=lazy), and because that will put each 1GB page into an allocated+mixed state, we end up splitting every 1GB to 4K and the guest can't even accept/PVALIDATE it 2MB at that point even if userspace doesn't touch anything in the range. As some point the guest will convert/accept the entire range, at which point we could merge, but for SNP we'd need guest cooperation to actually use a higher-granularity in stage2 page tables at that point since RMP entries are effectively all split to 4K.

I understand the intent is to default to private where this wouldn't be an issue, and we could punt to userspace to deal with it, but it feels like an artificial restriction to place on userspace. And if we do want to allow/expect guest_memfd contents to be initialized pre-boot just like normal memory, then userspace would need to jump through some hoops:

- if defaulting to private: add hooks to convert each range that's being modified to a shared state prior to writing to it
- if defaulting to shared: initialize memory in-place, then covert everything else to private to avoid unecessarily splitting folios at run-time

It feels like implementations details are bleeding out into the API to some degree here (e.g. we'd probably at least need to document this so users know how to take proper advantage of hugepage support).

2) There are some use-cases for HugeTLB + CoCo that have come to my attention recently that put a lot of weight on still being able to maximize mapping/hugepage size when accessing shared mem from userspace, e.g. for certain DPDK workloads that accessed shared guest buffers from host userspace. We don't really have a story for this, and I wouldn't expect us to at this stage, but I think it ties into #1 so might be worth considering in that context.

I'm still fine with the current approach as a starting point, but I'm wondering if improving both #1/#2 might not be so bad and maybe even give us some more flexibility (for instance, Sean had mentioned leaving open the option of tracking more than just shareability/mappability, and if there is split/merge logic associated with those transitions then re-scanning each of these attributes for a 1G range seems like it could benefit from some sort of intermediate data structure to help determine things like what mapping granularity is available for guest/userspace for a particular range.

One approach I was thinking of was that we introduce a data structure similar to KVM's memslot->arch.lpage_info() where we store information about what 1G/2M ranges are shared/private/mixed, and then instead of splitting ahead of time we just record that state into this data structure (using the same write lock as with the shareability/mappability state), and then at *fault* time we split the folio if our lpage_info-like data structure says the range is mixed.

Then, if guest converts a 2M/4M range to private while lazilly-accepting (for instance), we can still keep the folio intact as 1GB, but mark the 1G range in the lpage_info-like data structure as mixed so that we still inform KVM/etc. they need to map it as 2MB or lower in stage2 page tables. In that case, even at guest fault-time, we can leave the folio unsplit until userspace tries to touch it (though in most cases it never will and we can keep most of the guest's 1G intact for the duration of its lifetime).

On the userspace side, another nice thing there is if we see 1G is in a mixed state, but 2M is all-shared, then we can still leave the folio as 2M, and I think the refcount'ing logic would still work for the most part, which makes #2 a bit easier to implement as well.

And of course, we wouldn't need the INIT_PRIVATE then since we are only splitting when necessary.

But I guess this all comes down to how much extra pain there is in tracking a 1G folio that's been split into a mixed of 2MB/4K regions, but I think we'd get a lot more mileage out of getting that working and just completely stripping out all of the merging logic for initial implementation (other than at cleanup time), so maybe complexity-wise it balances out a bit?

Thanks,

Mike

Quoted 295 lines
Quoted 294 lines
Quoted 62 lines
Documentation/virt/kvm/api.rst +0 -0
 See KVM_SET_USER_MEMORY_REGION2 for additional details.
 
 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
index 4cc824a3a7c9..d7df312479aa 100644
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {
 #define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
 
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
+
 #define GUEST_MEMFD_FLAG_SUPPORT_SHARED	(1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE	(1UL << 1)
 
 struct kvm_create_guest_memfd {
 	__u64 size;
virt/kvm/guest_memfd.c +22 -0
index 239d0f13dcc1..590932499eba 100644
@@ -4,6 +4,7 @@
 #include <linux/falloc.h>
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
+#include <linux/maple_tree.h>
 #include <linux/pseudo_fs.h>
 #include <linux/pagemap.h>
 
@@ -17,6 +18,24 @@ struct kvm_gmem {
 	struct list_head entry;
 };
 
+struct kvm_gmem_inode_private {
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	struct maple_tree shareability;
+#endif
+};
+
+enum shareability {
+	SHAREABILITY_GUEST = 1,	/* Only the guest can map (fault) folios in this range. */
+	SHAREABILITY_ALL = 2,	/* Both guest and host can fault folios in this range. */
+};
+
+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index);
+
+static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)
+{
+	return inode->i_mapping->i_private_data;
+}
+
 /**
  * folio_file_pfn - like folio_file_page, but return a pfn.
  * @folio: The folio which contains this index.
@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
 	return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
 }
 
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+				      loff_t size, u64 flags)
+{
+	enum shareability m;
+	pgoff_t last;
+
+	last = (size >> PAGE_SHIFT) - 1;
+	m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+						    SHAREABILITY_ALL;
+	return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+				 GFP_KERNEL);

One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via KVM_SET_MEMORY_ATTRIBUTES (which is the current QEMU default behavior).

I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.

Maybe it would make sense for KVM memory attributes too?

Quoted 135 lines
virt/kvm/guest_memfd.c +87 -1
+}
+
+static enum shareability kvm_gmem_shareability_get(struct inode *inode,
+						 pgoff_t index)
+{
+	struct maple_tree *mt;
+	void *entry;
+
+	mt = &kvm_gmem_private(inode)->shareability;
+	entry = mtree_load(mt, index);
+	WARN(!entry,
+	     "Shareability should always be defined for all indices in inode.");
+
+	return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+		return ERR_PTR(-EACCES);
+
+	return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+	return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+	WARN_ONCE("Unexpected call to get shared folio.")
+	return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
 				    pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
 	filemap_invalidate_lock_shared(inode->i_mapping);
 
-	folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+	folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
 	if (IS_ERR(folio)) {
 		int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
 	.fallocate	= kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+	kfree(private);
+
+	free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+	struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+	/*
+	 * mtree_destroy() can't be used within rcu callback, hence can't be
+	 * done in ->free_inode().
+	 */
+	if (private)
+		mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
 	.statfs		= simple_statfs,
+	.destroy_inode	= kvm_gmem_destroy_inode,
+	.free_inode	= kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 						      loff_t size, u64 flags)
 {
+	struct kvm_gmem_inode_private *private;
 	struct inode *inode;
+	int err;
 
 	inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
 	if (IS_ERR(inode))
 		return inode;
 
+	err = -ENOMEM;
+	private = kzalloc(sizeof(*private), GFP_KERNEL);
+	if (!private)
+		goto out;
+
+	mt_init(&private->shareability);
+	inode->i_mapping->i_private_data = private;
+
+	err = kvm_gmem_shareability_setup(private, size, flags);
+	if (err)
+		goto out;
+
 	inode->i_private = (void *)(unsigned long)flags;
 	inode->i_op = &kvm_gmem_iops;
 	inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
 	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
 	return inode;
+
+out:
+	iput(inode);
+
+	return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
 	if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
 		valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+	if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+		valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
 	if (flags & ~valid_flags)
 		return -EINVAL;
 

virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964

Quoted 5 lines
virt/kvm/guest_memfd.c +2 -0
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 	if (!file)
 		return -EFAULT;
 
+	filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+

I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new SHAREABILITY_GUEST_PREPARED state) the SHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPARED transition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.

I was originally planning on introducing a new rw_semaphore with similar semantics to the rw_lock that Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle setting SHAREABILITY_GUEST_PREPARED within fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.

They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.

I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:

KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes

but figured I'd mention it here in case there are other things to consider on the locking front.

Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.

-Mike

[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/

Quoted 16 lines
virt/kvm/guest_memfd.c +1 -1
 	folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
 	if (IS_ERR(folio)) {
 		r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
 		*page = folio_file_page(folio, index);
 	else
 		folio_put(folio);
-
 out:
+	filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
 	fput(file);
 	return r;
 }
Signature · 1 line
2.49.0.1045.g170613ef41-goog
#15 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 96 lines · Michael Roth
Quoted 68 lines · Ackerley Tng
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 11 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

I can move this change to the later patch. Thanks! Will fix in the next revision.

Quoted 9 lines

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Quoted 7 lines

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

I guess we could also have userspace be careful not to do any allocation before converting.

I assume we do want to support things like preallocating guest memory so not sure this approach is feasible to avoid splits.

But I feel like we might be working around a deeper issue here, which is that we are pre-emptively splitting anything that *could* be mapped into userspace (i.e. allocated+shared/mixed), rather than splitting when necessary.

I know that was the plan laid out in the guest_memfd calls, but I've run into a couple instances that have me thinking we should revisit this.

1) Some of the recent guest_memfd seems to be gravitating towards having userspace populate/initialize guest memory payload prior to boot via mmap()'ing the shared guest_memfd pages so things work the same as they would for initialized normal VM memory payload (rather than relying on back-channels in the kernel to user data into guest_memfd pages).

Quoted 3 lines

When you do this though, for an SNP guest at least, that memory acceptance is done in chunks of 4MB (with accept_memory=lazy), and because that will put each 1GB page into an allocated+mixed state,

I would like your help in understanding why we need to start guest_memfd ranges as shared for SNP guests. guest_memfd ranges being private simply should mean that certain ranges are not faultable by the userspace.

Will following work?
1) Userspace starts all guest_memfd ranges as private.
2) During early guest boot it starts issuing PSC requests for converting memory from shared to private

    -> KVM forwards this request to userspace
    -> Userspace checks that the pages are already private and simply

does nothing.
3) Pvalidate from guest on that memory will result in guest_memfd offset query which will cause the RMP table entries to actually get populated.

Quoted 15 lines

we end up splitting every 1GB to 4K and the guest can't even accept/PVALIDATE it 2MB at that point even if userspace doesn't touch anything in the range. As some point the guest will convert/accept the entire range, at which point we could merge, but for SNP we'd need guest cooperation to actually use a higher-granularity in stage2 page tables at that point since RMP entries are effectively all split to 4K.

I understand the intent is to default to private where this wouldn't be an issue, and we could punt to userspace to deal with it, but it feels like an artificial restriction to place on userspace. And if we do want to allow/expect guest_memfd contents to be initialized pre-boot just like normal memory, then userspace would need to jump through some hoops:

Quoted 2 lines

- if defaulting to private: add hooks to convert each range that's being modified to a shared state prior to writing to it

Why is that a problem?

Quoted 7 lines

- if defaulting to shared: initialize memory in-place, then covert everything else to private to avoid unecessarily splitting folios at run-time

It feels like implementations details are bleeding out into the API to some degree here (e.g. we'd probably at least need to document this so users know how to take proper advantage of hugepage support).

Does it make sense to keep the default behavior as INIT_PRIVATE for SNP VMs always even without using hugepages?

Quoted 8 lines

2) There are some use-cases for HugeTLB + CoCo that have come to my attention recently that put a lot of weight on still being able to maximize mapping/hugepage size when accessing shared mem from userspace, e.g. for certain DPDK workloads that accessed shared guest buffers from host userspace. We don't really have a story for this, and I wouldn't expect us to at this stage, but I think it ties into #1 so might be worth considering in that context.

Major problem I see here is that if anything in the kernel does a GUP on shared memory ranges (which is very likely to happen), it would be difficult to get them to let go of the whole hugepage before it can be split safely.

Another problem is guest_memfd today doesn't support management of large user space page table mappings, this can turnout to be significant work to do referring to hugetlb pagetable management logic.

Quoted 342 lines

I'm still fine with the current approach as a starting point, but I'm wondering if improving both #1/#2 might not be so bad and maybe even give us some more flexibility (for instance, Sean had mentioned leaving open the option of tracking more than just shareability/mappability, and if there is split/merge logic associated with those transitions then re-scanning each of these attributes for a 1G range seems like it could benefit from some sort of intermediate data structure to help determine things like what mapping granularity is available for guest/userspace for a particular range.

One approach I was thinking of was that we introduce a data structure similar to KVM's memslot->arch.lpage_info() where we store information about what 1G/2M ranges are shared/private/mixed, and then instead of splitting ahead of time we just record that state into this data structure (using the same write lock as with the shareability/mappability state), and then at *fault* time we split the folio if our lpage_info-like data structure says the range is mixed.

Then, if guest converts a 2M/4M range to private while lazilly-accepting (for instance), we can still keep the folio intact as 1GB, but mark the 1G range in the lpage_info-like data structure as mixed so that we still inform KVM/etc. they need to map it as 2MB or lower in stage2 page tables. In that case, even at guest fault-time, we can leave the folio unsplit until userspace tries to touch it (though in most cases it never will and we can keep most of the guest's 1G intact for the duration of its lifetime).

On the userspace side, another nice thing there is if we see 1G is in a mixed state, but 2M is all-shared, then we can still leave the folio as 2M, and I think the refcount'ing logic would still work for the most part, which makes #2 a bit easier to implement as well.

And of course, we wouldn't need the INIT_PRIVATE then since we are only splitting when necessary.

But I guess this all comes down to how much extra pain there is in tracking a 1G folio that's been split into a mixed of 2MB/4K regions, but I think we'd get a lot more mileage out of getting that working and just completely stripping out all of the merging logic for initial implementation (other than at cleanup time), so maybe complexity-wise it balances out a bit?

Thanks,

Mike

Quoted 295 lines
Quoted 294 lines
Quoted 62 lines
Documentation/virt/kvm/api.rst +0 -0
 See KVM_SET_USER_MEMORY_REGION2 for additional details.
 
 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
index 4cc824a3a7c9..d7df312479aa 100644
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {
 #define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
 
 #define KVM_CREATE_GUEST_MEMFD    _IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
+
 #define GUEST_MEMFD_FLAG_SUPPORT_SHARED   (1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE     (1UL << 1)
 
 struct kvm_create_guest_memfd {
   __u64 size;
virt/kvm/guest_memfd.c +22 -0
index 239d0f13dcc1..590932499eba 100644
@@ -4,6 +4,7 @@
 #include <linux/falloc.h>
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
+#include <linux/maple_tree.h>
 #include <linux/pseudo_fs.h>
 #include <linux/pagemap.h>
 
@@ -17,6 +18,24 @@ struct kvm_gmem {
   struct list_head entry;
 };
 
+struct kvm_gmem_inode_private {
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+  struct maple_tree shareability;
+#endif
+};
+
+enum shareability {
+  SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */
+  SHAREABILITY_ALL = 2,   /* Both guest and host can fault folios in this range. */
+};
+
+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index);
+
+static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)
+{
+  return inode->i_mapping->i_private_data;
+}
+
 /**
  * folio_file_pfn - like folio_file_page, but return a pfn.
  * @folio: The folio which contains this index.
@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
   return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
 }
 
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+                                loff_t size, u64 flags)
+{
+  enum shareability m;
+  pgoff_t last;
+
+  last = (size >> PAGE_SHIFT) - 1;
+  m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+                                              SHAREABILITY_ALL;
+  return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+                           GFP_KERNEL);

One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via KVM_SET_MEMORY_ATTRIBUTES (which is the current QEMU default behavior).

I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.

Maybe it would make sense for KVM memory attributes too?

Quoted 135 lines
virt/kvm/guest_memfd.c +87 -1
+}
+
+static enum shareability kvm_gmem_shareability_get(struct inode *inode,
+                                           pgoff_t index)
+{
+  struct maple_tree *mt;
+  void *entry;
+
+  mt = &kvm_gmem_private(inode)->shareability;
+  entry = mtree_load(mt, index);
+  WARN(!entry,
+       "Shareability should always be defined for all indices in inode.");
+
+  return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+  if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+          return ERR_PTR(-EACCES);
+
+  return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+  return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+  WARN_ONCE("Unexpected call to get shared folio.")
+  return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
                               pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
   filemap_invalidate_lock_shared(inode->i_mapping);
 
-  folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+  folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
   if (IS_ERR(folio)) {
           int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
   .fallocate      = kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+  struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+  kfree(private);
+
+  free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+  struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+  /*
+   * mtree_destroy() can't be used within rcu callback, hence can't be
+   * done in ->free_inode().
+   */
+  if (private)
+          mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
   .statfs         = simple_statfs,
+  .destroy_inode  = kvm_gmem_destroy_inode,
+  .free_inode     = kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
                                                 loff_t size, u64 flags)
 {
+  struct kvm_gmem_inode_private *private;
   struct inode *inode;
+  int err;
 
   inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
   if (IS_ERR(inode))
           return inode;
 
+  err = -ENOMEM;
+  private = kzalloc(sizeof(*private), GFP_KERNEL);
+  if (!private)
+          goto out;
+
+  mt_init(&private->shareability);
+  inode->i_mapping->i_private_data = private;
+
+  err = kvm_gmem_shareability_setup(private, size, flags);
+  if (err)
+          goto out;
+
   inode->i_private = (void *)(unsigned long)flags;
   inode->i_op = &kvm_gmem_iops;
   inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
   WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
   return inode;
+
+out:
+  iput(inode);
+
+  return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
   if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
           valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+  if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+          valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
   if (flags & ~valid_flags)
           return -EINVAL;
 

virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964

Quoted 5 lines
virt/kvm/guest_memfd.c +2 -0
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
   if (!file)
           return -EFAULT;
 
+  filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+

I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new SHAREABILITY_GUEST_PREPARED state) the SHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPARED transition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.

I was originally planning on introducing a new rw_semaphore with similar semantics to the rw_lock that Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle setting SHAREABILITY_GUEST_PREPARED within fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.

They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.

I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:

KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes

but figured I'd mention it here in case there are other things to consider on the locking front.

Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.

-Mike

[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/

Quoted 16 lines
virt/kvm/guest_memfd.c +1 -2
   folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
   if (IS_ERR(folio)) {
           r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
           *page = folio_file_page(folio, index);
   else
           folio_put(folio);
-
 out:
+  filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
   fput(file);
   return r;
 }
--

2.49.0.1045.g170613ef41-goog

#16 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 10 lines · Vishal Annapurve

...

Quoted 8 lines

2) There are some use-cases for HugeTLB + CoCo that have come to my attention recently that put a lot of weight on still being able to maximize mapping/hugepage size when accessing shared mem from userspace, e.g. for certain DPDK workloads that accessed shared guest buffers from host userspace. We don't really have a story for this, and I wouldn't expect us to at this stage, but I think it ties into #1 so might be worth considering in that context.

Quoted 4 lines

Major problem I see here is that if anything in the kernel does a GUP on shared memory ranges (which is very likely to happen), it would be difficult to get them to let go of the whole hugepage before it can be split safely.

The scenario I was alluding to here:
guest trying to convert a subpage from a shared range backed by hugepage to private.

#17 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Vishal Annapurve
Quoted 71 lines · Vishal Annapurve
Quoted 70 lines · Michael Roth
Quoted 68 lines · Ackerley Tng
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 11 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

I can move this change to the later patch. Thanks! Will fix in the next revision.

Quoted 9 lines

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

I guess we could also have userspace be careful not to do any allocation before converting.

(Re-visiting this with the assumption that we *don't* intend to use mmap() to populate memory (in which case you can pretty much ignore my previous response))

I'm still not sure where the INIT_PRIVATE flag comes into play. For SNP, userspace already defaults to marking everything private pretty close to guest_memfd creation time, so the potential for allocations to occur in-between seems small, but worth confirming.

But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating guest_memfd memory (and even pre-faulting via KVM_PRE_FAULT_MEMORY), but I think that could still work right? The fallocate() handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for that fallocate() to happen before userspace does the "manually" shared->private conversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?

Quoted 19 lines
Quoted 19 lines

I assume we do want to support things like preallocating guest memory so not sure this approach is feasible to avoid splits.

But I feel like we might be working around a deeper issue here, which is that we are pre-emptively splitting anything that *could* be mapped into userspace (i.e. allocated+shared/mixed), rather than splitting when necessary.

I know that was the plan laid out in the guest_memfd calls, but I've run into a couple instances that have me thinking we should revisit this.

1) Some of the recent guest_memfd seems to be gravitating towards having userspace populate/initialize guest memory payload prior to boot via mmap()'ing the shared guest_memfd pages so things work the same as they would for initialized normal VM memory payload (rather than relying on back-channels in the kernel to user data into guest_memfd pages).

Quoted 8 lines
Quoted 3 lines

When you do this though, for an SNP guest at least, that memory acceptance is done in chunks of 4MB (with accept_memory=lazy), and because that will put each 1GB page into an allocated+mixed state,

I would like your help in understanding why we need to start guest_memfd ranges as shared for SNP guests. guest_memfd ranges being private simply should mean that certain ranges are not faultable by the userspace.

It's seeming like I probably misremembered, but I thought there was a discussion on guest_memfd call a month (or so?) ago about whether to continue to use backchannels to populate guest_memfd pages prior to launch. It was in the context of whether to keep using kvm_gmem_populate() for populating guest_memfd pages by copying them in from separate userspace buffer vs. simply populating them directly from userspace. I thought we were leaning on the latter since it was simpler all-around, which is great for SNP since that is already how it populates memory: by writing to it from userspace, which kvm_gmem_populate() then copies into guest_memfd pages. With shared gmem support, we just skip the latter now in the kernel rather needing changes to how userspace handles things in that regard. But maybe that was just wishful thinking :)

But you raise some very compelling points on why this might not be a good idea even if that was how that discussion went.

Quoted 11 lines

Will following work?
1) Userspace starts all guest_memfd ranges as private.
2) During early guest boot it starts issuing PSC requests for converting memory from shared to private

    -> KVM forwards this request to userspace
    -> Userspace checks that the pages are already private and simply

does nothing.
3) Pvalidate from guest on that memory will result in guest_memfd offset query which will cause the RMP table entries to actually get populated.

That would work, but there will need to be changes on userspace to deal with how SNP populates memory pre-boot just like normal VMs do. We will instead need to copy that data into separate buffers, and pass those in as the buffer hva instead of the shared hva corresponding to that GPA.

But that seems reasonable if it avoids so many other problems.

Quoted 16 lines
Quoted 16 lines

we end up splitting every 1GB to 4K and the guest can't even accept/PVALIDATE it 2MB at that point even if userspace doesn't touch anything in the range. As some point the guest will convert/accept the entire range, at which point we could merge, but for SNP we'd need guest cooperation to actually use a higher-granularity in stage2 page tables at that point since RMP entries are effectively all split to 4K.

I understand the intent is to default to private where this wouldn't be an issue, and we could punt to userspace to deal with it, but it feels like an artificial restriction to place on userspace. And if we do want to allow/expect guest_memfd contents to be initialized pre-boot just like normal memory, then userspace would need to jump through some hoops:

Quoted 4 lines
Quoted 2 lines

- if defaulting to private: add hooks to convert each range that's being modified to a shared state prior to writing to it

Why is that a problem?

These were only problems if we went the above-mentioned way of populating memory pre-boot via mmap() instead of other backchannels. If we don't do that, then both these things cease to be problems. Sounds goods to me. :)

Quoted 11 lines
Quoted 8 lines

- if defaulting to shared: initialize memory in-place, then covert everything else to private to avoid unecessarily splitting folios at run-time

It feels like implementations details are bleeding out into the API to some degree here (e.g. we'd probably at least need to document this so users know how to take proper advantage of hugepage support).

Does it make sense to keep the default behavior as INIT_PRIVATE for SNP VMs always even without using hugepages?

Yes!

Though, revisiting discussion around INIT_PRIVATE (without the baggage of potentially relying on mmap() to populate memory), I'm still not sure why it's needed. I responded in the context of Ackerley's initial reply above.

Quoted 15 lines
Quoted 9 lines

2) There are some use-cases for HugeTLB + CoCo that have come to my attention recently that put a lot of weight on still being able to maximize mapping/hugepage size when accessing shared mem from userspace, e.g. for certain DPDK workloads that accessed shared guest buffers from host userspace. We don't really have a story for this, and I wouldn't expect us to at this stage, but I think it ties into #1 so might be worth considering in that context.

Major problem I see here is that if anything in the kernel does a GUP on shared memory ranges (which is very likely to happen), it would be difficult to get them to let go of the whole hugepage before it can be split safely.

Quoted 4 lines

Another problem is guest_memfd today doesn't support management of large user space page table mappings, this can turnout to be significant work to do referring to hugetlb pagetable management logic.

Yah that was more line-of-sight that might be possible by going this route, but the refcount'ing issue above is a showstopper as always. I'd somehow convinced myself that supporting fine-grained splitting somehow worked around it, but you still have no idea what page you need to avoid converting and fancy splitting doesn't get you past that. More wishful thinking. =\

Thanks,

Mike

Quoted 343 lines
Quoted 343 lines

I'm still fine with the current approach as a starting point, but I'm wondering if improving both #1/#2 might not be so bad and maybe even give us some more flexibility (for instance, Sean had mentioned leaving open the option of tracking more than just shareability/mappability, and if there is split/merge logic associated with those transitions then re-scanning each of these attributes for a 1G range seems like it could benefit from some sort of intermediate data structure to help determine things like what mapping granularity is available for guest/userspace for a particular range.

One approach I was thinking of was that we introduce a data structure similar to KVM's memslot->arch.lpage_info() where we store information about what 1G/2M ranges are shared/private/mixed, and then instead of splitting ahead of time we just record that state into this data structure (using the same write lock as with the shareability/mappability state), and then at *fault* time we split the folio if our lpage_info-like data structure says the range is mixed.

Then, if guest converts a 2M/4M range to private while lazilly-accepting (for instance), we can still keep the folio intact as 1GB, but mark the 1G range in the lpage_info-like data structure as mixed so that we still inform KVM/etc. they need to map it as 2MB or lower in stage2 page tables. In that case, even at guest fault-time, we can leave the folio unsplit until userspace tries to touch it (though in most cases it never will and we can keep most of the guest's 1G intact for the duration of its lifetime).

On the userspace side, another nice thing there is if we see 1G is in a mixed state, but 2M is all-shared, then we can still leave the folio as 2M, and I think the refcount'ing logic would still work for the most part, which makes #2 a bit easier to implement as well.

And of course, we wouldn't need the INIT_PRIVATE then since we are only splitting when necessary.

But I guess this all comes down to how much extra pain there is in tracking a 1G folio that's been split into a mixed of 2MB/4K regions, but I think we'd get a lot more mileage out of getting that working and just completely stripping out all of the merging logic for initial implementation (other than at cleanup time), so maybe complexity-wise it balances out a bit?

Thanks,

Mike

Quoted 295 lines
Quoted 294 lines
Quoted 62 lines
Documentation/virt/kvm/api.rst +0 -0
 See KVM_SET_USER_MEMORY_REGION2 for additional details.
 
 4.143 KVM_PRE_FAULT_MEMORY
include/uapi/linux/kvm.h +2 -0
index 4cc824a3a7c9..d7df312479aa 100644
@@ -1567,7 +1567,9 @@ struct kvm_memory_attributes {
 #define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
 
 #define KVM_CREATE_GUEST_MEMFD    _IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
+
 #define GUEST_MEMFD_FLAG_SUPPORT_SHARED   (1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE     (1UL << 1)
 
 struct kvm_create_guest_memfd {
   __u64 size;
virt/kvm/guest_memfd.c +22 -0
index 239d0f13dcc1..590932499eba 100644
@@ -4,6 +4,7 @@
 #include <linux/falloc.h>
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
+#include <linux/maple_tree.h>
 #include <linux/pseudo_fs.h>
 #include <linux/pagemap.h>
 
@@ -17,6 +18,24 @@ struct kvm_gmem {
   struct list_head entry;
 };
 
+struct kvm_gmem_inode_private {
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+  struct maple_tree shareability;
+#endif
+};
+
+enum shareability {
+  SHAREABILITY_GUEST = 1, /* Only the guest can map (fault) folios in this range. */
+  SHAREABILITY_ALL = 2,   /* Both guest and host can fault folios in this range. */
+};
+
+static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index);
+
+static struct kvm_gmem_inode_private *kvm_gmem_private(struct inode *inode)
+{
+  return inode->i_mapping->i_private_data;
+}
+
 /**
  * folio_file_pfn - like folio_file_page, but return a pfn.
  * @folio: The folio which contains this index.
@@ -29,6 +48,58 @@ static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
   return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
 }
 
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+
+static int kvm_gmem_shareability_setup(struct kvm_gmem_inode_private *private,

virt/kvm/guest_memfd.c static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index) · line 63

Quoted 10 lines
virt/kvm/guest_memfd.c +10 -0
+                                loff_t size, u64 flags)
+{
+  enum shareability m;
+  pgoff_t last;
+
+  last = (size >> PAGE_SHIFT) - 1;
+  m = flags & GUEST_MEMFD_FLAG_INIT_PRIVATE ? SHAREABILITY_GUEST :
+                                              SHAREABILITY_ALL;
+  return mtree_store_range(&private->shareability, 0, last, xa_mk_value(m),
+                           GFP_KERNEL);

One really nice thing about using a maple tree is that it should get rid of a fairly significant startup delay for SNP/TDX when the entire xarray gets initialized with private attribute entries via KVM_SET_MEMORY_ATTRIBUTES (which is the current QEMU default behavior).

I'd originally advocated for sticking with the xarray implementation Fuad was using until we'd determined we really need it for HugeTLB support, but I'm sort of thinking it's already justified just based on the above.

Maybe it would make sense for KVM memory attributes too?

Quoted 135 lines
virt/kvm/guest_memfd.c +87 -1
+}
+
+static enum shareability kvm_gmem_shareability_get(struct inode *inode,
+                                           pgoff_t index)
+{
+  struct maple_tree *mt;
+  void *entry;
+
+  mt = &kvm_gmem_private(inode)->shareability;
+  entry = mtree_load(mt, index);
+  WARN(!entry,
+       "Shareability should always be defined for all indices in inode.");
+
+  return xa_to_value(entry);
+}
+
+static struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+  if (kvm_gmem_shareability_get(inode, index) != SHAREABILITY_ALL)
+          return ERR_PTR(-EACCES);
+
+  return kvm_gmem_get_folio(inode, index);
+}
+
+#else
+
+static int kvm_gmem_shareability_setup(struct maple_tree *mt, loff_t size, u64 flags)
+{
+  return 0;
+}
+
+static inline struct folio *kvm_gmem_get_shared_folio(struct inode *inode, pgoff_t index)
+{
+  WARN_ONCE("Unexpected call to get shared folio.")
+  return NULL;
+}
+
+#endif /* CONFIG_KVM_GMEM_SHARED_MEM */
+
 static int __kvm_gmem_prepare_folio(struct kvm *kvm, struct kvm_memory_slot *slot,
                               pgoff_t index, struct folio *folio)
 {
@@ -333,7 +404,7 @@ static vm_fault_t kvm_gmem_fault_shared(struct vm_fault *vmf)
 
   filemap_invalidate_lock_shared(inode->i_mapping);
 
-  folio = kvm_gmem_get_folio(inode, vmf->pgoff);
+  folio = kvm_gmem_get_shared_folio(inode, vmf->pgoff);
   if (IS_ERR(folio)) {
           int err = PTR_ERR(folio);
 
@@ -420,8 +491,33 @@ static struct file_operations kvm_gmem_fops = {
   .fallocate      = kvm_gmem_fallocate,
 };
 
+static void kvm_gmem_free_inode(struct inode *inode)
+{
+  struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+  kfree(private);
+
+  free_inode_nonrcu(inode);
+}
+
+static void kvm_gmem_destroy_inode(struct inode *inode)
+{
+  struct kvm_gmem_inode_private *private = kvm_gmem_private(inode);
+
+#ifdef CONFIG_KVM_GMEM_SHARED_MEM
+  /*
+   * mtree_destroy() can't be used within rcu callback, hence can't be
+   * done in ->free_inode().
+   */
+  if (private)
+          mtree_destroy(&private->shareability);
+#endif
+}
+
 static const struct super_operations kvm_gmem_super_operations = {
   .statfs         = simple_statfs,
+  .destroy_inode  = kvm_gmem_destroy_inode,
+  .free_inode     = kvm_gmem_free_inode,
 };
 
 static int kvm_gmem_init_fs_context(struct fs_context *fc)
@@ -549,12 +645,26 @@ static const struct inode_operations kvm_gmem_iops = {
 static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
                                                 loff_t size, u64 flags)
 {
+  struct kvm_gmem_inode_private *private;
   struct inode *inode;
+  int err;
 
   inode = alloc_anon_secure_inode(kvm_gmem_mnt->mnt_sb, name);
   if (IS_ERR(inode))
           return inode;
 
+  err = -ENOMEM;
+  private = kzalloc(sizeof(*private), GFP_KERNEL);
+  if (!private)
+          goto out;
+
+  mt_init(&private->shareability);
+  inode->i_mapping->i_private_data = private;
+
+  err = kvm_gmem_shareability_setup(private, size, flags);
+  if (err)
+          goto out;
+
   inode->i_private = (void *)(unsigned long)flags;
   inode->i_op = &kvm_gmem_iops;
   inode->i_mapping->a_ops = &kvm_gmem_aops;
@@ -566,6 +676,11 @@ static struct inode *kvm_gmem_inode_make_secure_inode(const char *name,
   WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
 
   return inode;
+
+out:
+  iput(inode);
+
+  return ERR_PTR(err);
 }
 
 static struct file *kvm_gmem_inode_create_getfile(void *priv, loff_t size,
@@ -654,6 +769,9 @@ int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
   if (kvm_arch_vm_supports_gmem_shared_mem(kvm))
           valid_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED;
 
+  if (flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED)
+          valid_flags |= GUEST_MEMFD_FLAG_INIT_PRIVATE;
+
   if (flags & ~valid_flags)
           return -EINVAL;
 

virt/kvm/guest_memfd.c int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, · line 964

Quoted 5 lines
virt/kvm/guest_memfd.c +2 -0
@@ -842,6 +960,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
   if (!file)
           return -EFAULT;
 
+  filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
+

I like the idea of using a write-lock/read-lock to protect write/read access to shareability state (though maybe not necessarily re-using filemap's invalidate lock), it's simple and still allows concurrent faulting in of gmem pages. One issue on the SNP side (which also came up in one of the gmem calls) is if we introduce support for tracking preparedness as discussed (e.g. via a new SHAREABILITY_GUEST_PREPARED state) the SHAREABILITY_GUEST->SHAREABILITY_GUEST_PREPARED transition would occur at fault-time, and so would need to take the write-lock and no longer allow for concurrent fault-handling.

I was originally planning on introducing a new rw_semaphore with similar semantics to the rw_lock that Fuad previously had in his restricted mmap series[1] (and simiar semantics to filemap invalidate lock here). The main difference, to handle setting SHAREABILITY_GUEST_PREPARED within fault paths, was that in the case of a folio being present for an index, the folio lock would also need to be held in order to update the shareability state. Because of that, fault paths (which will always either have or allocate folio basically) can rely on the folio lock to guard shareability state in a more granular way and so can avoid a global write lock.

They would still need to hold the read lock to access the tree however. Or more specifically, any paths that could allocate a folio need to take a read lock so there isn't a TOCTOU situation where shareability is being updated for an index for which a folio hasn't been allocated, but then just afterward the folio gets faulted in/allocated while the shareability state is already being updated which the understand that there was no folio around that needed locking.

I had a branch with in-place conversion support for SNP[2] that added this lock reworking on top of Fuad's series along with preparation tracking, but I'm now planning to rebase that on top of the patches from this series that Sean mentioned[3] earlier:

KVM: guest_memfd: Add CAP KVM_CAP_GMEM_CONVERSION
KVM: Query guest_memfd for private/shared status
KVM: guest_memfd: Skip LRU for guest_memfd folios
KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls
KVM: guest_memfd: Introduce and use shareability to guard faulting
KVM: guest_memfd: Make guest mem use guest mem inodes instead of anonymous inodes

but figured I'd mention it here in case there are other things to consider on the locking front.

Definitely agree with Sean though that it would be nice to start identifying a common base of patches for the in-place conversion enablement for SNP, TDX, and pKVM so the APIs/interfaces for hugepages can be handled separately.

-Mike

[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://github.com/mdroth/linux/commits/mmap-swprot-v10-snp0-wip2/
[3] https://lore.kernel.org/kvm/[email protected]/

Quoted 16 lines
virt/kvm/guest_memfd.c +1 -2
   folio = __kvm_gmem_get_pfn(file, slot, index, pfn, &is_prepared, max_order);
   if (IS_ERR(folio)) {
           r = PTR_ERR(folio);
@@ -857,8 +977,8 @@ int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
           *page = folio_file_page(folio, index);
   else
           folio_put(folio);
-
 out:
+  filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
   fput(file);
   return r;
 }
--

2.49.0.1045.g170613ef41-goog

#18 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 78 lines · Michael Roth
Quoted 76 lines · Vishal Annapurve
Quoted 75 lines · Michael Roth
Quoted 73 lines · Ackerley Tng
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 11 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

I can move this change to the later patch. Thanks! Will fix in the next revision.

Quoted 9 lines

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

Quoted 6 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

I guess we could also have userspace be careful not to do any allocation before converting.

(Re-visiting this with the assumption that we *don't* intend to use mmap() to populate memory (in which case you can pretty much ignore my previous response))

I am assuming in-place conversion with huge page backing for the discussion below.

Looks like there are three scenarios/usecases we are discussing here:
1) Pre-allocating guest_memfd file offsets
- Userspace can use fallocate to do this for hugepages by keeping
the file ranges marked private.
2) Prefaulting guest EPT/NPT entries
3) Populating initial guest payload into guest_memfd memory
- Userspace can mark certain ranges as shared, populate the
contents and convert the ranges back to private. So mmap will come in handy here.

Quoted 5 lines

I'm still not sure where the INIT_PRIVATE flag comes into play. For SNP, userspace already defaults to marking everything private pretty close to guest_memfd creation time, so the potential for allocations to occur in-between seems small, but worth confirming.

Ok, I am not much worried about whether the INIT_PRIVATE flag gets supported or not, but more about the default setting that different CVMs start with. To me, it looks like all CVMs should start as everything private by default and if there is a way to bake that configuration during guest_memfd creation time that would be good to have instead of doing "create and convert" operations and there is a fairly low cost to support this flag.

Quoted 9 lines

But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating guest_memfd memory (and even pre-faulting via KVM_PRE_FAULT_MEMORY), but I think that could still work right? The fallocate() handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for that fallocate() to happen before userspace does the "manually" shared->private conversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?

This usecase of being able to preallocate should still work with in-place conversion assuming all ranges are private before pre-population.

Quoted 29 lines
Quoted 20 lines
Quoted 20 lines

I assume we do want to support things like preallocating guest memory so not sure this approach is feasible to avoid splits.

But I feel like we might be working around a deeper issue here, which is that we are pre-emptively splitting anything that *could* be mapped into userspace (i.e. allocated+shared/mixed), rather than splitting when necessary.

I know that was the plan laid out in the guest_memfd calls, but I've run into a couple instances that have me thinking we should revisit this.

1) Some of the recent guest_memfd seems to be gravitating towards having userspace populate/initialize guest memory payload prior to boot via mmap()'ing the shared guest_memfd pages so things work the same as they would for initialized normal VM memory payload (rather than relying on back-channels in the kernel to user data into guest_memfd pages).

Quoted 8 lines
Quoted 3 lines

When you do this though, for an SNP guest at least, that memory acceptance is done in chunks of 4MB (with accept_memory=lazy), and because that will put each 1GB page into an allocated+mixed state,

I would like your help in understanding why we need to start guest_memfd ranges as shared for SNP guests. guest_memfd ranges being private simply should mean that certain ranges are not faultable by the userspace.

Quoted 12 lines

It's seeming like I probably misremembered, but I thought there was a discussion on guest_memfd call a month (or so?) ago about whether to continue to use backchannels to populate guest_memfd pages prior to launch. It was in the context of whether to keep using kvm_gmem_populate() for populating guest_memfd pages by copying them in from separate userspace buffer vs. simply populating them directly from userspace. I thought we were leaning on the latter since it was simpler all-around, which is great for SNP since that is already how it populates memory: by writing to it from userspace, which kvm_gmem_populate() then copies into guest_memfd pages. With shared gmem support, we just skip the latter now in the kernel rather needing changes to how userspace handles things in that regard. But maybe that was just wishful thinking :)

You remember it correctly and that's how userspace should pre-populate guest memory contents with in-place conversion support available. Userspace can simply do the following scheme as an example:
1) Create guest_memfd with the INIT_PRIVATE flag or if we decide to not go that way, create a guest_memfd file and set all ranges as private.
2) Preallocate the guest_memfd ranges.
3) Convert the needed ranges to shared, populate the initial guest payload and then convert those ranges back to private.

Important point here is that guest_memfd ranges can be marked as private before pre-allocating guest_memfd ranges.

Quoted 16 lines

But you raise some very compelling points on why this might not be a good idea even if that was how that discussion went.

Quoted 11 lines

Will following work?
1) Userspace starts all guest_memfd ranges as private.
2) During early guest boot it starts issuing PSC requests for converting memory from shared to private

    -> KVM forwards this request to userspace
    -> Userspace checks that the pages are already private and simply

does nothing.
3) Pvalidate from guest on that memory will result in guest_memfd offset query which will cause the RMP table entries to actually get populated.

Quoted 4 lines

That would work, but there will need to be changes on userspace to deal with how SNP populates memory pre-boot just like normal VMs do. We will instead need to copy that data into separate buffers, and pass those in as the buffer hva instead of the shared hva corresponding to that GPA.

Initial guest memory payload generally carries a much smaller footprint so I ignored that detail in the above sequence. As I said above, userspace should be able to use guest_memfd ranges to directly populate contents by converting those ranges to shared.

Quoted 22 lines

But that seems reasonable if it avoids so many other problems.

Quoted 19 lines
Quoted 18 lines

we end up splitting every 1GB to 4K and the guest can't even accept/PVALIDATE it 2MB at that point even if userspace doesn't touch anything in the range. As some point the guest will convert/accept the entire range, at which point we could merge, but for SNP we'd need guest cooperation to actually use a higher-granularity in stage2 page tables at that point since RMP entries are effectively all split to 4K.

I understand the intent is to default to private where this wouldn't be an issue, and we could punt to userspace to deal with it, but it feels like an artificial restriction to place on userspace. And if we do want to allow/expect guest_memfd contents to be initialized pre-boot just like normal memory, then userspace would need to jump through some hoops:

- if defaulting to private: add hooks to convert each range that's being modified to a shared state prior to writing to it

Quoted 6 lines
Quoted 1 line

Why is that a problem?

These were only problems if we went the above-mentioned way of populating memory pre-boot via mmap() instead of other backchannels. If we don't do that, then both these things cease to be problems. Sounds goods to me. :)

I think there wouldn't be a problem even if we pre-populated memory pre-boot via mmap(). Using mmap() seems a preferable option to me.

#19 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 123 lines · Vishal Annapurve
Quoted 78 lines · Michael Roth
Quoted 76 lines · Vishal Annapurve
Quoted 75 lines · Michael Roth
Quoted 73 lines · Ackerley Tng
Quoted 41 lines · Michael Roth
Quoted 40 lines · Ackerley Tng

Track guest_memfd memory's shareability status within the inode as opposed to the file, since it is property of the guest_memfd's memory contents.

Shareability is a property of the memory and is indexed using the page's index in the inode. Because shareability is the memory's property, it is stored within guest_memfd instead of within KVM, like in kvm->mem_attr_array.

KVM_MEMORY_ATTRIBUTE_PRIVATE in kvm->mem_attr_array must still be retained to allow VMs to only use guest_memfd for private memory and some other memory for shared memory.

Not all use cases require guest_memfd() to be shared with the host when first created. Add a new flag, GUEST_MEMFD_FLAG_INIT_PRIVATE, which when set on KVM_CREATE_GUEST_MEMFD, initializes the memory as private to the guest, and therefore not mappable by the host. Otherwise, memory is shared until explicitly converted to private.

Change-Id If03609cbab3ad1564685c85bdba6dcbb6b240c0f
---
 Documentation/virt/kvm/api.rst |   5 ++
 include/uapi/linux/kvm.h       |   2 +
 virt/kvm/guest_memfd.c         | 124 ++++++++++++++++++++++++++++++++-
 3 files changed, 129 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +0 -0
index 86f74ce7f12a..f609337ae1c2 100644
@@ -6408,6 +6408,11 @@ belonging to the slot via its userspace_addr.
 The use of GUEST_MEMFD_FLAG_SUPPORT_SHARED will not be allowed for CoCo VMs.
 This is validated when the guest_memfd instance is bound to the VM.
 
Quoted 11 lines

Documentation/virt/kvm/api.rst belonging to the slot via its userspace_addr. · line 6415

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+If the capability KVM_CAP_GMEM_CONVERSIONS is supported, then the 'flags' field
+supports GUEST_MEMFD_FLAG_INIT_PRIVATE.  Setting GUEST_MEMFD_FLAG_INIT_PRIVATE
+will initialize the memory for the guest_memfd as guest-only and not faultable
+by the host.
+

KVM_CAP_GMEM_CONVERSION doesn't get introduced until later, so it seems like this flag should be deferred until that patch is in place. Is it really needed at that point though? Userspace would be able to set the initial state via KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls.

I can move this change to the later patch. Thanks! Will fix in the next revision.

Quoted 9 lines

The mtree contents seems to get stored in the same manner in either case so performance-wise only the overhead of a few userspace<->kernel switches would be saved. Are there any other reasons?

Otherwise, maybe just settle on SHARED as a documented default (since at least non-CoCo VMs would be able to reliably benefit) and let CoCo/GUEST_MEMFD_FLAG_SUPPORT_SHARED VMs set PRIVATE at whatever granularity makes sense for the architecture/guest configuration.

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

Quoted 6 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

I guess we could also have userspace be careful not to do any allocation before converting.

(Re-visiting this with the assumption that we *don't* intend to use mmap() to populate memory (in which case you can pretty much ignore my previous response))

I am assuming in-place conversion with huge page backing for the discussion below.

Looks like there are three scenarios/usecases we are discussing here:
1) Pre-allocating guest_memfd file offsets
- Userspace can use fallocate to do this for hugepages by keeping
the file ranges marked private.
2) Prefaulting guest EPT/NPT entries
3) Populating initial guest payload into guest_memfd memory
- Userspace can mark certain ranges as shared, populate the
contents and convert the ranges back to private. So mmap will come in handy here.

Quoted 5 lines

I'm still not sure where the INIT_PRIVATE flag comes into play. For SNP, userspace already defaults to marking everything private pretty close to guest_memfd creation time, so the potential for allocations to occur in-between seems small, but worth confirming.

Ok, I am not much worried about whether the INIT_PRIVATE flag gets supported or not, but more about the default setting that different CVMs start with. To me, it looks like all CVMs should start as everything private by default and if there is a way to bake that configuration during guest_memfd creation time that would be good to have instead of doing "create and convert" operations and there is a fairly low cost to support this flag.

Quoted 9 lines

But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating guest_memfd memory (and even pre-faulting via KVM_PRE_FAULT_MEMORY), but I think that could still work right? The fallocate() handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for that fallocate() to happen before userspace does the "manually" shared->private conversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?

Quoted 3 lines

This usecase of being able to preallocate should still work with in-place conversion assuming all ranges are private before pre-population.

Ok, I think I was missing that the merge logic here will then restore it to 1GB before the guest starts, so the folio isn't permanently split if we do the mmap() and that gives us more flexibility on how we can use it.

I was thinking we needed to avoid the split from the start by avoiding paths like mmap() which might trigger the split. I was trying to avoid any merge->unsplit logic in the THP case (or unsplit in general), in which case we'd get permanent splits via the mmap() approach, but for 2MB that's probably not a big deal.

Quoted 53 lines
Quoted 30 lines
Quoted 21 lines
Quoted 21 lines

I assume we do want to support things like preallocating guest memory so not sure this approach is feasible to avoid splits.

But I feel like we might be working around a deeper issue here, which is that we are pre-emptively splitting anything that *could* be mapped into userspace (i.e. allocated+shared/mixed), rather than splitting when necessary.

I know that was the plan laid out in the guest_memfd calls, but I've run into a couple instances that have me thinking we should revisit this.

1) Some of the recent guest_memfd seems to be gravitating towards having userspace populate/initialize guest memory payload prior to boot via mmap()'ing the shared guest_memfd pages so things work the same as they would for initialized normal VM memory payload (rather than relying on back-channels in the kernel to user data into guest_memfd pages).

Quoted 8 lines
Quoted 3 lines

When you do this though, for an SNP guest at least, that memory acceptance is done in chunks of 4MB (with accept_memory=lazy), and because that will put each 1GB page into an allocated+mixed state,

I would like your help in understanding why we need to start guest_memfd ranges as shared for SNP guests. guest_memfd ranges being private simply should mean that certain ranges are not faultable by the userspace.

Quoted 12 lines

It's seeming like I probably misremembered, but I thought there was a discussion on guest_memfd call a month (or so?) ago about whether to continue to use backchannels to populate guest_memfd pages prior to launch. It was in the context of whether to keep using kvm_gmem_populate() for populating guest_memfd pages by copying them in from separate userspace buffer vs. simply populating them directly from userspace. I thought we were leaning on the latter since it was simpler all-around, which is great for SNP since that is already how it populates memory: by writing to it from userspace, which kvm_gmem_populate() then copies into guest_memfd pages. With shared gmem support, we just skip the latter now in the kernel rather needing changes to how userspace handles things in that regard. But maybe that was just wishful thinking :)

You remember it correctly and that's how userspace should pre-populate guest memory contents with in-place conversion support available. Userspace can simply do the following scheme as an example:
1) Create guest_memfd with the INIT_PRIVATE flag or if we decide to not go that way, create a guest_memfd file and set all ranges as private.
2) Preallocate the guest_memfd ranges.
3) Convert the needed ranges to shared, populate the initial guest payload and then convert those ranges back to private.

Quoted 2 lines

Important point here is that guest_memfd ranges can be marked as private before pre-allocating guest_memfd ranges.

Got it, and then the merge logic triggers so you get the 1GB back before guest launch. That seems reasonable. I was only thinking of the merge logic in the context of a running guest and it didn't seem all that useful in that regard, but it makes perfect sense for the above sort of scenario.

Thanks,

Mike

Quoted 59 lines
Quoted 17 lines

But you raise some very compelling points on why this might not be a good idea even if that was how that discussion went.

Quoted 11 lines

Will following work?
1) Userspace starts all guest_memfd ranges as private.
2) During early guest boot it starts issuing PSC requests for converting memory from shared to private

    -> KVM forwards this request to userspace
    -> Userspace checks that the pages are already private and simply

does nothing.
3) Pvalidate from guest on that memory will result in guest_memfd offset query which will cause the RMP table entries to actually get populated.

Quoted 4 lines

That would work, but there will need to be changes on userspace to deal with how SNP populates memory pre-boot just like normal VMs do. We will instead need to copy that data into separate buffers, and pass those in as the buffer hva instead of the shared hva corresponding to that GPA.

Initial guest memory payload generally carries a much smaller footprint so I ignored that detail in the above sequence. As I said above, userspace should be able to use guest_memfd ranges to directly populate contents by converting those ranges to shared.

Quoted 22 lines

But that seems reasonable if it avoids so many other problems.

Quoted 19 lines
Quoted 18 lines

we end up splitting every 1GB to 4K and the guest can't even accept/PVALIDATE it 2MB at that point even if userspace doesn't touch anything in the range. As some point the guest will convert/accept the entire range, at which point we could merge, but for SNP we'd need guest cooperation to actually use a higher-granularity in stage2 page tables at that point since RMP entries are effectively all split to 4K.

I understand the intent is to default to private where this wouldn't be an issue, and we could punt to userspace to deal with it, but it feels like an artificial restriction to place on userspace. And if we do want to allow/expect guest_memfd contents to be initialized pre-boot just like normal memory, then userspace would need to jump through some hoops:

- if defaulting to private: add hooks to convert each range that's being modified to a shared state prior to writing to it

Quoted 6 lines
Quoted 1 line

Why is that a problem?

These were only problems if we went the above-mentioned way of populating memory pre-boot via mmap() instead of other backchannels. If we don't do that, then both these things cease to be problems. Sounds goods to me. :)

I think there wouldn't be a problem even if we pre-populated memory pre-boot via mmap(). Using mmap() seems a preferable option to me.

#20 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

Quoted 59 lines · Michael Roth
Quoted 50 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

Quoted 6 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

I guess we could also have userspace be careful not to do any allocation before converting.

(Re-visiting this with the assumption that we *don't* intend to use mmap() to populate memory (in which case you can pretty much ignore my previous response))

I am assuming in-place conversion with huge page backing for the discussion below.

Looks like there are three scenarios/usecases we are discussing here:
1) Pre-allocating guest_memfd file offsets
- Userspace can use fallocate to do this for hugepages by keeping
the file ranges marked private.
2) Prefaulting guest EPT/NPT entries
3) Populating initial guest payload into guest_memfd memory
- Userspace can mark certain ranges as shared, populate the
contents and convert the ranges back to private. So mmap will come in handy here.

Quoted 5 lines

I'm still not sure where the INIT_PRIVATE flag comes into play. For SNP, userspace already defaults to marking everything private pretty close to guest_memfd creation time, so the potential for allocations to occur in-between seems small, but worth confirming.

Ok, I am not much worried about whether the INIT_PRIVATE flag gets supported or not, but more about the default setting that different CVMs start with. To me, it looks like all CVMs should start as everything private by default and if there is a way to bake that configuration during guest_memfd creation time that would be good to have instead of doing "create and convert" operations and there is a fairly low cost to support this flag.

Quoted 9 lines

But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating guest_memfd memory (and even pre-faulting via KVM_PRE_FAULT_MEMORY), but I think that could still work right? The fallocate() handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for that fallocate() to happen before userspace does the "manually" shared->private conversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?

Quoted 3 lines

This usecase of being able to preallocate should still work with in-place conversion assuming all ranges are private before pre-population.

Ok, I think I was missing that the merge logic here will then restore it to 1GB before the guest starts, so the folio isn't permanently split if we do the mmap() and that gives us more flexibility on how we can use it.

Quoted 5 lines

I was thinking we needed to avoid the split from the start by avoiding paths like mmap() which might trigger the split. I was trying to avoid any merge->unsplit logic in the THP case (or unsplit in general), in which case we'd get permanent splits via the mmap() approach, but for 2MB that's probably not a big deal.

After initial payload population, during its runtime guest can cause different hugepages to get split which can remain split even after guest converts them back to private. For THP there may not be much benefit of merging those pages together specially if NPT/EPT entries can't be promoted back to hugepage mapping and there is no memory penalty as THP doesn't use HVO.

Wishful thinking on my part: It would be great to figure out a way to promote these pagetable entries without relying on the guest, if possible with ABI updates, as I think the host should have some control over EPT/NPT granularities even for Confidential VMs. Along the similar lines, it would be great to have "page struct"-less memory working for Confidential VMs, which should greatly reduce the toil with merge/split operations and will render the conversions mostly to be pagetable manipulations.

That being said, memory split and merge seem to be relatively lightweight for THP (with no memory allocation/freeing) and reusing the memory files after reboot of the guest VM will require pages to be merged to start with a clean slate. One possible option is to always merge as early as possible, second option is to invent a new UAPI to do it on demand.

For 1G pages, even if we go with 1G -> 2M -> 4K split stages, page splits result in higher memory usage with HVO around and it becomes useful to merge them back as early as possible as guest proceeds to convert subranges of different hugepages over its lifetime. Merging pages as early as possible also allows reusing of memory files during the next reboot without having to invent a new UAPI.

Caveats with "merge as early as possible":
- Shared to private conversions will be slower for hugetlb pages.
* Counter argument: These conversions are already slow as we need
safe refcounts to reach on the ranges getting converted.
- If guests convert a particular range often then extra merge/split operations will result in overhead.
* Counter argument: Since conversions are anyways slow, it's
beneficial for guests to avoid such a scenario and keep back and forth conversions as less frequent as possible.

#127 lore raw

Re: [RFC PATCH v2 18/51] mm: hugetlb: Cleanup interpretation of map_chg_state within alloc_hugetlb_folio()

In reply to Ackerley Tng
Quoted 21 lines · Ackerley Tng

Interpreting map_chg_state inline, within alloc_hugetlb_folio(), improves readability.

Instead of having cow_from_owner and the result of vma_needs_reservation() compute a map_chg_state, and then interpreting map_chg_state within alloc_hugetlb_folio() to determine whether to

+ Get a page from the subpool or
+ Charge cgroup reservations or
+ Commit vma reservations or
+ Clean up reservations

This refactoring makes those decisions just based on whether a vma_reservation_exists. If a vma_reservation_exists, the subpool had already been debited and the cgroup had been charged, hence alloc_hugetlb_folio() should not double-debit or double-charge. If the vma reservation can't be used (as in cow_from_owner), then the vma reservation effectively does not exist and vma_reservation_exists is set to false.

Quoted 6 lines

The conditions for committing reservations or cleaning are also updated to be paired with the corresponding conditions guarding reservation creation.

Change-Id I22d72a2cae61fb64dc78e0a870b254811a06a31e

Hi Ackerley,

Can you help me better understand how useful the refactors in this and the preceding patch are for the series as a whole?

It seems like you and Peter had two different, but mostly equivalent, directions with how this code should be refactored[1]. Do you gain much by replacing Peter's refactoring strategy? If it's mostly a stylistic thing, maybe it would be better to remove these patches just to get the number of patches to review down.

The logic in these two patches looks good to me, and I think I do slightly prefer your approach. But if we could drop these patches (i.e., mail them separately), that's probably better.

[1]: https://lore.kernel.org/linux-mm/[email protected]/

Reviewed-by on v2 16/51
#124 lore raw

Re: [RFC PATCH v2 16/51] mm: hugetlb: Consolidate interpretation of gbl_chg within alloc_hugetlb_folio()

In reply to Ackerley Tng
Quoted 5 lines · Ackerley Tng

Previously, gbl_chg was passed from alloc_hugetlb_folio() into dequeue_hugetlb_folio_vma(), leaking the concept of gbl_chg into dequeue_hugetlb_folio_vma().

Quoted 7 lines

This patch consolidates the interpretation of gbl_chg into alloc_hugetlb_folio(), also renaming dequeue_hugetlb_folio_vma() to dequeue_hugetlb_folio() so dequeue_hugetlb_folio() can just focus on dequeuing a folio.

Change-Id I31bf48af2400b6e13b44d03c8be22ce1a9092a9c

I think I agree with Binbin[1] to either put the rename of dequeue_hugetlb_folio{_vma => }() in its own patch or drop it entirely.

I think the rename would 100% make sense if all of the dequeue_hugetlb_folio*() functions were called from dequeue_hugetlb_folio_vma() (i.e., after this patch, dequeue_hugetlb_folio() was always the entry point to dequeue a folio), but in fact dequeue_hugetlb_folio_nodemask() is not always called from dequeue_hugetlb_folio_vma().

I don't feel strongly at all, either way the name is not confusing. So feel free to add:

[1]: https://lore.kernel.org/all/[email protected]/

Quoted 69 lines
---
 mm/hugetlb.c | 28 +++++++++++-----------------
 1 file changed, 11 insertions(+), 17 deletions(-)
mm/hugetlb.c +11 -18
index 6ea1be71aa42..b843e869496f 100644
@@ -1364,9 +1364,9 @@ static unsigned long available_huge_pages(struct hstate *h)
        return h->free_huge_pages - h->resv_huge_pages;
 }
 
-static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
-                               struct vm_area_struct *vma,
-                               unsigned long address, long gbl_chg)
+static struct folio *dequeue_hugetlb_folio(struct hstate *h,
+                                          struct vm_area_struct *vma,
+                                          unsigned long address)
 {
        struct folio *folio = NULL;
        struct mempolicy *mpol;
@@ -1374,13 +1374,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
        nodemask_t *nodemask;
        int nid;
 
-       /*
-        * gbl_chg==1 means the allocation requires a new page that was not
-        * reserved before.  Making sure there's at least one free page.
-        */
-       if (gbl_chg && !available_huge_pages(h))
-               goto err;
-
        gfp_mask = htlb_alloc_mask(h);
        nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
 
@@ -1398,9 +1391,6 @@ static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
 
        mpol_cond_put(mpol);
        return folio;
-
-err:
-       return NULL;
 }
 
 /*
@@ -3074,12 +3064,16 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
                goto out_uncharge_cgroup_reservation;
 
        spin_lock_irq(&hugetlb_lock);
+
        /*
-        * glb_chg is passed to indicate whether or not a page must be taken
-        * from the global free pool (global change).  gbl_chg == 0 indicates
-        * a reservation exists for the allocation.
+        * gbl_chg == 0 indicates a reservation exists for the allocation - so
+        * try dequeuing a page. If there are available_huge_pages(), try using
+        * them!
         */
-       folio = dequeue_hugetlb_folio_vma(h, vma, addr, gbl_chg);
+       folio = NULL;
+       if (!gbl_chg || available_huge_pages(h))
+               folio = dequeue_hugetlb_folio(h, vma, addr);
+
        if (!folio) {
                spin_unlock_irq(&hugetlb_lock);
                folio = alloc_buddy_hugetlb_folio_with_mpol(h, vma, addr);
--

2.49.0.1045.g170613ef41-goog

#234 lore raw
In reply to Vishal Annapurve
Quoted 3 lines · Vishal Annapurve

I would be curious to understand if we need zeroing on conversion for Confidential VMs. If not, then the simple rule of zeroing on allocation only will work for all usecases.

Unless I'm misunderstanding what your asking, pKVM very specific does NOT want zeroing on conversion, because one of its use cases is in-place conversion, e.g. to fill a shared buffer and then convert it to private so that the buffer can be processed in the TEE.

Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion, but that's essentially a property of the architecture, i.e. an arch/vendor specific detail.

#235 lore raw
Quoted 10 lines · Sean Christopherson
Quoted 3 lines · Vishal Annapurve

I would be curious to understand if we need zeroing on conversion for Confidential VMs. If not, then the simple rule of zeroing on allocation only will work for all usecases.

Unless I'm misunderstanding what your asking, pKVM very specific does NOT want zeroing on conversion, because one of its use cases is in-place conversion, e.g. to fill a shared buffer and then convert it to private so that the buffer can be processed in the TEE.

Yeah, that makes sense. So "just zero on allocation" (and no more zeroing during conversion) policy will work for pKVM.

Quoted 4 lines

Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion, but that's essentially a property of the architecture, i.e. an arch/vendor specific detail.

Conversion operation is a unique capability supported by guest_memfd files so my intention of bringing up zeroing was to better understand the need and clarify the role of guest_memfd in handling zeroing during conversion.

Not sure if I am misinterpreting you, but treating "zeroing during conversion" as the responsibility of arch/vendor specific implementation outside of guest_memfd sounds good to me.

#236 lore raw
Quoted 7 lines · Vishal Annapurve
Quoted 6 lines

Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion,
but that's essentially a property of the architecture, i.e. an arch/vendor specific
detail.

Quoted 8 lines

Conversion operation is a unique capability supported by guest_memfd files so my intention of bringing up zeroing was to better understand the need and clarify the role of guest_memfd in handling zeroing during conversion.

Not sure if I am misinterpreting you, but treating "zeroing during conversion" as the responsibility of arch/vendor specific implementation outside of guest_memfd sounds good to me.

For TDX if we don't zero on conversion from private->shared we will be dependent on behavior of the CPU when reading memory with keyid 0, which was previously encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the kernel in order to not make non-architectual behavior into userspace ABI.

Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning? Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)

#237 lore raw
Quoted 17 lines · Rick P Edgecombe
Quoted 7 lines · Vishal Annapurve
Quoted 6 lines

Some architectures, e.g. SNP and TDX, may effectively require zeroing on conversion,
but that's essentially a property of the architecture, i.e. an arch/vendor specific
detail.

Quoted 8 lines

Conversion operation is a unique capability supported by guest_memfd files so my intention of bringing up zeroing was to better understand the need and clarify the role of guest_memfd in handling zeroing during conversion.

Not sure if I am misinterpreting you, but treating "zeroing during conversion" as the responsibility of arch/vendor specific implementation outside of guest_memfd sounds good to me.

Quoted 5 lines

For TDX if we don't zero on conversion from private->shared we will be dependent on behavior of the CPU when reading memory with keyid 0, which was previously encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the kernel in order to not make non-architectual behavior into userspace ABI.

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Quoted 3 lines

Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?

Because it's literally converting memory from shared to private? And IICU, it's not a one-time provisioning, e.g. memory can go:

shared => fill => private => consume => shared => fill => private => consume

Quoted 2 lines

Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)

Are you referring to this suggestion?

: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion, and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

#238 lore raw
Quoted 9 lines · Sean Christopherson
Quoted 8 lines

For TDX if we don't zero on conversion from private->shared we will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.

Quoted 3 lines

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.

Quoted 9 lines
Quoted 4 lines

Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?

Because it's literally converting memory from shared to private?  And IICU, it's
not a one-time provisioning, e.g. memory can go:

Quoted 6 lines

  shared => fill => private => consume => shared => fill => private => consume

Quoted 2 lines

Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)

Are you referring to this suggestion?

Yea, in general to make it a specific operation preserving operation.

Quoted 11 lines

 : And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever.  That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

Ok, we should POC how it works with TDX.

#239 lore raw
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines

For TDX if we don't zero on conversion from private->shared we will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.

Quoted 3 lines

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Quoted 6 lines

Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.

If the answer is that "always zero on private to shared conversions" for all CC VMs, then does the scheme outlined in [1] make sense for handling the private -> shared conversions? For pKVM, there can be a VM type check to avoid the zeroing during conversions and instead just zero on allocations. This allows delaying zeroing until the fault time for CC VMs and can be done in guest_memfd centrally. We will need more inputs from the SEV side for this discussion.

[1] https://lore.kernel.org/lkml/CAGtprH-83EOz8rrUjE+O8m7nUDjt=THyXx=kfft1xQry65mtQg@mail.gmail.com/

Quoted 25 lines
Quoted 10 lines
Quoted 5 lines

Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?

Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:

Quoted 6 lines

shared => fill => private => consume => shared => fill => private => consume

Quoted 2 lines

Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)

Are you referring to this suggestion?

Yea, in general to make it a specific operation preserving operation.

Quoted 6 lines

: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

Quoted 7 lines
Quoted 5 lines

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

Ok, we should POC how it works with TDX.

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
2) Shared to private conversions are always content-preserving for all VMs as far as guest_memfd is concerned.
3) Private to shared conversions are not content-preserving for CC VMs as far as guest_memfd is concerned, subject to more discussions.

[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/

#240 lore raw
Quoted 32 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines

For TDX if we don't zero on conversion from private->shared we will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.

Quoted 3 lines

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Quoted 6 lines

Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.

If the answer is that "always zero on private to shared conversions" for all CC VMs, then does the scheme outlined in [1] make sense for handling the private -> shared conversions? For pKVM, there can be a VM type check to avoid the zeroing during conversions and instead just zero on allocations. This allows delaying zeroing until the fault time for CC VMs and can be done in guest_memfd centrally. We will need more inputs from the SEV side for this discussion.

Quoted 1 line

[1] https://lore.kernel.org/lkml/CAGtprH-83EOz8rrUjE+O8m7nUDjt=THyXx=kfft1xQry65mtQg@mail.gmail.com/

It's nice that we don't double zero (since TDX module will do it too) for private allocation/mapping. Seems ok to me.

Quoted 34 lines
Quoted 26 lines
Quoted 11 lines
Quoted 6 lines

Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?

Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:

Quoted 6 lines

shared => fill => private => consume => shared => fill => private => consume

Quoted 2 lines

Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)

Are you referring to this suggestion?

Yea, in general to make it a specific operation preserving operation.

Quoted 6 lines

: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

Quoted 7 lines
Quoted 5 lines

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

Ok, we should POC how it works with TDX.

Quoted 8 lines

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
2) Shared to private conversions are always content-preserving for all VMs as far as guest_memfd is concerned.
3) Private to shared conversions are not content-preserving for CC VMs as far as guest_memfd is concerned, subject to more discussions.

[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/

Right, I read that. I still don't see why pKVM needs to do normal private/shared conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.

I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?

So for all VM types, the user ABI would be:
private->shared - Always zero's page
shared->private - Always destructive
shared->private (w/flag) - Always preserves data or return error if not possible

Do you see a problem?

#258 lore raw
In reply to Vishal Annapurve
Quoted 24 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines

For TDX if we don't zero on conversion from private->shared we will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.

Quoted 3 lines

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Quoted 6 lines

Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.

Quoted 2 lines

If the answer is that "always zero on private to shared conversions" for all CC VMs,

pKVM VMs *are* CoCo VMs. Just because pKVM doesn't rely on third party firmware to provide confidentiality and integrity doesn't make it any less of a CoCo VM.

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

Quoted 4 lines
Quoted 1 line

Ok, we should POC how it works with TDX.

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.

No? Perserving contents on private => shared is a security vulnerability waiting to happen.

Quoted 2 lines

2) Shared to private conversions are always content-preserving for all VMs as far as guest_memfd is concerned.

There is no "as far as guest_memfd is concerned". Userspace doesn't care whether code lives in guest_memfd.c versus arch/xxx/kvm, the only thing that matters is the behavior that userspace sees. I don't want to end up with userspace ABI that is vendor/VM specific.

Quoted 4 lines

3) Private to shared conversions are not content-preserving for CC VMs as far as guest_memfd is concerned, subject to more discussions.

[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/

#259 lore raw

Hi Sean,

Quoted 45 lines · Sean Christopherson
Quoted 24 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines

For TDX if we don't zero on conversion from private->shared we will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.

Quoted 3 lines

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Quoted 6 lines

Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.

Quoted 2 lines

If the answer is that "always zero on private to shared conversions" for all CC VMs,

pKVM VMs *are* CoCo VMs. Just because pKVM doesn't rely on third party firmware to provide confidentiality and integrity doesn't make it any less of a CoCo VM.

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

Ok, we should POC how it works with TDX.

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.

No? Perserving contents on private => shared is a security vulnerability waiting to happen.

Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).

To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.

Cheers,
/fuad

Quoted 12 lines
Quoted 2 lines

2) Shared to private conversions are always content-preserving for all VMs as far as guest_memfd is concerned.

There is no "as far as guest_memfd is concerned". Userspace doesn't care whether code lives in guest_memfd.c versus arch/xxx/kvm, the only thing that matters is the behavior that userspace sees. I don't want to end up with userspace ABI that is vendor/VM specific.

Quoted 4 lines

3) Private to shared conversions are not content-preserving for CC VMs as far as guest_memfd is concerned, subject to more discussions.

[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/

#241 lore raw
In reply to Edgecombe, Rick P
Quoted 80 lines · Rick P
Quoted 32 lines · Vishal Annapurve
Quoted 15 lines · Rick P
Quoted 9 lines · Sean Christopherson
Quoted 8 lines

For TDX if we don't zero on conversion from private->shared we will be dependent
on behavior of the CPU when reading memory with keyid 0, which was previously
encrypted and has some protection bits set. I don't *think* the behavior is architectural. So it might be prudent to either make it so, or zero it in the
kernel in order to not make non-architectual behavior into userspace ABI.

Quoted 3 lines

Ya, by "vendor specific", I was also lumping in cases where the kernel would need to zero memory in order to not end up with effectively undefined behavior.

Quoted 6 lines

Yea, more of an answer to Vishal's question about if CC VMs need zeroing. And the answer is sort of yes, even though TDX doesn't require it. But we actually don't want to zero memory when reclaiming memory. So TDX KVM code needs to know that the operation is a to-shared conversion and not another type of private zap. Like a callback from gmem, or maybe more simply a kernel internal flag to set in gmem such that it knows it should zero it.

If the answer is that "always zero on private to shared conversions" for all CC VMs, then does the scheme outlined in [1] make sense for handling the private -> shared conversions? For pKVM, there can be a VM type check to avoid the zeroing during conversions and instead just zero on allocations. This allows delaying zeroing until the fault time for CC VMs and can be done in guest_memfd centrally. We will need more inputs from the SEV side for this discussion.

Quoted 1 line

[1] https://lore.kernel.org/lkml/CAGtprH-83EOz8rrUjE+O8m7nUDjt=THyXx=kfft1xQry65mtQg@mail.gmail.com/

It's nice that we don't double zero (since TDX module will do it too) for private allocation/mapping. Seems ok to me.

Quoted 41 lines
Quoted 26 lines
Quoted 11 lines
Quoted 6 lines

Up the thread Vishal says we need to support operations that use in-place conversion (overloaded term now I think, btw). Why exactly is pKVM using private/shared conversion for this private data provisioning?

Because it's literally converting memory from shared to private? And IICU, it's
not a one-time provisioning, e.g. memory can go:

Quoted 6 lines

shared => fill => private => consume => shared => fill => private => consume

Quoted 2 lines

Instead of a special provisioning operation like the others? (Xiaoyao's suggestion)

Are you referring to this suggestion?

Yea, in general to make it a specific operation preserving operation.

Quoted 6 lines

: And maybe a new flag for KVM_GMEM_CONVERT_PRIVATE for user space to : explicitly request that the page range is converted to private and the : content needs to be retained. So that TDX can identify which case needs : to call in-place TDH.PAGE.ADD.

Quoted 7 lines
Quoted 5 lines

If so, I agree with that idea, e.g. add a PRESERVE flag or whatever. That way userspace has explicit control over what happens to the data during conversion,
and KVM can reject unsupported conversions, e.g. PRESERVE is only allowed for shared => private and only for select VM types.

Ok, we should POC how it works with TDX.

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.
2) Shared to private conversions are always content-preserving for all VMs as far as guest_memfd is concerned.
3) Private to shared conversions are not content-preserving for CC VMs as far as guest_memfd is concerned, subject to more discussions.

Quoted 5 lines
Quoted 1 line

[2] https://lore.kernel.org/lkml/CAGtprH-Kzn2kOGZ4JuNtUT53Hugw64M-_XMmhz_gCiDS6BAFtQ@mail.gmail.com/

Right, I read that. I still don't see why pKVM needs to do normal private/shared conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.

It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.

Quoted 5 lines

I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?

I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type). Common operations in guest_memfd will need to either check for the userspace passed flag or the VM type, so no major change in guest_memfd implementation for either mechanism.

Quoted 9 lines

So for all VM types, the user ABI would be:
private->shared - Always zero's page
shared->private - Always destructive
shared->private (w/flag) - Always preserves data or return error if not possible

Do you see a problem?

#260 lore raw
In reply to Fuad Tabba
Quoted 11 lines · Fuad Tabba
Quoted 5 lines
Quoted 2 lines

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.

No? Perserving contents on private => shared is a security vulnerability waiting to happen.

Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).

Quoted 4 lines

To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.

I forget, what's the "explicit sharing" flow look like? E.g. how/when does pKVM know it's ok to convert memory from private to shared? I think we'd still want to make data preservation optional, e.g. to avoid potential leakage with setups where memory is private by default, but a flag in KVM's uAPI might not be a good fit since whether or not to preserve data is more of a guest decision (or at least needs to be ok'd by the guest).

#242 lore raw
In reply to Vishal Annapurve
Quoted 7 lines · Vishal Annapurve
Quoted 4 lines

Right, I read that. I still don't see why pKVM needs to do normal private/shared
conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.

It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.

We are weighing pros/cons between:
- Unifying this uABI across all gmemfd VM types
- Userspace for one VM type passing a flag for it's special non-shared use case

I don't see how passing a flag or not is dictated by pKVM use case.

P.S. This doesn't really impact TDX I think. Except that TDX development needs to work in the code without bumping anything. So just wishing to work in code with less conditionals.

Quoted 9 lines
Quoted 6 lines

I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace  always use the operation that says preserve content? Vs changing the behavior of the common operations?

I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type).

The benefit is that we don't need to have special VM default behavior for gmemfd. Think about if some day (very hypothetical and made up) we want to add a mode for TDX that adds new private data to a running guest (with special accept on the guest side or something). Then we might want to add a flag to override the default destructive behavior. Then maybe pKVM wants to add a "don't preserve" operation and it adds a second flag to not destroy. Now gmemfd has lots of VM specific flags. The point of this example is to show how unified uABI can he helpful.

Quoted 3 lines

Common operations in guest_memfd will need to either check for the userspace passed flag or the VM type, so no major change in guest_memfd implementation for either mechanism.

While we discuss ABI, we should allow ourselves to think ahead. So, is a gmemfd fd tied to a VM? I think there is interest in de-coupling it? Is the VM type sticky?

It seems the more they are separate, the better it will be to not have VM-aware behavior living in gmem.

#243 lore raw
Quoted 6 lines · Rick P Edgecombe
Quoted 5 lines · Vishal Annapurve
Quoted 4 lines

Right, I read that. I still don't see why pKVM needs to do normal private/shared
conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.

Quoted 8 lines
Quoted 2 lines

It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.

We are weighing pros/cons between:
- Unifying this uABI across all gmemfd VM types
- Userspace for one VM type passing a flag for it's special non-shared use case

I don't see how passing a flag or not is dictated by pKVM use case.

Yep. Baking the behavior of a single usecase into the kernel's ABI is rarely a good idea. Just because pKVM's current usecases always wants contents to be preserved doesn't mean that pKVM will never change.

As a general rule, KVM should push policy to userspace whenever possible.

Quoted 14 lines

P.S. This doesn't really impact TDX I think. Except that TDX development needs to work in the code without bumping anything. So just wishing to work in code with less conditionals.

Quoted 9 lines
Quoted 6 lines

I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace  always use the operation that says preserve content? Vs changing the behavior of the common operations?

I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type).

Quoted 8 lines

The benefit is that we don't need to have special VM default behavior for gmemfd. Think about if some day (very hypothetical and made up) we want to add a mode for TDX that adds new private data to a running guest (with special accept on the guest side or something). Then we might want to add a flag to override the default destructive behavior. Then maybe pKVM wants to add a "don't preserve" operation and it adds a second flag to not destroy. Now gmemfd has lots of VM specific flags. The point of this example is to show how unified uABI can he helpful.

Yep again. Pivoting on the VM type would be completely inflexible. If pKVM gains a usecase that wants to zero memory on conversions, we're hosed. If SNP or TDX gains the ability to preserve data on conversions, we're hosed.

The VM type may restrict what is possible, but (a) that should be abstracted, e.g. by defining the allowed flags during guest_memfd creation, and (b) the capabilities of the guest_memfd instance need to be communicated to userspace.

Quoted 6 lines
Quoted 3 lines

Common operations in guest_memfd will need to either check for the userspace passed flag or the VM type, so no major change in guest_memfd implementation for either mechanism.

While we discuss ABI, we should allow ourselves to think ahead. So, is a gmemfd fd tied to a VM?

Yes.

Quoted 1 line

I think there is interest in de-coupling it?

No? Even if we get to a point where multiple distinct VMs can bind to a single guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole owner of the memory. AFAICT, fully decoupling guest_memfd from a VM would add non-trivial complexity for zero practical benefit.

Quoted 4 lines

Is the VM type sticky?

It seems the more they are separate, the better it will be to not have VM-aware behavior living in gmem.

Ya. A guest_memfd instance may have capabilities/features that are restricted and/or defined based on the properties of the owning VM, but we should do our best to make guest_memfd itself blissly unaware of the VM type.

#244 lore raw
Quoted 3 lines · Sean Christopherson
Quoted 1 line

I think there is interest in de-coupling it?

No?

I'm talking about the intra-host migration/reboot optimization stuff. And not doing a good job, sorry.

Quoted 5 lines

  Even if we get to a point where multiple distinct VMs can bind to a single guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole
owner of the memory.  AFAICT, fully decoupling guest_memfd from a VM would add non-trivial complexity for zero practical benefit.

I'm talking about moving a gmem fd between different VMs or something using KVM_LINK_GUEST_MEMFD [0]. Not advocating to try to support it. But trying to feel out where the concepts are headed. It kind of allows gmem fds (or just their source memory?) to live beyond a VM lifecycle.

[0] https://lore.kernel.org/all/[email protected]/
https://lore.kernel.org/kvm/[email protected]/

#261 lore raw
In reply to Sean Christopherson
Quoted 18 lines · Sean Christopherson
Quoted 11 lines · Fuad Tabba
Quoted 5 lines
Quoted 2 lines

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.

No? Perserving contents on private => shared is a security vulnerability waiting to happen.

Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).

Quoted 4 lines

To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.

Quoted 6 lines

I forget, what's the "explicit sharing" flow look like? E.g. how/when does pKVM know it's ok to convert memory from private to shared? I think we'd still want to make data preservation optional, e.g. to avoid potential leakage with setups where memory is private by default, but a flag in KVM's uAPI might not be a good fit since whether or not to preserve data is more of a guest decision (or at least needs to be ok'd by the guest).

In pKVM all sharing and unsharing is triggered by the guest via hypercalls. The host cannot unshare. That said, making data preservation optional works for pKVM and is a good idea, for the reasons that you've mentioned.

Cheers,
/fuad

#245 lore raw
In reply to Edgecombe, Rick P
Quoted 14 lines · Rick P Edgecombe
Quoted 3 lines · Sean Christopherson
Quoted 1 line

I think there is interest in de-coupling it?

No?

I'm talking about the intra-host migration/reboot optimization stuff. And not doing a good job, sorry.

Quoted 5 lines

  Even if we get to a point where multiple distinct VMs can bind to a single guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole
owner of the memory.  AFAICT, fully decoupling guest_memfd from a VM would add non-trivial complexity for zero practical benefit.

Quoted 4 lines

I'm talking about moving a gmem fd between different VMs or something using KVM_LINK_GUEST_MEMFD [0]. Not advocating to try to support it. But trying to feel out where the concepts are headed. It kind of allows gmem fds (or just their source memory?) to live beyond a VM lifecycle.

I think the answer is that we want to let guest_memfd live beyond the "struct kvm" instance, but not beyond the Virtual Machine. From a past discussion on this topic[*].

: No go. Because again, the inode (physical memory) is coupled to the virtual machine : as a thing, not to a "struct kvm". Or more concretely, the inode is coupled to an : ASID or an HKID, and there can be multiple "struct kvm" objects associated with a : single ASID. And at some point in the future, I suspect we'll have multiple KVM : objects per HKID too.
:
: The current SEV use case is for the migration helper, where two KVM objects share : a single ASID (the "real" VM and the helper). I suspect TDX will end up with : similar behavior where helper "VMs" can use the HKID of the "real" VM. For KVM, : that means multiple struct kvm objects being associated with a single HKID. :
: To prevent use-after-free, KVM "just" needs to ensure the helper instances can't : outlive the real instance, i.e. can't use the HKID/ASID after the owning virtual : machine has been destroyed.
:
: To put it differently, "struct kvm" is a KVM software construct that _usually_, : but not always, is associated 1:1 with a virtual machine.
:
: And FWIW, stashing the pointer without holding a reference would not be a complete : solution, because it couldn't guard against KVM reusing a pointer. E.g. if a : struct kvm was unbound and then freed, KVM could reuse the same memory for a new : struct kvm, with a different ASID/HKID, and get a false negative on the rebinding : check.

Exactly what that will look like in code is TBD, but the concept/logic holds up.

[*] https://lore.kernel.org/all/[email protected]

Quoted 2 lines

[0] https://lore.kernel.org/all/[email protected]/
https://lore.kernel.org/kvm/[email protected]/

#255 lore raw
In reply to Sean Christopherson
Quoted 46 lines · Sean Christopherson
Quoted 6 lines · Rick P Edgecombe
Quoted 5 lines · Vishal Annapurve
Quoted 4 lines

Right, I read that. I still don't see why pKVM needs to do normal private/shared
conversion for data provisioning. Vs a dedicated operation/flag to make it a special case.

Quoted 8 lines
Quoted 2 lines

It's dictated by pKVM usecases, memory contents need to be preserved for every conversion not just for initial payload population.

We are weighing pros/cons between:
- Unifying this uABI across all gmemfd VM types
- Userspace for one VM type passing a flag for it's special non-shared use case

I don't see how passing a flag or not is dictated by pKVM use case.

Yep. Baking the behavior of a single usecase into the kernel's ABI is rarely a good idea. Just because pKVM's current usecases always wants contents to be preserved doesn't mean that pKVM will never change.

As a general rule, KVM should push policy to userspace whenever possible.

Quoted 14 lines

P.S. This doesn't really impact TDX I think. Except that TDX development needs to work in the code without bumping anything. So just wishing to work in code with less conditionals.

Quoted 9 lines
Quoted 6 lines

I'm trying to suggest there could be a benefit to making all gmem VM types behave the same. If conversions are always content preserving for pKVM, why can't userspace always use the operation that says preserve content? Vs changing the behavior of the common operations?

I don't see a benefit of userspace passing a flag that's kind of default for the VM type (assuming pKVM will use a special VM type).

Quoted 8 lines

The benefit is that we don't need to have special VM default behavior for gmemfd. Think about if some day (very hypothetical and made up) we want to add a mode for TDX that adds new private data to a running guest (with special accept on the guest side or something). Then we might want to add a flag to override the default destructive behavior. Then maybe pKVM wants to add a "don't preserve" operation and it adds a second flag to not destroy. Now gmemfd has lots of VM specific flags. The point of this example is to show how unified uABI can he helpful.

Quoted 7 lines

Yep again. Pivoting on the VM type would be completely inflexible. If pKVM gains a usecase that wants to zero memory on conversions, we're hosed. If SNP or TDX gains the ability to preserve data on conversions, we're hosed.

The VM type may restrict what is possible, but (a) that should be abstracted, e.g. by defining the allowed flags during guest_memfd creation, and (b) the capabilities of the guest_memfd instance need to be communicated to userspace.

Ok, I concur with this: It's beneficial to keep a unified ABI that allows guest_memfd to make runtime decisions without relying on VM type as far as possible.

Few points that seem important here:
1) Userspace can and should be able to only dictate if memory contents need to be preserved on shared to private conversion.
-> For SNP/TDX VMs:
* Only usecase for preserving contents is initial memory
population, which can be achieved by:
- Userspace converting the ranges to shared,
populating the contents, converting them back to private and then calling SNP/TDX specific existing ABI functions.
* For runtime conversions, guest_memfd can't ensure memory
contents are preserved during shared to private conversions as the architectures don't support that behavior.
* So IMO, this "preserve" flag doesn't make sense for SNP/TDX
VMs, even if we add this flag, today guest_memfd should effectively mark this unsupported based on the backing architecture support.
2) For pKVM, if userspace wants to specify a "preserve" flag then this flag can be allowed based on the known capabilities of the backing architecture.

So this topic is still orthogonal to "zeroing on private to shared conversion".

Quoted 25 lines
Quoted 7 lines
Quoted 4 lines

Common operations in guest_memfd will need to either check for the userspace passed flag or the VM type, so no major change in guest_memfd implementation for either mechanism.

While we discuss ABI, we should allow ourselves to think ahead. So, is a gmemfd fd tied to a VM?

Yes.

Quoted 1 line

I think there is interest in de-coupling it?

No? Even if we get to a point where multiple distinct VMs can bind to a single guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole owner of the memory. AFAICT, fully decoupling guest_memfd from a VM would add non-trivial complexity for zero practical benefit.

Quoted 4 lines

Is the VM type sticky?

It seems the more they are separate, the better it will be to not have VM-aware behavior living in gmem.

Ya. A guest_memfd instance may have capabilities/features that are restricted and/or defined based on the properties of the owning VM, but we should do our best to make guest_memfd itself blissly unaware of the VM type.

#256 lore raw
Quoted 4 lines · Vishal Annapurve

On Tue, Jul 8, 2025 at 11:03 AM Sean Christopherson <[email protected]> wrote:
Few points that seem important here:
1) Userspace can and should be able to only dictate if memory contents need to be preserved on shared to private conversion.

No, I was wrong, pKVM has use cases where it's desirable to preserve data on private => shared conversions.

Side topic, if you're going to use fancy indentation, align the indentation so it's actually readable.

Quoted 10 lines

-> For SNP/TDX VMs:
* Only usecase for preserving contents is initial memory population, which can be achieved by:
- Userspace converting the ranges to shared, populating the contents, converting them back to private and then calling SNP/TDX specific existing ABI functions.
* For runtime conversions, guest_memfd can't ensure memory contents are preserved during shared to private conversions as the architectures don't support that behavior.
* So IMO, this "preserve" flag doesn't make sense for SNP/TDX VMs, even

It makes sense, it's just not supported by the architecture *at runtime*. Case in point, *something* needs to allow preserving data prior to launching the VM. If we want to go with the PRIVATE => SHARED => FILL => PRIVATE approach for TDX and SNP, then we'll probably want to allow PRESERVE only until the VM image is finalized.

Quoted 4 lines

if we add this flag, today guest_memfd should effectively mark this unsupported based on the backing architecture support.

2) For pKVM, if userspace wants to specify a "preserve" flag then this

There is no "For pKVM". We are defining uAPI for guest_memfd. I.e. this statement holds true for all implementations: PRESERVE is allowed based on the capabilities of the architecture.

Quoted 1 line

So this topic is still orthogonal to "zeroing on private to shared conversion".

As above, no. pKVM might not expose PRESERVE to _userspace_ since all current conversions are initiated by the guest, but for guest_memfd itself, this is all one and the same.

#246 lore raw
In reply to Sean Christopherson
Quoted 4 lines · Sean Christopherson

I think the answer is that we want to let guest_memfd live beyond the "struct kvm" instance, but not beyond the Virtual Machine.  From a past discussion on this topic[*].

[snip]

Quoted 3 lines

Exactly what that will look like in code is TBD, but the concept/logic holds up.

[*] https://lore.kernel.org/all/[email protected]

Thanks for digging this up. Makes sense. One gmemfd per VM, but struct kvm != a VM.

#257 lore raw
In reply to Sean Christopherson
Quoted 24 lines · Sean Christopherson
Quoted 4 lines · Vishal Annapurve

On Tue, Jul 8, 2025 at 11:03 AM Sean Christopherson <[email protected]> wrote:
Few points that seem important here:
1) Userspace can and should be able to only dictate if memory contents need to be preserved on shared to private conversion.

No, I was wrong, pKVM has use cases where it's desirable to preserve data on private => shared conversions.

Side topic, if you're going to use fancy indentation, align the indentation so it's actually readable.

Quoted 10 lines

-> For SNP/TDX VMs:
* Only usecase for preserving contents is initial memory population, which can be achieved by:
- Userspace converting the ranges to shared, populating the contents, converting them back to private and then calling SNP/TDX specific existing ABI functions.
* For runtime conversions, guest_memfd can't ensure memory contents are preserved during shared to private conversions as the architectures don't support that behavior.
* So IMO, this "preserve" flag doesn't make sense for SNP/TDX VMs, even

Quoted 5 lines

It makes sense, it's just not supported by the architecture *at runtime*. Case in point, *something* needs to allow preserving data prior to launching the VM. If we want to go with the PRIVATE => SHARED => FILL => PRIVATE approach for TDX and SNP, then we'll probably want to allow PRESERVE only until the VM image is finalized.

Maybe we can simplify the story a bit here for today, how about:
1) For shared to private conversions:
* Is it safe to say that the conversion itself is always
content preserving, it's upto the
architecture what it does with memory contents on the private faults?
- During initial memory setup, userspace can control
how private memory would
be faulted in by architecture supported ABI operations.
- After initial memory setup, userspace can't control
how private memory would
be faulted in.
2) For private to shared conversions:
* Architecture decides what should be done with the memory on
shared faults.
- guest_memfd can query architecture whether to zero
memory or not.

-> guest_memfd will only take on the responsibility of zeroing if needed by the architecture on shared faults.
-> Architecture is responsible for the behavior on private faults.

In future, if there is a usecase for controlling runtime behavior of private faults, architecture can expose additional ABI that userspace can use after initiating guest_memfd conversion.

#247 lore raw
In reply to Sean Christopherson
Quoted 48 lines · Sean Christopherson
Quoted 14 lines · Rick P Edgecombe
Quoted 3 lines · Sean Christopherson
Quoted 1 line

I think there is interest in de-coupling it?

No?

I'm talking about the intra-host migration/reboot optimization stuff. And not doing a good job, sorry.

Quoted 5 lines

Even if we get to a point where multiple distinct VMs can bind to a single
guest_memfd, e.g. for inter-VM shared memory, there will still need to be a sole
owner of the memory. AFAICT, fully decoupling guest_memfd from a VM would add non-trivial complexity for zero practical benefit.

Quoted 4 lines

I'm talking about moving a gmem fd between different VMs or something using KVM_LINK_GUEST_MEMFD [0]. Not advocating to try to support it. But trying to feel out where the concepts are headed. It kind of allows gmem fds (or just their source memory?) to live beyond a VM lifecycle.

I think the answer is that we want to let guest_memfd live beyond the "struct kvm" instance, but not beyond the Virtual Machine. From a past discussion on this topic[*].

: No go. Because again, the inode (physical memory) is coupled to the virtual machine : as a thing, not to a "struct kvm". Or more concretely, the inode is coupled to an : ASID or an HKID, and there can be multiple "struct kvm" objects associated with a : single ASID. And at some point in the future, I suspect we'll have multiple KVM : objects per HKID too.
:
: The current SEV use case is for the migration helper, where two KVM objects share : a single ASID (the "real" VM and the helper). I suspect TDX will end up with : similar behavior where helper "VMs" can use the HKID of the "real" VM. For KVM, : that means multiple struct kvm objects being associated with a single HKID. :
: To prevent use-after-free, KVM "just" needs to ensure the helper instances can't : outlive the real instance, i.e. can't use the HKID/ASID after the owning virtual : machine has been destroyed.
:
: To put it differently, "struct kvm" is a KVM software construct that _usually_, : but not always, is associated 1:1 with a virtual machine.
:
: And FWIW, stashing the pointer without holding a reference would not be a complete : solution, because it couldn't guard against KVM reusing a pointer. E.g. if a : struct kvm was unbound and then freed, KVM could reuse the same memory for a new : struct kvm, with a different ASID/HKID, and get a false negative on the rebinding : check.

Quoted 1 line

Exactly what that will look like in code is TBD, but the concept/logic holds up.

I think we can simplify the role of guest_memfd in line with discussion [1]:
1) guest_memfd is a memory provider for userspace, KVM, IOMMU.
- It allows fallocate to populate/deallocate memory
2) guest_memfd supports the notion of private/shared faults.
3) guest_memfd supports memory access control:
- It allows shared faults from userspace, KVM, IOMMU
- It allows private faults from KVM, IOMMU
4) guest_memfd supports changing access control on its ranges between shared/private.
- It notifies the users to invalidate their mappings for the
ranges getting converted/truncated.

Responsibilities that ideally should not be taken up by guest_memfd:
1) guest_memfd can not initiate pre-faulting on behalf of it's users.
2) guest_memfd should not be directly communicating with the underlying architecture layers.
- All communication should go via KVM/IOMMU.
3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.
- Today KVM SNP logic ties RMP table entry lifetimes with how
long the folios are mapped in guest_memfd, which I think should be revisited.

Some very early thoughts on how guest_memfd could be laid out for the long term:
1) guest_memfd code ideally should be built-in to the kernel.
2) guest_memfd instances should still be created using KVM IOCTLs that carry specific capabilities/restrictions for its users based on the backing VM/arch.
3) Any outgoing communication from guest_memfd to it's users like userspace/KVM/IOMMU should be via notifiers to invalidate similar to how MMU notifiers work.
4) KVM and IOMMU can implement intermediate layers to handle interaction with guest_memfd.
- e.g. there could be a layer within kvm that handles:
- creating guest_memfd files and associating a
kvm_gmem_context with those files.
- memslot binding
- kvm_gmem_context will be used to bind kvm
memslots with the context ranges.
- invalidate notifier handling
- kvm_gmem_context will be used to intercept
guest_memfd callbacks and
translate them to the right GPA ranges.
- linking
- kvm_gmem_context can be linked to different
KVM instances.

This line of thinking can allow cleaner separation between guest_memfd/KVM/IOMMU [2].

[1] https://lore.kernel.org/lkml/CAGtprH-+gPN8J_RaEit=M_ErHWTmFHeCipC6viT6PHhG3ELg6A@mail.gmail.com/#t
[2] https://lore.kernel.org/lkml/[email protected]/

Quoted 5 lines

[*] https://lore.kernel.org/all/[email protected]

Quoted 2 lines

[0] https://lore.kernel.org/all/[email protected]/
https://lore.kernel.org/kvm/[email protected]/

#248 lore raw
Quoted 1 line · Vishal Annapurve

I think we can simplify the role of guest_memfd in line with discussion [1]:

I genuinely don't understand what you're trying to "simplify". We need to define an ABI that is flexible and robust, but beyond that most of these guidelines boil down to "don't write bad code".

Quoted 1 line

1) guest_memfd is a memory provider for userspace, KVM, IOMMU.

No, guest_memfd is a memory provider for KVM guests. That memory *might* be mapped by userspace and/or into IOMMU page tables in order out of functional necessity, but guest_memfd exists solely to serve memory to KVM guests, full stop.

Quoted 3 lines

3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.

Again, please align your indentation.

Quoted 3 lines

- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in guest_memfd, which I think should be revisited.

Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance.

Quoted 2 lines

Some very early thoughts on how guest_memfd could be laid out for the long term:
1) guest_memfd code ideally should be built-in to the kernel.

Why? How is this at all relevant? If we need to bake some parts of guest_memfd into the kernel in order to avoid nasty exports and/or ordering dependencies, then we can do so. But that is 100% an implementation detail and in no way a design goal.

#253 lore raw
In reply to Vishal Annapurve
Quoted 11 lines · Vishal Annapurve

I think we can simplify the role of guest_memfd in line with discussion [1]:
1) guest_memfd is a memory provider for userspace, KVM, IOMMU.
- It allows fallocate to populate/deallocate memory
2) guest_memfd supports the notion of private/shared faults.
3) guest_memfd supports memory access control:
- It allows shared faults from userspace, KVM, IOMMU
- It allows private faults from KVM, IOMMU
4) guest_memfd supports changing access control on its ranges between shared/private.
- It notifies the users to invalidate their mappings for the
ranges getting converted/truncated.

KVM needs to know if a GFN is private/shared. I think it is also intended to now be a repository for this information, right? Besides invalidations, it needs to be queryable.

Quoted 6 lines

Responsibilities that ideally should not be taken up by guest_memfd:
1) guest_memfd can not initiate pre-faulting on behalf of it's users.
2) guest_memfd should not be directly communicating with the underlying architecture layers.
- All communication should go via KVM/IOMMU.

Maybe stronger, there should be generic gmem behaviors. Not any special if (vm_type == tdx) type logic.

Quoted 6 lines

3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.
- Today KVM SNP logic ties RMP table entry lifetimes with how
long the folios are mapped in guest_memfd, which I think should be revisited.

I don't understand the problem. KVM needs to respond to user accessible invalidations, but how long it keeps other resources around could be useful for various optimizations. Like deferring work to a work queue or something.

I think it would help to just target the ackerly series goals. We should get that code into shape and this kind of stuff will fall out of it.

Quoted 16 lines

Some very early thoughts on how guest_memfd could be laid out for the long term:
1) guest_memfd code ideally should be built-in to the kernel.
2) guest_memfd instances should still be created using KVM IOCTLs that carry specific capabilities/restrictions for its users based on the backing VM/arch.
3) Any outgoing communication from guest_memfd to it's users like userspace/KVM/IOMMU should be via notifiers to invalidate similar to how MMU notifiers work.
4) KVM and IOMMU can implement intermediate layers to handle interaction with guest_memfd.
- e.g. there could be a layer within kvm that handles:
- creating guest_memfd files and associating a
kvm_gmem_context with those files.
- memslot binding
- kvm_gmem_context will be used to bind kvm

Quoted 8 lines

memslots with the context ranges.
- invalidate notifier handling
- kvm_gmem_context will be used to intercept
guest_memfd callbacks and
translate them to the right GPA ranges.
- linking
- kvm_gmem_context can be linked to different
KVM instances.

We can probably look at the code to decide these.

Quoted 14 lines

This line of thinking can allow cleaner separation between guest_memfd/KVM/IOMMU [2].

[1] https://lore.kernel.org/lkml/CAGtprH-+gPN8J_RaEit=M_ErHWTmFHeCipC6viT6PHhG3ELg6A@mail.gmail.com/#t
[2] https://lore.kernel.org/lkml/[email protected]/

Quoted 5 lines

[*] https://lore.kernel.org/all/[email protected]

Quoted 2 lines

[0] https://lore.kernel.org/all/[email protected]/
https://lore.kernel.org/kvm/[email protected]/

#249 lore raw
In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson
Quoted 1 line · Vishal Annapurve

I think we can simplify the role of guest_memfd in line with discussion [1]:

I genuinely don't understand what you're trying to "simplify". We need to define an ABI that is flexible and robust, but beyond that most of these guidelines boil down to "don't write bad code".

My goal for bringing this discussion up is to see if we can better define the role of guest_memfd and how it interacts with other layers, as I see some scenarios that can be improved like kvm_gmem_populate[1] where guest_memfd is trying to fault in pages on behalf of KVM.

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 6 lines
Quoted 2 lines

1) guest_memfd is a memory provider for userspace, KVM, IOMMU.

No, guest_memfd is a memory provider for KVM guests. That memory *might* be mapped by userspace and/or into IOMMU page tables in order out of functional necessity, but guest_memfd exists solely to serve memory to KVM guests, full stop.

I look at this as guest_memfd should serve memory to KVM guests and to other users by following some KVM/Arch related guidelines e.g. for CC VMs, guest_memfd can handle certain behavior differently.

Quoted 5 lines
Quoted 4 lines

3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.

Quoted 8 lines

Again, please align your indentation.

Quoted 3 lines

- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in guest_memfd, which I think should be revisited.

Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance.

IIUC guest_memfd can only be accessed through the window of memslots and if there are no memslots I don't see the reason for memory still being associated with "virtual machine". Likely because I am yet to completely wrap my head around 'guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance', I need to spend more time on this one.

Quoted 8 lines
Quoted 3 lines

Some very early thoughts on how guest_memfd could be laid out for the long term:
1) guest_memfd code ideally should be built-in to the kernel.

Why? How is this at all relevant? If we need to bake some parts of guest_memfd into the kernel in order to avoid nasty exports and/or ordering dependencies, then we can do so. But that is 100% an implementation detail and in no way a design goal.

I agree, this is implementation detail and we need real code to discuss this better.

#254 lore raw
In reply to Edgecombe, Rick P
Quoted 14 lines · Rick P
Quoted 11 lines · Vishal Annapurve

I think we can simplify the role of guest_memfd in line with discussion [1]:
1) guest_memfd is a memory provider for userspace, KVM, IOMMU.
- It allows fallocate to populate/deallocate memory
2) guest_memfd supports the notion of private/shared faults.
3) guest_memfd supports memory access control:
- It allows shared faults from userspace, KVM, IOMMU
- It allows private faults from KVM, IOMMU
4) guest_memfd supports changing access control on its ranges between shared/private.
- It notifies the users to invalidate their mappings for the
ranges getting converted/truncated.

Quoted 3 lines

KVM needs to know if a GFN is private/shared. I think it is also intended to now be a repository for this information, right? Besides invalidations, it needs to be queryable.

Yeah, that interface can be added as well. Though, if possible KVM can just directly pass the fault type to guest_memfd and it can return an error if the fault type doesn't match the permission. Additionally KVM does query the mapping order for a certain pfn/gfn which will need to be supported as well.

Quoted 18 lines
Quoted 7 lines

Responsibilities that ideally should not be taken up by guest_memfd:
1) guest_memfd can not initiate pre-faulting on behalf of it's users.
2) guest_memfd should not be directly communicating with the underlying architecture layers.
- All communication should go via KVM/IOMMU.

Maybe stronger, there should be generic gmem behaviors. Not any special if (vm_type == tdx) type logic.

Quoted 6 lines

3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.
- Today KVM SNP logic ties RMP table entry lifetimes with how
long the folios are mapped in guest_memfd, which I think should be revisited.

Quoted 3 lines

I don't understand the problem. KVM needs to respond to user accessible invalidations, but how long it keeps other resources around could be useful for various optimizations. Like deferring work to a work queue or something.

I don't think it could be deferred to a work queue as the RMP table entries will need to be removed synchronously once the last reference on the guest_memfd drops, unless memory itself is kept around after filemap eviction. I can see benefits of this approach for handling scenarios like intrahost-migration.

Quoted 29 lines

I think it would help to just target the ackerly series goals. We should get that code into shape and this kind of stuff will fall out of it.

Quoted 16 lines

Some very early thoughts on how guest_memfd could be laid out for the long term:
1) guest_memfd code ideally should be built-in to the kernel.
2) guest_memfd instances should still be created using KVM IOCTLs that carry specific capabilities/restrictions for its users based on the backing VM/arch.
3) Any outgoing communication from guest_memfd to it's users like userspace/KVM/IOMMU should be via notifiers to invalidate similar to how MMU notifiers work.
4) KVM and IOMMU can implement intermediate layers to handle interaction with guest_memfd.
- e.g. there could be a layer within kvm that handles:
- creating guest_memfd files and associating a
kvm_gmem_context with those files.
- memslot binding
- kvm_gmem_context will be used to bind kvm

Quoted 8 lines

memslots with the context ranges.
- invalidate notifier handling
- kvm_gmem_context will be used to intercept
guest_memfd callbacks and
translate them to the right GPA ranges.
- linking
- kvm_gmem_context can be linked to different
KVM instances.

Quoted 2 lines

We can probably look at the code to decide these.

Agree.

#77 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Vishal Annapurve
Quoted 92 lines · Vishal Annapurve
Quoted 67 lines · Alexey Kardashevskiy

...

Quoted 18 lines
Quoted 18 lines
Quoted 5 lines

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges

Done that.

Quoted 2 lines

* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

This API imho should drop the confusing kvm_ prefix.

Quoted 4 lines
       -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.

Quoted 6 lines
Quoted 1 line

Right now I cutnpasted kvm_gmem_get_folio() (which essentially is filemap_lock_folio()/filemap_alloc_folio()/__filemap_add_folio()) to avoid new links between iommufd.ko and kvm.ko. It is probably unavoidable though.

I don't think that's the way to avoid links between iommufd.ko and kvm.ko. Cleaner way probably is to have gmem logic built-in and allow runtime registration of invalidation callbacks from KVM/IOMMU backends. Need to think about this more.

Yeah, otherwise iommufd.ko will have to install a hook in guest_memfd (==kvm.ko) in run time so more beloved symbol_get() :)

Quoted 31 lines
Quoted 31 lines
Quoted 29 lines

* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

              -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

            -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

Quoted 6 lines
Quoted 1 line

Alright (although this zap+map is not necessary on the AMD hw).

IMO guest_memfd ideally should not directly interact or cater to arch specific needs, it should implement a mechanism that works for all archs. KVM/IOMMU implement invalidation callbacks and have all the architecture specific knowledge to take the right decisions.

Quoted 5 lines

Every page conversion will go through:

kvm-amd.ko -1-> guest_memfd (kvm.ko) -2-> iommufd.ko -3-> amd-iommu (build-in).

Which one decides on IOMMU not needing (un)mapping? Got to be (1) but then it need to propagate the decision to amd-iommu (and we do not have (3) at the moment in that path).

If there is a need, guest_memfd can support two different callbacks:
1) Conversion notifier/callback invoked by guest_memfd during conversion handling.
2) Invalidation notifier/callback invoked by guest_memfd during truncation.

Iommufd/kvm can handle conversion callback/notifier as per the needs of underlying architecture. e.g. for TDX connect do the unmapping vs for SEV Trusted IO skip the unmapping.

Invalidation callback/notifier will need to be handled by unmapping page tables.

Quoted 3 lines

Or we just always do unmap+map (and trigger unwanted page huge page smashing)? All is doable and neither particularly horrible, I'm trying to see where the consensus is now. Thanks,

I assume when you say huge page smashing, it means huge page NPT mapping getting split.

Quoted 7 lines

AFAIR, based on discussion with Michael during guest_memfd calls, stage2 NPT entries need to be of the same granularity as RMP tables for AMD SNP guests. i.e. huge page NPT mappings need to be smashed on the KVM side during conversion. So today guest_memfd sends invalidation notification to KVM for both conversion and truncation. Doesn't the same constraint for keeping IOMMU page tables at the same granularity as RMP tables hold for trusted IO?

Currently I handle this from the KVM with a hack to get IOPDE from AMD IOMMU so both 2MB RMP entry and IOPDE entries are smashed in one go in one of many firmwares running on EPYC, and atm this is too hacky to be posted even as an RFC. This likely needs to move to IOMMUFD then (via some callbacks) which could call AMD IOMMU which then would call that firmware (called "TMPM" and it is not the PSP which is "TSM), probably. Thanks,

Signature · 1 line
Alexey
#83 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Vishal Annapurve
Quoted 26 lines · Vishal Annapurve
Quoted 25 lines · Jason Gunthorpe
Quoted 22 lines · Vishal Annapurve
Quoted 21 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

Quoted 5 lines
Quoted 5 lines

I don't see this as having much to do with iommufd.

iommufd will somehow support the T=1 iommu inside the TDX module but it won't have an IOAS for it since the VMM does not control the translation.

I partially agree with this.

This is still the DMA Silent drop issue for security. The HW (Also applicable to AMD/ARM) screams out if the trusted DMA path (IOMMU mapping, or access control table like RMP) is changed out of TD's expectation. So from HW POV, it is the iommu problem.

For SW, if we don't blame iommu, maybe we rephrase as gmemfd can't invalidate private pages unless TD agrees.

Quoted 11 lines
Quoted 11 lines

The discussion here is for the T=0 iommu which is controlled by iommufd and does have an IOAS. It should be popoulated with all the shared pages from the guestmemfd.

Quoted 3 lines
Quoted 3 lines

If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so guest_memfd can reject the request before attempting the actual unmap.

This has to be delt with between the TDX module and KVM. When KVM gives pages to become secure it may not be able to get them back..

Just to be clear. With In-place conversion, it is not KVM gives pages to become secure, it is gmemfd. Or maybe you mean gmemfd is part of KVM.

https://lore.kernel.org/all/[email protected]/

Quoted 11 lines
Quoted 11 lines

This problem has nothing to do with iommufd.

But generally I expect that the T=1 iommu follows the S-EPT entirely and there is no notion of pages "locked for dma". If DMA is ongoing and a page is made non-secure then the DMA fails.

Obviously in a mode where there is a vPCI device we will need all the pages to be pinned in the guestmemfd to prevent any kind of migrations. Only shared/private conversions should change the page around.

Only *guest permitted* conversion should change the page. I.e only when VMM is dealing with the KVM_HC_MAP_GPA_RANGE hypercall. Not sure if we could just let QEMU ensure this or KVM/guestmemfd should ensure this.

Thanks,
Yilun

Quoted 11 lines

Yes, guest_memfd ensures that all the faulted-in pages (irrespective of shared or private ranges) are not migratable. We already have a similar restriction with CPU accesses to encrypted memory ranges that need arch specific protocols to migrate memory contents.

Quoted 4 lines

Maybe this needs to be an integral functionality in guestmemfd?

Jason

#84 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 33 lines · Xu Yilun
Quoted 26 lines · Vishal Annapurve
Quoted 25 lines · Jason Gunthorpe
Quoted 22 lines · Vishal Annapurve
Quoted 21 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

Quoted 5 lines
Quoted 5 lines

I don't see this as having much to do with iommufd.

iommufd will somehow support the T=1 iommu inside the TDX module but it won't have an IOAS for it since the VMM does not control the translation.

Quoted 6 lines

I partially agree with this.

This is still the DMA Silent drop issue for security. The HW (Also applicable to AMD/ARM) screams out if the trusted DMA path (IOMMU mapping, or access control table like RMP) is changed out of TD's expectation. So from HW POV, it is the iommu problem.

I thought the basic idea was that the secure world would sanity check what the insecure is doing and if it is not OK then it blows up. So if the DMA fails because the untrusted world revoked sharability when it should not have then this is correct and expected?

Quoted 2 lines

For SW, if we don't blame iommu, maybe we rephrase as gmemfd can't invalidate private pages unless TD agrees.

I think you mean guestmemfd in the kernel cannot autonomously change 'something' unless instructed to explicitly by userspace.

The expectation is the userspace will only give such instructions based on the VM telling it to do a shared/private change.

If userspace gives an instruction that was not agreed with the guest then the secure world can police the error and blow up.

Quoted 2 lines

Just to be clear. With In-place conversion, it is not KVM gives pages to become secure, it is gmemfd. Or maybe you mean gmemfd is part of KVM.

Yeah, I mean part of.

Quoted 8 lines
Quoted 4 lines
Quoted 4 lines

Obviously in a mode where there is a vPCI device we will need all the pages to be pinned in the guestmemfd to prevent any kind of migrations. Only shared/private conversions should change the page around.

Only *guest permitted* conversion should change the page. I.e only when VMM is dealing with the KVM_HC_MAP_GPA_RANGE hypercall. Not sure if we could just let QEMU ensure this or KVM/guestmemfd should ensure this.

I think it should not be part of the kernel, no need. From a kernel perspective userspace has requested a shared/private conversion and if it wasn't agreed with the VM then it will explode.

Jason

#78 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Alexey Kardashevskiy
Quoted 7 lines · Alexey Kardashevskiy

Currently I handle this from the KVM with a hack to get IOPDE from AMD IOMMU so both 2MB RMP entry and IOPDE entries are smashed in one go in one of many firmwares running on EPYC, and atm this is too hacky to be posted even as an RFC. This likely needs to move to IOMMUFD then (via some callbacks) which could call AMD IOMMU which then would call that firmware (called "TMPM" and it is not the PSP which is "TSM), probably. Thanks,

Wasn't the issue with the iommu that it needed to have a PTE break whenever the shared/private changed in the RMP? Because the HW can't handle an IOPTE that crosses more than one RMP entry? Or do I misunderstand the problem?

If this is the problem I was expecting the page table code that translates the guest memfd into the iommu PTEs would respect the shared/private conversion boundaries and break up the PTEs automatically.

I had thought there were three versions of of how to copy from guest memfd into the IOPTEs:
- HW must never have a private physaddr in an IOPTE
- HW must have IOPTEs entirely private or shared
- HW handles everything and IOPTEs should be maximally sized

Is this right? Is AMD #2?

Jason

#250 lore raw
In reply to Vishal Annapurve
Quoted 5 lines · Vishal Annapurve
Quoted 4 lines · Sean Christopherson
Quoted 1 line · Vishal Annapurve

I think we can simplify the role of guest_memfd in line with discussion [1]:

Quoted 8 lines
Quoted 3 lines

I genuinely don't understand what you're trying to "simplify". We need to define an ABI that is flexible and robust, but beyond that most of these guidelines boil down to "don't write bad code".

My goal for bringing this discussion up is to see if we can better define the role of guest_memfd and how it interacts with other layers, as I see some scenarios that can be improved like kvm_gmem_populate[1] where guest_memfd is trying to fault in pages on behalf of KVM.

Ah, gotcha. From my perspective, it's all just KVM, which is why I'm not feeling the same sense of urgency to formally define anything. We want to encapsulate code, have separate of concerns, etc., but I don't see that as being anything unique or special to guest_memfd. We try to achieve the same for all major areas of KVM, though obviously with mixed results :-)

#85 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Jason Gunthorpe
Quoted 36 lines · Jason Gunthorpe
Quoted 35 lines · Xu Yilun
Quoted 26 lines · Vishal Annapurve
Quoted 25 lines · Jason Gunthorpe
Quoted 22 lines · Vishal Annapurve
Quoted 21 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

Quoted 5 lines
Quoted 5 lines

I don't see this as having much to do with iommufd.

iommufd will somehow support the T=1 iommu inside the TDX module but it won't have an IOAS for it since the VMM does not control the translation.

I partially agree with this.

Quoted 7 lines
Quoted 4 lines

This is still the DMA Silent drop issue for security. The HW (Also applicable to AMD/ARM) screams out if the trusted DMA path (IOMMU mapping, or access control table like RMP) is changed out of TD's expectation. So from HW POV, it is the iommu problem.

I thought the basic idea was that the secure world would sanity check what the insecure is doing and if it is not OK then it blows up. So if

Yes. The secure world checks. But it let alone the unexpected change on CPU path cause CPU is synchronous and VM just pends on the fault, no security concern. While DMA is asynchronous and the secure world must blow up.

Quoted 2 lines

the DMA fails because the untrusted world revoked sharability when it should not have then this is correct and expected?

OK. From secure world POV the failing is correct & expected.

Quoted 4 lines
Quoted 3 lines

For SW, if we don't blame iommu, maybe we rephrase as gmemfd can't invalidate private pages unless TD agrees.

Quoted 8 lines

I think you mean guestmemfd in the kernel cannot autonomously change 'something' unless instructed to explicitly by userspace.

The expectation is the userspace will only give such instructions based on the VM telling it to do a shared/private change.

If userspace gives an instruction that was not agreed with the guest then the secure world can police the error and blow up.

Yes.

Quoted 11 lines
Quoted 3 lines

Just to be clear. With In-place conversion, it is not KVM gives pages to become secure, it is gmemfd. Or maybe you mean gmemfd is part of KVM.

Yeah, I mean part of.

Quoted 5 lines
Quoted 4 lines
Quoted 4 lines

Obviously in a mode where there is a vPCI device we will need all the pages to be pinned in the guestmemfd to prevent any kind of migrations. Only shared/private conversions should change the page around.

Quoted 7 lines
Quoted 3 lines

Only *guest permitted* conversion should change the page. I.e only when VMM is dealing with the KVM_HC_MAP_GPA_RANGE hypercall. Not sure if we could just let QEMU ensure this or KVM/guestmemfd should ensure this.

I think it should not be part of the kernel, no need. From a kernel perspective userspace has requested a shared/private conversion and if it wasn't agreed with the VM then it will explode.

I'm OK with it now. It's simple if we don't try to recover from the explosion. Although I see the after explosion processing in kernel is complex and not sure how it will advance.

Thanks,
Yilun

Quoted 2 lines

Jason

#86 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Only *guest permitted* conversion should change the page. I.e only when VMM is dealing with the KVM_HC_MAP_GPA_RANGE hypercall. Not sure if we could just let QEMU ensure this or KVM/guestmemfd should ensure this.

Quoted 7 lines
Quoted 3 lines

I think it should not be part of the kernel, no need. From a kernel perspective userspace has requested a shared/private conversion and if it wasn't agreed with the VM then it will explode.

I'm OK with it now. It's simple if we don't try to recover from the explosion. Although I see the after explosion processing in kernel is complex and not sure how it will advance.

I see the discussion in another thread about similar issue. That TDX Module BUG causes S-EPT unmap impossible and just KVM_BUG_ON(). But this conversion issue is a little different, usually it's not decent to panic because of userspace request. So may need further error handling, or a KVM/gmemfd kAPI to disallow/allow conversion and prevent more complex error.

Thanks,
Yilun

Quoted 7 lines

Thanks,
Yilun

Quoted 2 lines

Jason

#251 lore raw
In reply to Vishal Annapurve
Quoted 13 lines · Vishal Annapurve
Quoted 4 lines
Quoted 3 lines

3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.

Quoted 8 lines

Again, please align your indentation.

Quoted 3 lines

- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in guest_memfd, which I think should be revisited.

Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance.

Quoted 7 lines

IIUC guest_memfd can only be accessed through the window of memslots and if there are no memslots I don't see the reason for memory still being associated with "virtual machine". Likely because I am yet to completely wrap my head around 'guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance', I need to spend more time on this one.

I see the benefits of tying inodes to the virtual machine and different guest_memfd files to different KVM instances. This allows us to exercise intra-host migration usecases for TDX/SNP. But I think this model doesn't allow us to reuse guest_memfd files for SNP VMs during reboot.

Reboot scenario assuming reuse of existing guest_memfd inode for the next instance:
1) Create a VM
2) Create guest_memfd files that pin KVM instance
3) Create memslots
4) Start the VM
5) For reboot/shutdown, Execute VM specific Termination (e.g. KVM_TDX_TERMINATE_VM)
6) if allowed, delete the memslots
7) Create a new VM instance
8) Link the existing guest_memfd files to the new VM -> which creates new files for the same inode.
9) Close the existing guest_memfd files and the existing VM
10) Jump to step 3

The difference between SNP and TDX is that TDX memory ownership is limited to the duration the pages are mapped in the second stage secure EPT tables, whereas SNP/RMP memory ownership lasts beyond memslots and effectively remains till folios are punched out from guest_memfd filemap. IIUC CCA might follow the suite of SNP in this regard with the pfns populated in GPT entries.

I don't have a sense of how critical this problem could be, but this would mean for every reboot all large memory allocations will have to let go and need to be reallocated. For 1G support, we will be freeing guest_memfd pages using a background thread which may add some delays in being able to free up the memory in time.

Instead if we did this:
1) Support creating guest_memfd files for a certain VM type that allows KVM to dictate the behavior of the guest_memfd.
2) Tie lifetime of KVM SNP/TDX memory ownership with guest_memfd and memslot bindings
- Each binding will increase a refcount on both guest_memfd file
and KVM, so both can't go away while the binding exists.
3) For SNP/CCA, pfns are invalidated from RMP/GPT tables during unbind operations while for TDX, KVM will invalidate secure EPT entries.

This can allow us to decouple memory lifecycle from VM lifecycle and match the behavior with non-confidential VMs where memory can outlast VMs. Though this approach will mean change in intrahost migration implementation as we don't need to differentiate guest_memfd files and inodes.

That being said, I might be missing something here and I don't have any data to back the criticality of this usecase for SNP and possibly CCA VMs.

#21 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Vishal Annapurve
Quoted 73 lines · Vishal Annapurve
Quoted 59 lines · Michael Roth
Quoted 50 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

Because shared pages are split once any memory is allocated, having a way to INIT_PRIVATE could avoid the split and then merge on conversion. I feel that is enough value to have this config flag, what do you think?

Quoted 6 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

I guess we could also have userspace be careful not to do any allocation before converting.

(Re-visiting this with the assumption that we *don't* intend to use mmap() to populate memory (in which case you can pretty much ignore my previous response))

I am assuming in-place conversion with huge page backing for the discussion below.

Looks like there are three scenarios/usecases we are discussing here:
1) Pre-allocating guest_memfd file offsets
- Userspace can use fallocate to do this for hugepages by keeping
the file ranges marked private.
2) Prefaulting guest EPT/NPT entries
3) Populating initial guest payload into guest_memfd memory
- Userspace can mark certain ranges as shared, populate the
contents and convert the ranges back to private. So mmap will come in handy here.

Quoted 5 lines

I'm still not sure where the INIT_PRIVATE flag comes into play. For SNP, userspace already defaults to marking everything private pretty close to guest_memfd creation time, so the potential for allocations to occur in-between seems small, but worth confirming.

Ok, I am not much worried about whether the INIT_PRIVATE flag gets supported or not, but more about the default setting that different CVMs start with. To me, it looks like all CVMs should start as everything private by default and if there is a way to bake that configuration during guest_memfd creation time that would be good to have instead of doing "create and convert" operations and there is a fairly low cost to support this flag.

Quoted 9 lines

But I know in the past there was a desire to ensure TDX/SNP could support pre-allocating guest_memfd memory (and even pre-faulting via KVM_PRE_FAULT_MEMORY), but I think that could still work right? The fallocate() handling could still avoid the split if the whole hugepage is private, though there is a bit more potential for that fallocate() to happen before userspace does the "manually" shared->private conversion. I'll double-check on that aspect, but otherwise, is there still any other need for it?

Quoted 3 lines

This usecase of being able to preallocate should still work with in-place conversion assuming all ranges are private before pre-population.

Ok, I think I was missing that the merge logic here will then restore it to 1GB before the guest starts, so the folio isn't permanently split if we do the mmap() and that gives us more flexibility on how we can use it.

Quoted 5 lines

I was thinking we needed to avoid the split from the start by avoiding paths like mmap() which might trigger the split. I was trying to avoid any merge->unsplit logic in the THP case (or unsplit in general), in which case we'd get permanent splits via the mmap() approach, but for 2MB that's probably not a big deal.

After initial payload population, during its runtime guest can cause different hugepages to get split which can remain split even after guest converts them back to private. For THP there may not be much benefit of merging those pages together specially if NPT/EPT entries can't be promoted back to hugepage mapping and there is no memory penalty as THP doesn't use HVO.

Quoted 4 lines

Wishful thinking on my part: It would be great to figure out a way to promote these pagetable entries without relying on the guest, if possible with ABI updates, as I think the host should have some control over EPT/NPT granularities even for Confidential VMs. Along

I'm not sure how much it would buy us. For example, for a 2MB hugetlb SNP guest boot with 16GB of memory I see 622 2MB hugepages getting split, but only about 30 or so of those get merged back to 2MB folios during guest run-time. These are presumably the set of 2MB regions we could promote back up, but it's not much given that we wouldn't expect that value to grow proportionally for larger guests: it's really separate things like the number of vCPUs (for shared GHCB pages), number of virtio buffers, etc. that end up determining the upper bound on how many pages might get split due to 4K private->shared conversion, and these would vary all that much from get to get outside maybe vCPU count.

For 1GB hugetlb I see about 6 1GB pages get split, and only 2 get merged during run-time and would be candidates for promotion.

This could be greatly improved from the guest side by using higher-order allocations to create pools of shared memory that could then be used to reduce the number of splits caused by doing private->shared conversions on random ranges of malloc'd memory, and this could be done even without special promotion support on the host for pretty much the entirety of guest memory. The idea there would be to just making optimized guests avoid the splits completely, rather than relying on the limited subset that hardware can optimize without guest cooperation.

Quoted 4 lines

the similar lines, it would be great to have "page struct"-less memory working for Confidential VMs, which should greatly reduce the toil with merge/split operations and will render the conversions mostly to be pagetable manipulations.

FWIW, I did some profiling of split/merge vs. overall conversion time (by that I mean all cycles spent within kvm_gmem_convert_execute_work()), and while split/merge does take quite a few more cycles than your average conversion operation (~100x more), the total cycles spent splitting/merging ended up being about 7% of the total cycles spent handling conversions (1043938460 cycles in this case).

For 1GB, a split/merge take >1000x more than a normal conversion operation (46475980 cycles vs 320 in this sample), but it's probably still not too bad vs the overall conversion path, and as mentioned above it only happens about 6x for 16GB SNP guest so I don't think split/merge overhead is a huge deal for current guests, especially if we work toward optimizing guest-side usage of shared memory in the future. (There is potential for this to crater performance for a very poorly-optimized guest however but I think the guest should bear some burden for that sort of thing: e.g. flipping the same page back-and-forth between shared/private vs. caching it for continued usage as shared page in the guest driver path isn't something we should put too much effort into optimizing.)

Quoted 15 lines

That being said, memory split and merge seem to be relatively lightweight for THP (with no memory allocation/freeing) and reusing the memory files after reboot of the guest VM will require pages to be merged to start with a clean slate. One possible option is to always merge as early as possible, second option is to invent a new UAPI to do it on demand.

For 1G pages, even if we go with 1G -> 2M -> 4K split stages, page splits result in higher memory usage with HVO around and it becomes useful to merge them back as early as possible as guest proceeds to convert subranges of different hugepages over its lifetime. Merging pages as early as possible also allows reusing of memory files during the next reboot without having to invent a new UAPI.

Quoted 9 lines

Caveats with "merge as early as possible":
- Shared to private conversions will be slower for hugetlb pages.
* Counter argument: These conversions are already slow as we need
safe refcounts to reach on the ranges getting converted.
- If guests convert a particular range often then extra merge/split operations will result in overhead.
* Counter argument: Since conversions are anyways slow, it's
beneficial for guests to avoid such a scenario and keep back and forth conversions as less frequent as possible.

Fair enough. I'm not seeing any major reason not to do things this way, as the overhead doesn't seem to be very significant for the common case.

(even though, as noted above, the amount of hugetlb pages we actually end up merging at guest run-time seems to be fairly small, but maybe there are scenarios where this will have a bigger impact, and it certainly helps to have it there for the pre-boot merges.)

-Mike

#252 lore raw
In reply to Vishal Annapurve
Quoted 57 lines · Vishal Annapurve
Quoted 13 lines · Vishal Annapurve
Quoted 4 lines
Quoted 3 lines

3) KVM should ideally associate the lifetime of backing pagetables/protection tables/RMP tables with the lifetime of the binding of memslots with guest_memfd.

Quoted 8 lines

Again, please align your indentation.

Quoted 3 lines

- Today KVM SNP logic ties RMP table entry lifetimes with how long the folios are mapped in guest_memfd, which I think should be revisited.

Why? Memslots are ephemeral per-"struct kvm" mappings. RMP entries and guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance.

Quoted 7 lines

IIUC guest_memfd can only be accessed through the window of memslots and if there are no memslots I don't see the reason for memory still being associated with "virtual machine". Likely because I am yet to completely wrap my head around 'guest_memfd inodes are tied to the Virtual Machine, not to the "struct kvm" instance', I need to spend more time on this one.

I see the benefits of tying inodes to the virtual machine and different guest_memfd files to different KVM instances. This allows us to exercise intra-host migration usecases for TDX/SNP. But I think this model doesn't allow us to reuse guest_memfd files for SNP VMs during reboot.

Reboot scenario assuming reuse of existing guest_memfd inode for the next instance:
1) Create a VM
2) Create guest_memfd files that pin KVM instance
3) Create memslots
4) Start the VM
5) For reboot/shutdown, Execute VM specific Termination (e.g. KVM_TDX_TERMINATE_VM)
6) if allowed, delete the memslots
7) Create a new VM instance
8) Link the existing guest_memfd files to the new VM -> which creates new files for the same inode.
9) Close the existing guest_memfd files and the existing VM
10) Jump to step 3

The difference between SNP and TDX is that TDX memory ownership is limited to the duration the pages are mapped in the second stage secure EPT tables, whereas SNP/RMP memory ownership lasts beyond memslots and effectively remains till folios are punched out from guest_memfd filemap. IIUC CCA might follow the suite of SNP in this regard with the pfns populated in GPT entries.

I don't have a sense of how critical this problem could be, but this would mean for every reboot all large memory allocations will have to let go and need to be reallocated. For 1G support, we will be freeing guest_memfd pages using a background thread which may add some delays in being able to free up the memory in time.

Quoted 7 lines

Instead if we did this:
1) Support creating guest_memfd files for a certain VM type that allows KVM to dictate the behavior of the guest_memfd.
2) Tie lifetime of KVM SNP/TDX memory ownership with guest_memfd and memslot bindings
- Each binding will increase a refcount on both guest_memfd file
and KVM, so both can't go away while the binding exists.

I think if we can ensure that any guest_memfd initiated interaction with KVM is only for invalidation and is based on binding and under filemap_invalidate_lock then there is no need to pin KVM on each binding, as binding/unbinding should be protected using filemap_invalidate_lock and so KVM can't go away during invalidation.

Quoted 12 lines

3) For SNP/CCA, pfns are invalidated from RMP/GPT tables during unbind operations while for TDX, KVM will invalidate secure EPT entries.

This can allow us to decouple memory lifecycle from VM lifecycle and match the behavior with non-confidential VMs where memory can outlast VMs. Though this approach will mean change in intrahost migration implementation as we don't need to differentiate guest_memfd files and inodes.

That being said, I might be missing something here and I don't have any data to back the criticality of this usecase for SNP and possibly CCA VMs.

#22 lore raw

Re: [RFC PATCH v2 02/51] KVM: guest_memfd: Introduce and use shareability to guard faulting

In reply to Michael Roth
Quoted 18 lines · Michael Roth
Quoted 5 lines

Wishful thinking on my part: It would be great to figure out a way to promote these pagetable entries without relying on the guest, if possible with ABI updates, as I think the host should have some control over EPT/NPT granularities even for Confidential VMs. Along

I'm not sure how much it would buy us. For example, for a 2MB hugetlb SNP guest boot with 16GB of memory I see 622 2MB hugepages getting split, but only about 30 or so of those get merged back to 2MB folios during guest run-time. These are presumably the set of 2MB regions we could promote back up, but it's not much given that we wouldn't expect that value to grow proportionally for larger guests: it's really separate things like the number of vCPUs (for shared GHCB pages), number of virtio buffers, etc. that end up determining the upper bound on how many pages might get split due to 4K private->shared conversion, and these would vary all that much from get to get outside maybe vCPU count.

Quoted 3 lines

For 1GB hugetlb I see about 6 1GB pages get split, and only 2 get merged during run-time and would be candidates for promotion.

Thanks for the great analysis here. I think we will need to repeat such analysis for other scenarios such as usage with accelerators.

Quoted 9 lines

This could be greatly improved from the guest side by using higher-order allocations to create pools of shared memory that could then be used to reduce the number of splits caused by doing private->shared conversions on random ranges of malloc'd memory, and this could be done even without special promotion support on the host for pretty much the entirety of guest memory. The idea there would be to just making optimized guests avoid the splits completely, rather than relying on the limited subset that hardware can optimize without guest cooperation.

Yes, it would be great to improve the situation from the guest side, e.g. I tried with a rough draft [1], the conclusion there was that we need to set aside "enough" guest memory as CMA to cause all the DMA go through 2M aligned buffers. It's hard to figure out how much is "enough", but we could start somewhere. That being said, the host still has to manage memory this way by splitting/merging at runtime because I don't think it's possible to enforce all conversions to happen at 2M (or any at 1G) granularity. So it's also very likely that even if guests do significant chunk of conversions at hugepage granularity, host still needs to split pages all the way to 4K for all shared regions unless we can bake another restriction in the conversion ABI that guests can only convert the same ranges to private as were converted before to shared.

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 13 lines
Quoted 5 lines

the similar lines, it would be great to have "page struct"-less memory working for Confidential VMs, which should greatly reduce the toil with merge/split operations and will render the conversions mostly to be pagetable manipulations.

FWIW, I did some profiling of split/merge vs. overall conversion time (by that I mean all cycles spent within kvm_gmem_convert_execute_work()), and while split/merge does take quite a few more cycles than your average conversion operation (~100x more), the total cycles spent splitting/merging ended up being about 7% of the total cycles spent handling conversions (1043938460 cycles in this case).

Quoted 13 lines

For 1GB, a split/merge take >1000x more than a normal conversion operation (46475980 cycles vs 320 in this sample), but it's probably still not too bad vs the overall conversion path, and as mentioned above it only happens about 6x for 16GB SNP guest so I don't think split/merge overhead is a huge deal for current guests, especially if we work toward optimizing guest-side usage of shared memory in the future. (There is potential for this to crater performance for a very poorly-optimized guest however but I think the guest should bear some burden for that sort of thing: e.g. flipping the same page back-and-forth between shared/private vs. caching it for continued usage as shared page in the guest driver path isn't something we should put too much effort into optimizing.)

As per discussions in the past, guest_memfd private pages are simply only managed by guest_memfd. We don't need and effectively don't want the kernel to manage guest private memory. So effectively we can get rid of page structs in theory just for private pages as well and allocate page structs only for shared memory on conversion and deallocate on conversion back to private.

And when we have base core-mm allocators that hand out raw pfns to start with, we don't even need shared memory ranges to be backed by page structs.

Few hurdles we need to cross:
1) Invent a new filemap equivalent that maps guest_memfd offsets to pfns
2) Modify TDX EPT management to work with pfns and not page structs
3) Modify generic KVM NPT/EPT management logic to work with pfns and not rely on page structs
4) Modify memory error/hwpoison handling to route all memory errors on such pfns to guest_memfd.

I believe there are obvious benefits (reduced complexity, reduced memory footprint etc) if we go this route and we are very likely to go this route for future usecases even if we decide to live with conversion costs today.

#264 lore raw

cover QEMU: Enable in-place conversion and hugetlb gmem

In reply to Ackerley Tng

Hi all,

This is the POC to enable in-place conversion and hugetlb support of gmem (guest memfd) in QEMU. It can work with 1G gmem support series[1] and TDX hugepage support series[2] to run TDX guest with hugepage. I don't have SNP environment and don't know how it goes with SNP.

It is just the POC and we share it to show how QEMU work with gmem ABI.

The POC uses the simple implementation that switches to use in-place conversion and hugetlb when it is supported and it doesn't introduce new interface in QEMU so that existing command line to boot TDX can work without any change.

Please go to each patch (specifically patch 3/4/5) to discuss the ABI usage, potential issue, and maybe the upstreamable design.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Xiaoyao Li (4):
update-linux-headers: Add guestmem.h
headers: Fetch gmem updates
memory/guest_memfd: Enable hugetlb support
[HACK] memory: Don't enable in-place conversion for internal
MemoryRegion with gmem

Yan Zhao (1):
memory/guest_memfd: Enable in-place conversion when available

 accel/kvm/kvm-all.c             | 82 ++++++++++++++++++++++++---------
 accel/stubs/kvm-stub.c          |  2 +
 include/system/kvm.h            |  2 +
 include/system/memory.h         |  5 ++
 include/system/ramblock.h       |  1 +
 linux-headers/linux/guestmem.h  | 29 ++++++++++++
 linux-headers/linux/kvm.h       | 18 ++++++++
 scripts/update-linux-headers.sh |  2 +-
 system/memory.c                 |  9 +++-
 system/physmem.c                | 40 ++++++++++++++--
 10 files changed, 163 insertions(+), 27 deletions(-)
 create mode 100644 linux-headers/linux/guestmem.h
Signature · 1 line
2.43.0
#265 lore raw

PATCH 1/5 update-linux-headers: Add guestmem.h

---
 scripts/update-linux-headers.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/update-linux-headers.sh +1 -1
index b43b8ef75a63..3f6169a121a8 100755
@@ -200,7 +200,7 @@ rm -rf "$output/linux-headers/linux"
 mkdir -p "$output/linux-headers/linux"
 for header in const.h stddef.h kvm.h vfio.h vfio_ccw.h vfio_zdev.h vhost.h \
               psci.h psp-sev.h userfaultfd.h memfd.h mman.h nvme_ioctl.h \
-              vduse.h iommufd.h bits.h; do
+              vduse.h iommufd.h bits.h guestmem.h; do
     cp "$hdrdir/include/linux/$header" "$output/linux-headers/linux"
 done
 
Signature · 1 line
2.43.0
#266 lore raw

PATCH 2/5 headers: Fetch gmem updates

In reply to Xiaoyao Li
---
 linux-headers/linux/guestmem.h | 29 +++++++++++++++++++++++++++++
 linux-headers/linux/kvm.h      | 18 ++++++++++++++++++
 2 files changed, 47 insertions(+)
 create mode 100644 linux-headers/linux/guestmem.h
linux-headers/linux/guestmem.h new file +29 -0
new file mode 100644
index 000000000000..be045fbad230
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _LINUX_GUESTMEM_H
+#define _LINUX_GUESTMEM_H
+
+/*
+ * Huge page size must be explicitly defined when using the guestmem_hugetlb
+ * allocator for guest_memfd.  It is the responsibility of the application to
+ * know which sizes are supported on the running system.  See mmap(2) man page
+ * for details.
+ */
+
+#define GUESTMEM_HUGETLB_FLAG_SHIFT	58
+#define GUESTMEM_HUGETLB_FLAG_MASK	0x3fUL
+
+#define GUESTMEM_HUGETLB_FLAG_16KB	(14UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_64KB	(16UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_512KB	(19UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_1MB	(20UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_2MB	(21UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_8MB	(23UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_16MB	(24UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_32MB	(25UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_256MB	(28UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_512MB	(29UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_1GB	(30UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_2GB	(31UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+#define GUESTMEM_HUGETLB_FLAG_16GB	(34UL << GUESTMEM_HUGETLB_FLAG_SHIFT)
+
+#endif /* _LINUX_GUESTMEM_H */
linux-headers/linux/kvm.h +18 -0
index 32c5885a3c20..ff9ef5fb37c5 100644
@@ -952,6 +952,9 @@ struct kvm_enable_cap {
 #define KVM_CAP_ARM_EL2 240
 #define KVM_CAP_ARM_EL2_E2H0 241
 #define KVM_CAP_RISCV_MP_STATE_RESET 242
+#define KVM_CAP_GMEM_SHARED_MEM 240
+#define KVM_CAP_GMEM_CONVERSION 241
+#define KVM_CAP_GMEM_HUGETLB 242
 
 struct kvm_irq_routing_irqchip {
 	__u32 irqchip;
@@ -1589,12 +1592,27 @@ struct kvm_memory_attributes {
 
 #define KVM_CREATE_GUEST_MEMFD	_IOWR(KVMIO,  0xd4, struct kvm_create_guest_memfd)
 
+#define GUEST_MEMFD_FLAG_SUPPORT_SHARED	(1UL << 0)
+#define GUEST_MEMFD_FLAG_INIT_PRIVATE	(1UL << 1)
+#define GUEST_MEMFD_FLAG_HUGETLB	(1UL << 2)
+
 struct kvm_create_guest_memfd {
 	__u64 size;
 	__u64 flags;
 	__u64 reserved[6];
 };
 
+#define KVM_GMEM_IO 0xAF
+#define KVM_GMEM_CONVERT_SHARED		_IOWR(KVM_GMEM_IO,  0x41, struct kvm_gmem_convert)
+#define KVM_GMEM_CONVERT_PRIVATE	_IOWR(KVM_GMEM_IO,  0x42, struct kvm_gmem_convert)
+
+struct kvm_gmem_convert {
+	__u64 offset;
+	__u64 size;
+	__u64 error_offset;
+	__u64 reserved[5];
+};
+
 #define KVM_PRE_FAULT_MEMORY	_IOWR(KVMIO, 0xd5, struct kvm_pre_fault_memory)
 
 struct kvm_pre_fault_memory {
Signature · 1 line
2.43.0
#267 lore raw

PATCH 3/5 memory/guest_memfd: Enable in-place conversion when available

In reply to Xiaoyao Li

From: Yan Zhao <[email protected]>

(This is just the POC code to use in-place conversion gmem.)

Try to use in-place conversion gmem when it is supported.

When in-place conversion is enabled, there is no need to discard memory since it still needs to be used as the memory of opposite attribute after conversion.

For a upstreamable solution, we can introduce memory-backend-guestmemfd for in-place conversion. With the non in-place conversion, it needs seperate non-gmem memory to back the shared memory and gmem is created implicitly and internally based on vm type. While with in-place conversion, there is no need for seperate non-gmem memory because gmem itself can be served as shared memory. So that we can introduce memory-backend-guestmemfd as the specific backend for in-place conversion gmem.

Co-developed-by Xiaoyao Li <[email protected]>

---
 accel/kvm/kvm-all.c       | 79 ++++++++++++++++++++++++++++-----------
 accel/stubs/kvm-stub.c    |  1 +
 include/system/kvm.h      |  1 +
 include/system/memory.h   |  2 +
 include/system/ramblock.h |  1 +
 system/memory.c           |  7 ++++
 system/physmem.c          | 21 ++++++++++-
 7 files changed, 90 insertions(+), 22 deletions(-)
accel/kvm/kvm-all.c +58 -21
index a106d1ba0f0b..609537738d38 100644
@@ -105,6 +105,7 @@ static int kvm_sstep_flags;
 static bool kvm_immediate_exit;
 static uint64_t kvm_supported_memory_attributes;
 static bool kvm_guest_memfd_supported;
+bool kvm_guest_memfd_inplace_supported;
 static hwaddr kvm_max_slot_size = ~0;
 
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
@@ -1487,6 +1488,30 @@ static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)
     return r;
 }
 
+static int kvm_set_guest_memfd_shareability(MemoryRegion *mr, ram_addr_t offset,
+                                            uint64_t size, bool shared)
+{
+    int guest_memfd = mr->ram_block->guest_memfd;
+    struct kvm_gmem_convert param = {
+                .offset = offset,
+                .size = size,
+                .error_offset = 0,
+    };
+    unsigned long op;
+    int r;
+
+    op = shared ? KVM_GMEM_CONVERT_SHARED : KVM_GMEM_CONVERT_PRIVATE;
+
+    r = ioctl(guest_memfd, op, &param);
+    if (r) {
+        error_report("failed to set guest_memfd offset 0x%lx size 0x%lx to %s  "
+                     "error '%s' error offset 0x%llx",
+                     offset, size, shared ? "shared" : "private",
+                     strerror(errno), param.error_offset);
+    }
+    return r;
+}
+
 int kvm_set_memory_attributes_private(hwaddr start, uint64_t size)
 {
     return kvm_set_memory_attributes(start, size, KVM_MEMORY_ATTRIBUTE_PRIVATE);
@@ -1604,7 +1629,8 @@ static void kvm_set_phys_mem(KVMMemoryListener *kml,
             abort();
         }
 
-        if (memory_region_has_guest_memfd(mr)) {
+        if (memory_region_has_guest_memfd(mr) &&
+            !memory_region_guest_memfd_in_place_conversion(mr)) {
             err = kvm_set_memory_attributes_private(start_addr, slot_size);
             if (err) {
                 error_report("%s: failed to set memory attribute private: %s",
@@ -2779,6 +2805,9 @@ static int kvm_init(AccelState *as, MachineState *ms)
         kvm_check_extension(s, KVM_CAP_GUEST_MEMFD) &&
         kvm_check_extension(s, KVM_CAP_USER_MEMORY2) &&
         (kvm_supported_memory_attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE);
+    kvm_guest_memfd_inplace_supported =
+        kvm_check_extension(s, KVM_CAP_GMEM_SHARED_MEM) &&
+        kvm_check_extension(s, KVM_CAP_GMEM_CONVERSION);
     kvm_pre_fault_memory_supported = kvm_vm_check_extension(s, KVM_CAP_PRE_FAULT_MEMORY);
 
     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
@@ -3056,6 +3085,7 @@ static void kvm_eat_signals(CPUState *cpu)
 
 int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
 {
+    bool in_place_conversion = false;
     MemoryRegionSection section;
     ram_addr_t offset;
     MemoryRegion *mr;
@@ -3112,18 +3142,23 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
         goto out_unref;
     }
 
-    if (to_private) {
-        ret = kvm_set_memory_attributes_private(start, size);
-    } else {
-        ret = kvm_set_memory_attributes_shared(start, size);
-    }
-    if (ret) {
-        goto out_unref;
-    }
-
     addr = memory_region_get_ram_ptr(mr) + section.offset_within_region;
     rb = qemu_ram_block_from_host(addr, false, &offset);
 
+    in_place_conversion = memory_region_guest_memfd_in_place_conversion(mr);
+    if (in_place_conversion) {
+        ret = kvm_set_guest_memfd_shareability(mr, offset, size, !to_private);
+    } else {
+        if (to_private) {
+            ret = kvm_set_memory_attributes_private(start, size);
+        } else {
+            ret = kvm_set_memory_attributes_shared(start, size);
+        }
+    }
+    if (ret) {
+        goto out_unref;
+    }
+
     ret = ram_block_attributes_state_change(RAM_BLOCK_ATTRIBUTES(mr->rdm),
                                             offset, size, to_private);
     if (ret) {
@@ -3133,17 +3168,19 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
         goto out_unref;
     }
 
-    if (to_private) {
-        if (rb->page_size != qemu_real_host_page_size()) {
-            /*
-             * shared memory is backed by hugetlb, which is supposed to be
-             * pre-allocated and doesn't need to be discarded
-             */
-            goto out_unref;
-        }
-        ret = ram_block_discard_range(rb, offset, size);
-    } else {
-        ret = ram_block_discard_guest_memfd_range(rb, offset, size);
+    if (!in_place_conversion) {
+        if (to_private) {
+            if (rb->page_size != qemu_real_host_page_size()) {
+               /*
+                * shared memory is backed by hugetlb, which is supposed to be
+                * pre-allocated and doesn't need to be discarded
+                */
+                goto out_unref;
+             }
+             ret = ram_block_discard_range(rb, offset, size);
+         } else {
+             ret = ram_block_discard_guest_memfd_range(rb, offset, size);
+         }
     }
 
 out_unref:
accel/stubs/kvm-stub.c +1 -0
index 68cd33ba9735..bf0ccae27b62 100644
@@ -24,6 +24,7 @@ bool kvm_gsi_direct_mapping;
 bool kvm_allowed;
 bool kvm_readonly_mem_allowed;
 bool kvm_msi_use_devid;
+bool kvm_guest_memfd_inplace_supported;
 
 void kvm_flush_coalesced_mmio_buffer(void)
 {
include/system/kvm.h +1 -0
index 3c7d31473663..32f2be5f92e1 100644
@@ -43,6 +43,7 @@ extern bool kvm_gsi_direct_mapping;
 extern bool kvm_readonly_mem_allowed;
 extern bool kvm_msi_use_devid;
 extern bool kvm_pre_fault_memory_supported;
+extern bool kvm_guest_memfd_inplace_supported;
 
 #define kvm_enabled()           (kvm_allowed)
 /**
include/system/memory.h +2 -0
index 46248d4a52c4..f14fbf65805d 100644
@@ -1812,6 +1812,8 @@ bool memory_region_is_protected(MemoryRegion *mr);
  */
 bool memory_region_has_guest_memfd(MemoryRegion *mr);
 
+bool memory_region_guest_memfd_in_place_conversion(MemoryRegion *mr);
+
 /**
  * memory_region_get_iommu: check whether a memory region is an iommu
  *
include/system/ramblock.h +1 -0
index 87e847e184aa..87757940ea21 100644
@@ -46,6 +46,7 @@ struct RAMBlock {
     int fd;
     uint64_t fd_offset;
     int guest_memfd;
+    uint64_t guest_memfd_flags;
     RamBlockAttributes *attributes;
     size_t page_size;
     /* dirty bitmap used during migration */
system/memory.c +7 -0
index e8d9b15b28f6..6870a41629ef 100644
@@ -35,6 +35,7 @@
 
 #include "memory-internal.h"
 
+#include <linux/kvm.h>
 //#define DEBUG_UNASSIGNED
 
 static unsigned memory_region_transaction_depth;
@@ -1878,6 +1879,12 @@ bool memory_region_has_guest_memfd(MemoryRegion *mr)
     return mr->ram_block && mr->ram_block->guest_memfd >= 0;
 }
 
+bool memory_region_guest_memfd_in_place_conversion(MemoryRegion *mr)
+{
+    return mr && memory_region_has_guest_memfd(mr) &&
+           (mr->ram_block->guest_memfd_flags & GUEST_MEMFD_FLAG_SUPPORT_SHARED);
+}
+
 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
 {
     uint8_t mask = mr->dirty_log_mask;
system/physmem.c +20 -1
index 130c148ffb5c..955480685310 100644
@@ -89,6 +89,9 @@
 
 #include "memory-internal.h"
 
+#include <linux/guestmem.h>
+#include <linux/kvm.h>
+
 //#define DEBUG_SUBPAGE
 
 /* ram_list is read under rcu_read_lock()/rcu_read_unlock().  Writes
@@ -1913,6 +1916,9 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)
 
     if (new_block->flags & RAM_GUEST_MEMFD) {
         int ret;
+        bool in_place = kvm_guest_memfd_inplace_supported;
+
+        new_block->guest_memfd_flags = 0;
 
         if (!kvm_enabled()) {
             error_setg(errp, "cannot set up private guest memory for %s: KVM required",
@@ -1929,13 +1935,26 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)
             goto out_free;
         }
 
+        if (in_place) {
+            new_block->guest_memfd_flags |= GUEST_MEMFD_FLAG_SUPPORT_SHARED |
+                                            GUEST_MEMFD_FLAG_INIT_PRIVATE;
+        }
+
         new_block->guest_memfd = kvm_create_guest_memfd(new_block->max_length,
-                                                        0, errp);
+                                 new_block->guest_memfd_flags, errp);
         if (new_block->guest_memfd < 0) {
             qemu_mutex_unlock_ramlist();
             goto out_free;
         }
 
+        if (in_place) {
+            qemu_ram_munmap(new_block->fd, new_block->host, new_block->max_length);
+            new_block->host = qemu_ram_mmap(new_block->guest_memfd,
+                                            new_block->max_length,
+                                            QEMU_VMALLOC_ALIGN,
+                                            QEMU_MAP_SHARED, 0);
+        }
+
         /*
          * The attribute bitmap of the RamBlockAttributes is default to
          * discarded, which mimics the behavior of kvm_set_phys_mem() when it
Signature · 1 line
2.43.0
#270 lore raw

PATCH 4/5 memory/guest_memfd: Enable hugetlb support

In reply to Xiaoyao Li

(This is just the POC code to use gmem with hugetlb.)

Try with hugetlb first when hugetlb is supported by gmem. If hugetlb cannot afford the requested memory size and returns -ENOMEM, fallback to create gmem withtout hugetlb.

The hugetlb size is hardcoded as GUESTMEM_HUGETLB_FLAG_2MB. I'm not sure if it will be better if gmem can report the supported hugetlb size. But look at the current implementation of memfd, it just tries with the requested hugetlb size from user and fail when not supported. Hence gmem can do the same way without the supported size being enuemrated.

For a upstreamable solution, the hugetlb support of gmem can be implemented as "hugetlb" and "hugetlbsize" properties of memory-backend-guestmemfd as similar of memory-backend-memfd. (It requires memory-backed-guestmemfd introduced for in-place conversion gmem at first)

---
 accel/kvm/kvm-all.c    |  3 ++-
 accel/stubs/kvm-stub.c |  1 +
 include/system/kvm.h   |  1 +
 system/physmem.c       | 13 +++++++++++++
 4 files changed, 17 insertions(+), 1 deletion(-)
accel/kvm/kvm-all.c +2 -1
index 609537738d38..2d18e961714e 100644
@@ -106,6 +106,7 @@ static bool kvm_immediate_exit;
 static uint64_t kvm_supported_memory_attributes;
 static bool kvm_guest_memfd_supported;
 bool kvm_guest_memfd_inplace_supported;
+bool kvm_guest_memfd_hugetlb_supported;
 static hwaddr kvm_max_slot_size = ~0;
 
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
@@ -2808,6 +2809,7 @@ static int kvm_init(AccelState *as, MachineState *ms)
     kvm_guest_memfd_inplace_supported =
         kvm_check_extension(s, KVM_CAP_GMEM_SHARED_MEM) &&
         kvm_check_extension(s, KVM_CAP_GMEM_CONVERSION);
+    kvm_guest_memfd_hugetlb_supported = kvm_check_extension(s, KVM_CAP_GMEM_HUGETLB);
     kvm_pre_fault_memory_supported = kvm_vm_check_extension(s, KVM_CAP_PRE_FAULT_MEMORY);
 
     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
@@ -4536,7 +4538,6 @@ int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
     fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
     if (fd < 0) {
         error_setg_errno(errp, errno, "Error creating KVM guest_memfd");
-        return -1;
     }
 
     return fd;
accel/stubs/kvm-stub.c +1 -0
index bf0ccae27b62..fbc1d7c4e9b5 100644
@@ -25,6 +25,7 @@ bool kvm_allowed;
 bool kvm_readonly_mem_allowed;
 bool kvm_msi_use_devid;
 bool kvm_guest_memfd_inplace_supported;
+bool kvm_guest_memfd_hugetlb_supported;
 
 void kvm_flush_coalesced_mmio_buffer(void)
 {
include/system/kvm.h +1 -0
index 32f2be5f92e1..d1d79510ee26 100644
@@ -44,6 +44,7 @@ extern bool kvm_readonly_mem_allowed;
 extern bool kvm_msi_use_devid;
 extern bool kvm_pre_fault_memory_supported;
 extern bool kvm_guest_memfd_inplace_supported;
+extern bool kvm_guest_memfd_hugetlb_supported;
 
 #define kvm_enabled()           (kvm_allowed)
 /**
system/physmem.c +13 -0
index 955480685310..ea1c27ea2b99 100644
@@ -1940,8 +1940,21 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)
                                             GUEST_MEMFD_FLAG_INIT_PRIVATE;
         }
 
+        if (kvm_guest_memfd_hugetlb_supported) {
+            new_block->guest_memfd_flags |= GUEST_MEMFD_FLAG_HUGETLB |
+                                            GUESTMEM_HUGETLB_FLAG_2MB;
+        }
+
+        new_block->guest_memfd = kvm_create_guest_memfd(new_block->max_length,
+                                 new_block->guest_memfd_flags, &err);
+        if (new_block->guest_memfd == -ENOMEM) {
+            error_free(err);
+            new_block->guest_memfd_flags &= ~(GUEST_MEMFD_FLAG_HUGETLB |
+                                              GUESTMEM_HUGETLB_FLAG_2MB);
+        }
         new_block->guest_memfd = kvm_create_guest_memfd(new_block->max_length,
                                  new_block->guest_memfd_flags, errp);
+
         if (new_block->guest_memfd < 0) {
             qemu_mutex_unlock_ramlist();
             goto out_free;
Signature · 1 line
2.43.0
#271 lore raw

PATCH 5/5 memory: Don't enable in-place conversion for internal MemoryRegion with gmem

In reply to Xiaoyao Li

Currently, the TDVF cannot work with gmem in-place conversion because current implementation of KVM_TDX_INIT_MEM_REGION in KVM requires gmem of TDVF to be valid for both shared and private at the same time.

To workaround it, explicitly not enable in-place conversion for internal MemoryRegion with gmem. So that TDVF doesn't use in-place conversion gmem and KVM_TDX_INIT_MEM_REGION will initialize the gmem with the separate shared memory.

To make in-place conversion work with TDX's initial memory, the one possible solution and flow would be as below and it requires KVM change:

- QEMU create gmem as shared;
- QEMU mmap the gmem and load TDVF binary into it;
- QEMU convert gmem to private with the content preserved[1];
- QEMU invokes KVM_TDX_INIT_MEM_REGION without valid src, so that KVM knows to fetch the content in-place and use in-place PAGE.ADD for TDX.

[1] https://lore.kernel.org/all/[email protected]/

---
 include/system/memory.h | 3 +++
 system/memory.c         | 2 +-
 system/physmem.c        | 8 +++++---
 3 files changed, 9 insertions(+), 4 deletions(-)
include/system/memory.h +3 -0
index f14fbf65805d..89d6449cef70 100644
@@ -256,6 +256,9 @@ typedef struct IOMMUTLBEvent {
  */
 #define RAM_PRIVATE (1 << 13)
 
+/* Don't use enable in-place conversion for the guest mmefd backend */
+#define RAM_GUEST_MEMFD_NO_INPLACE (1 << 14)
+
 static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
                                        IOMMUNotifierFlag flags,
                                        hwaddr start, hwaddr end,
system/memory.c +1 -1
index 6870a41629ef..c1b73abc4c94 100644
@@ -3702,7 +3702,7 @@ bool memory_region_init_ram_guest_memfd(MemoryRegion *mr,
     DeviceState *owner_dev;
 
     if (!memory_region_init_ram_flags_nomigrate(mr, owner, name, size,
-                                                RAM_GUEST_MEMFD, errp)) {
+                                                RAM_GUEST_MEMFD | RAM_GUEST_MEMFD_NO_INPLACE, errp)) {
         return false;
     }
     /* This will assert if owner is neither NULL nor a DeviceState.
system/physmem.c +5 -3
index ea1c27ea2b99..c23379082f38 100644
@@ -1916,7 +1916,8 @@ static void ram_block_add(RAMBlock *new_block, Error **errp)
 
     if (new_block->flags & RAM_GUEST_MEMFD) {
         int ret;
-        bool in_place = kvm_guest_memfd_inplace_supported;
+        bool in_place = !(new_block->flags & RAM_GUEST_MEMFD_NO_INPLACE) &&
+                        kvm_guest_memfd_inplace_supported;
 
         new_block->guest_memfd_flags = 0;
 
@@ -2230,7 +2231,8 @@ RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
     ram_flags &= ~RAM_PRIVATE;
 
     assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
-                          RAM_NORESERVE | RAM_GUEST_MEMFD)) == 0);
+                          RAM_NORESERVE | RAM_GUEST_MEMFD |
+                          RAM_GUEST_MEMFD_NO_INPLACE)) == 0);
     assert(!host ^ (ram_flags & RAM_PREALLOC));
     assert(max_size >= size);
 
@@ -2314,7 +2316,7 @@ RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
                          MemoryRegion *mr, Error **errp)
 {
     assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE | RAM_GUEST_MEMFD |
-                          RAM_PRIVATE)) == 0);
+                          RAM_PRIVATE | RAM_GUEST_MEMFD_NO_INPLACE)) == 0);
     return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
 }
 
Signature · 1 line
2.43.0
#162 lore raw

Re: [RFC PATCH v2 33/51] KVM: guest_memfd: Allocate and truncate from custom allocator

In reply to Binbin Wu
Quoted 7 lines · Binbin Wu

On 5/15/2025 7:42 AM, Ackerley Tng wrote:
[...]

Quoted 5 lines
  
  	list_for_each_entry(gmem, gmem_list, entry)
  		kvm_gmem_invalidate_end(gmem, start, end);
(quoted diff) +0 -0
@@ -776,6 +879,16 @@ static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
 
Quoted 14 lines

virt/kvm/guest_memfd.c static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len) · line 890

Quoted 11 lines
virt/kvm/guest_memfd.c +9 -0
  	start = offset >> PAGE_SHIFT;
  	end = (offset + len) >> PAGE_SHIFT;
+	if (kvm_gmem_has_custom_allocator(inode)) {
+		size_t nr_pages;
+		void *p;
+
+		p = kvm_gmem_allocator_private(inode);
+		nr_pages = kvm_gmem_allocator_ops(inode)->nr_pages_in_folio(p);
+
+		start = round_down(start, nr_pages);
+		end = round_down(end, nr_pages);

It's weird here.
Should the end be round_up()?

Thanks, you're right.

I believe the current consensus is that fallocate() will only be permitted for offset and lengths that are aligned not only to PAGE_SIZE but to allocator page size.

In a future revision I'll check for allocator page size earlier on, before this function will get called, so this rounding will probably go away.

Quoted 6 lines
Quoted 5 lines
virt/kvm/guest_memfd.c +1 -0
+	}
 
  	r = 0;
  	for (index = start; index < end; ) {

[...]

#87 lore raw

Re: [RFC PATCH v2 04/51] KVM: guest_memfd: Introduce KVM_GMEM_CONVERT_SHARED/PRIVATE ioctls

In reply to Yan Zhao
Quoted 21 lines · Yan Zhao
Quoted 8 lines · Vishal Annapurve
Quoted 7 lines · Jason Gunthorpe
Quoted 4 lines · Alexey Kardashevskiy

Now, I am rebasing my RFC on top of this patchset and it fails in kvm_gmem_has_safe_refcount() as IOMMU holds references to all these folios in my RFC.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So what is the expected sequence here? The userspace unmaps a DMA page and maps it back right away, all from the userspace? The end result will be the exactly same which seems useless. And IOMMU TLB

As Jason described, ideally IOMMU just like KVM, should just:
1) Directly rely on guest_memfd for pinning -> no page refcounts taken by IOMMU stack

In TDX connect, TDX module and TDs do not trust VMM. So, it's the TDs to inform TDX module about which pages are used by it for DMAs purposes.
So, if a page is regarded as pinned by TDs for DMA, the TDX module will fail the unmap of the pages from S-EPT.

Quoted 9 lines

If IOMMU side does not increase refcount, IMHO, some way to indicate that certain PFNs are used by TDs for DMA is still required, so guest_memfd can reject the request before attempting the actual unmap. Otherwise, the unmap of TD-DMA-pinned pages will fail.

Upon this kind of unmapping failure, it also doesn't help for host to retry unmapping without unpinning from TD.

Yan, Yilun, would it work if, on conversion,

1. guest_memfd notifies IOMMU that a conversion is about to happen for a PFN range
2. IOMMU forwards the notification to TDX code in the kernel
3. TDX code in kernel tells TDX module to stop thinking of any PFNs in the range as pinned for DMA?

If the above is possible then by the time we get to unmapping from S-EPTs, TDX module would already consider the PFNs in the range "not pinned for DMA".

Quoted 46 lines
Quoted 39 lines

2) Directly query pfns from guest_memfd for both shared/private ranges
3) Implement an invalidation callback that guest_memfd can invoke on conversions.

Current flow:
Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range

         -> KVM has the concept of invalidation_begin() and end(),

which effectively ensures that between these function calls, no new EPT/NPT entries can be added for the range.
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.

============================

For IOMMU, could something like below work?

* A new UAPI to bind IOMMU FDs with guest_memfd ranges
* VFIO_DMA_MAP/UNMAP operations modified to directly fetch pfns from guest_memfd ranges using kvm_gmem_get_pfn()

    -> kvm invokes kvm_gmem_is_private() to check for the range

shareability, IOMMU could use the same or we could add an API in gmem that takes in access type and checks the shareability before returning the pfn.
* IOMMU stack exposes an invalidation callback that can be invoked by guest_memfd.

Quoted 7 lines

Private to Shared conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the KVM SEPT/NPT entries.

           -> guest_memfd invokes IOMMU invalidation callback to zap

the secure IOMMU entries.

Quoted 6 lines

If guest_memfd could determine if a page is used by DMA purposes before attempting the actual unmaps, it could reject and fail the conversion earlier, thereby keeping IOMMU/S-EPT mappings intact.

This could prevent the conversion from partially failing.

If the above suggestion works, then instead of checking if pages are allowed to be unmapped, guest_memfd will just force everyone to unmap.

Quoted 47 lines
Quoted 47 lines

3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then splits the folios if needed
4) Userspace invokes IOMMU map operation to map the ranges in
non-secure IOMMU.

Shared to private conversion via kvm_gmem_convert_range() -
1) guest_memfd invokes kvm_gmem_invalidate_begin() for the ranges
on each bound memslot overlapping with the range
2) guest_memfd invokes kvm_gmem_convert_should_proceed() which
actually unmaps the host mappings which will unmap the KVM non-seucure EPT/NPT entries.

         -> guest_memfd invokes IOMMU invalidation callback to zap the

non-secure IOMMU entries.
3) guest_memfd invokes kvm_gmem_execute_work() which updates the
shareability and then merges the folios if needed.
4) Userspace invokes IOMMU map operation to map the ranges in secure IOMMU.

There should be a way to block external IOMMU pagetable updates while guest_memfd is performing conversion e.g. something like kvm_invalidate_begin()/end().

Quoted 4 lines
Quoted 2 lines

is going to be flushed on a page conversion anyway (the RMPUPDATE instruction does that). All this is about AMD's x86 though.

The iommu should not be using the VMA to manage the mapping. It should

+1.

Quoted 7 lines

be directly linked to the guestmemfd in some way that does not disturb its operations. I imagine there would be some kind of invalidation callback directly to the iommu.

Presumably that invalidation call back can include a reason for the invalidation (addr change, shared/private conversion, etc)

Quoted 6 lines

I'm not sure how we will figure out which case is which but guestmemfd should allow the iommu to plug in either invalidation scheme..

Probably invalidation should be a global to the FD thing, I imagine that once invalidation is established the iommu will not be incrementing page refcounts.

+1.

Quoted 2 lines

Jason

#262 lore raw
In reply to Fuad Tabba
Quoted 26 lines · Fuad Tabba
Quoted 18 lines · Sean Christopherson
Quoted 11 lines · Fuad Tabba
Quoted 5 lines
Quoted 2 lines

I don't think we need a flag to preserve memory as I mentioned in [2]. IIUC,
1) Conversions are always content-preserving for pKVM.

No? Perserving contents on private => shared is a security vulnerability waiting to happen.

Actually it is one of the requirements for pKVM as well as its current behavior. We would like to preserve contents both ways, private <=> shared, since it is required by some of the potential use cases (e.g., guest handling video encoding/decoding).

Quoted 4 lines

To make it clear, I'm talking about explicit sharing from the guest, not relinquishing memory back to the host. In the case of relinquishing (and guest teardown), relinquished memory is poisoned (zeroed) in pKVM.

Quoted 6 lines

I forget, what's the "explicit sharing" flow look like? E.g. how/when does pKVM know it's ok to convert memory from private to shared? I think we'd still want to make data preservation optional, e.g. to avoid potential leakage with setups where memory is private by default, but a flag in KVM's uAPI might not be a good fit since whether or not to preserve data is more of a guest decision (or at least needs to be ok'd by the guest).

Quoted 2 lines

In pKVM all sharing and unsharing is triggered by the guest via hypercalls. The host cannot unshare.

In pKVM's case, would the conversion ioctl be disabled completely, or would the ioctl be allowed, but conversion always checks with pKVM to see if the guest had previously requested a unshare?

Quoted 6 lines

That said, making data
preservation optional works for pKVM and is a good idea, for the reasons that you've mentioned.

Cheers,
/fuad