Skip to contentSkip to conversation

hv: vmbus: make rings and host-visible buffers survive buddy fragmentation

PATCH In review Emerson Busson 7 participants 30 messages Oct 7 – Oct 15

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

v2 cover hv: vmbus: make rings and host-visible buffers survive buddy fragmentation

This series moves VMBus ring backing to the chunk allocator and keeps the allocation, GPADL ownership, and mapping references together. It preserves the exported four-argument interfaces while allowing the private allocation paths to carry ownership and sharing policy.

A review of the original vzalloc fallback noted that CCA and TDX guests without a paravisor need direct-map page transitions. This revision uses contiguous chunks for buffers that must be host-shared, transitions each page through page_address(), and combines the chunks with vmap(). Ordinary guest-private buffers retain vzalloc-style allocation.

Allocation and compatibility
----------------------------

Every ring allocation uses the chunk allocator. Ordinary guests and buffers kept private by channel policy use vzalloc(). For host-shared buffers in an encrypted or isolated guest, the allocator uses contiguous chunks and transitions them page by page. Guest-memory encryption is selected independently of Hyper-V isolation.

Ring consumers select co_ring_buffer. External buffers and the legacy allocator select co_external_memory. The exported allocator and caller- decrypted GPADL prototypes retain four arguments throughout all fourteen patches. UIO migration follows its release support.

The address, page and chunk arrays, and embedded GPADL belong to one buffer. The allocation extent, host-described GPADL extent, and retained allocation extent remain distinct. Interior GPADL duplication preserves the existing exported interfaces. Prepared owned buffers avoid repeat decryption, and HV_GPADL_BUFFER_DECRYPTED is removed.

Lifetime and host acknowledgement
---------------------------------

A host rescind alone does not prove GPADL revocation. For a known-live GPADL whose channel identifier is still held, teardown posts a request and waits for a matching GPADL_TORNDOWN message before clearing ownership. Synthetic rescind notification cannot replace this acknowledgement. Unknown creates, local removal, invalid identifiers, failed posting, and timeouts retain ownership.

Waiter removal shares the response-list lock with matching replies so a late acknowledgement cannot use a freed waiter. Released owners retain pages across mapping references and failed page-state restoration. Reclaimer shutdown cancels pending timers under the owner lock and requeues only work that was actually canceled; running callbacks drain through workqueue destruction without re-executing freed embedded work.

Sysfs mappings install no vm_ops and release the bridge pin on every setup outcome. UIO mappings hold their pin through VMA close. Page, count, and protection snapshots share the owner-lock boundary. New tests call the real sysfs wrapper, insert actual PTEs, and check readable bytes and page references through success and partial -EBUSY. They do not execute a full kernfs syscall or full device destruction.

The final four fixes use vzalloc() for guest-private requestor arrays and bitmaps, kvzalloc_obj() for guest-private RNDIS descriptors, handle NULL control requests on empty NetVSC completions, and use kvzalloc_obj()/kvfree() for the large guest-private NetVSC device object.

Qualification on the exact fourteen-patch series
------------------------------------------------

The code mails are pinned by series/SHA256SUMS. Applying all fourteen to 93f51579e7df248780214094418f205253383cc5 produces source tree e6fe523ca92ce30ea7edb265b8a26bf20a867c47.

The VMBus workflow builds x86_64 and arm64 with W=1 and C=2, passes sparse, and passes all 69 linked x86_64 QEMU KUnit cases. The distinct WSL backport passes all 26 of its KUnit cases. CoCo source invariants pass on both architectures; these are necessary static checks, not confidential-hardware qualification.

Exact-source Hyper-V runtime, including controlled host rescind:
https://github.com/emersonbusson/WSL2-Linux-Kernel/actions/runs/37650468077

On both windows-2025 and windows-latest, the candidate passes 100 bind/unbind cycles, bounded buddy fragmentation, channel rebind, UIO mapping teardown, and the controlled host-origin NIC removal. Each report records HYPERV_DRILL_HOST_RESCIND status=PASS, target_absent=yes, matching_events=1. Both report zero splats and faults, restore the measured kernel settings, and return lifecycle map accounting to the settled operational baseline. Captured owner accounting reports 722 created, zero unobserved creates, 715 reclaimed, and seven still active; active owners are not classified as leaks. Trace capture has no overruns or dropped events, and the disposable VM, VHD, and switch cleanup passes.

The baseline is an intentional negative control. It reproduces the expected fragmented-allocation failure without guest faults; the workflow accepts that exact signature as a passing control. It is not a candidate result.

WSL backport runtime matrix:
https://github.com/emersonbusson/WSL2-Linux-Kernel/actions/runs/37645708153

That separate backport passes the actual Windows candidate matrix. Each runner completes 64 commands with matching teardown acknowledgements, zero unacknowledged requests, no backing or tail growth, and all six shutdown checks. The shutdown retry path is covered by 40 local parser and refusal regressions; the live candidate runs required zero retries. These results qualify the WSL backport's measured ordinary behavior, not the mainline mail series.

Qualification limits
--------------------

The Hyper-V runtime uses the ordinary x86_64 vzalloc path. It does not execute confidential chunk transitions. Full memory saturation, the chunked CoCo fallback on hardware, SEV-SNP, TDX without a paravisor, Arm CCA, and complete VMBus module unload and retained-owner destruction remain unqualified. The exact mainline series has not been installed or booted on the daily WSL host; the installed kernel and Windows WSL matrix are a separate backport. The baseline is one intentional fragmentation negative control, not a matched same-configuration diagnostic-count comparison for every patch. No confidential-platform result is inferred from ordinary Hyper-V or static checks.

---
Emerson Busson (14):
hv: vmbus: convert ring backing through the chunk allocator
hv: vmbus: validate chunk buffer allocation and cleanup
uio: hv_generic: describe buffers for owned allocation
hv: vmbus: add KUnit tests for GPADL post failure injection
hv: vmbus: add KUnit test for order-zero allocation fallback
hv: vmbus: cover all shared-page policy combinations
hv: vmbus: distinguish host rescind from local channel unload
hv: vmbus: retain backing until ownership and references clear
hv: use owned VMBus buffers in NetVSC and UIO
hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race
hv: vmbus: vmalloc requestor metadata
hv: netvsc: allocate RNDIS request descriptors with kvzalloc_obj()
hv: netvsc: handle a NULL request address on empty completions
hv: netvsc: use kvzalloc for device state

#1 lore raw

PATCH v2 1/14 hv: vmbus: convert ring backing through the chunk allocator

Use the existing virtually contiguous allocator for ring backing with the ring confidentiality policy. An internal helper keeps that choice distinct from the established external-buffer compatibility policy. Preserve the exported allocator and caller-decrypted GPADL signatures throughout the series; carry uncertain creation in the descriptor instead of widening an exported function. The independent guest-memory-encryption condition is present at the first ring consumer.

---
 drivers/hv/channel.c            | 176 +++++++++++++++++++++-----------
 drivers/hv/hyperv_vmbus.h       |   4 +-
 drivers/hv/ring_buffer.c        |   9 +-
 drivers/net/hyperv/hyperv_net.h |  10 +-
 drivers/net/hyperv/netvsc.c     |  58 ++++++-----
 drivers/uio/uio_hv_generic.c    |  37 ++++---
 include/linux/hyperv.h          |  18 +++-
 7 files changed, 196 insertions(+), 116 deletions(-)
drivers/hv/channel.c +119 -57
index 7e4cc6f55237..f8feb2a0ec0a 100644
@@ -12,6 +12,8 @@
 #include <linux/sched.h>
 #include <linux/wait.h>
 #include <linux/mm.h>
+#include <linux/cc_platform.h>
+#include <linux/overflow.h>
 #include <linux/slab.h>
 #include <linux/log2.h>
 #include <linux/module.h>
@@ -26,6 +28,12 @@
 
 #include "hyperv_vmbus.h"
 
+static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
+				  u32 size,
+				  bool confidential,
+				  struct page ***chunks_out,
+				  u32 *chunk_cnt_out);
+
 /*
  * hv_gpadl_size - Return the real size of a gpadl, the size that Hyper-V uses
  *
@@ -42,7 +50,6 @@ static inline u32 hv_gpadl_size(enum hv_gpadl_type type, u32 size)
 {
 	switch (type) {
 	case HV_GPADL_BUFFER:
-	case HV_GPADL_BUFFER_DECRYPTED:
 		return size;
 	case HV_GPADL_RING:
 		/* The size of a ringbuffer must be page-aligned */
@@ -103,7 +110,6 @@ static inline u64 hv_gpadl_hvpfn(enum hv_gpadl_type type, void *kbuffer,
 
 	switch (type) {
 	case HV_GPADL_BUFFER:
-	case HV_GPADL_BUFFER_DECRYPTED:
 		break;
 	case HV_GPADL_RING:
 		if (i == 0)
@@ -154,17 +160,15 @@ EXPORT_SYMBOL_GPL(vmbus_setevent);
 /* vmbus_free_ring - drop mapping of ring buffer */
 void vmbus_free_ring(struct vmbus_channel *channel)
 {
+	struct vmbus_buffer *buffer = &channel->ringbuffer;
+
 	hv_ringbuffer_cleanup(&channel->outbound);
 	hv_ringbuffer_cleanup(&channel->inbound);
 
-	if (channel->ringbuffer_page) {
-		/* In a CoCo VM leak the memory if it didn't get re-encrypted */
-		if (!channel->ringbuffer_gpadlhandle.decrypted)
-			__free_pages(channel->ringbuffer_page,
-			     get_order(channel->ringbuffer_pagecount
-				       << PAGE_SHIFT));
-		channel->ringbuffer_page = NULL;
-	}
+	if (!buffer->addr)
+		return;
+
+	vmbus_release_buffer(buffer);
 }
 EXPORT_SYMBOL_GPL(vmbus_free_ring);
 
@@ -172,26 +176,32 @@ EXPORT_SYMBOL_GPL(vmbus_free_ring);
 int vmbus_alloc_ring(struct vmbus_channel *newchannel,
 		     u32 send_size, u32 recv_size)
 {
-	struct page *page;
-	int order;
+	struct vmbus_buffer *buffer = &newchannel->ringbuffer;
+	u32 size;
+	u32 i;
 
-	if (send_size % PAGE_SIZE || recv_size % PAGE_SIZE)
+	if (!send_size || !recv_size ||
+	    send_size % PAGE_SIZE || recv_size % PAGE_SIZE ||
+	    check_add_overflow(send_size, recv_size, &size))
 		return -EINVAL;
 
-	/* Allocate the ring buffer */
-	order = get_order(send_size + recv_size);
-	page = alloc_pages_node(cpu_to_node(newchannel->target_cpu),
-				GFP_KERNEL|__GFP_ZERO, order);
-
-	if (!page)
-		page = alloc_pages(GFP_KERNEL|__GFP_ZERO, order);
-
-	if (!page)
+	buffer->addr = __vmbus_alloc_buffer(newchannel, size,
+					    newchannel->co_ring_buffer,
+					    &buffer->chunks, &buffer->chunk_cnt);
+	if (!buffer->addr)
 		return -ENOMEM;
 
-	newchannel->ringbuffer_page = page;
-	newchannel->ringbuffer_pagecount = (send_size + recv_size) >> PAGE_SHIFT;
+	newchannel->ringbuffer_pagecount = size >> PAGE_SHIFT;
 	newchannel->ringbuffer_send_offset = send_size >> PAGE_SHIFT;
+	buffer->pages = kvcalloc(newchannel->ringbuffer_pagecount,
+				 sizeof(*buffer->pages), GFP_KERNEL);
+	if (!buffer->pages) {
+		vmbus_release_buffer(buffer);
+		return -ENOMEM;
+	}
+
+	for (i = 0; i < newchannel->ringbuffer_pagecount; i++)
+		buffer->pages[i] = vmalloc_to_page(buffer->addr + (i << PAGE_SHIFT));
 
 	return 0;
 }
@@ -442,7 +452,8 @@ static void vmbus_free_channel_msginfo(struct vmbus_channel_msginfo *msginfo)
  */
 static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 				   enum hv_gpadl_type type, void *kbuffer,
-				   u32 size, u32 send_offset,
+				   u32 size, u32 send_offset, bool memory_prepared,
+				   bool *leak,
 				   struct vmbus_gpadl *gpadl)
 {
 	struct vmbus_channel_gpadl_header *gpadlmsg;
@@ -452,8 +463,13 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 	struct list_head *curr;
 	u32 next_gpadl_handle;
 	unsigned long flags;
+	bool posted = false;
 	int ret = 0;
 
+	if (leak)
+		*leak = false;
+	gpadl->leak = false;
+
 	next_gpadl_handle =
 		(atomic_inc_return(&vmbus_connection.next_gpadl_handle) - 1);
 
@@ -463,9 +479,9 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 		return ret;
 	}
 
-	gpadl->decrypted = !((channel->co_external_memory && type == HV_GPADL_BUFFER) ||
-		(channel->co_ring_buffer && type == HV_GPADL_RING) ||
-		(type == HV_GPADL_BUFFER_DECRYPTED));
+	gpadl->decrypted = !memory_prepared &&
+		!((channel->co_external_memory && type == HV_GPADL_BUFFER) ||
+		  (channel->co_ring_buffer && type == HV_GPADL_RING));
 	if (gpadl->decrypted) {
 		/*
 		 * The "decrypted" flag being true assumes that set_memory_decrypted() succeeds.
@@ -504,6 +520,8 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 		goto cleanup;
 	}
 
+	/* A failed post may still have reached the host. */
+	posted = true;
 	ret = vmbus_post_msg(gpadlmsg, msginfo->msgsize -
 			     sizeof(*msginfo), true);
 
@@ -534,6 +552,7 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 	wait_for_completion(&msginfo->waitevent);
 
 	if (msginfo->response.gpadl_created.creation_status != 0) {
+		posted = false;
 		pr_err("Failed to establish GPADL: err = 0x%x\n",
 		       msginfo->response.gpadl_created.creation_status);
 
@@ -542,6 +561,7 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 	}
 
 	if (channel->rescind) {
+		posted = false;
 		ret = -ENODEV;
 		goto cleanup;
 	}
@@ -550,6 +570,7 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 	gpadl->gpadl_handle = gpadlmsg->gpadl;
 	gpadl->buffer = kbuffer;
 	gpadl->size = size;
+	posted = false;
 
 
 cleanup:
@@ -559,7 +580,13 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 
 	vmbus_free_channel_msginfo(msginfo);
 
-	if (ret) {
+	if (ret && posted) {
+		gpadl->leak = true;
+		if (leak)
+			*leak = true;
+	}
+
+	if (ret && !posted) {
 		/*
 		 * If set_memory_encrypted() fails, the decrypted flag is
 		 * left as true so the memory is leaked instead of being
@@ -586,7 +613,7 @@ int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,
 			  u32 size, struct vmbus_gpadl *gpadl)
 {
 	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, kbuffer, size,
-				       0U, gpadl);
+				       0U, false, &gpadl->leak, gpadl);
 }
 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
 
@@ -597,6 +624,8 @@ EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
  * @channel: a channel
  * @kbuffer: from kmalloc or vmalloc; must already be decrypted by the caller
  * @size: page-size multiple
+ * @leak: set when a GPADL message may have reached the host but completion is
+ *        uncertain; the caller must retain the backing pages
  * @gpadl: output gpadl
  *
  * The caller is responsible for re-encrypting the buffer before freeing it.
@@ -605,8 +634,8 @@ int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,
 					   void *kbuffer, u32 size,
 					   struct vmbus_gpadl *gpadl)
 {
-	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER_DECRYPTED,
-				       kbuffer, size, 0U, gpadl);
+	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER,
+				       kbuffer, size, 0U, true, &gpadl->leak, gpadl);
 }
 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl_caller_decrypted);
 
@@ -648,11 +677,26 @@ void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt)
 }
 EXPORT_SYMBOL_GPL(vmbus_free_buffer);
 
+void vmbus_release_buffer(struct vmbus_buffer *buffer)
+{
+	if (!buffer->addr)
+		return;
+
+	kvfree(buffer->pages);
+	if (!buffer->leak && !buffer->gpadl.leak &&
+	    !buffer->gpadl.gpadl_handle)
+		vmbus_free_buffer(buffer->addr, buffer->chunks,
+				  buffer->chunk_cnt);
+	memset(buffer, 0, sizeof(*buffer));
+}
+EXPORT_SYMBOL_GPL(vmbus_release_buffer);
+
 /**
- * vmbus_alloc_buffer - allocate a host-visible, virtually-contiguous buffer.
+ * __vmbus_alloc_buffer - allocate host-visible, virtually-contiguous backing.
  *
  * @channel: the channel the buffer will be attached to
  * @size: requested buffer size in bytes (will be rounded up to PAGE_SIZE)
+ * @confidential: keep the buffer private to the guest
  * @chunks_out: on success, set to the array of underlying chunks, or NULL when
  *              the buffer was allocated with vzalloc()
  * @chunk_cnt_out: on success, set to the number of chunks
@@ -667,10 +711,11 @@ EXPORT_SYMBOL_GPL(vmbus_free_buffer);
  *
  * Return: the buffer's virtual address, or NULL on failure.
  */
-void *vmbus_alloc_buffer(struct vmbus_channel *channel,
-			 u32 size,
-			 struct page ***chunks_out,
-			 u32 *chunk_cnt_out)
+static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
+				  u32 size,
+				  bool confidential,
+				  struct page ***chunks_out,
+				  u32 *chunk_cnt_out)
 {
 	unsigned long nr_pages = PFN_UP(size);
 	unsigned long remaining = nr_pages;
@@ -690,7 +735,8 @@ void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 		return NULL;
 
 	/* If the buffer does not need to be decrypted, just use vzalloc() */
-	if (!hv_is_isolation_supported() || channel->co_external_memory)
+	if ((!hv_is_isolation_supported() &&
+	     !cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) || confidential)
 		return vzalloc(nr_pages << PAGE_SHIFT);
 
 	/* Worst case: every chunk is a single page. */
@@ -760,6 +806,14 @@ void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 	vmbus_free_buffer(NULL, chunks, chunk_cnt);
 	return NULL;
 }
+
+void *vmbus_alloc_buffer(struct vmbus_channel *channel,
+			 u32 size, struct page ***chunks_out,
+			 u32 *chunk_cnt_out)
+{
+	return __vmbus_alloc_buffer(channel, size, channel->co_external_memory,
+				    chunks_out, chunk_cnt_out);
+}
 EXPORT_SYMBOL_GPL(vmbus_alloc_buffer);
 
 /**
@@ -832,7 +886,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 {
 	struct vmbus_channel_open_channel *open_msg;
 	struct vmbus_channel_msginfo *open_info = NULL;
-	struct page *page = newchannel->ringbuffer_page;
+	struct vmbus_buffer *buffer = &newchannel->ringbuffer;
 	u32 send_pages, recv_pages;
 	unsigned long flags;
 	int err;
@@ -860,22 +914,24 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 		newchannel->max_pkt_size = VMBUS_DEFAULT_MAX_PKT_SIZE;
 
 	/* Establish the gpadl for the ring buffer */
-	newchannel->ringbuffer_gpadlhandle.gpadl_handle = 0;
+	buffer->gpadl.gpadl_handle = 0;
 
 	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING,
-				      page_address(newchannel->ringbuffer_page),
+				      buffer->addr,
 				      (send_pages + recv_pages) << PAGE_SHIFT,
 				      newchannel->ringbuffer_send_offset << PAGE_SHIFT,
-				      &newchannel->ringbuffer_gpadlhandle);
+				      true, &buffer->leak, &buffer->gpadl);
 	if (err)
 		goto error_clean_ring;
 
 	err = hv_ringbuffer_init(&newchannel->outbound,
-				 page, send_pages, 0, newchannel->co_ring_buffer);
+				 buffer->addr, send_pages, 0,
+				 newchannel->co_ring_buffer);
 	if (err)
 		goto error_free_gpadl;
 
-	err = hv_ringbuffer_init(&newchannel->inbound, &page[send_pages],
+	err = hv_ringbuffer_init(&newchannel->inbound,
+				 buffer->addr + (send_pages << PAGE_SHIFT),
 				 recv_pages, newchannel->max_pkt_size,
 				 newchannel->co_ring_buffer);
 	if (err)
@@ -897,8 +953,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 	open_msg->header.msgtype = CHANNELMSG_OPENCHANNEL;
 	open_msg->openid = newchannel->offermsg.child_relid;
 	open_msg->child_relid = newchannel->offermsg.child_relid;
-	open_msg->ringbuffer_gpadlhandle
-		= newchannel->ringbuffer_gpadlhandle.gpadl_handle;
+	open_msg->ringbuffer_gpadlhandle = buffer->gpadl.gpadl_handle;
 	/*
 	 * The unit of ->downstream_ringbuffer_pageoffset is HV_HYP_PAGE and
 	 * the unit of ->ringbuffer_send_offset (i.e. send_pages) is PAGE, so
@@ -956,7 +1011,8 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 error_free_info:
 	kfree(open_info);
 error_free_gpadl:
-	vmbus_teardown_gpadl(newchannel, &newchannel->ringbuffer_gpadlhandle);
+	if (vmbus_teardown_gpadl(newchannel, &buffer->gpadl))
+		buffer->leak = true;
 error_clean_ring:
 	hv_ringbuffer_cleanup(&newchannel->outbound);
 	hv_ringbuffer_cleanup(&newchannel->inbound);
@@ -1058,15 +1114,20 @@ int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpad
 
 	kfree(info);
 
-	if (gpadl->decrypted)
-		ret = set_memory_encrypted((unsigned long)gpadl->buffer,
-					PFN_UP(gpadl->size));
-	else
-		ret = 0;
-	if (ret)
-		pr_warn("Fail to set mem host visibility in GPADL teardown %d.\n", ret);
+	if (!ret && gpadl->decrypted) {
+		int encrypt_ret;
 
-	gpadl->decrypted = ret;
+		encrypt_ret = set_memory_encrypted((unsigned long)gpadl->buffer,
+						   PFN_UP(gpadl->size));
+		if (encrypt_ret) {
+			pr_warn("Failed to re-encrypt GPADL buffer: %d\n",
+				encrypt_ret);
+			ret = encrypt_ret;
+		}
+		gpadl->decrypted = !!encrypt_ret;
+	}
+	if (ret)
+		gpadl->leak = true;
 
 	return ret;
 }
@@ -1142,9 +1203,10 @@ static int vmbus_close_internal(struct vmbus_channel *channel)
 	}
 
 	/* Tear down the gpadl for the channel's ring buffer */
-	else if (channel->ringbuffer_gpadlhandle.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(channel, &channel->ringbuffer_gpadlhandle);
+	else if (channel->ringbuffer.gpadl.gpadl_handle) {
+		ret = vmbus_teardown_gpadl(channel, &channel->ringbuffer.gpadl);
 		if (ret) {
+			channel->ringbuffer.leak = true;
 			pr_err("Close failed: teardown gpadl return %d\n", ret);
 			/*
 			 * If we failed to teardown gpadl,
drivers/hv/hyperv_vmbus.h +2 -2
index 33923621a5a3..20d023c9735e 100644
@@ -204,8 +204,8 @@ extern int hv_synic_cleanup(unsigned int cpu);
 void hv_ringbuffer_pre_init(struct vmbus_channel *channel);
 
 int hv_ringbuffer_init(struct hv_ring_buffer_info *ring_info,
-		       struct page *pages, u32 pagecnt, u32 max_pkt_size,
-			   bool confidential);
+		       void *addr, u32 pagecnt, u32 max_pkt_size,
+		       bool confidential);
 
 void hv_ringbuffer_cleanup(struct hv_ring_buffer_info *ring_info);
 
drivers/hv/ring_buffer.c +5 -4
index 592a9601faaa..16b1c2910789 100644
@@ -184,8 +184,8 @@ void hv_ringbuffer_pre_init(struct vmbus_channel *channel)
 
 /* Initialize the ring buffer. */
 int hv_ringbuffer_init(struct hv_ring_buffer_info *ring_info,
-		       struct page *pages, u32 page_cnt, u32 max_pkt_size,
-			   bool confidential)
+		       void *addr, u32 page_cnt, u32 max_pkt_size,
+		       bool confidential)
 {
 	struct page **pages_wraparound;
 	int i;
@@ -200,10 +200,11 @@ int hv_ringbuffer_init(struct hv_ring_buffer_info *ring_info,
 	if (!pages_wraparound)
 		return -ENOMEM;
 
-	pages_wraparound[0] = pages;
+	pages_wraparound[0] = vmalloc_to_page(addr);
 	for (i = 0; i < 2 * (page_cnt - 1); i++)
 		pages_wraparound[i + 1] =
-			&pages[i % (page_cnt - 1) + 1];
+			vmalloc_to_page(addr +
+				((i % (page_cnt - 1) + 1) << PAGE_SHIFT));
 
 	ring_info->ring_buffer = (struct hv_ring_buffer *)
 		vmap(pages_wraparound, page_cnt * 2 - 1, VM_MAP,
drivers/net/hyperv/hyperv_net.h +2 -8
index 4841367fdab2..a15cb2460344 100644
@@ -1158,21 +1158,15 @@ struct netvsc_device {
 	bool tx_disable; /* if true, do not wake up queue again */
 
 	/* Receive buffer allocated by us but manages by NetVSP */
-	void *recv_buf;
+	struct vmbus_buffer recv_buffer;
 	u32 recv_buf_size; /* allocated bytes */
-	struct page **recv_buf_chunks;
-	u32 recv_buf_chunk_cnt;
-	struct vmbus_gpadl recv_buf_gpadl_handle;
 	u32 recv_section_cnt;
 	u32 recv_section_size;
 	u32 recv_completion_cnt;
 
 	/* Send buffer allocated by us */
-	void *send_buf;
+	struct vmbus_buffer send_buffer;
 	u32 send_buf_size;
-	struct page **send_buf_chunks;
-	u32 send_buf_chunk_cnt;
-	struct vmbus_gpadl send_buf_gpadl_handle;
 	u32 send_section_cnt;
 	u32 send_section_size;
 	unsigned long *send_section_map;
drivers/net/hyperv/netvsc.c +34 -24

152 lines not on this page · raw message

drivers/uio/uio_hv_generic.c +21 -16
index 7b4cc456c453..b3f41ffc74f8 100644
@@ -150,19 +150,21 @@ static void hv_uio_rescind(struct vmbus_channel *channel)
 	vmbus_device_unregister(channel->device_obj);
 }
 
-/* Function used for mmap of ring buffer sysfs interface.
- * The ring buffer is allocated as contiguous memory by vmbus_open
- */
+/* Function used for mmap of the ring buffer sysfs interface. */
 static int
 hv_uio_ring_mmap_prepare(struct vmbus_channel *channel, struct vm_area_desc *desc)
 {
-	void *ring_buffer = page_address(channel->ringbuffer_page);
+	unsigned long pages = vma_desc_pages(desc);
+	pgoff_t offset = desc->pgoff;
 
 	if (channel->state != CHANNEL_OPENED_STATE)
 		return -ENODEV;
+	if (offset >= channel->ringbuffer_pagecount ||
+	    pages > channel->ringbuffer_pagecount - offset)
+		return -EINVAL;
 
-	mmap_action_simple_ioremap(desc, virt_to_phys(ring_buffer),
-			channel->ringbuffer_pagecount << PAGE_SHIFT);
+	mmap_action_map_kernel_pages(desc, desc->start,
+				     channel->ringbuffer.pages + offset, pages);
 	return 0;
 }
 
@@ -196,14 +198,16 @@ static void
 hv_uio_cleanup(struct hv_device *dev, struct hv_uio_private_data *pdata)
 {
 	if (pdata->send_gpadl.gpadl_handle) {
-		vmbus_teardown_gpadl(dev->channel, &pdata->send_gpadl);
-		if (!pdata->send_gpadl.decrypted)
+		if (vmbus_teardown_gpadl(dev->channel, &pdata->send_gpadl))
+			pdata->send_gpadl.leak = true;
+		if (!pdata->send_gpadl.leak && !pdata->send_gpadl.decrypted)
 			vfree(pdata->send_buf);
 	}
 
 	if (pdata->recv_gpadl.gpadl_handle) {
-		vmbus_teardown_gpadl(dev->channel, &pdata->recv_gpadl);
-		if (!pdata->recv_gpadl.decrypted)
+		if (vmbus_teardown_gpadl(dev->channel, &pdata->recv_gpadl))
+			pdata->recv_gpadl.leak = true;
+		if (!pdata->recv_gpadl.leak && !pdata->recv_gpadl.decrypted)
 			vfree(pdata->recv_buf);
 	}
 }
@@ -283,12 +287,11 @@ hv_uio_probe(struct hv_device *dev,
 
 	/* mem resources */
 	pdata->info.mem[TXRX_RING_MAP].name = "txrx_rings";
-	ring_buffer = page_address(channel->ringbuffer_page);
-	pdata->info.mem[TXRX_RING_MAP].addr
-		= (uintptr_t)virt_to_phys(ring_buffer);
+	ring_buffer = channel->ringbuffer.addr;
+	pdata->info.mem[TXRX_RING_MAP].addr = (uintptr_t)ring_buffer;
 	pdata->info.mem[TXRX_RING_MAP].size
 		= channel->ringbuffer_pagecount << PAGE_SHIFT;
-	pdata->info.mem[TXRX_RING_MAP].memtype = UIO_MEM_IOVA;
+	pdata->info.mem[TXRX_RING_MAP].memtype = UIO_MEM_VIRTUAL;
 
 	pdata->info.mem[INT_PAGE_MAP].name = "int_page";
 	pdata->info.mem[INT_PAGE_MAP].addr
@@ -312,7 +315,8 @@ hv_uio_probe(struct hv_device *dev,
 		ret = vmbus_establish_gpadl(channel, pdata->recv_buf,
 					    RECV_BUFFER_SIZE, &pdata->recv_gpadl);
 		if (ret) {
-			if (!pdata->recv_gpadl.decrypted)
+			if (!pdata->recv_gpadl.leak &&
+			    !pdata->recv_gpadl.decrypted)
 				vfree(pdata->recv_buf);
 			goto fail_close;
 		}
@@ -334,7 +338,8 @@ hv_uio_probe(struct hv_device *dev,
 		ret = vmbus_establish_gpadl(channel, pdata->send_buf,
 					    SEND_BUFFER_SIZE, &pdata->send_gpadl);
 		if (ret) {
-			if (!pdata->send_gpadl.decrypted)
+			if (!pdata->send_gpadl.leak &&
+			    !pdata->send_gpadl.decrypted)
 				vfree(pdata->send_buf);
 			goto fail_close;
 		}
include/linux/hyperv.h +13 -5
index 9e109d91aa14..2878aed14c45 100644
@@ -70,8 +70,7 @@
  */
 enum hv_gpadl_type {
 	HV_GPADL_BUFFER,
-	HV_GPADL_RING,
-	HV_GPADL_BUFFER_DECRYPTED
+	HV_GPADL_RING
 };
 
 /* Single-page buffer */
@@ -782,6 +781,16 @@ struct vmbus_gpadl {
 	u32 size;
 	void *buffer;
 	bool decrypted;
+	bool leak;
+};
+
+struct vmbus_buffer {
+	void *addr;
+	struct page **chunks;
+	struct page **pages;
+	u32 chunk_cnt;
+	struct vmbus_gpadl gpadl;
+	bool leak;
 };
 
 struct vmbus_channel {
@@ -803,10 +812,8 @@ struct vmbus_channel {
 	bool rescind_ref; /* got rescind msg, got channel reference */
 	struct completion rescind_event;
 
-	struct vmbus_gpadl ringbuffer_gpadlhandle;
-
 	/* Allocated memory for ring buffer */
-	struct page *ringbuffer_page;
+	struct vmbus_buffer ringbuffer;
 	u32 ringbuffer_pagecount;
 	u32 ringbuffer_send_offset;
 	struct hv_ring_buffer_info outbound;	/* send to parent */
@@ -1219,6 +1226,7 @@ extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 				u32 *chunk_cnt_out);
 
 extern void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt);
+void vmbus_release_buffer(struct vmbus_buffer *buffer);
 
 void vmbus_reset_channel_cb(struct vmbus_channel *channel);
 
Signature · 1 line
2.43.0
#2 lore raw

PATCH v2 2/14 hv: vmbus: validate chunk buffer allocation and cleanup

In reply to Emerson Busson

Validate rounded sizes before storing them and preserve allocated chunks when cleanup or GPADL teardown has an uncertain outcome. Add focused KUnit coverage for buffer sizing, ownership decisions, and the ring fallback order descent.

vmbus_alloc_buffer() rounds the requested size up to PAGE_SIZE before it computes nr_pages. A zero size, and a size within PAGE_SIZE of U32_MAX, both produce a rounded value that is wrong: zero allocates nothing, and the near-U32_MAX cases wrap to a small nr_pages, so a small chunk array is built for a buffer the host is told is large. Reject both before the rounded size is stored or used.

vmbus_buffer_should_free() gathers the leak decision in one place. A cleanup whose GPADL create or teardown message may have reached the host cannot prove the host has released the pages. Handing those pages back to the allocator, or re-encrypting them, while the host may still map them is a use-after-free from the host's side and a Confidential Computing hazard. Such a buffer is marked leaked and its chunks are retained instead of freed.

The new cases live in drivers/hv/vmbus_buffer_test.c, which is built into the hv_vmbus object rather than a separate module. That keeps the cases off the production sources while still letting them call the internal sizing, order-descent and free-decision helpers. Those helpers are therefore not static; nothing outside hv_vmbus links against them, and no symbol is exported for test purposes.

The cases pin both rules, the partial-allocation rollback, and the order-descent fallback.

---
 drivers/hv/Kconfig             |  11 ++++
 drivers/hv/Makefile            |   1 +
 drivers/hv/channel.c           |  67 ++++++++++++++++++----
 drivers/hv/hyperv_vmbus.h      |  12 ++++
 drivers/hv/vmbus_buffer_test.c | 102 +++++++++++++++++++++++++++++++++
 5 files changed, 181 insertions(+), 12 deletions(-)
 create mode 100644 drivers/hv/vmbus_buffer_test.c
drivers/hv/Kconfig +11 -0
index aa11bcefddf2..d44dd60fbc23 100644
@@ -65,6 +65,17 @@ config HYPERV_VMBUS
 	help
 	  Select this option to enable Hyper-V Vmbus driver.
 
+config HYPERV_VMBUS_KUNIT_TEST
+	bool "Build Hyper-V VMBus buffer KUnit tests"
+	depends on HYPERV_VMBUS && KUNIT
+	default KUNIT_ALL_TESTS
+	help
+	  Build the vmbus buffer sizing, GPADL lifetime and reclaim KUnit
+	  cases into the hv_vmbus object. The cases reach internal helpers
+	  that are not exported, so they cannot live in a separate module.
+
+	  If unsure, say N.
+
 config MSHV_ROOT
 	tristate "Microsoft Hyper-V root partition support"
 	depends on HYPERV && (X86_64 || ARM64)
drivers/hv/Makefile +1 -0
index 888a748cc7cb..80d33e9c0e57 100644
@@ -12,6 +12,7 @@ hv_vmbus-y := vmbus_drv.o \
 		 hv.o connection.o channel.o \
 		 channel_mgmt.o ring_buffer.o hv_trace.o
 hv_vmbus-$(CONFIG_HYPERV_TESTING)	+= hv_debugfs.o
+hv_vmbus-$(CONFIG_HYPERV_VMBUS_KUNIT_TEST) += vmbus_buffer_test.o
 hv_utils-y := hv_util.o hv_kvp.o hv_snapshot.o hv_utils_transport.o
 mshv_root-y := mshv_root_main.o mshv_synic.o mshv_eventfd.o mshv_irq.o \
 	       mshv_root_hv_call.o mshv_portid_table.o mshv_regions.o
drivers/hv/channel.c +55 -12

130 lines not on this page · raw message

drivers/hv/hyperv_vmbus.h +12 -0
index 20d023c9735e..93df3b35cfd4 100644
@@ -551,4 +551,16 @@ int hv_create_ring_sysfs(struct vmbus_channel *channel,
 							    struct vm_area_desc *desc));
 int hv_remove_ring_sysfs(struct vmbus_channel *channel);
 
+/*
+ * vmbus buffer sizing, order-descent and free-decision helpers.
+ *
+ * These are shared with vmbus_buffer_test.c, which is built into the
+ * hv_vmbus object alongside channel.c. They stay unexported.
+ */
+int vmbus_buffer_round_size(u32 size, u32 *rounded_size);
+unsigned int vmbus_buffer_order(unsigned long remaining,
+				unsigned int max_order);
+bool vmbus_buffer_lower_order(unsigned int *order);
+bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer);
+
 #endif /* _HYPERV_VMBUS_H */
drivers/hv/vmbus_buffer_test.c new file +102 -0

102 lines not on this page · raw message

Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH v2 02/14] hv: vmbus: validate chunk buffer allocation and cleanup

kernel test robot noticed the following build errors:

Hi Emerson,

kernel test robot noticed the following build errors:

[auto build test ERROR on char-misc/char-misc-testing]
[also build test ERROR on char-misc/char-misc-next char-misc/char-misc-linus linus/master v7.3-rc6 next-20261008] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Emerson-Busson/hv-vmbus-convert-ring-backing-through-the-chunk-allocator/20261007-160739
base:   char-misc/char-misc-testing
patch link:    https://lore.kernel.org/r/20261007190752.336426-3-emersonbusson%40gmail.com
patch subject: [PATCH v2 02/14] hv: vmbus: validate chunk buffer allocation and cleanup
config: i386-randconfig-1005-20261008 (https://download.01.org/0day-ci/archive/20261009/[email protected]/config)
compiler: clang version 22.1.3 (https://github.com/llvm/llvm-project e9846648fd6183ee6d8cbdb4502213fcf902a211)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261009/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> ld.lld: error: undefined symbol: kunit_unary_assert_format
   >>> referenced by vmbus_buffer_test.c:48 (drivers/hv/vmbus_buffer_test.c:48)
   >>>               drivers/hv/vmbus_buffer_test.o:(vmbus_ring_fallback_order_zero_test) in archive vmlinux.a
   >>> referenced by vmbus_buffer_test.c:49 (drivers/hv/vmbus_buffer_test.c:49)
   >>>               drivers/hv/vmbus_buffer_test.o:(vmbus_ring_fallback_order_zero_test) in archive vmlinux.a
   >>> referenced by vmbus_buffer_test.c:61 (drivers/hv/vmbus_buffer_test.c:61)
   >>>               drivers/hv/vmbus_buffer_test.o:(vmbus_buffer_failed_teardown_leaks_test) in archive vmlinux.a
   >>> referenced 3 more times

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#4 lore raw

PATCH v2 3/14 uio: hv_generic: describe buffers for owned allocation

In reply to Emerson Busson

Group receive and send backing in VMBus descriptors before adopting the owned allocation and release APIs. Keep the existing vzalloc and ordinary GPADL path until the lifetime prerequisites land.

---
 drivers/uio/uio_hv_generic.c | 70 +++++++++++++++++-------------------
 1 file changed, 32 insertions(+), 38 deletions(-)
drivers/uio/uio_hv_generic.c +32 -38
index b3f41ffc74f8..2cb95b4786ca 100644
@@ -56,12 +56,10 @@ struct hv_uio_private_data {
 	struct hv_device *device;
 	atomic_t refcnt;
 
-	void	*recv_buf;
-	struct vmbus_gpadl recv_gpadl;
+	struct vmbus_buffer recv_buffer;
 	char	recv_name[32];	/* "recv_4294967295" */
 
-	void	*send_buf;
-	struct vmbus_gpadl send_gpadl;
+	struct vmbus_buffer send_buffer;
 	char	send_name[32];
 };
 
@@ -197,19 +195,13 @@ hv_uio_new_channel(struct vmbus_channel *new_sc)
 static void
 hv_uio_cleanup(struct hv_device *dev, struct hv_uio_private_data *pdata)
 {
-	if (pdata->send_gpadl.gpadl_handle) {
-		if (vmbus_teardown_gpadl(dev->channel, &pdata->send_gpadl))
-			pdata->send_gpadl.leak = true;
-		if (!pdata->send_gpadl.leak && !pdata->send_gpadl.decrypted)
-			vfree(pdata->send_buf);
-	}
+	if (pdata->send_buffer.gpadl.gpadl_handle)
+		vmbus_teardown_gpadl(dev->channel, &pdata->send_buffer.gpadl);
+	vmbus_release_buffer(&pdata->send_buffer);
 
-	if (pdata->recv_gpadl.gpadl_handle) {
-		if (vmbus_teardown_gpadl(dev->channel, &pdata->recv_gpadl))
-			pdata->recv_gpadl.leak = true;
-		if (!pdata->recv_gpadl.leak && !pdata->recv_gpadl.decrypted)
-			vfree(pdata->recv_buf);
-	}
+	if (pdata->recv_buffer.gpadl.gpadl_handle)
+		vmbus_teardown_gpadl(dev->channel, &pdata->recv_buffer.gpadl);
+	vmbus_release_buffer(&pdata->recv_buffer);
 }
 
 /* VMBus primary channel is opened on first use */
@@ -306,48 +298,50 @@ hv_uio_probe(struct hv_device *dev,
 	pdata->info.mem[MON_PAGE_MAP].memtype = UIO_MEM_LOGICAL;
 
 	if (channel->device_id == HV_NIC) {
-		pdata->recv_buf = vzalloc(RECV_BUFFER_SIZE);
-		if (!pdata->recv_buf) {
+		pdata->recv_buffer.addr =
+			vzalloc(RECV_BUFFER_SIZE);
+		if (!pdata->recv_buffer.addr) {
 			ret = -ENOMEM;
 			goto fail_free_ring;
 		}
 
-		ret = vmbus_establish_gpadl(channel, pdata->recv_buf,
-					    RECV_BUFFER_SIZE, &pdata->recv_gpadl);
-		if (ret) {
-			if (!pdata->recv_gpadl.leak &&
-			    !pdata->recv_gpadl.decrypted)
-				vfree(pdata->recv_buf);
+		ret = vmbus_establish_gpadl(channel,
+					    pdata->recv_buffer.addr,
+					    RECV_BUFFER_SIZE,
+					    &pdata->recv_buffer.gpadl);
+		pdata->recv_buffer.leak |= pdata->recv_buffer.gpadl.leak;
+		if (ret)
 			goto fail_close;
-		}
 
 		/* put Global Physical Address Label in name */
 		snprintf(pdata->recv_name, sizeof(pdata->recv_name),
-			 "recv:%u", pdata->recv_gpadl.gpadl_handle);
+			 "recv:%u", pdata->recv_buffer.gpadl.gpadl_handle);
 		pdata->info.mem[RECV_BUF_MAP].name = pdata->recv_name;
-		pdata->info.mem[RECV_BUF_MAP].addr = (uintptr_t)pdata->recv_buf;
+		pdata->info.mem[RECV_BUF_MAP].addr =
+			(uintptr_t)pdata->recv_buffer.addr;
 		pdata->info.mem[RECV_BUF_MAP].size = RECV_BUFFER_SIZE;
 		pdata->info.mem[RECV_BUF_MAP].memtype = UIO_MEM_VIRTUAL;
 
-		pdata->send_buf = vzalloc(SEND_BUFFER_SIZE);
-		if (!pdata->send_buf) {
+		pdata->send_buffer.addr =
+			vzalloc(SEND_BUFFER_SIZE);
+		if (!pdata->send_buffer.addr) {
 			ret = -ENOMEM;
 			goto fail_close;
 		}
 
-		ret = vmbus_establish_gpadl(channel, pdata->send_buf,
-					    SEND_BUFFER_SIZE, &pdata->send_gpadl);
-		if (ret) {
-			if (!pdata->send_gpadl.leak &&
-			    !pdata->send_gpadl.decrypted)
-				vfree(pdata->send_buf);
+		ret = vmbus_establish_gpadl(channel,
+					    pdata->send_buffer.addr,
+					    SEND_BUFFER_SIZE,
+					    &pdata->send_buffer.gpadl);
+		pdata->send_buffer.leak |= pdata->send_buffer.gpadl.leak;
+		if (ret)
 			goto fail_close;
-		}
 
 		snprintf(pdata->send_name, sizeof(pdata->send_name),
-			 "send:%u", pdata->send_gpadl.gpadl_handle);
+			 "send:%u", pdata->send_buffer.gpadl.gpadl_handle);
 		pdata->info.mem[SEND_BUF_MAP].name = pdata->send_name;
-		pdata->info.mem[SEND_BUF_MAP].addr = (uintptr_t)pdata->send_buf;
+		pdata->info.mem[SEND_BUF_MAP].addr =
+			(uintptr_t)pdata->send_buffer.addr;
 		pdata->info.mem[SEND_BUF_MAP].size = SEND_BUFFER_SIZE;
 		pdata->info.mem[SEND_BUF_MAP].memtype = UIO_MEM_VIRTUAL;
 	}
Signature · 1 line
2.43.0
#5 lore raw

PATCH v2 4/14 hv: vmbus: add KUnit tests for GPADL post failure injection

In reply to Emerson Busson

Route GPADL message posting through a private callback so KUnit can inject header, each body, and teardown post failures without a live host. Exercise uncertain host ownership after failed posts, host rejection, and channel rescind response handling through the same helpers used by production.

The cases join the existing ones in drivers/hv/vmbus_buffer_test.c, which is built into the hv_vmbus object. That keeps tests out of the production sources while still letting them drive vmbus_post_gpadl_messages(), vmbus_gpadl_response_status() and vmbus_post_gpadl_teardown(). Those three are therefore not static, and their callback type is declared in hyperv_vmbus.h alongside the sizing helpers. Nothing outside hv_vmbus links against them, and no symbol is exported.

---
 drivers/hv/channel.c           | 142 ++++++++++++++++----------
 drivers/hv/hyperv_vmbus.h      |  19 ++++
 drivers/hv/vmbus_buffer_test.c | 176 +++++++++++++++++++++++++++++++++
 3 files changed, 286 insertions(+), 51 deletions(-)
drivers/hv/channel.c +91 -51
index 7d5b99281872..6a1bc9b17869 100644
@@ -488,6 +488,84 @@ static void vmbus_free_channel_msginfo(struct vmbus_channel_msginfo *msginfo)
  *              should be 0 for BUFFER type gpadl
  * @gpadl_handle: some funky thing
  */
+static int vmbus_gpadl_post_real(void *context, void *buffer,
+				 size_t buflen, bool can_sleep)
+{
+	(void)context;
+	return vmbus_post_msg(buffer, buflen, can_sleep);
+}
+
+int vmbus_post_gpadl_messages(struct vmbus_channel_msginfo *msginfo,
+			      u32 gpadl, bool *posted,
+			      vmbus_gpadl_post_fn post_msg,
+			      void *context)
+{
+	struct vmbus_channel_gpadl_header *gpadl_header;
+	struct vmbus_channel_msginfo *submsginfo;
+	struct list_head *curr;
+	int ret;
+
+	gpadl_header = (struct vmbus_channel_gpadl_header *)msginfo->msg;
+	gpadl_header->header.msgtype = CHANNELMSG_GPADL_HEADER;
+	gpadl_header->gpadl = gpadl;
+
+	/* A failed post may still have reached the host. */
+	*posted = true;
+	ret = post_msg(context, gpadl_header,
+		       msginfo->msgsize - sizeof(*msginfo), true);
+	trace_vmbus_establish_gpadl_header(gpadl_header, ret);
+	if (ret)
+		return ret;
+
+	list_for_each(curr, &msginfo->submsglist) {
+		struct vmbus_channel_gpadl_body *gpadl_body;
+
+		submsginfo = list_entry(curr, struct vmbus_channel_msginfo,
+					msglistentry);
+		gpadl_body = (struct vmbus_channel_gpadl_body *)submsginfo->msg;
+		gpadl_body->header.msgtype = CHANNELMSG_GPADL_BODY;
+		gpadl_body->gpadl = gpadl;
+
+		ret = post_msg(context, gpadl_body,
+			       submsginfo->msgsize - sizeof(*submsginfo), true);
+		trace_vmbus_establish_gpadl_body(gpadl_body, ret);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+int vmbus_gpadl_response_status(u32 creation_status, bool rescind,
+				bool *posted)
+{
+	*posted = false;
+	if (creation_status)
+		return -EDQUOT;
+	if (rescind)
+		return -ENODEV;
+
+	return 0;
+}
+
+int vmbus_post_gpadl_teardown(u32 child_relid,
+			      struct vmbus_channel_gpadl_teardown *msg,
+			      u32 gpadl,
+			      vmbus_gpadl_post_fn post_msg,
+			      void *context)
+{
+	int ret;
+
+	msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
+	msg->child_relid = child_relid;
+	msg->gpadl = gpadl;
+
+	ret = post_msg(context, msg, sizeof(*msg), true);
+	trace_vmbus_teardown_gpadl(msg, ret);
+
+	return ret;
+}
+
 static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 				   enum hv_gpadl_type type, void *kbuffer,
 				   u32 size, u32 send_offset, bool memory_prepared,
@@ -495,11 +573,9 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 				   struct vmbus_gpadl *gpadl)
 {
 	struct vmbus_channel_gpadl_header *gpadlmsg;
-	struct vmbus_channel_gpadl_body *gpadl_body;
 	struct vmbus_channel_msginfo *msginfo = NULL;
-	struct vmbus_channel_msginfo *submsginfo;
-	struct list_head *curr;
 	u32 next_gpadl_handle;
+	u32 creation_status;
 	unsigned long flags;
 	bool posted = false;
 	int ret = 0;
@@ -558,49 +634,20 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 		goto cleanup;
 	}
 
-	/* A failed post may still have reached the host. */
-	posted = true;
-	ret = vmbus_post_msg(gpadlmsg, msginfo->msgsize -
-			     sizeof(*msginfo), true);
-
-	trace_vmbus_establish_gpadl_header(gpadlmsg, ret);
-
-	if (ret != 0)
+	ret = vmbus_post_gpadl_messages(msginfo, next_gpadl_handle, &posted,
+					vmbus_gpadl_post_real, NULL);
+	if (ret)
 		goto cleanup;
 
-	list_for_each(curr, &msginfo->submsglist) {
-		submsginfo = (struct vmbus_channel_msginfo *)curr;
-		gpadl_body =
-			(struct vmbus_channel_gpadl_body *)submsginfo->msg;
-
-		gpadl_body->header.msgtype =
-			CHANNELMSG_GPADL_BODY;
-		gpadl_body->gpadl = next_gpadl_handle;
-
-		ret = vmbus_post_msg(gpadl_body,
-				     submsginfo->msgsize - sizeof(*submsginfo),
-				     true);
-
-		trace_vmbus_establish_gpadl_body(gpadl_body, ret);
-
-		if (ret != 0)
-			goto cleanup;
-
-	}
 	wait_for_completion(&msginfo->waitevent);
 
-	if (msginfo->response.gpadl_created.creation_status != 0) {
-		posted = false;
-		pr_err("Failed to establish GPADL: err = 0x%x\n",
-		       msginfo->response.gpadl_created.creation_status);
-
-		ret = -EDQUOT;
-		goto cleanup;
-	}
-
-	if (channel->rescind) {
-		posted = false;
-		ret = -ENODEV;
+	creation_status = msginfo->response.gpadl_created.creation_status;
+	ret = vmbus_gpadl_response_status(creation_status, channel->rescind,
+					  &posted);
+	if (ret) {
+		if (creation_status)
+			pr_err("Failed to establish GPADL: err = 0x%x\n",
+			       creation_status);
 		goto cleanup;
 	}
 
@@ -608,8 +655,6 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 	gpadl->gpadl_handle = gpadlmsg->gpadl;
 	gpadl->buffer = kbuffer;
 	gpadl->size = size;
-	posted = false;
-
 
 cleanup:
 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
@@ -1118,9 +1163,6 @@ int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpad
 
 	msg = (struct vmbus_channel_gpadl_teardown *)info->msg;
 
-	msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
-	msg->child_relid = channel->offermsg.child_relid;
-	msg->gpadl = gpadl->gpadl_handle;
 
 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
 	list_add_tail(&info->msglistentry,
@@ -1130,10 +1172,8 @@ int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpad
 	if (channel->rescind)
 		goto post_msg_err;
 
-	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),
-			     true);
-
-	trace_vmbus_teardown_gpadl(msg, ret);
+	ret = vmbus_post_gpadl_teardown(channel->offermsg.child_relid, msg, gpadl->gpadl_handle,
+					vmbus_gpadl_post_real, NULL);
 
 	if (ret)
 		goto post_msg_err;
drivers/hv/hyperv_vmbus.h +19 -0
index 93df3b35cfd4..bb585ac2ceac 100644
@@ -563,4 +563,23 @@ unsigned int vmbus_buffer_order(unsigned long remaining,
 bool vmbus_buffer_lower_order(unsigned int *order);
 bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer);
 
+/*
+ * GPADL post and response helpers, also shared with vmbus_buffer_test.c.
+ * Same deal as the sizing helpers above: defined in channel.c, built into
+ * the hv_vmbus object, never exported.
+ */
+typedef int (*vmbus_gpadl_post_fn)(void *context, void *buffer,
+				   size_t buflen, bool can_sleep);
+int vmbus_post_gpadl_messages(struct vmbus_channel_msginfo *msginfo,
+			      u32 gpadl, bool *posted,
+			      vmbus_gpadl_post_fn post_msg,
+			      void *context);
+int vmbus_gpadl_response_status(u32 creation_status, bool rescind,
+				bool *posted);
+int vmbus_post_gpadl_teardown(u32 child_relid,
+			      struct vmbus_channel_gpadl_teardown *msg,
+			      u32 gpadl,
+			      vmbus_gpadl_post_fn post_msg,
+			      void *context);
+
 #endif /* _HYPERV_VMBUS_H */
drivers/hv/vmbus_buffer_test.c +176 -0

188 lines not on this page · raw message

Signature · 1 line
2.43.0
#6 lore raw

PATCH v2 5/14 hv: vmbus: add KUnit test for order-zero allocation fallback

In reply to Emerson Busson

Factor the order-descent allocation loop so KUnit can inject failures for orders above zero while retaining a real order-zero allocation in the test path. Also verify clean exhaustion when the order-zero attempt fails.

The factoring keeps the per-order GFP policy of the loop it replaces. Speculative attempts above order 0 still carry __GFP_COMP together with __GFP_NORETRY | __GFP_NOWARN so they cannot OOM-kill, and the order-0 attempt is still the plain GFP_KERNEL | __GFP_ZERO final fallback that is allowed to try harder. Reusing one gfp across the whole descent would leave __GFP_NORETRY set on the order-0 attempt and silently weaken that last resort.

The case joins the others in drivers/hv/vmbus_buffer_test.c, built into the hv_vmbus object. vmbus_alloc_pages_with_fallback() and its callback type are therefore declared in hyperv_vmbus.h instead of staying static in channel.c. Nothing outside hv_vmbus links against them, and no symbol is exported.

---
 drivers/hv/channel.c           | 56 ++++++++++++++++++++++----------
 drivers/hv/hyperv_vmbus.h      | 13 ++++++++
 drivers/hv/vmbus_buffer_test.c | 58 ++++++++++++++++++++++++++++++++++
 3 files changed, 111 insertions(+), 16 deletions(-)
drivers/hv/channel.c +40 -16
index 6a1bc9b17869..0c025a12808a 100644
@@ -60,6 +60,31 @@ bool vmbus_buffer_lower_order(unsigned int *order)
 	return true;
 }
 
+struct page *vmbus_alloc_pages_with_fallback(int nid, gfp_t gfp,
+					     unsigned int *order,
+					     vmbus_alloc_pages_fn alloc,
+					     void *context)
+{
+	struct page *page;
+
+	do {
+		gfp_t try_gfp = gfp;
+
+		/*
+		 * Use __GFP_NORETRY | __GFP_NOWARN to avoid OOM-killing,
+		 * but try harder at order 0 since that is the final
+		 * fallback.
+		 * __GFP_COMP stores order information in the page folio.
+		 */
+		if (*order)
+			try_gfp |= __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN;
+
+		page = alloc(context, nid, try_gfp, *order);
+		if (page || !vmbus_buffer_lower_order(order))
+			return page;
+	} while (true);
+}
+
 bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer)
 {
 	return !buffer->leak && !buffer->gpadl.leak &&
@@ -774,6 +799,14 @@ void vmbus_release_buffer(struct vmbus_buffer *buffer)
 }
 EXPORT_SYMBOL_GPL(vmbus_release_buffer);
 
+static struct page *vmbus_alloc_pages_node(void *context, int nid,
+					   gfp_t gfp,
+					   unsigned int order)
+{
+	(void)context;
+	return alloc_pages_node(nid, gfp, order);
+}
+
 /**
  * __vmbus_alloc_buffer - allocate host-visible, virtually-contiguous backing.
  *
@@ -837,26 +870,17 @@ static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
 	while (remaining) {
 		struct page *page;
 		gfp_t gfp;
+		int nid;
 
 		order = vmbus_buffer_order(remaining, order);
 
-		/*
-		 * Use __GFP_NORETRY | __GFP_NOWARN to avoid OOM-killing,
-		 * but try harder at order 0 since that is the final
-		 * fallback.
-		 * __GFP_COMP stores order information in the page folio.
-		 */
 		gfp = GFP_KERNEL | __GFP_ZERO;
-		if (order)
-			gfp |= __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN;
-
-		page = alloc_pages_node(cpu_to_node(channel->target_cpu),
-					gfp, order);
-		if (!page) {
-			if (!vmbus_buffer_lower_order(&order))
-				goto err;
-			continue;
-		}
+
+		nid = cpu_to_node(channel->target_cpu);
+		page = vmbus_alloc_pages_with_fallback(nid, gfp, &order,
+						       vmbus_alloc_pages_node, NULL);
+		if (!page)
+			goto err;
 
 		ret = set_memory_decrypted((unsigned long)page_address(page),
 					   1U << order);
drivers/hv/hyperv_vmbus.h +13 -0
index bb585ac2ceac..e08c472041d5 100644
@@ -563,6 +563,19 @@ unsigned int vmbus_buffer_order(unsigned long remaining,
 bool vmbus_buffer_lower_order(unsigned int *order);
 bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer);
 
+/*
+ * Order-descent allocation, shared with vmbus_buffer_test.c so the
+ * cases can inject per-order failures. Defined in channel.c, built
+ * into the hv_vmbus object, never exported.
+ */
+typedef struct page *(*vmbus_alloc_pages_fn)(void *context, int nid,
+					     gfp_t gfp,
+					     unsigned int order);
+struct page *vmbus_alloc_pages_with_fallback(int nid, gfp_t gfp,
+					     unsigned int *order,
+					     vmbus_alloc_pages_fn alloc,
+					     void *context);
+
 /*
  * GPADL post and response helpers, also shared with vmbus_buffer_test.c.
  * Same deal as the sizing helpers above: defined in channel.c, built into
drivers/hv/vmbus_buffer_test.c +58 -0

70 lines not on this page · raw message

Signature · 1 line
2.43.0
#7 lore raw

PATCH v2 6/14 hv: vmbus: cover all shared-page policy combinations

In reply to Emerson Busson

Name the shared-page selection and enumerate all eight combinations of Hyper-V isolation, independent guest-memory encryption and channel confidentiality. Either platform visibility signal selects shared backing; the confidential-channel override keeps private backing. These are decision tests, not confidential hardware qualification.

---
 drivers/hv/channel.c           | 16 ++++++++++++++--
 drivers/hv/hyperv_vmbus.h      |  2 ++
 drivers/hv/vmbus_buffer_test.c | 29 +++++++++++++++++++++++++++++
 3 files changed, 45 insertions(+), 2 deletions(-)
drivers/hv/channel.c +14 -2
index 0c025a12808a..8ed155f2669f 100644
@@ -45,6 +45,13 @@ int vmbus_buffer_round_size(u32 size, u32 *rounded_size)
 	return 0;
 }
 
+bool
+vmbus_needs_shared_pages(bool hv_isolation, bool guest_mem_encrypted,
+			 bool confidential)
+{
+	return !confidential && (hv_isolation || guest_mem_encrypted);
+}
+
 unsigned int vmbus_buffer_order(unsigned long remaining,
 				unsigned int max_order)
 {
@@ -837,6 +844,8 @@ static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
 	unsigned long nr_pages;
 	unsigned long remaining;
 	unsigned long page_idx = 0;
+	bool hv_isolation;
+	bool guest_mem_encrypted;
 	struct page **chunks = NULL;
 	struct page **pages = NULL;
 	unsigned int order = MAX_PAGE_ORDER;
@@ -853,9 +862,12 @@ static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
 	nr_pages = rounded_size >> PAGE_SHIFT;
 	remaining = nr_pages;
 
+	hv_isolation = hv_is_isolation_supported();
+	guest_mem_encrypted = cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT);
+
 	/* If the buffer does not need to be decrypted, just use vzalloc() */
-	if ((!hv_is_isolation_supported() &&
-	     !cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) || confidential)
+	if (!vmbus_needs_shared_pages(hv_isolation, guest_mem_encrypted,
+				      confidential))
 		return vzalloc(rounded_size);
 
 	/* Worst case: every chunk is a single page. */
drivers/hv/hyperv_vmbus.h +2 -0
index e08c472041d5..06094000f2f1 100644
@@ -557,6 +557,8 @@ int hv_remove_ring_sysfs(struct vmbus_channel *channel);
  * These are shared with vmbus_buffer_test.c, which is built into the
  * hv_vmbus object alongside channel.c. They stay unexported.
  */
+bool vmbus_needs_shared_pages(bool hv_isolation, bool guest_mem_encrypted,
+			      bool confidential);
 int vmbus_buffer_round_size(u32 size, u32 *rounded_size);
 unsigned int vmbus_buffer_order(unsigned long remaining,
 				unsigned int max_order);
drivers/hv/vmbus_buffer_test.c +29 -0
index 60fc526af1af..9b401ef2ceea 100644
@@ -38,6 +38,34 @@ static void vmbus_buffer_size_overflow_test(struct kunit *test)
 			(u32)(U32_MAX - PAGE_SIZE + 1));
 }
 
+static void vmbus_buffer_private_shared_selection_test(struct kunit *test)
+{
+	static const struct {
+		bool isolation;
+		bool encrypted;
+		bool confidential;
+		bool shared;
+	} cases[] = {
+		{ false, false, false, false },
+		{ false, false, true, false },
+		{ false, true, false, true },
+		{ false, true, true, false },
+		{ true, false, false, true },
+		{ true, false, true, false },
+		{ true, true, false, true },
+		{ true, true, true, false },
+	};
+	unsigned int i;
+
+	/* Either platform signal requires visibility; confidential stays private. */
+	for (i = 0; i < ARRAY_SIZE(cases); i++)
+		KUNIT_EXPECT_EQ(test,
+				vmbus_needs_shared_pages(cases[i].isolation,
+							 cases[i].encrypted,
+							 cases[i].confidential),
+				cases[i].shared);
+}
+
 static void vmbus_ring_fallback_order_zero_test(struct kunit *test)
 {
 	unsigned int order;
@@ -317,6 +345,7 @@ static void vmbus_buffer_order_zero_allocation_test(struct kunit *test)
 static struct kunit_case vmbus_buffer_test_cases[] = {
 	KUNIT_CASE(vmbus_buffer_size_rounding_test),
 	KUNIT_CASE(vmbus_buffer_size_overflow_test),
+	KUNIT_CASE(vmbus_buffer_private_shared_selection_test),
 	KUNIT_CASE(vmbus_ring_fallback_order_zero_test),
 	KUNIT_CASE(vmbus_buffer_failed_teardown_leaks_test),
 	KUNIT_CASE(vmbus_buffer_partial_allocation_cleanup_test),
Signature · 1 line
2.43.0
#8 lore raw

PATCH v2 7/14 hv: vmbus: distinguish host rescind from local channel unload

In reply to Emerson Busson

A channel can go away because the host revoked the offer, or because the guest is tearing the channel down itself. Both paths arrive at vmbus_onoffer_rescind() and set channel->rescind, so a later buffer consumer cannot tell whether the host has already taken the pages back or whether the guest still owns them and is about to free them.

Carry the origin through the message layer. vmbus_onmessage() takes a host_generated flag: the DPC work item sets it for host messages and vmbus_force_channel_rescinded() clears it for the local unload path. A small table adapter keeps the dispatch signature unchanged, while the rescind handler itself records the origin in channel->rescind_from_host next to the existing rescind flag. Both flags are cleared when a channel is set up.

The disconnected message path frees its work context instead of returning without a kfree(); it now owns that allocation from the moment container_of() runs.

Nothing reads rescind_from_host yet. The buffer-ownership rework lands in the next patch and is what consumes the flag.

---
 drivers/hv/channel_mgmt.c | 31 +++++++++++++++++++++++++------
 drivers/hv/vmbus_drv.c    | 13 ++++++++-----
 include/linux/hyperv.h    |  4 +++-
 3 files changed, 36 insertions(+), 12 deletions(-)
drivers/hv/channel_mgmt.c +25 -6
index a044fd3b3c4e..93fc105cd179 100644
@@ -170,14 +170,17 @@ static const struct {
  * The rescinded channel may be blocked waiting for a response from the host;
  * take care of that.
  */
-static void vmbus_rescind_cleanup(struct vmbus_channel *channel)
+static void vmbus_rescind_cleanup(struct vmbus_channel *channel,
+				  bool host_generated)
 {
 	struct vmbus_channel_msginfo *msginfo;
 	unsigned long flags;
 
 
 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
-	channel->rescind = true;
+	if (host_generated)
+		WRITE_ONCE(channel->rescind_from_host, true);
+	WRITE_ONCE(channel->rescind, true);
 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
 				msglistentry) {
 
@@ -955,6 +958,9 @@ EXPORT_SYMBOL_GPL(vmbus_initiate_unload);
 static void vmbus_setup_channel_state(struct vmbus_channel *channel,
 				      struct vmbus_channel_offer_channel *offer)
 {
+	WRITE_ONCE(channel->rescind, false);
+	WRITE_ONCE(channel->rescind_from_host, false);
+
 	/*
 	 * Setup state for signalling the host.
 	 */
@@ -1159,7 +1165,8 @@ static void check_ready_for_suspend_event(void)
  *
  * We queue a work item to process this offer synchronously
  */
-static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr)
+static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr,
+				  bool host_generated)
 {
 	struct vmbus_channel_rescind_offer *rescind;
 	struct vmbus_channel *channel;
@@ -1238,7 +1245,7 @@ static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr)
 	/*
 	 * Now wait for offer handling to complete.
 	 */
-	vmbus_rescind_cleanup(channel);
+	vmbus_rescind_cleanup(channel, host_generated);
 	while (READ_ONCE(channel->probe_done) == false) {
 		/*
 		 * We wait here until any channel offer is currently
@@ -1555,12 +1562,18 @@ static void vmbus_onversion_response(
 }
 
 /* Channel message dispatch table */
+static void
+vmbus_onoffer_rescind_from_table(struct vmbus_channel_message_header *hdr)
+{
+	vmbus_onoffer_rescind(hdr, true);
+}
+
 const struct vmbus_channel_message_table_entry
 channel_message_table[CHANNELMSG_COUNT] = {
 	{ CHANNELMSG_INVALID,			0, NULL, 0},
 	{ CHANNELMSG_OFFERCHANNEL,		0, vmbus_onoffer,
 		sizeof(struct vmbus_channel_offer_channel)},
-	{ CHANNELMSG_RESCIND_CHANNELOFFER,	0, vmbus_onoffer_rescind,
+	{ CHANNELMSG_RESCIND_CHANNELOFFER,	0, vmbus_onoffer_rescind_from_table,
 		sizeof(struct vmbus_channel_rescind_offer) },
 	{ CHANNELMSG_REQUESTOFFERS,		0, NULL, 0},
 	{ CHANNELMSG_ALLOFFERS_DELIVERED,	1, vmbus_onoffers_delivered, 0},
@@ -1596,7 +1609,8 @@ channel_message_table[CHANNELMSG_COUNT] = {
  *
  * This is invoked in the vmbus worker thread context.
  */
-void vmbus_onmessage(struct vmbus_channel_message_header *hdr)
+void vmbus_onmessage(struct vmbus_channel_message_header *hdr,
+		     bool host_generated)
 {
 	trace_vmbus_on_message(hdr);
 
@@ -1604,6 +1618,11 @@ void vmbus_onmessage(struct vmbus_channel_message_header *hdr)
 	 * vmbus_on_msg_dpc() makes sure the hdr->msgtype here can not go
 	 * out of bound and the message_handler pointer can not be NULL.
 	 */
+	if (hdr->msgtype == CHANNELMSG_RESCIND_CHANNELOFFER) {
+		vmbus_onoffer_rescind(hdr, host_generated);
+		return;
+	}
+
 	channel_message_table[hdr->msgtype].message_handler(hdr);
 }
 
drivers/hv/vmbus_drv.c +8 -5
index 5ebdbe24b5a1..723252f1b551 100644
@@ -1022,6 +1022,7 @@ static const struct bus_type  hv_bus = {
 
 struct onmessage_work_context {
 	struct work_struct work;
+	bool host_generated;
 	struct {
 		struct hv_message_header header;
 		u8 payload[];
@@ -1032,14 +1033,14 @@ static void vmbus_onmessage_work(struct work_struct *work)
 {
 	struct onmessage_work_context *ctx;
 
+	ctx = container_of(work, struct onmessage_work_context, work);
 	/* Do not process messages if we're in DISCONNECTED state */
-	if (vmbus_connection.conn_state == DISCONNECTED)
+	if (vmbus_connection.conn_state == DISCONNECTED) {
+		kfree(ctx);
 		return;
-
-	ctx = container_of(work, struct onmessage_work_context,
-			   work);
+	}
 	vmbus_onmessage((struct vmbus_channel_message_header *)
-			&ctx->msg.payload);
+			&ctx->msg.payload, ctx->host_generated);
 	kfree(ctx);
 }
 
@@ -1109,6 +1110,7 @@ static void __vmbus_on_msg_dpc(void *message_page_addr)
 			return;
 
 		INIT_WORK(&ctx->work, vmbus_onmessage_work);
+		ctx->host_generated = true;
 		ctx->msg.header = msg_copy.header;
 		memcpy(&ctx->msg.payload, msg_copy.u.payload, payload_size);
 
@@ -1222,6 +1224,7 @@ static void vmbus_force_channel_rescinded(struct vmbus_channel *channel)
 	rescind->child_relid = channel->offermsg.child_relid;
 
 	INIT_WORK(&ctx->work, vmbus_onmessage_work);
+	ctx->host_generated = false;
 
 	queue_work(vmbus_connection.work_queue, &ctx->work);
 }
include/linux/hyperv.h +3 -1
index 2878aed14c45..096054fa07a3 100644
@@ -809,6 +809,7 @@ struct vmbus_channel {
 	u8 monitor_bit;
 
 	bool rescind; /* got rescind msg */
+	bool rescind_from_host; /* host revocation, not local channel removal */
 	bool rescind_ref; /* got rescind msg, got channel reference */
 	struct completion rescind_event;
 
@@ -1117,7 +1118,8 @@ static inline void set_channel_pending_send_size(struct vmbus_channel *c,
 	c->outbound.ring_buffer->pending_send_sz = size;
 }
 
-void vmbus_onmessage(struct vmbus_channel_message_header *hdr);
+void vmbus_onmessage(struct vmbus_channel_message_header *hdr,
+		     bool host_generated);
 
 int vmbus_request_offers(void);
 
Signature · 1 line
2.43.0
#9 lore raw

PATCH v2 8/14 hv: vmbus: retain backing until ownership and references clear

In reply to Emerson Busson

Keep allocation and GPADL state in one retained owner. Unknown create or teardown ownership and failed page transitions retain backing. A known live handle may request teardown after a host rescind, but only an actual matching reply releases host ownership; timeout and local removal do not. Remove response waiters under their list lock before freeing them.

Drain only pending reclaim work successfully acquired by cancellation. A running callback retains custody and is never queued for another execution. Native-workqueue and private-connection tests cover those boundaries without mutating the live connection.

Rollback trigger: revert the lifecycle change if ordinary backing, response identity or callback custody cannot be qualified; never free unknown host-owned pages to satisfy a bound.

---
 drivers/hv/channel.c           | 757 ++++++++++++++++++++++++++-------
 drivers/hv/channel_mgmt.c      |  24 +-
 drivers/hv/hv_trace.h          |  24 ++
 drivers/hv/hyperv_vmbus.h      |  51 +++
 drivers/hv/vmbus_buffer_test.c | 453 +++++++++++++++++++-
 drivers/hv/vmbus_drv.c         |   1 +
 include/linux/hyperv.h         |  18 +
 7 files changed, 1171 insertions(+), 157 deletions(-)
drivers/hv/channel.c +610 -147
index 8ed155f2669f..aa33a0f08a7f 100644
@@ -23,11 +23,37 @@
 #include <linux/set_memory.h>
 #include <linux/vmalloc.h>
 #include <linux/export.h>
+#include <linux/list.h>
+#include <linux/mutex.h>
+#include <linux/workqueue.h>
 #include <asm/page.h>
 #include <asm/mshyperv.h>
 
 #include "hyperv_vmbus.h"
 
+static LIST_HEAD(vmbus_buffer_owners);
+static DEFINE_MUTEX(vmbus_buffer_owners_lock);
+static struct workqueue_struct *vmbus_buffer_reclaim_wq;
+static bool vmbus_buffer_reclaimer_stopping;
+static atomic64_t vmbus_buffer_owner_sequence = ATOMIC64_INIT(0);
+
+/*
+ * Reclaim scheduling. VMBUS_BUFFER_RECLAIM_SCHEDULE_MS is the delay
+ * before the first reclaim attempt after ownership state changes;
+ * it is kept at one jiffy so a completed GPADL teardown frees the
+ * buffer promptly. VMBUS_BUFFER_RECLAIM_RETRY_MS is the steady-state
+ * retry while a guest mapping still holds the pages. The workqueue
+ * is unbound so reclaim never runs in the caller's context, and
+ * WQ_MEM_RECLAIM so the free path is not blocked by the very
+ * pressure it is relieving. max_active stays at one: re-encryption
+ * is serialized and the cost of a second concurrent worker is not
+ * worth the ordering questions it would raise.
+ */
+#define VMBUS_BUFFER_RECLAIM_SCHEDULE_MS	1
+#define VMBUS_BUFFER_RECLAIM_RETRY_MS		1000
+#define VMBUS_BUFFER_RECLAIM_WQ_FLAGS		(WQ_UNBOUND | WQ_MEM_RECLAIM)
+#define VMBUS_BUFFER_RECLAIM_WQ_MAX_ACTIVE	1
+
 /*
  * vmbus_buffer_round_size() and the order-descent helpers are also called
  * from vmbus_buffer_test.c, which is built into this same object. They are
@@ -98,11 +124,276 @@ bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer)
 	       !buffer->gpadl.gpadl_handle;
 }
 
-static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
-				  u32 size,
-				  bool confidential,
-				  struct page ***chunks_out,
-				  u32 *chunk_cnt_out);
+/* Caller holds the owner lock or exclusive custody of this owner. */
+static void vmbus_buffer_trace_owner(const struct vmbus_buffer_retained *owner,
+				     const char *action)
+{
+	/* Bit 0: host uncertainty; bit 1: page state; bit 2: permanent retain. */
+	u8 state = owner->host_may_own | (owner->encryption_unknown << 1) |
+		   (owner->permanent_leak << 2);
+
+	trace_vmbus_buffer_owner(owner->owner_id, owner->channel_id, action,
+				 owner->size, owner->page_cnt, state);
+}
+
+bool
+vmbus_buffer_owner_can_reclaim(const struct vmbus_buffer_retained *owner)
+{
+	return owner->released && !owner->permanent_leak &&
+	       !owner->encryption_unknown &&
+	       !owner->host_may_own;
+}
+
+bool
+vmbus_buffer_owner_should_schedule(const struct vmbus_buffer_retained *owner,
+				   bool stopping, bool queue_live)
+{
+	return !owner->work_active && !owner->reclaiming &&
+	       vmbus_buffer_owner_can_reclaim(owner) && !stopping && queue_live;
+}
+
+static void
+vmbus_buffer_schedule_reclaim_locked(struct vmbus_buffer_retained *owner)
+{
+	if (!vmbus_buffer_owner_should_schedule(owner,
+						vmbus_buffer_reclaimer_stopping,
+						vmbus_buffer_reclaim_wq))
+		return;
+
+	owner->work_active = true;
+	mod_delayed_work(vmbus_buffer_reclaim_wq, &owner->reclaim_work,
+			 msecs_to_jiffies(VMBUS_BUFFER_RECLAIM_SCHEDULE_MS));
+}
+
+static void
+vmbus_buffer_update_host_ownership(struct vmbus_buffer_retained *owner,
+				   bool host_may_own)
+{
+	mutex_lock(&vmbus_buffer_owners_lock);
+	owner->host_may_own = host_may_own;
+	vmbus_buffer_schedule_reclaim_locked(owner);
+	mutex_unlock(&vmbus_buffer_owners_lock);
+}
+
+/*
+ * Declared before vmbus_buffer_owner_alloc() hands the callback pointer
+ * to INIT_DELAYED_WORK(); defined below with the rest of the reclaim
+ * machinery.
+ */
+static void vmbus_buffer_reclaim_work(struct work_struct *work);
+
+struct vmbus_buffer_retained *
+vmbus_buffer_owner_alloc(struct vmbus_channel *channel)
+{
+	struct vmbus_buffer_retained *owner;
+
+	owner = kzalloc_obj(*owner);
+	if (!owner)
+		return NULL;
+
+	INIT_LIST_HEAD(&owner->list);
+	INIT_DELAYED_WORK(&owner->reclaim_work, vmbus_buffer_reclaim_work);
+	owner->channel_id = channel->lifetime_id;
+	owner->owner_id = atomic64_inc_return(&vmbus_buffer_owner_sequence);
+
+	mutex_lock(&vmbus_buffer_owners_lock);
+	if (vmbus_buffer_reclaimer_stopping)
+		goto err_unlock;
+	if (!vmbus_buffer_reclaim_wq) {
+		vmbus_buffer_reclaim_wq =
+			alloc_workqueue("vmbus-buffer-reclaim",
+					VMBUS_BUFFER_RECLAIM_WQ_FLAGS,
+					VMBUS_BUFFER_RECLAIM_WQ_MAX_ACTIVE);
+		if (!vmbus_buffer_reclaim_wq)
+			goto err_unlock;
+	}
+	list_add_tail(&owner->list, &vmbus_buffer_owners);
+	vmbus_buffer_trace_owner(owner, "created");
+	mutex_unlock(&vmbus_buffer_owners_lock);
+
+	return owner;
+
+err_unlock:
+	mutex_unlock(&vmbus_buffer_owners_lock);
+	kfree(owner);
+	return NULL;
+}
+
+static void vmbus_buffer_owner_free(struct vmbus_buffer_retained *owner)
+{
+	mutex_lock(&vmbus_buffer_owners_lock);
+	if (!list_empty(&owner->list))
+		list_del_init(&owner->list);
+	mutex_unlock(&vmbus_buffer_owners_lock);
+
+	kfree(owner);
+}
+
+static void vmbus_buffer_owner_remove(struct vmbus_buffer_retained *owner)
+{
+	/*
+	 * The owner embeds a delayed_work and its timer may still be
+	 * armed when an external caller drops the last reference.
+	 * Freeing the object under an armed timer would let the
+	 * callback reach freed memory, so stop the timer first. The
+	 * reclaim work itself must not come through here: it would
+	 * wait for its own completion.
+	 */
+	cancel_delayed_work_sync(&owner->reclaim_work);
+	vmbus_buffer_trace_owner(owner, "discarded");
+	vmbus_buffer_owner_free(owner);
+}
+
+bool vmbus_buffer_pages_busy(struct vmbus_buffer_retained *owner)
+{
+	u32 i;
+
+	for (i = 0; i < owner->page_cnt; i++) {
+		if (WARN_ON_ONCE(!owner->pages || !owner->pages[i]))
+			return true;
+		if (folio_ref_count(page_folio(owner->pages[i])) != 1)
+			return true;
+	}
+
+	return false;
+}
+
+static void vmbus_buffer_reclaim_work(struct work_struct *work)
+{
+	struct vmbus_buffer_retained *owner = container_of(to_delayed_work(work),
+								   struct vmbus_buffer_retained,
+								   reclaim_work);
+	unsigned long delay = msecs_to_jiffies(VMBUS_BUFFER_RECLAIM_RETRY_MS);
+	u32 i;
+	int ret = 0;
+
+	mutex_lock(&vmbus_buffer_owners_lock);
+	/*
+	 * A ready owner must still be reclaimable while the workqueue
+	 * is being destroyed: shutdown re-queues exactly those so they
+	 * drain before destroy_workqueue() returns. New work is never
+	 * scheduled past that point because
+	 * vmbus_buffer_owner_should_schedule() refuses once stopping.
+	 */
+	if (!vmbus_buffer_owner_can_reclaim(owner)) {
+		owner->work_active = false;
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		return;
+	}
+
+	if (vmbus_buffer_pages_busy(owner)) {
+		if (vmbus_buffer_reclaimer_stopping) {
+			/*
+			 * A guest mapping still holds these pages as the
+			 * workqueue goes away. Freeing them would be a
+			 * use-after-free, so retain and say so.
+			 */
+			owner->permanent_leak = true;
+			owner->work_active = false;
+			vmbus_buffer_trace_owner(owner, "retained");
+		} else {
+			mod_delayed_work(vmbus_buffer_reclaim_wq,
+					 &owner->reclaim_work, delay);
+		}
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		return;
+	}
+	owner->reclaiming = true;
+	mutex_unlock(&vmbus_buffer_owners_lock);
+
+	if (owner->needs_encrypt) {
+		for (i = 0; i < owner->chunk_cnt; i++) {
+			struct page *page = owner->chunks[i];
+			unsigned int order = folio_order(page_folio(page));
+
+			ret = set_memory_encrypted((unsigned long)page_address(page),
+						   1U << order);
+			if (ret)
+				break;
+		}
+	} else if (owner->raw_decrypted) {
+		ret = set_memory_encrypted((unsigned long)owner->addr,
+					   PFN_UP(owner->size));
+	}
+
+	if (ret) {
+		mutex_lock(&vmbus_buffer_owners_lock);
+		owner->permanent_leak = true;
+		owner->work_active = false;
+		owner->reclaiming = false;
+		vmbus_buffer_trace_owner(owner, "retained");
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		pr_warn_ratelimited("VMBus buffer reclaim retained pages after encryption failure: %d\n",
+				    ret);
+		return;
+	}
+
+	vmbus_buffer_trace_owner(owner, "reclaimed");
+	if (owner->addr) {
+		if (owner->chunks)
+			vunmap(owner->addr);
+		else
+			vfree(owner->addr);
+	}
+
+	for (i = 0; i < owner->chunk_cnt; i++) {
+		struct page *page = owner->chunks[i];
+		unsigned int order = folio_order(page_folio(page));
+
+		__free_pages(page, order);
+	}
+
+	kvfree(owner->chunks);
+	kvfree(owner->pages);
+	vmbus_buffer_owner_free(owner);
+}
+
+/* Caller holds the owner lock or exclusive custody of this owner. */
+void vmbus_buffer_owner_drain(struct vmbus_buffer_retained *owner,
+			      struct workqueue_struct *wq)
+{
+	if (!cancel_delayed_work(&owner->reclaim_work))
+		return;
+
+	owner->work_active = false;
+	if (wq && vmbus_buffer_owner_can_reclaim(owner)) {
+		owner->work_active = true;
+		mod_delayed_work(wq, &owner->reclaim_work, 0);
+	}
+}
+
+void vmbus_buffer_reclaimer_shutdown(void)
+{
+	struct workqueue_struct *wq;
+	struct vmbus_buffer_retained *owner;
+
+	mutex_lock(&vmbus_buffer_owners_lock);
+	vmbus_buffer_reclaimer_stopping = true;
+	wq = vmbus_buffer_reclaim_wq;
+	vmbus_buffer_reclaim_wq = NULL;
+
+	/*
+	 * destroy_workqueue() drains work that is queued or already
+	 * running. A delayed_work still waiting on its timer is not
+	 * on the workqueue yet, so cancel those timers here or they
+	 * fire against a workqueue that is about to be freed.
+	 * cancel_delayed_work() rather than _sync: reclaim work that
+	 * is already running blocks on this same lock, and
+	 * destroy_workqueue() below waits for it to finish.
+	 *
+	 * An owner that is already ready to reclaim must not be lost
+	 * with its cancelled timer. Requeue only work that was actually
+	 * cancelled: a running callback owns its embedded work item and
+	 * may free the owner before a second queued execution can run.
+	 * destroy_workqueue() drains that running callback itself.
+	 */
+	list_for_each_entry(owner, &vmbus_buffer_owners, list)
+		vmbus_buffer_owner_drain(owner, wq);
+	mutex_unlock(&vmbus_buffer_owners_lock);
+
+	if (wq)
+		destroy_workqueue(wq);
+}
 
 /*
  * hv_gpadl_size - Return the real size of a gpadl, the size that Hyper-V uses
@@ -248,30 +539,20 @@ int vmbus_alloc_ring(struct vmbus_channel *newchannel,
 {
 	struct vmbus_buffer *buffer = &newchannel->ringbuffer;
 	u32 size;
-	u32 i;
+	int ret;
 
 	if (!send_size || !recv_size ||
 	    send_size % PAGE_SIZE || recv_size % PAGE_SIZE ||
 	    check_add_overflow(send_size, recv_size, &size))
 		return -EINVAL;
 
-	buffer->addr = __vmbus_alloc_buffer(newchannel, size,
-					    newchannel->co_ring_buffer,
-					    &buffer->chunks, &buffer->chunk_cnt);
-	if (!buffer->addr)
-		return -ENOMEM;
+	ret = vmbus_alloc_buffer_owned(newchannel, size,
+				       newchannel->co_ring_buffer, buffer);
+	if (ret)
+		return ret;
 
 	newchannel->ringbuffer_pagecount = size >> PAGE_SHIFT;
 	newchannel->ringbuffer_send_offset = send_size >> PAGE_SHIFT;
-	buffer->pages = kvcalloc(newchannel->ringbuffer_pagecount,
-				 sizeof(*buffer->pages), GFP_KERNEL);
-	if (!buffer->pages) {
-		vmbus_release_buffer(buffer);
-		return -ENOMEM;
-	}
-
-	for (i = 0; i < newchannel->ringbuffer_pagecount; i++)
-		buffer->pages[i] = vmalloc_to_page(buffer->addr + (i << PAGE_SHIFT));
 
 	return 0;
 }
@@ -571,12 +852,15 @@ int vmbus_post_gpadl_messages(struct vmbus_channel_msginfo *msginfo,
 int vmbus_gpadl_response_status(u32 creation_status, bool rescind,
 				bool *posted)
 {
-	*posted = false;
-	if (creation_status)
+	if (creation_status) {
+		*posted = false;
 		return -EDQUOT;
+	}
 	if (rescind)
 		return -ENODEV;
 
+	/* A response resolved the request; a successful GPADL is tracked by handle. */
+	*posted = false;
 	return 0;
 }
 
@@ -599,21 +883,22 @@ int vmbus_post_gpadl_teardown(u32 child_relid,
 }
 
 static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
-				   enum hv_gpadl_type type, void *kbuffer,
-				   u32 size, u32 send_offset, bool memory_prepared,
-				   bool *leak,
-				   struct vmbus_gpadl *gpadl)
+				   enum hv_gpadl_type type,
+				   struct vmbus_buffer *buffer,
+				   u32 send_offset, bool memory_prepared)
 {
 	struct vmbus_channel_gpadl_header *gpadlmsg;
 	struct vmbus_channel_msginfo *msginfo = NULL;
+	struct vmbus_buffer_retained *owner = buffer->owner;
+	struct vmbus_gpadl *gpadl = &buffer->gpadl;
+	void *kbuffer = buffer->addr;
+	u32 size = buffer->size;
 	u32 next_gpadl_handle;
 	u32 creation_status;
 	unsigned long flags;
 	bool posted = false;
 	int ret = 0;
 
-	if (leak)
-		*leak = false;
 	gpadl->leak = false;
 
 	next_gpadl_handle =
@@ -641,6 +926,9 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 			dev_warn(&channel->device_obj->device,
 				"Failed to set host visibility for new GPADL %d.\n",
 				ret);
+			if (owner)
+				owner->encryption_unknown = true;
+			gpadl->leak = true;
 			vmbus_free_channel_msginfo(msginfo);
 			return ret;
 		}
@@ -668,6 +956,8 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 
 	ret = vmbus_post_gpadl_messages(msginfo, next_gpadl_handle, &posted,
 					vmbus_gpadl_post_real, NULL);
+	if (posted && owner)
+		vmbus_buffer_update_host_ownership(owner, true);
 	if (ret)
 		goto cleanup;
 
@@ -687,6 +977,8 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 	gpadl->gpadl_handle = gpadlmsg->gpadl;
 	gpadl->buffer = kbuffer;
 	gpadl->size = size;
+	if (owner)
+		vmbus_buffer_update_host_ownership(owner, true);
 
 cleanup:
 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
@@ -695,40 +987,44 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 
 	vmbus_free_channel_msginfo(msginfo);
 
-	if (ret && posted) {
+	if (ret && posted)
 		gpadl->leak = true;
-		if (leak)
-			*leak = true;
-	}
-
-	if (ret && !posted) {
-		/*
-		 * If set_memory_encrypted() fails, the decrypted flag is
-		 * left as true so the memory is leaked instead of being
-		 * put back on the free list.
-		 */
-		if (gpadl->decrypted) {
-			if (!set_memory_encrypted((unsigned long)kbuffer, PFN_UP(size)))
-				gpadl->decrypted = false;
-		}
-	}
+	else if (ret && owner)
+		vmbus_buffer_update_host_ownership(owner, false);
 
 	return ret;
 }
 
 /*
- * vmbus_establish_gpadl - Establish a GPADL for the specified buffer
+ * vmbus_establish_gpadl_owned - Establish a GPADL for an owned buffer whose
+ * memory has already been prepared by the allocator.
  *
  * @channel: a channel
- * @kbuffer: from kmalloc or vmalloc
- * @size: page-size multiple
- * @gpadl: output gpadl
+ * @buffer: allocated by vmbus_alloc_buffer_owned()
  */
+int vmbus_establish_gpadl_owned(struct vmbus_channel *channel,
+				struct vmbus_buffer *buffer)
+{
+	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, buffer,
+				       0U, true);
+}
+EXPORT_SYMBOL_GPL(vmbus_establish_gpadl_owned);
+
+/* Preserve the established exported API for non-owned caller buffers. */
 int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,
 			  u32 size, struct vmbus_gpadl *gpadl)
 {
-	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, kbuffer, size,
-				       0U, false, &gpadl->leak, gpadl);
+	struct vmbus_buffer buffer = {
+		.addr = kbuffer,
+		.size = size,
+		.gpadl = *gpadl,
+	};
+	int ret;
+
+	ret = __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, &buffer,
+				      0U, false);
+	*gpadl = buffer.gpadl;
+	return ret;
 }
 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
 
@@ -746,11 +1042,20 @@ EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
  * The caller is responsible for re-encrypting the buffer before freeing it.
  */
 int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,
-					   void *kbuffer, u32 size,
-					   struct vmbus_gpadl *gpadl)
+					  void *kbuffer, u32 size,
+					  struct vmbus_gpadl *gpadl)
 {
-	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER,
-				       kbuffer, size, 0U, true, &gpadl->leak, gpadl);
+	struct vmbus_buffer buffer = {
+		.addr = kbuffer,
+		.size = size,
+		.gpadl = *gpadl,
+	};
+	int ret;
+
+	ret = __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, &buffer,
+				      0U, true);
+	*gpadl = buffer.gpadl;
+	return ret;
 }
 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl_caller_decrypted);
 
@@ -793,16 +1098,51 @@ void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt)
 }
 EXPORT_SYMBOL_GPL(vmbus_free_buffer);
 
+/* Retain backing until the host and any guest mappings have released it. */
 void vmbus_release_buffer(struct vmbus_buffer *buffer)
 {
-	if (!buffer->addr)
+	struct vmbus_buffer_retained *owner = buffer->owner;
+
+	if (!buffer->addr && !buffer->chunks && !buffer->pages) {
+		if (owner)
+			vmbus_buffer_owner_remove(owner);
+		memset(buffer, 0, sizeof(*buffer));
 		return;
+	}
+
+	if (!owner) {
+		if (vmbus_buffer_should_free(buffer)) {
+			if (buffer->chunks)
+				vmbus_free_buffer(buffer->addr, buffer->chunks,
+						  buffer->chunk_cnt);
+			else
+				vfree(buffer->addr);
+		} else {
+			pr_warn_ratelimited("VMBus buffer has no ownership record; retaining backing pages\n");
+		}
+		memset(buffer, 0, sizeof(*buffer));
+		return;
+	}
+
+	mutex_lock(&vmbus_buffer_owners_lock);
+	owner->addr = buffer->addr;
+	owner->chunks = buffer->chunks;
+	owner->pages = buffer->pages;
+	owner->chunk_cnt = buffer->chunk_cnt;
+	owner->page_cnt = buffer->page_cnt;
+	owner->size = buffer->size;
+	owner->host_may_own |= buffer->gpadl.gpadl_handle ||
+			       buffer->gpadl.leak;
+	owner->raw_decrypted |= buffer->gpadl.decrypted;
+	owner->permanent_leak |= buffer->leak;
+	owner->released = true;
+	vmbus_buffer_trace_owner(owner, "released");
+	if (!vmbus_buffer_owner_can_reclaim(owner))
+		vmbus_buffer_trace_owner(owner, "retained");
 
-	kvfree(buffer->pages);
-	if (vmbus_buffer_should_free(buffer))
-		vmbus_free_buffer(buffer->addr, buffer->chunks,
-				  buffer->chunk_cnt);
 	memset(buffer, 0, sizeof(*buffer));
+	vmbus_buffer_schedule_reclaim_locked(owner);
+	mutex_unlock(&vmbus_buffer_owners_lock);
 }
 EXPORT_SYMBOL_GPL(vmbus_release_buffer);
 
@@ -815,14 +1155,13 @@ static struct page *vmbus_alloc_pages_node(void *context, int nid,
 }
 
 /**
- * __vmbus_alloc_buffer - allocate host-visible, virtually-contiguous backing.
+ * vmbus_alloc_buffer_owned - allocate a host-visible, virtually-contiguous
+ * buffer with VMBus-managed backing-page lifetime.
  *
  * @channel: the channel the buffer will be attached to
  * @size: requested buffer size in bytes (will be rounded up to PAGE_SIZE)
  * @confidential: keep the buffer private to the guest
- * @chunks_out: on success, set to the array of underlying chunks, or NULL when
- *              the buffer was allocated with vzalloc()
- * @chunk_cnt_out: on success, set to the number of chunks
+ * @buffer: output descriptor that owns the allocation and its backing pages
  *
  * Buffers not requiring decryption are allocated with vzalloc().
  *
@@ -832,51 +1171,67 @@ static struct page *vmbus_alloc_pages_node(void *context, int nid,
  * host-visible via set_memory_decrypted() on its direct-map address, then all
  * chunks are combined into a virtually-contiguous range via vmap().
  *
- * Return: the buffer's virtual address, or NULL on failure.
+ * Return: 0 on success, or a negative error code.
  */
-static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
-				  u32 size,
-				  bool confidential,
-				  struct page ***chunks_out,
-				  u32 *chunk_cnt_out)
+int vmbus_alloc_buffer_owned(struct vmbus_channel *channel, u32 size,
+			     bool confidential, struct vmbus_buffer *buffer)
 {
 	u32 rounded_size;
 	unsigned long nr_pages;
 	unsigned long remaining;
 	unsigned long page_idx = 0;
+	struct vmbus_buffer_retained *owner;
+	unsigned int order = MAX_PAGE_ORDER;
 	bool hv_isolation;
 	bool guest_mem_encrypted;
-	struct page **chunks = NULL;
-	struct page **pages = NULL;
-	unsigned int order = MAX_PAGE_ORDER;
-	u32 chunk_cnt = 0;
-	void *addr;
 	u32 i;
 	int ret;
 
-	*chunks_out = NULL;
-	*chunk_cnt_out = 0;
+	memset(buffer, 0, sizeof(*buffer));
 
-	if (vmbus_buffer_round_size(size, &rounded_size))
-		return NULL;
+	ret = vmbus_buffer_round_size(size, &rounded_size);
+	if (ret)
+		return ret;
 	nr_pages = rounded_size >> PAGE_SHIFT;
 	remaining = nr_pages;
-
+	owner = vmbus_buffer_owner_alloc(channel);
+	if (!owner)
+		return -ENOMEM;
+	buffer->owner = owner;
+	buffer->size = rounded_size;
+	owner->size = rounded_size;
 	hv_isolation = hv_is_isolation_supported();
 	guest_mem_encrypted = cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT);
 
 	/* If the buffer does not need to be decrypted, just use vzalloc() */
 	if (!vmbus_needs_shared_pages(hv_isolation, guest_mem_encrypted,
-				      confidential))
-		return vzalloc(rounded_size);
+				      confidential)) {
+		buffer->addr = vzalloc(rounded_size);
+		if (!buffer->addr) {
+			vmbus_release_buffer(buffer);
+			return -ENOMEM;
+		}
+		buffer->pages = kvcalloc(nr_pages, sizeof(*buffer->pages), GFP_KERNEL);
+		if (!buffer->pages) {
+			vmbus_release_buffer(buffer);
+			return -ENOMEM;
+		}
+		for (page_idx = 0; page_idx < nr_pages; page_idx++)
+			buffer->pages[page_idx] =
+				vmalloc_to_page(buffer->addr +
+						(page_idx << PAGE_SHIFT));
+		buffer->page_cnt = nr_pages;
+		return 0;
+	}
 
 	/* Worst case: every chunk is a single page. */
-	chunks = kvmalloc_objs(*chunks, nr_pages, GFP_KERNEL | __GFP_ZERO);
-	if (!chunks)
+	buffer->chunks = kvmalloc_array(nr_pages, sizeof(*buffer->chunks),
+					GFP_KERNEL | __GFP_ZERO);
+	if (!buffer->chunks)
 		goto err;
 
-	pages = kvmalloc_objs(*pages, nr_pages);
-	if (!pages)
+	buffer->pages = kvmalloc_array(nr_pages, sizeof(*buffer->pages), GFP_KERNEL);
+	if (!buffer->pages)
 		goto err;
 
 	while (remaining) {
@@ -894,6 +1249,11 @@ static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
 		if (!page)
 			goto err;
 
+		buffer->chunks[buffer->chunk_cnt++] = page;
+		for (i = 0; i < (1U << order); i++)
+			buffer->pages[page_idx++] = page + i;
+		buffer->page_cnt = page_idx;
+
 		ret = set_memory_decrypted((unsigned long)page_address(page),
 					   1U << order);
 		if (ret) {
@@ -901,40 +1261,56 @@ static void *__vmbus_alloc_buffer(struct vmbus_channel *channel,
 			 * set_memory_decrypted() failed; the page state is
 			 * unknown so it must be leaked rather than freed.
 			 */
+			owner->encryption_unknown = true;
 			goto err;
 		}
-
-		chunks[chunk_cnt++] = page;
-
-		for (i = 0; i < (1U << order); i++)
-			pages[page_idx++] = page + i;
+		owner->needs_encrypt = true;
 
 		remaining -= 1U << order;
 	}
 
-	addr = vmap(pages, nr_pages, VM_MAP, pgprot_decrypted(PAGE_KERNEL));
-	if (!addr)
+	buffer->addr = vmap(buffer->pages, nr_pages, VM_MAP,
+			    pgprot_decrypted(PAGE_KERNEL));
+	if (!buffer->addr)
 		goto err;
 
-	memset(addr, 0, rounded_size);
-
-	kvfree(pages);
-	*chunks_out = chunks;
-	*chunk_cnt_out = chunk_cnt;
-	return addr;
+	memset(buffer->addr, 0, rounded_size);
+	return 0;
 
 err:
-	kvfree(pages);
-	vmbus_free_buffer(NULL, chunks, chunk_cnt);
-	return NULL;
+	vmbus_release_buffer(buffer);
+	return -ENOMEM;
 }
-
-void *vmbus_alloc_buffer(struct vmbus_channel *channel,
-			 u32 size, struct page ***chunks_out,
-			 u32 *chunk_cnt_out)
+EXPORT_SYMBOL_GPL(vmbus_alloc_buffer_owned);
+/*
+ * vmbus_alloc_buffer - compatibility allocator for callers managing lifetime.
+ * New callers that need retained GPADL and mmap ownership should use
+ * vmbus_alloc_buffer_owned().
+ */
+void *vmbus_alloc_buffer(struct vmbus_channel *channel, u32 size,
+			 struct page ***chunks_out, u32 *chunk_cnt_out)
 {
-	return __vmbus_alloc_buffer(channel, size, channel->co_external_memory,
-				    chunks_out, chunk_cnt_out);
+	struct vmbus_buffer buffer = {};
+	void *addr;
+	int ret;
+
+	if (!chunks_out || !chunk_cnt_out)
+		return NULL;
+
+	*chunks_out = NULL;
+	*chunk_cnt_out = 0;
+	ret = vmbus_alloc_buffer_owned(channel, size,
+				       channel->co_external_memory, &buffer);
+	if (ret)
+		return NULL;
+
+	addr = buffer.addr;
+	*chunks_out = buffer.chunks;
+	*chunk_cnt_out = buffer.chunk_cnt;
+	kvfree(buffer.pages);
+	vmbus_buffer_owner_remove(buffer.owner);
+
+	return addr;
 }
 EXPORT_SYMBOL_GPL(vmbus_alloc_buffer);
 
@@ -1038,11 +1414,9 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 	/* Establish the gpadl for the ring buffer */
 	buffer->gpadl.gpadl_handle = 0;
 
-	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING,
-				      buffer->addr,
-				      (send_pages + recv_pages) << PAGE_SHIFT,
+	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING, buffer,
 				      newchannel->ringbuffer_send_offset << PAGE_SHIFT,
-				      true, &buffer->leak, &buffer->gpadl);
+				      true);
 	if (err)
 		goto error_clean_ring;
 
@@ -1133,8 +1507,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 error_free_info:
 	kfree(open_info);
 error_free_gpadl:
-	if (vmbus_teardown_gpadl(newchannel, &buffer->gpadl))
-		buffer->leak = true;
+	vmbus_teardown_gpadl_owned(newchannel, buffer);
 error_clean_ring:
 	hv_ringbuffer_cleanup(&newchannel->outbound);
 	hv_ringbuffer_cleanup(&newchannel->inbound);
@@ -1180,62 +1553,155 @@ EXPORT_SYMBOL_GPL(vmbus_open);
 /*
  * vmbus_teardown_gpadl -Teardown the specified GPADL handle
  */
-int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpadl)
+int vmbus_gpadl_teardown_request(struct vmbus_channel *channel,
+				 struct vmbus_buffer *buffer,
+				 vmbus_gpadl_info_alloc_fn alloc_info,
+				 struct vmbus_connection *connection,
+				 vmbus_gpadl_teardown_post_fn post,
+				 unsigned long timeout)
 {
 	struct vmbus_channel_gpadl_teardown *msg;
 	struct vmbus_channel_msginfo *info;
+	struct vmbus_gpadl *gpadl = &buffer->gpadl;
+	struct vmbus_buffer_retained *owner = buffer->owner;
 	unsigned long flags;
-	int ret;
+	int ret = -ENODEV;
+	u32 handle = gpadl->gpadl_handle;
+	u32 relid = channel->offermsg.child_relid;
+
+	if (!handle && !gpadl->leak)
+		return 0;
+
+	/* Host rescind permits a request, but only the actual ACK releases it. */
+	if (relid == INVALID_RELID ||
+	    (READ_ONCE(channel->rescind) &&
+	     !READ_ONCE(channel->rescind_from_host)))
+		goto retain;
+
+	if (!handle) {
+		ret = -EINPROGRESS;
+		goto retain;
+	}
 
-	info = kzalloc(sizeof(*info) +
-		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
+	info = alloc_info();
 	if (!info) {
-		gpadl->leak = true;
-		return -ENOMEM;
+		ret = -ENOMEM;
+		goto retain;
 	}
 
 	init_completion(&info->waitevent);
-	info->waiting_channel = channel;
+	/* A synthetic rescind completion must not stand in for the host reply. */
+	info->waiting_channel = NULL;
 
 	msg = (struct vmbus_channel_gpadl_teardown *)info->msg;
+	msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
+	msg->child_relid = relid;
+	msg->gpadl = handle;
 
 
-	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
-	list_add_tail(&info->msglistentry,
-		      &vmbus_connection.chn_msg_list);
-	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
+	spin_lock_irqsave(&connection->channelmsg_lock, flags);
+	list_add_tail(&info->msglistentry, &connection->chn_msg_list);
+	spin_unlock_irqrestore(&connection->channelmsg_lock, flags);
 
-	if (channel->rescind)
-		goto post_msg_err;
+	if (channel->offermsg.child_relid != relid ||
+	    (READ_ONCE(channel->rescind) &&
+	     !READ_ONCE(channel->rescind_from_host)))
+		goto cleanup;
 
-	ret = vmbus_post_gpadl_teardown(channel->offermsg.child_relid, msg, gpadl->gpadl_handle,
-					vmbus_gpadl_post_real, NULL);
+	ret = post(connection, info);
 
 	if (ret)
-		goto post_msg_err;
-
-	wait_for_completion(&info->waitevent);
+		goto cleanup;
 
-	gpadl->gpadl_handle = 0;
+	/* A lost transport is bounded; expiry retains unknown host ownership. */
+	if (!wait_for_completion_timeout(&info->waitevent, timeout)) {
+		ret = -ETIMEDOUT;
+		goto cleanup;
+	}
 
-post_msg_err:
-	/*
-	 * If the channel has been rescinded;
-	 * we will be awakened by the rescind
-	 * handler; set the error code to zero so we don't leak memory.
-	 */
-	if (channel->rescind)
+	if (info->response.gpadl_torndown.header.msgtype ==
+	    CHANNELMSG_GPADL_TORNDOWN &&
+	    info->response.gpadl_torndown.gpadl == handle) {
 		ret = 0;
+		gpadl->gpadl_handle = 0;
+		gpadl->leak = false;
+		if (owner)
+			vmbus_buffer_update_host_ownership(owner, false);
+		goto cleanup;
+	}
 
-	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
+	ret = -ENODEV;
+
+cleanup:
+	spin_lock_irqsave(&connection->channelmsg_lock, flags);
 	list_del(&info->msglistentry);
-	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
+	spin_unlock_irqrestore(&connection->channelmsg_lock, flags);
 
 	kfree(info);
 
-	if (!ret && gpadl->decrypted) {
-		int encrypt_ret;
+retain:
+	if (ret) {
+		gpadl->leak = true;
+		if (owner)
+			vmbus_buffer_update_host_ownership(owner, true);
+	}
+
+	return ret;
+}
 
+static struct vmbus_channel_msginfo *vmbus_alloc_teardown_info(void)
+{
+	return kzalloc(sizeof(struct vmbus_channel_msginfo) +
+		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
+}
+
+static int vmbus_gpadl_teardown_post_real(struct vmbus_connection *connection,
+					  struct vmbus_channel_msginfo *info)
+{
+	struct vmbus_channel_gpadl_teardown *msg = (void *)info->msg;
+
+	return vmbus_post_gpadl_teardown(msg->child_relid, msg, msg->gpadl,
+					vmbus_gpadl_post_real, NULL);
+}
+
+static int __vmbus_teardown_gpadl_buffer(struct vmbus_channel *channel,
+					 struct vmbus_buffer *buffer)
+{
+	return vmbus_gpadl_teardown_request(channel, buffer,
+					  vmbus_alloc_teardown_info,
+					  &vmbus_connection,
+					  vmbus_gpadl_teardown_post_real, 5 * HZ);
+}
+
+int vmbus_teardown_gpadl_owned(struct vmbus_channel *channel,
+			       struct vmbus_buffer *buffer)
+{
+	return __vmbus_teardown_gpadl_buffer(channel, buffer);
+}
+EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl_owned);
+
+int vmbus_teardown_gpadl(struct vmbus_channel *channel,
+			 struct vmbus_gpadl *gpadl)
+{
+	struct vmbus_buffer buffer = {
+		.gpadl = *gpadl,
+	};
+	int encrypt_ret;
+	int ret;
+
+	ret = __vmbus_teardown_gpadl_buffer(channel, &buffer);
+	*gpadl = buffer.gpadl;
+
+	/*
+	 * The compat entry point builds an owner-less buffer, so the
+	 * reclaim path never sees it and cannot re-encrypt on its
+	 * behalf. Restore the synchronous re-encryption this symbol
+	 * has always performed: the caller is about to release the
+	 * range, and returning it decrypted would put shared pages
+	 * back on the free list. The owned path defers the same work
+	 * to reclaim through owner->raw_decrypted.
+	 */
+	if (!ret && gpadl->decrypted) {
 		encrypt_ret = set_memory_encrypted((unsigned long)gpadl->buffer,
 						   PFN_UP(gpadl->size));
 		if (encrypt_ret) {
@@ -1245,8 +1711,6 @@ int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpad
 		}
 		gpadl->decrypted = !!encrypt_ret;
 	}
-	if (ret)
-		gpadl->leak = true;
 
 	return ret;
 }
@@ -1323,9 +1787,8 @@ static int vmbus_close_internal(struct vmbus_channel *channel)
 
 	/* Tear down the gpadl for the channel's ring buffer */
 	else if (channel->ringbuffer.gpadl.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(channel, &channel->ringbuffer.gpadl);
+		ret = vmbus_teardown_gpadl_owned(channel, &channel->ringbuffer);
 		if (ret) {
-			channel->ringbuffer.leak = true;
 			pr_err("Close failed: teardown gpadl return %d\n", ret);
 			/*
 			 * If we failed to teardown gpadl,
drivers/hv/channel_mgmt.c +15 -9
index 93fc105cd179..be0f70a3541c 100644
@@ -26,6 +26,8 @@
 
 #include "hyperv_vmbus.h"
 
+static atomic64_t vmbus_channel_lifetime_id = ATOMIC64_INIT(0);
+
 static void init_vp_index(struct vmbus_channel *channel);
 
 const struct vmbus_device vmbus_devs[] = {
@@ -958,6 +960,7 @@ EXPORT_SYMBOL_GPL(vmbus_initiate_unload);
 static void vmbus_setup_channel_state(struct vmbus_channel *channel,
 				      struct vmbus_channel_offer_channel *offer)
 {
+	channel->lifetime_id = atomic64_inc_return(&vmbus_channel_lifetime_id);
 	WRITE_ONCE(channel->rescind, false);
 	WRITE_ONCE(channel->rescind_from_host, false);
 
@@ -1484,26 +1487,23 @@ static void vmbus_onmodifychannel_response(struct vmbus_channel_message_header *
  * Find the matching request, copy the response and signal the requesting
  * thread.
  */
-static void vmbus_ongpadl_torndown(
-			struct vmbus_channel_message_header *hdr)
+void vmbus_complete_gpadl_teardown(struct vmbus_connection *connection,
+				   struct vmbus_channel_gpadl_torndown *gpadl_torndown)
 {
-	struct vmbus_channel_gpadl_torndown *gpadl_torndown;
 	struct vmbus_channel_msginfo *msginfo;
 	struct vmbus_channel_message_header *requestheader;
 	struct vmbus_channel_gpadl_teardown *gpadl_teardown;
 	unsigned long flags;
 
-	gpadl_torndown = (struct vmbus_channel_gpadl_torndown *)hdr;
-
 	trace_vmbus_ongpadl_torndown(gpadl_torndown);
 
 	/*
 	 * Find the open msg, copy the result and signal/unblock the wait event
 	 */
-	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
+	spin_lock_irqsave(&connection->channelmsg_lock, flags);
 
-	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
-				msglistentry) {
+	list_for_each_entry(msginfo, &connection->chn_msg_list,
+			    msglistentry) {
 		requestheader =
 			(struct vmbus_channel_message_header *)msginfo->msg;
 
@@ -1521,7 +1521,13 @@ static void vmbus_ongpadl_torndown(
 			}
 		}
 	}
-	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
+	spin_unlock_irqrestore(&connection->channelmsg_lock, flags);
+}
+
+static void vmbus_ongpadl_torndown(struct vmbus_channel_message_header *hdr)
+{
+	vmbus_complete_gpadl_teardown(&vmbus_connection,
+				      (struct vmbus_channel_gpadl_torndown *)hdr);
 }
 
 /*
drivers/hv/hv_trace.h +24 -0
index c02a1719e92f..a3eeb817b00e 100644
@@ -8,6 +8,30 @@
 
 #include <linux/tracepoint.h>
 
+/* Opaque allocation identities; never expose a kernel pointer. */
+TRACE_EVENT(vmbus_buffer_owner,
+	    TP_PROTO(u64 owner_id, u64 channel_id, const char *action,
+		     u32 size, u32 pages, u8 state),
+	    TP_ARGS(owner_id, channel_id, action, size, pages, state),
+	    TP_STRUCT__entry(__field(u64, owner_id)
+		__field(u64, channel_id)
+		__string(action, action)
+		__field(u32, size)
+		__field(u32, pages)
+		__field(u8, state)
+	),
+	    TP_fast_assign(__entry->owner_id = owner_id;
+		__entry->channel_id = channel_id;
+		__assign_str(action);
+		__entry->size = size;
+		__entry->pages = pages;
+		__entry->state = state;
+	),
+	    TP_printk("owner_id=%llu channel_id=%llu action=%s size=%u pages=%u state=%u",
+		      __entry->owner_id, __entry->channel_id, __get_str(action),
+		      __entry->size, __entry->pages, __entry->state)
+);
+
 DECLARE_EVENT_CLASS(vmbus_hdr_msg,
 	TP_PROTO(const struct vmbus_channel_message_header *hdr),
 	TP_ARGS(hdr),
drivers/hv/hyperv_vmbus.h +51 -0

74 lines not on this page · raw message

drivers/hv/vmbus_buffer_test.c +452 -1

478 lines not on this page · raw message

drivers/hv/vmbus_drv.c +1 -0
index 723252f1b551..bce835c4a015 100644
@@ -3075,6 +3075,7 @@ static void __exit vmbus_exit(void)
 					&hyperv_panic_vmbus_unload_block);
 
 	bus_unregister(&hv_bus);
+	vmbus_buffer_reclaimer_shutdown();
 
 	cpuhp_remove_state(hyperv_cpuhp_online);
 	hv_synic_free();
include/linux/hyperv.h +18 -0
index 096054fa07a3..90bdbacee054 100644
@@ -784,13 +784,18 @@ struct vmbus_gpadl {
 	bool leak;
 };
 
+struct vmbus_buffer_retained;
+
 struct vmbus_buffer {
 	void *addr;
 	struct page **chunks;
 	struct page **pages;
 	u32 chunk_cnt;
+	u32 page_cnt;
+	u32 size;
 	struct vmbus_gpadl gpadl;
 	bool leak;
+	struct vmbus_buffer_retained *owner;
 };
 
 struct vmbus_channel {
@@ -811,6 +816,7 @@ struct vmbus_channel {
 	bool rescind; /* got rescind msg */
 	bool rescind_from_host; /* host revocation, not local channel removal */
 	bool rescind_ref; /* got rescind msg, got channel reference */
+	u64 lifetime_id;
 	struct completion rescind_event;
 
 	/* Allocated memory for ring buffer */
@@ -1228,6 +1234,18 @@ extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 				u32 *chunk_cnt_out);
 
 extern void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt);
+
+int vmbus_establish_gpadl_owned(struct vmbus_channel *channel,
+				struct vmbus_buffer *buffer);
+
+int vmbus_teardown_gpadl_owned(struct vmbus_channel *channel,
+			       struct vmbus_buffer *buffer);
+
+int vmbus_alloc_buffer_owned(struct vmbus_channel *channel,
+			     u32 size,
+			     bool confidential,
+			     struct vmbus_buffer *buffer);
+
 void vmbus_release_buffer(struct vmbus_buffer *buffer);
 
 void vmbus_reset_channel_cb(struct vmbus_channel *channel);
Signature · 1 line
2.43.0
#10 lore raw

Re: [PATCH v2 08/14] hv: vmbus: retain backing until ownership and references clear

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] workqueue: UAF of workqueue in vmbus_buffer_reclaimer_shutdown() racing with timer - [Medium] mm…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] workqueue: UAF of workqueue in vmbus_buffer_reclaimer_shutdown() racing with timer
- [Medium] mm: permanent memory leak of arrays and successful pages on partial encryption failure --

commit 6530feb3fbe0165655c6797c004705143b2a41a7
Author: Emerson Busson <[email protected]>
Subject: hv: vmbus: retain backing until ownership and references clear

This commit changes the VMBus channel code to keep buffer allocations and GPADL states retained until ownership, page-state, and mapping-reference conditions are clear. It adds a background workqueue for delayed reclaim when mappings are released or teardown is acknowledged.

Quoted 3 lines
drivers/hv/channel.c +0 -0

[ ... ]

Quoted 2 lines
drivers/hv/channel.c +2 -0
+static void vmbus_buffer_reclaim_work(struct work_struct *work)
+{

[ ... ]

drivers/hv/channel.c bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer) · line 328

Quoted 10 lines
drivers/hv/channel.c +10 -0
+	if (ret) {
+		mutex_lock(&vmbus_buffer_owners_lock);
+		owner->permanent_leak = true;
+		owner->work_active = false;
+		owner->reclaiming = false;
+		vmbus_buffer_trace_owner(owner, "retained");
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		pr_warn_ratelimited("VMBus buffer reclaim retained pages after encryption failure: %d\n",
+				    ret);
+		return;

[Severity: Medium]
Will this early return permanently leak previously processed pages?

In vmbus_buffer_reclaim_work(), if set_memory_encrypted() fails on a chunk, it breaks the loop and returns early.

Bypassing the cleanup paths permanently leaks all other successfully processed pages in the buffer, as well as the owner->chunks and owner->pages tracking arrays allocated via kvmalloc_array, and the owner struct itself.

Quoted 3 lines
drivers/hv/channel.c +3 -0
+	}
+
+	vmbus_buffer_trace_owner(owner, "reclaimed");

[ ... ]

drivers/hv/channel.c bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer) · line 356

Quoted 6 lines
drivers/hv/channel.c +6 -0
+/* Caller holds the owner lock or exclusive custody of this owner. */
+void vmbus_buffer_owner_drain(struct vmbus_buffer_retained *owner,
+			      struct workqueue_struct *wq)
+{
+	if (!cancel_delayed_work(&owner->reclaim_work))
+		return;

[Severity: High]
Does this non-sync cancel risk a use-after-free when racing with the timer callback?

If the delayed work's timer has just expired and its softirq handler (delayed_work_timer_fn) is concurrently running on another CPU, cancel_delayed_work() returns 0 without waiting.

Quoted 12 lines
drivers/hv/channel.c +12 -0
+
+	owner->work_active = false;
+	if (wq && vmbus_buffer_owner_can_reclaim(owner)) {
+		owner->work_active = true;
+		mod_delayed_work(wq, &owner->reclaim_work, 0);
+	}
+}
+
+void vmbus_buffer_reclaimer_shutdown(void)
+{
+	struct workqueue_struct *wq;
+	struct vmbus_buffer_retained *owner;

[ ... ]

drivers/hv/channel.c bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer) · line 395

Quoted 6 lines
drivers/hv/channel.c +6 -0
+	list_for_each_entry(owner, &vmbus_buffer_owners, list)
+		vmbus_buffer_owner_drain(owner, wq);
+	mutex_unlock(&vmbus_buffer_owners_lock);
+
+	if (wq)
+		destroy_workqueue(wq);

[Severity: High]
Can destroy_workqueue() complete while the timer handler is still running?

vmbus_buffer_reclaimer_shutdown() uses cancel_delayed_work() to stop reclaim works. If the delayed work's timer just expired, it returns immediately.

The shutdown function then drops the mutex and calls destroy_workqueue(wq).

destroy_workqueue() flushes existing work but does not synchronize with concurrent timer handlers that have not yet called queue_work().

destroy_workqueue() finishes and frees the workqueue structure.

The timer handler then proceeds to call queue_work() on the freed workqueue, causing a use-after-free on module unload.

Quoted 1 line

+}

[ ... ]

Quoted 3 lines
drivers/hv/channel.c +3 -0
+int vmbus_alloc_buffer_owned(struct vmbus_channel *channel, u32 size,
+			     bool confidential, struct vmbus_buffer *buffer)
+{

[ ... ]

Quoted 19 lines
drivers/hv/channel.c +19 -0
+	while (remaining) {
+		struct page *page;
+		gfp_t gfp;
+		int nid;
+
+		order = vmbus_buffer_order(remaining, order);
+
+		gfp = GFP_KERNEL | __GFP_ZERO;
+
+		nid = cpu_to_node(channel->target_cpu);
+		page = vmbus_alloc_pages_with_fallback(nid, gfp, &order,
+						       vmbus_alloc_pages_node, NULL);
+		if (!page)
+			goto err;
+
+		buffer->chunks[buffer->chunk_cnt++] = page;
+		for (i = 0; i < (1U << order); i++)
+			buffer->pages[page_idx++] = page + i;
+		buffer->page_cnt = page_idx;

drivers/hv/channel.c

Quoted 10 lines
drivers/hv/channel.c +10 -0
+
+		ret = set_memory_decrypted((unsigned long)page_address(page),
+					   1U << order);
+		if (ret) {
+			/*
+			 * set_memory_decrypted() failed; the page state is
+			 * unknown so it must be leaked rather than freed.
+			 */
+			owner->encryption_unknown = true;
+			goto err;

[Severity: Medium]
Could this goto leak the successfully processed pages?

In vmbus_alloc_buffer_owned(), if set_memory_decrypted() fails on a chunk, it sets owner->encryption_unknown = true and jumps to err.

This marks the entire owner as non-reclaimable, leaking all previously populated chunks and tracking arrays.

Quoted 5 lines
drivers/hv/channel.c +5 -0
+		}
+		owner->needs_encrypt = true;
+
+		remaining -= 1U << order;
+	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#11 lore raw

PATCH v2 9/14 hv: use owned VMBus buffers in NetVSC and UIO

In reply to Emerson Busson

Move the remaining buffer consumers to the allocation, GPADL and release entry points that carry one descriptor throughout their lifetime. Preserve established exported signatures throughout the series. Ring confidentiality comes from co_ring_buffer; external-buffer compatibility uses co_external_memory, while UIO buffers explicitly require host-visible backing.

---
 drivers/hv/channel.c         |  4 +--
 drivers/net/hyperv/netvsc.c  | 52 +++++++++++-------------------------
 drivers/uio/uio_hv_generic.c | 32 +++++++---------------
 include/linux/hyperv.h       |  8 +++---
 4 files changed, 32 insertions(+), 64 deletions(-)
drivers/hv/channel.c +2 -2
index aa33a0f08a7f..7eb9ea814ef4 100644
@@ -1035,11 +1035,10 @@ EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
  * @channel: a channel
  * @kbuffer: from kmalloc or vmalloc; must already be decrypted by the caller
  * @size: page-size multiple
- * @leak: set when a GPADL message may have reached the host but completion is
- *        uncertain; the caller must retain the backing pages
  * @gpadl: output gpadl
  *
  * The caller is responsible for re-encrypting the buffer before freeing it.
+ * Ownership of the backing pages stays with the caller's vmbus_buffer.
  */
 int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,
 					  void *kbuffer, u32 size,
@@ -1282,6 +1281,7 @@ int vmbus_alloc_buffer_owned(struct vmbus_channel *channel, u32 size,
 	return -ENOMEM;
 }
 EXPORT_SYMBOL_GPL(vmbus_alloc_buffer_owned);
+
 /*
  * vmbus_alloc_buffer - compatibility allocator for callers managing lifetime.
  * New callers that need retained GPADL and mmap ownership should use
drivers/net/hyperv/netvsc.c +16 -36

117 lines not on this page · raw message

drivers/uio/uio_hv_generic.c +10 -22
index 2cb95b4786ca..b40e80e19c6c 100644
@@ -196,11 +196,11 @@ static void
 hv_uio_cleanup(struct hv_device *dev, struct hv_uio_private_data *pdata)
 {
 	if (pdata->send_buffer.gpadl.gpadl_handle)
-		vmbus_teardown_gpadl(dev->channel, &pdata->send_buffer.gpadl);
+		vmbus_teardown_gpadl_owned(dev->channel, &pdata->send_buffer);
 	vmbus_release_buffer(&pdata->send_buffer);
 
 	if (pdata->recv_buffer.gpadl.gpadl_handle)
-		vmbus_teardown_gpadl(dev->channel, &pdata->recv_buffer.gpadl);
+		vmbus_teardown_gpadl_owned(dev->channel, &pdata->recv_buffer);
 	vmbus_release_buffer(&pdata->recv_buffer);
 }
 
@@ -298,18 +298,12 @@ hv_uio_probe(struct hv_device *dev,
 	pdata->info.mem[MON_PAGE_MAP].memtype = UIO_MEM_LOGICAL;
 
 	if (channel->device_id == HV_NIC) {
-		pdata->recv_buffer.addr =
-			vzalloc(RECV_BUFFER_SIZE);
-		if (!pdata->recv_buffer.addr) {
-			ret = -ENOMEM;
+		ret = vmbus_alloc_buffer_owned(channel, RECV_BUFFER_SIZE, false,
+					       &pdata->recv_buffer);
+		if (ret)
 			goto fail_free_ring;
-		}
 
-		ret = vmbus_establish_gpadl(channel,
-					    pdata->recv_buffer.addr,
-					    RECV_BUFFER_SIZE,
-					    &pdata->recv_buffer.gpadl);
-		pdata->recv_buffer.leak |= pdata->recv_buffer.gpadl.leak;
+		ret = vmbus_establish_gpadl_owned(channel, &pdata->recv_buffer);
 		if (ret)
 			goto fail_close;
 
@@ -322,18 +316,12 @@ hv_uio_probe(struct hv_device *dev,
 		pdata->info.mem[RECV_BUF_MAP].size = RECV_BUFFER_SIZE;
 		pdata->info.mem[RECV_BUF_MAP].memtype = UIO_MEM_VIRTUAL;
 
-		pdata->send_buffer.addr =
-			vzalloc(SEND_BUFFER_SIZE);
-		if (!pdata->send_buffer.addr) {
-			ret = -ENOMEM;
+		ret = vmbus_alloc_buffer_owned(channel, SEND_BUFFER_SIZE, false,
+					       &pdata->send_buffer);
+		if (ret)
 			goto fail_close;
-		}
 
-		ret = vmbus_establish_gpadl(channel,
-					    pdata->send_buffer.addr,
-					    SEND_BUFFER_SIZE,
-					    &pdata->send_buffer.gpadl);
-		pdata->send_buffer.leak |= pdata->send_buffer.gpadl.leak;
+		ret = vmbus_establish_gpadl_owned(channel, &pdata->send_buffer);
 		if (ret)
 			goto fail_close;
 
include/linux/hyperv.h +4 -4
index 90bdbacee054..0f482ed5c776 100644
@@ -1216,9 +1216,9 @@ extern int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,
 				     u64 requestid);
 
 extern int vmbus_establish_gpadl(struct vmbus_channel *channel,
-				      void *kbuffer,
-				      u32 size,
-				      struct vmbus_gpadl *gpadl);
+				 void *kbuffer,
+				 u32 size,
+				 struct vmbus_gpadl *gpadl);
 
 extern int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,
 						  void *kbuffer,
@@ -1226,7 +1226,7 @@ extern int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,
 						  struct vmbus_gpadl *gpadl);
 
 extern int vmbus_teardown_gpadl(struct vmbus_channel *channel,
-				     struct vmbus_gpadl *gpadl);
+				struct vmbus_gpadl *gpadl);
 
 extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 				u32 size,
Signature · 1 line
2.43.0
#12 lore raw

Re: [PATCH v2 09/14] hv: use owned VMBus buffers in NetVSC and UIO

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] hv_netvsc: host bugcheck DoS due to GPADL teardown after failed revoke --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] hv_netvsc: host bugcheck DoS due to GPADL teardown after failed revoke --

commit 418182ccc1e62bfbe8d59179d5fb1baf3aaa6d53
Author: Emerson Busson <[email protected]>

hv: use owned VMBus buffers in NetVSC and UIO

Move the remaining buffer consumers to the allocation, GPADL and release entry points that carry one descriptor throughout their lifetime. Preserve established exported signatures throughout the series.

Quoted 22 lines
drivers/net/hyperv/netvsc.c +0 -2
index ffba1443396ab..fd8aa7a3dcb32 100644
@@ -243,7 +243,6 @@ static void netvsc_revoke_recv_buf(struct hv_device *device,
 		if (ret != 0) {
 			netdev_err(ndev, "unable to send "
 				"revoke receive buffer to netvsp\n");
-			net_device->recv_buffer.leak = true;
 			return;
 		}
 		net_device->recv_section_cnt = 0;
@@ -295,7 +294,6 @@ static void netvsc_revoke_send_buf(struct hv_device *device,
 		if (ret != 0) {
 			netdev_err(ndev, "unable to send "
 				   "revoke send buffer to netvsp\n");
-			net_device->send_buffer.leak = true;
 			return;
 		}
 		net_device->send_section_cnt = 0;
@@ -308,18 +306,14 @@ static void netvsc_teardown_recv_gpadl(struct hv_device *device,
 {

drivers/net/hyperv/netvsc.c static void netvsc_teardown_recv_gpadl(struct hv_device *device, · line 311

Quoted 10 lines
drivers/net/hyperv/netvsc.c +2 -5
 	int ret;
 
-	if (net_device->recv_buffer.leak)
-		return;
-
 	if (net_device->recv_buffer.gpadl.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(device->channel,
-					   &net_device->recv_buffer.gpadl);
+		ret = vmbus_teardown_gpadl_owned(device->channel,
+						 &net_device->recv_buffer);

[Severity: High]
With the removal of the leak check here and the manual assignment in netvsc_revoke_recv_buf(), is there a risk of a host bugcheck if the protocol-level revoke message fails?

If vmbus_sendpacket() returns an error (like -EAGAIN from a full ring) in netvsc_revoke_recv_buf(), the NetVSP layer won't receive the revoke message and might still actively map the GPADL. Unconditionally sending a VMBus GPADL teardown request in this scenario violates the protocol invariant. Could this lead to a Denial of Service via a host bugcheck or guest termination?

Quoted 11 lines
drivers/net/hyperv/netvsc.c +0 -1
 		/* If we failed here, we might as well return and have a leak
 		 * rather than continue and a bugchk
 		 */
 		if (ret != 0) {
-			net_device->recv_buffer.leak = true;
 			netdev_err(ndev,
 				   "unable to teardown receive buffer's gpadl\n");
 			return;
@@ -333,18 +327,14 @@ static void netvsc_teardown_send_gpadl(struct hv_device *device,
 {

drivers/net/hyperv/netvsc.c static void netvsc_teardown_send_gpadl(struct hv_device *device, · line 332

Quoted 10 lines
drivers/net/hyperv/netvsc.c +2 -5
 	int ret;
 
-	if (net_device->send_buffer.leak)
-		return;
-
 	if (net_device->send_buffer.gpadl.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(device->channel,
-					   &net_device->send_buffer.gpadl);
+		ret = vmbus_teardown_gpadl_owned(device->channel,
+						 &net_device->send_buffer);

[Severity: High]
Similarly for the send buffer, does removing the leak check and flag tracking in netvsc_revoke_send_buf() expose the host to the same bugcheck risk if the revoke message fails to send?

Quoted 9 lines
drivers/net/hyperv/netvsc.c +0 -1
 		/* If we failed here, we might as well return and have a leak
 		 * rather than continue and a bugchk
 		 */
 		if (ret != 0) {
-			net_device->send_buffer.leak = true;
 			netdev_err(ndev,
 				   "unable to teardown send buffer's gpadl\n");
 			return;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#13 lore raw

PATCH v2 10/14 hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race

In reply to Emerson Busson

UIO maps the channel ring, the send/receive buffers, the interrupt page and the monitor page directly into userspace. Those maps are built from page arrays that the reclaim worker can free once the buffer owner is released: the snapshot taken in the mmap path and the moment the new VMA holds its own references are not the same instant, so a reclaim in that window frees pages a mapping is about to publish.

Add vmbus_buffer_pin_pages() and vmbus_buffer_unpin_pages(). Pinning takes a reference on every page of a vmbus_buffer and refuses to start once reclaiming has begun or the owner leaked for good. Every field of the returned struct vmbus_buffer_pin is read under vmbus_buffer_owners_lock, the lock that publishes and clears the owner and the page array. The pin carries the page array, its length and the mapping-protection state of the pages being pinned, so a mapper never has to look at the buffer descriptor again: a concurrent vmbus_release_buffer() can clear that descriptor while the pin still holds the pages alive.

The pin cannot be dropped when mmap_prepare() returns. mmap_action_map_kernel_pages() only stores the page-array pointer, and the mapping takes its own folio references inside insert_pages(), which runs after the hook. Dropping the pin therefore waits for the VMA to be established or for the attempt to be abandoned. Release is
one-shot: both can run.

Two surfaces need two ownership contracts, because fs/kernfs/file.c rejects a VMA whose vm_ops carry .close: kernfs has to replace the set with its own and cannot wrap close. That check runs after the .mmap hook has already succeeded, so a successful sysfs mapping cannot carry an abandon path in vm_ops at all.

The /dev/uioN character device is not a kernfs path. It installs hv_uio_pin_vm_ops (.mapped and .close) and a struct hv_uio_pin, and drops the pin on whichever of the two runs first. The "ring" sysfs bin attribute installs no vm_ops and hands a bare struct vmbus_buffer_pin to hv_mmap_ring_buffer_wrapper(), a synchronous legacy .mmap that owns it across __compat_vma_mmap() and releases it exactly once when that
returns: success is safe because insert_pages() has already taken a folio reference per page, failure is safe because the attempt is over.

The legacy .mmap error path frees the VMA without calling vma_close(), and a failure in mmap_action_prepare() never reaches compat_set_vma_from_desc(). The wrapper therefore installs the per-VMA state before __compat_vma_mmap() when a contract does carry close(), so that abandon path stays reachable.

The ring-buffer sysfs mmap and the UIO mmap_prepare hook share one page-selection and validation path. Buffer-backed regions are described only by their owning buffer at selection time; the page array and the protection state come from the locked pin snapshot and from nowhere else. The interrupt and monitor pages are snapshot as struct page * at probe, where the backing is guaranteed to still exist, and are not buffer-backed so they take no pin.

The mapping KUnit cases cover the range check, the ring mmap path, the per-map region selection, the mmap_prepare hook, the pin spanning the mapped() boundary, close() before mapped() including a second close and a foreign private_data, the absence of .close on the sysfs ops, a successful buffer-backed character-device map, pin release on prepare failure, pin release when the mapping is abandoned after prepare, pages kept alive by the pin across a concurrent buffer release, and the protection snapshot surviving a cleared descriptor. They are included from uio_hv_generic.c so they can reach the static helpers without exporting them.

Disconnect an open channel after unregistering UIO callbacks. An eventual fd close cannot call .release after unregister, so removal must close the channel before releasing its ring and external buffers. Mapped pages retain their folio references until VMA close; disconnect failure leaves host ownership uncertain and retained. Test open, already closed, repeated and failed disconnection through the same helper used by remove.

Hold the UIO notifier device reference across unregister and channel disconnect. If the last fd closes in that interval, an in-flight channel callback can still notify the UIO device until disconnect synchronizes callbacks.

Use ordinary VMBus rescind device unregistration instead of a private UIO rescind callback. The callback previously outlived a UIO-to-netvsc rebind and interpreted netvsc private data as UIO, panicking in uio_event_notify when the host removed the restored adapter. A callback reset or null check cannot synchronize that race. Generic unregister already withdraws UIO info and wakes blocked readers with EIO/POLL_HUP. Add an actual registered UIO withdrawal test verifying reader wakeup and info removal while a device reference keeps the notifier alive.

Add actual synchronous-wrapper/MM success and partial-insertion cases with KUnit-managed memory. Read the inserted bytes, check VMA and bridge references, then unmap. A wrapper-unpin mutation fails both cases. The controlled prepare callback uses production pin acquisition; full retained-owner and confidential integration remain separate.

---
 drivers/hv/channel.c                   |  92 +++
 drivers/hv/vmbus_drv.c                 |  49 +-
 drivers/hv/vmbus_mmap_test.c           | 145 ++++
 drivers/uio/Kconfig                    |  11 +
 drivers/uio/uio.c                      |  20 +
 drivers/uio/uio_hv_generic.c           | 321 ++++++++-
 drivers/uio/uio_hv_generic_mmap_test.c | 875 +++++++++++++++++++++++++
 include/linux/hyperv.h                 |  24 +
 8 files changed, 1512 insertions(+), 25 deletions(-)
 create mode 100644 drivers/hv/vmbus_mmap_test.c
 create mode 100644 drivers/uio/uio_hv_generic_mmap_test.c
drivers/hv/channel.c +92 -0
index 7eb9ea814ef4..2793ca1b7f32 100644
@@ -1145,6 +1145,98 @@ void vmbus_release_buffer(struct vmbus_buffer *buffer)
 }
 EXPORT_SYMBOL_GPL(vmbus_release_buffer);
 
+/**
+ * vmbus_buffer_pin_pages - snapshot a buffer's pages and hold references
+ * @buffer: buffer whose pages the caller is about to map
+ * @pin: out parameter filled entirely under the owners lock
+ *
+ * Take a reference on every page of @buffer and fill @pin with the page
+ * array, the page count and the mapping-protection state that describe
+ * them. The references close the window between the snapshot and the
+ * point where a new mapping holds its own: the reclaim worker refuses to
+ * free pages whose folio reference count is above one, and refuses to
+ * start at all once it has begun reclaiming. Call
+ * vmbus_buffer_unpin_pages() after the mapping holds its own references.
+ *
+ * Every field of @pin is read under vmbus_buffer_owners_lock so the
+ * caller never has to look at @buffer again. In particular @pin->decrypted
+ * is the protection state of the pages being pinned, not of whatever
+ * @buffer looks like after a concurrent vmbus_release_buffer() has
+ * cleared it.
+ *
+ * Return: 0 on success, -ENODEV if the pages are gone or reclaim
+ * has already taken ownership of them.
+ */
+int vmbus_buffer_pin_pages(struct vmbus_buffer *buffer,
+			   struct vmbus_buffer_pin *pin)
+{
+	struct vmbus_buffer_retained *owner;
+	u32 i;
+
+	/*
+	 * The owner and page array are published and cleared under
+	 * vmbus_buffer_owners_lock (see vmbus_release_buffer()). Reading
+	 * either outside that lock lets a concurrent release free the array
+	 * while this loop still walks it.
+	 */
+	mutex_lock(&vmbus_buffer_owners_lock);
+	owner = buffer->owner;
+	if (!buffer->pages || !buffer->page_cnt) {
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		return -ENODEV;
+	}
+
+	if (owner && (owner->reclaiming || owner->permanent_leak)) {
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		return -ENODEV;
+	}
+
+	for (i = 0; i < buffer->page_cnt; i++) {
+		if (WARN_ON_ONCE(!buffer->pages[i])) {
+			while (i--)
+				put_page(buffer->pages[i]);
+			mutex_unlock(&vmbus_buffer_owners_lock);
+			return -ENODEV;
+		}
+		get_page(buffer->pages[i]);
+	}
+
+	pin->pages = buffer->pages;
+	pin->page_count = buffer->page_cnt;
+	/*
+	 * Only the shared-page path populates the chunk array, and that is
+	 * the path that decrypts each chunk before mapping it. Read it here
+	 * so the protection state cannot disagree with the pages pinned.
+	 */
+	pin->decrypted = !!buffer->chunks;
+	mutex_unlock(&vmbus_buffer_owners_lock);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(vmbus_buffer_pin_pages);
+
+/**
+ * vmbus_buffer_unpin_pages - drop references taken by vmbus_buffer_pin_pages
+ * @pin: pin filled by vmbus_buffer_pin_pages(), or NULL
+ *
+ * Idempotent: a pin that has already been released, or a NULL pin, is a
+ * no-op. Release is one-shot because a VMA can be established and then
+ * torn down, and the abandon path must not put the same pages twice.
+ */
+void vmbus_buffer_unpin_pages(struct vmbus_buffer_pin *pin)
+{
+	unsigned long i;
+
+	if (!pin || !pin->pages)
+		return;
+
+	for (i = 0; i < pin->page_count; i++)
+		put_page(pin->pages[i]);
+	pin->pages = NULL;
+	pin->page_count = 0;
+}
+EXPORT_SYMBOL_GPL(vmbus_buffer_unpin_pages);
+
 static struct page *vmbus_alloc_pages_node(void *context, int nid,
 					   gfp_t gfp,
 					   unsigned int order)
drivers/hv/vmbus_drv.c +48 -1

63 lines not on this page · raw message

drivers/hv/vmbus_mmap_test.c new file +145 -0

145 lines not on this page · raw message

drivers/uio/Kconfig +11 -0
index 9242e77385c6..0a01906bd6cd 100644
@@ -148,6 +148,17 @@ config UIO_HV_GENERIC
 
 	  If you compile this as a module, it will be called uio_hv_generic.
 
+config UIO_HV_GENERIC_KUNIT_TEST
+	bool "Tests for the UIO Hyper-V generic mmap" if !KUNIT_ALL_TESTS
+	depends on UIO_HV_GENERIC && KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Enable KUnit tests for the UIO Hyper-V generic mmap paths.
+	  The tests are included from uio_hv_generic.c so they can
+	  reach the static page-selection helpers. Select this option
+	  only if you will boot the kernel for the purpose of running
+	  unit tests (e.g. under UML or qemu). If unsure, say N.
+
 config UIO_DFL
 	tristate "Generic driver for DFL (Device Feature List) bus"
 	depends on FPGA_DFL
drivers/uio/uio.c +20 -0
index f8fa20522660..4767ed0661f7 100644
@@ -857,7 +857,27 @@ static int uio_mmap(struct file *filep, struct vm_area_struct *vma)
 		ret = idev->info->mmap_prepare(idev->info, &desc);
 		if (ret)
 			goto out;
+
+		/*
+		 * Install the per-VMA state before __compat_vma_mmap() so a
+		 * failure in mmap_action_prepare() still reaches close(). That
+		 * path never runs compat_set_vma_from_desc(), and the legacy
+		 * .mmap error path frees the VMA without calling close() on
+		 * its own. __compat_vma_mmap() installs the same values again
+		 * on its way to the action.
+		 *
+		 * close() must be safe to call without a prior mapped() when
+		 * it tears down state mmap_prepare() installed. Drivers that
+		 * leave vm_ops alone have nothing to tear down here.
+		 */
+		if (desc.vm_ops) {
+			vma->vm_ops = desc.vm_ops;
+			vma->vm_private_data = desc.private_data;
+		}
+
 		ret = __compat_vma_mmap(&desc, vma);
+		if (ret && vma->vm_ops && vma->vm_ops->close)
+			vma->vm_ops->close(vma);
 		goto out;
 	}
 
drivers/uio/uio_hv_generic.c +297 -24

397 lines not on this page · raw message

drivers/uio/uio_hv_generic_mmap_test.c new file +875 -0

875 lines not on this page · raw message

include/linux/hyperv.h +24 -0
index 0f482ed5c776..f0e8f1af8e75 100644
@@ -1248,6 +1248,30 @@ int vmbus_alloc_buffer_owned(struct vmbus_channel *channel,
 
 void vmbus_release_buffer(struct vmbus_buffer *buffer);
 
+/**
+ * struct vmbus_buffer_pin - locked snapshot of a buffer's mappable pages
+ * @pages: page array owned by the buffer
+ * @page_count: number of pages in @pages
+ * @decrypted: backing pages are in the decrypted (host-shared) state
+ *
+ * vmbus_buffer_pin_pages() fills every field under
+ * vmbus_buffer_owners_lock. A mapper reads only this snapshot and must
+ * not re-read the buffer descriptor afterwards: vmbus_release_buffer()
+ * clears the descriptor under that same lock while the pin still holds
+ * the pages alive, so a later descriptor read describes the cleared
+ * descriptor rather than the pages this mapper holds.
+ */
+struct vmbus_buffer_pin {
+	struct page **pages;
+	unsigned long page_count;
+	bool decrypted;
+};
+
+int vmbus_buffer_pin_pages(struct vmbus_buffer *buffer,
+			   struct vmbus_buffer_pin *pin);
+
+void vmbus_buffer_unpin_pages(struct vmbus_buffer_pin *pin);
+
 void vmbus_reset_channel_cb(struct vmbus_channel *channel);
 
 extern int vmbus_recvpacket(struct vmbus_channel *channel,
Signature · 1 line
2.43.0
#14 lore raw

Re: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race

kernel test robot noticed the following build warnings:

Hi Emerson,

kernel test robot noticed the following build warnings:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus linus/master v7.3-rc6 next-20261008] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Emerson-Busson/hv-vmbus-convert-ring-backing-through-the-chunk-allocator/20261007-160739
base:   char-misc/char-misc-testing
patch link:    https://lore.kernel.org/r/20261007190752.336426-11-emersonbusson%40gmail.com
patch subject: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race
config: i386-randconfig-1001-20261008 (https://download.01.org/0day-ci/archive/20261009/[email protected]/config)
compiler: clang version 22.1.3 (https://github.com/llvm/llvm-project e9846648fd6183ee6d8cbdb4502213fcf902a211)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261009/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

In file included from drivers/uio/uio_hv_generic.c:428:

>> drivers/uio/uio_hv_generic_mmap_test.c:36:34: warning: implicit conversion from 'u64' (aka 'unsigned long long') to 'unsigned long' changes value from 18446744073709551615 to 4294967295 [-Wconstant-conversion]
      36 |                            hv_uio_mmap_range_valid(8, U64_MAX, 1));
         |                            ~~~~~~~~~~~~~~~~~~~~~~~    ^~~~~~~
   include/linux/limits.h:25:19: note: expanded from macro 'U64_MAX'
      25 | #define U64_MAX         ((u64)~0ULL)
         |                          ^~~~~~~~~~
   include/kunit/test.h:1014:31: note: expanded from macro 'KUNIT_EXPECT_FALSE'
    1014 |         KUNIT_EXPECT_FALSE_MSG(test, condition, NULL)
         |                                      ^~~~~~~~~
   include/kunit/test.h:1019:7: note: expanded from macro 'KUNIT_EXPECT_FALSE_MSG'
    1019 |                                   condition,                                   \
         |                                   ^~~~~~~~~
   include/kunit/test.h:812:10: note: expanded from macro 'KUNIT_FALSE_MSG_ASSERTION'
     812 |                               condition,                                       \
         |                               ^~~~~~~~~
   include/kunit/test.h:788:16: note: expanded from macro 'KUNIT_UNARY_ASSERTION'
     788 |         if (likely(!!(condition_) == !!expected_true_))                        \
         |                       ^~~~~~~~~~
   include/linux/compiler.h:76:40: note: expanded from macro 'likely'
      76 | # define likely(x)      __builtin_expect(!!(x), 1)
         |                                             ^

1 warning generated.

vim +36 drivers/uio/uio_hv_generic_mmap_test.c

    27	
    28	static void hv_uio_ring_mmap_range_test(struct kunit *test)
    29	{
    30		KUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 0, 8));
    31		KUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 4, 4));
    32		KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 8, 1));
    33		KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 7, 2));
    34		KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 0, 0));
    35		KUNIT_EXPECT_FALSE(test,
  > 36				   hv_uio_mmap_range_valid(8, U64_MAX, 1));
    37	}
    38	

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#15 lore raw

Re: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race

Quoted 23 lines · kernel test robot

Hi Emerson,

kernel test robot noticed the following build warnings:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus linus/master v7.3-rc6 next-20261008] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Emerson-Busson/hv-vmbus-convert-ring-backing-through-the-chunk-allocator/20261007-160739
base:   char-misc/char-misc-testing
patch link:    https://lore.kernel.org/r/20261007190752.336426-11-emersonbusson%40gmail.com
patch subject: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race
config: i386-randconfig-1001-20261008 (https://download.01.org/0day-ci/archive/20261009/[email protected]/config)
compiler: clang version 22.1.3 (https://github.com/llvm/llvm-project e9846648fd6183ee6d8cbdb4502213fcf902a211)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261009/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

Quoted 6 lines

All warnings (new ones prefixed by >>):

In file included from drivers/uio/uio_hv_generic.c:428:

Quoted 1 line
Quoted 1 line

drivers/uio/uio_hv_generic_mmap_test.c:36:34: warning: implicit conversion from 'u64' (aka 'unsigned long long') to 'unsigned long' changes value from 18446744073709551615 to 4294967295 [-Wconstant-conversion]

      36 |                            hv_uio_mmap_range_valid(8, U64_MAX, 1));
         |                            ~~~~~~~~~~~~~~~~~~~~~~~    ^~~~~~~

GCC also warns in the same way. Should probably be ULONG_MAX since 'pgoff_t' is 'unsigned long'?

Signature · 2 lines
Cheers,
Nathan
#16 lore raw

Re: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race

In reply to Emerson Busson
kernel test robot noticed the following build warnings:

Hi Emerson,

kernel test robot noticed the following build warnings:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus linus/master v7.3-rc6 next-20261008] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Emerson-Busson/hv-vmbus-convert-ring-backing-through-the-chunk-allocator/20261007-160739
base:   char-misc/char-misc-testing
patch link:    https://lore.kernel.org/r/20261007190752.336426-11-emersonbusson%40gmail.com
patch subject: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race
config: i386-randconfig-1013-20261008 (https://download.01.org/0day-ci/archive/20261009/[email protected]/config)
compiler: gcc-14 (Debian 14.2.0-19) 14.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261009/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

In file included from include/linux/dev_printk.h:14,
from include/linux/device.h:15,
from drivers/uio/uio_hv_generic.c:22:
drivers/uio/uio_hv_generic_mmap_test.c: In function 'hv_uio_ring_mmap_range_test':

>> include/linux/limits.h:25:25: warning: conversion from 'long long unsigned int' to 'long unsigned int' changes value from '18446744073709551615' to '4294967295' [-Woverflow]
      25 | #define U64_MAX         ((u64)~0ULL)
         |                         ^~~~~~~~~~~~
   include/linux/compiler.h:76:45: note: in definition of macro 'likely'
      76 | # define likely(x)      __builtin_expect(!!(x), 1)
         |                                             ^
   include/kunit/test.h:810:9: note: in expansion of macro 'KUNIT_UNARY_ASSERTION'
     810 |         KUNIT_UNARY_ASSERTION(test,                                            \
         |         ^~~~~~~~~~~~~~~~~~~~~
   include/kunit/test.h:1017:9: note: in expansion of macro 'KUNIT_FALSE_MSG_ASSERTION'
    1017 |         KUNIT_FALSE_MSG_ASSERTION(test,                                        \
         |         ^~~~~~~~~~~~~~~~~~~~~~~~~
   include/kunit/test.h:1014:9: note: in expansion of macro 'KUNIT_EXPECT_FALSE_MSG'
    1014 |         KUNIT_EXPECT_FALSE_MSG(test, condition, NULL)
         |         ^~~~~~~~~~~~~~~~~~~~~~
   drivers/uio/uio_hv_generic_mmap_test.c:35:9: note: in expansion of macro 'KUNIT_EXPECT_FALSE'
      35 |         KUNIT_EXPECT_FALSE(test,
         |         ^~~~~~~~~~~~~~~~~~
   drivers/uio/uio_hv_generic_mmap_test.c:36:55: note: in expansion of macro 'U64_MAX'
      36 |                            hv_uio_mmap_range_valid(8, U64_MAX, 1));
         |                                                       ^~~~~~~

vim +25 include/linux/limits.h

3c9d017cc283df Andy Shevchenko 2023-08-04  14  
54d50897d544c8 Masahiro Yamada 2019-03-07  15  #define U8_MAX		((u8)~0U)
54d50897d544c8 Masahiro Yamada 2019-03-07  16  #define S8_MAX		((s8)(U8_MAX >> 1))
54d50897d544c8 Masahiro Yamada 2019-03-07  17  #define S8_MIN		((s8)(-S8_MAX - 1))
54d50897d544c8 Masahiro Yamada 2019-03-07  18  #define U16_MAX		((u16)~0U)
54d50897d544c8 Masahiro Yamada 2019-03-07  19  #define S16_MAX		((s16)(U16_MAX >> 1))
54d50897d544c8 Masahiro Yamada 2019-03-07  20  #define S16_MIN		((s16)(-S16_MAX - 1))
54d50897d544c8 Masahiro Yamada 2019-03-07  21  #define U32_MAX		((u32)~0U)
3f50f132d8400e John Fastabend  2020-03-30  22  #define U32_MIN		((u32)0)
54d50897d544c8 Masahiro Yamada 2019-03-07  23  #define S32_MAX		((s32)(U32_MAX >> 1))
54d50897d544c8 Masahiro Yamada 2019-03-07  24  #define S32_MIN		((s32)(-S32_MAX - 1))
54d50897d544c8 Masahiro Yamada 2019-03-07 @25  #define U64_MAX		((u64)~0ULL)
54d50897d544c8 Masahiro Yamada 2019-03-07  26  #define S64_MAX		((s64)(U64_MAX >> 1))
54d50897d544c8 Masahiro Yamada 2019-03-07  27  #define S64_MIN		((s64)(-S64_MAX - 1))

54d50897d544c8 Masahiro Yamada 2019-03-07 28

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#17 lore raw

Re: [PATCH v2 10/14] hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race

In reply to Emerson Busson
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] hv: vmbus_buffer_pin_pages UAF race on subchannel ringbuffers --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] hv: vmbus_buffer_pin_pages UAF race on subchannel ringbuffers
--

commit 69d0c6246e4ab3d36e972718b31a04ff08d2eee9
Author: Emerson Busson <[email protected]>
Subject: hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race

This commit pins buffer pages across UIO mmap to prevent a race condition with the reclaim worker. It adds vmbus_buffer_pin_pages() and vmbus_buffer_unpin_pages() to safely take references on the pages. The sysfs ring mmap wrapper is adjusted to handle the new pin lifecycle.

Quoted 4 lines
drivers/hv/channel.c +0 -0
index 7eb9ea814ef45..2793ca1b7f320 100644

[ ... ]

Quoted 6 lines
drivers/hv/channel.c +2 -0
@@ -1145,6 +1145,98 @@ void vmbus_release_buffer(struct vmbus_buffer *buffer)
 }
 EXPORT_SYMBOL_GPL(vmbus_release_buffer);
 
+/**
+ * vmbus_buffer_pin_pages - snapshot a buffer's pages and hold references

[ ... ]

drivers/hv/channel.c void vmbus_release_buffer(struct vmbus_buffer *buffer) · line 1182

Quoted 13 lines
drivers/hv/channel.c +13 -0
+int vmbus_buffer_pin_pages(struct vmbus_buffer *buffer,
+			   struct vmbus_buffer_pin *pin)
+{
+	struct vmbus_buffer_retained *owner;
+	u32 i;
+
+	/*
+	 * The owner and page array are published and cleared under
+	 * vmbus_buffer_owners_lock (see vmbus_release_buffer()). Reading
+	 * either outside that lock lets a concurrent release free the array
+	 * while this loop still walks it.
+	 */
+	mutex_lock(&vmbus_buffer_owners_lock);

[Severity: High]
Does this code still have a use-after-free race for subchannel ringbuffers?

In vmbus_release_buffer(), if buffer->owner is NULL, the buffer is freed and zeroed without acquiring vmbus_buffer_owners_lock. Subchannel ringbuffers do not have an owner, so their release bypasses this lock.

If a concurrent mmap() is called on a subchannel's sysfs ring file during device removal, this function will acquire the lock and start walking buffer->pages while vmbus_release_buffer() concurrently zeroes and frees it without the lock, causing a crash.

Quoted 5 lines
drivers/hv/channel.c +5 -0
+	owner = buffer->owner;
+	if (!buffer->pages || !buffer->page_cnt) {
+		mutex_unlock(&vmbus_buffer_owners_lock);
+		return -ENODEV;
+	}

[ ... ]

Quoted 4 lines
drivers/uio/uio_hv_generic.c +0 -0
index b40e80e19c6c6..91cb25d019be9 100644

[ ... ]

drivers/uio/uio_hv_generic.c static void · line 645

Quoted 10 lines
drivers/uio/uio_hv_generic.c +1 -0
@@ -372,12 +637,20 @@ static void
 hv_uio_remove(struct hv_device *dev)
 {
 	struct hv_uio_private_data *pdata = hv_get_drvdata(dev);
+	int ret;
 
 	if (!pdata)
 		return;
 
 	hv_remove_ring_sysfs(dev->channel);

[Severity: High]
Does this code leave subchannel sysfs files active and mapped?

hv_remove_ring_sysfs() is only called on the primary channel, which leaves any subchannel ring sysfs files active.

drivers/uio/uio_hv_generic.c static void · line 650

Quoted 5 lines
drivers/uio/uio_hv_generic.c +4 -0
+	/* Keep event notification alive until channel callbacks are stopped. */
+	get_device(&pdata->info.uio_dev->dev);
 	uio_unregister_device(&pdata->info);
+	/* unregister prevents the eventual fd close from calling .release. */
+	ret = hv_uio_disconnect_if_open(dev->channel, vmbus_disconnect_ring);

vmbus_disconnect_ring() iterates over the subchannels and frees their ringbuffers directly. Because the subchannel sysfs ring files are still active, userspace can call mmap() concurrently on them. This triggers the lockless vmbus_release_buffer() vs vmbus_buffer_pin_pages() race described above.

Could hv_remove_ring_sysfs() be invoked on all subchannels before their ringbuffers are freed?

Quoted 6 lines
drivers/uio/uio_hv_generic.c +3 -0
+	if (ret)
+		dev_err(&dev->device, "channel disconnect failed: %d\n", ret);
+	put_device(&pdata->info.uio_dev->dev);
 	hv_uio_cleanup(dev, pdata);
 
 	vmbus_free_ring(dev->channel);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#18 lore raw

PATCH v2 11/14 hv: vmbus: vmalloc requestor metadata

In reply to Emerson Busson

Channel opens allocate request-ID arrays from the ring size. With the 128-page default ring, kvcalloc() can request an order-7 allocation. The bitmap created by bitmap_zalloc() is another physically contiguous allocation; at normal NetVSC sizes it can require order-1 pages. Either allocation can fail under buddy fragmentation while order-0 pages remain available.

Always allocate both guest-private structures with vzalloc(). Reject a zero requestor count and check byte-size calculations before allocating, then pair the allocations with vfree() on rollback and teardown. Neither structure is exposed to the host, so neither needs to be decrypted for Confidential Computing.

Extend KUnit coverage to require vmalloc backing for a typical 8 KiB requestor array, a bitmap larger than one page, and an array above KMALLOC_MAX_SIZE. Existing requestor cases continue to cover ID lifecycle and cleanup.

Rollback trigger: revert if requestor metadata is exposed to the host, if request-ID allocation or teardown regresses on a healthy channel open, or if hyperv-vmbus-buffer KUnit fails.

---
 drivers/hv/channel.c           |  39 ++++++--
 drivers/hv/hyperv_vmbus.h      |  11 +++
 drivers/hv/vmbus_buffer_test.c | 160 +++++++++++++++++++++++++++++++++
 3 files changed, 201 insertions(+), 9 deletions(-)
drivers/hv/channel.c +30 -9
index 2793ca1b7f32..c7f3f5c6c0d2 100644
@@ -1411,14 +1411,26 @@ EXPORT_SYMBOL_GPL(vmbus_alloc_buffer);
  * keeps track of the next available slot in the array. Initially, each
  * slot points to the next one (as in a Linked List). The last slot
  * does not point to anything, so its value is U64_MAX by default.
+ *
+ * Allocated with vzalloc() rather than kvcalloc(). kvcalloc() can use a
+ * higher-order kmalloc allocation for arrays up to KMALLOC_MAX_SIZE, so
+ * both small requestor arrays and the default 128-page ring array may need
+ * contiguous pages while opening a channel under buddy fragmentation. The
+ * array is guest-private request bookkeeping -- the host never sees the
+ * slot values -- so a vmalloc-backed mapping carries no Confidential
+ * Computing implication and needs no set_memory_decrypted().
  * @size: The size of the array
  */
-static u64 *request_arr_init(u32 size)
+u64 *request_arr_init(u32 size)
 {
-	int i;
+	size_t bytes;
+	u32 i;
 	u64 *req_arr;
 
-	req_arr = kcalloc(size, sizeof(u64), GFP_KERNEL);
+	if (!size || check_mul_overflow((size_t)size, sizeof(*req_arr), &bytes))
+		return NULL;
+
+	req_arr = vzalloc(bytes);
 	if (!req_arr)
 		return NULL;
 
@@ -1436,8 +1448,9 @@ static u64 *request_arr_init(u32 size)
  * Index 0 is the first free slot
  * @size: Size of the requestor array
  */
-static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)
+int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)
 {
+	size_t bitmap_longs, bitmap_bytes;
 	u64 *rqst_arr;
 	unsigned long *bitmap;
 
@@ -1445,9 +1458,17 @@ static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)
 	if (!rqst_arr)
 		return -ENOMEM;
 
-	bitmap = bitmap_zalloc(size, GFP_KERNEL);
+	bitmap_longs = size / BITS_PER_LONG;
+	if (size % BITS_PER_LONG)
+		bitmap_longs++;
+	if (check_mul_overflow(bitmap_longs, sizeof(*bitmap), &bitmap_bytes)) {
+		vfree(rqst_arr);
+		return -ENOMEM;
+	}
+
+	bitmap = vzalloc(bitmap_bytes);
 	if (!bitmap) {
-		kfree(rqst_arr);
+		vfree(rqst_arr);
 		return -ENOMEM;
 	}
 
@@ -1464,10 +1485,10 @@ static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)
  * vmbus_free_requestor - Frees memory allocated for @rqstor
  * @rqstor: Pointer to the requestor struct
  */
-static void vmbus_free_requestor(struct vmbus_requestor *rqstor)
+void vmbus_free_requestor(struct vmbus_requestor *rqstor)
 {
-	kfree(rqstor->req_arr);
-	bitmap_free(rqstor->req_bitmap);
+	vfree(rqstor->req_arr);
+	vfree(rqstor->req_bitmap);
 }
 
 static int __vmbus_open(struct vmbus_channel *newchannel,
drivers/hv/hyperv_vmbus.h +11 -0
index 2edeb7988bdc..9819a6b686ce 100644
@@ -648,4 +648,15 @@ int vmbus_gpadl_teardown_request(struct vmbus_channel *channel,
 void vmbus_complete_gpadl_teardown(struct vmbus_connection *connection,
 				   struct vmbus_channel_gpadl_torndown *response);
 
+/*
+ * Requestor array lifetime helpers, shared with vmbus_buffer_test.c for
+ * the same reason as the sizing helpers. Defined in channel.c, unexported.
+ * request_arr_init() returns a vmalloc-backed array the caller must vfree();
+ * vmbus_alloc_requestor() owns both vmalloc-backed objects on success, and
+ * vmbus_free_requestor() releases them.
+ */
+u64 *request_arr_init(u32 size);
+int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size);
+void vmbus_free_requestor(struct vmbus_requestor *rqstor);
+
 #endif /* _HYPERV_VMBUS_H */
drivers/hv/vmbus_buffer_test.c +160 -0

178 lines not on this page · raw message

Signature · 1 line
2.43.0
#19 lore raw

Re: [PATCH v2 11/14] hv: vmbus: vmalloc requestor metadata

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] hv: memory leak in vmbus KUnit tests on KUNIT_ASSERT_EQ failure --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] hv: memory leak in vmbus KUnit tests on KUNIT_ASSERT_EQ failure
--

commit 691cb947fd6eb3bbd5abcb1f0c1c8a97f9b7e21e
Author: Emerson Busson <[email protected]>

hv: vmbus: vmalloc requestor metadata

This commit changes the channel open requestor array and bitmap allocations from kvcalloc and bitmap_zalloc to vzalloc to avoid high-order allocations under memory fragmentation, and adds KUnit tests for these structures.

Quoted 4 lines
drivers/hv/vmbus_buffer_test.c +0 -0
index 5c8e70d861adb..d0102dabef737 100644

[ ... ]

Quoted 10 lines
drivers/hv/vmbus_buffer_test.c +10 -0
+static void vmbus_requestor_invalid_ids_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rqstor_size = 4 };
+	struct vmbus_requestor *rqstor = &channel.requestor;
+	u64 id, addr;
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 4), 0);
+
+	/* ID 0 is the unsolicited-message sentinel and is never in the set. */
+	KUNIT_EXPECT_EQ(test, vmbus_request_addr_match(&channel, 0, 0),

drivers/hv/vmbus_buffer_test.c static void vmbus_buffer_order_zero_allocation_test(struct kunit *test) · line 895

Quoted 10 lines
drivers/hv/vmbus_buffer_test.c +10 -0
+			VMBUS_RQST_ERROR);
+
+	/* Out-of-range IDs are refused, not wrapped. */
+	KUNIT_EXPECT_EQ(test, vmbus_request_addr_match(&channel, 5, 0),
+			VMBUS_RQST_ERROR);
+	KUNIT_EXPECT_EQ(test, vmbus_request_addr_match(&channel, U64_MAX, 0),
+			VMBUS_RQST_ERROR);
+
+	id = vmbus_next_request_id(&channel, 0xABCD);
+	KUNIT_ASSERT_EQ(test, id, 1U);

[Severity: Low]
Does this abort the test and skip the cleanup on failure?

In vmbus_requestor_invalid_ids_test(), vmbus_alloc_requestor() is called earlier to allocate the vmalloc-backed metadata arrays. If this KUNIT_ASSERT_EQ() fails, KUnit immediately aborts the execution of the test function.

This would skip the manual cleanup call to vmbus_free_requestor() at the end of the function, resulting in a memory leak of the requestor arrays.

Could this be changed to use KUNIT_EXPECT_EQ(), which reports the failure but continues execution, or could a deferred cleanup action be registered with KUnit?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#20 lore raw

PATCH v2 12/14 hv: netvsc: allocate RNDIS request descriptors with kvzalloc_obj()

In reply to Emerson Busson

struct rndis_request embeds two RNDIS_EXT_LEN protocol tails. RNDIS_EXT_LEN is HV_HYP_PAGE_SIZE, so the two tails alone are 8 KiB and the struct is just over KMALLOC_MAX_CACHE_SIZE. kzalloc_obj() therefore needs an order-2 compound page for every RNDIS control request, which can fail under buddy fragmentation.

Use kvzalloc_obj() and kvfree() so allocation can fall back to vmalloc. RNDIS control payloads are sent as GPA-direct page buffers, however, so a vmalloc-backed descriptor cannot be described by one virt_to_phys() PFN. Build one hv_page_buffer per Linux/Hyper-V page and resolve vmalloc backing with vmalloc_to_page(). Linear allocations use virt_to_page(). This keeps the GPA list valid and preserves the existing per-range DMA mapping for isolated guests.

Keep both protocol tails unchanged. The response is copied after request->response_msg into response_ext, within the existing sizeof(struct rndis_message) + RNDIS_EXT_LEN bound.

Adds a fifth named RNDIS request KUnit case. It builds GPA descriptors from a vmalloc buffer that crosses a page boundary and checks every PFN, offset, and length against the backing pages. The existing cases retain the allocation-size, response-layout, zeroing, request-id, and cleanup checks.

Rollback trigger: revert if the vmalloc page-buffer KUnit case fails or an exact-source fragmented rebind shows malformed GPA descriptors from this path.

Fixes 5b54dac856cb ("hyperv: Add support for virtual Receive Side Scaling (vRSS)")
---
 drivers/net/hyperv/Kconfig              |  12 ++
 drivers/net/hyperv/Makefile             |   1 +
 drivers/net/hyperv/hyperv_net.h         |  43 ++++-
 drivers/net/hyperv/rndis_filter.c       | 117 ++++++++-----
 drivers/net/hyperv/rndis_request_test.c | 216 ++++++++++++++++++++++++
 5 files changed, 349 insertions(+), 40 deletions(-)
 create mode 100644 drivers/net/hyperv/rndis_request_test.c
drivers/net/hyperv/Kconfig +12 -0
index 982964c1a9fb..226728fd77d7 100644
@@ -6,3 +6,15 @@ config HYPERV_NET
 	select NLS
 	help
 	  Select this option to enable the Hyper-V virtual network driver.
+
+config HYPERV_NET_KUNIT_TEST
+	bool "Build Hyper-V netvsc KUnit tests"
+	depends on HYPERV_NET && KUNIT
+	default KUNIT_ALL_TESTS
+	help
+	  Build the netvsc KUnit test suites into the hv_netvsc object.
+	  Built into the module rather than as a separate one so the
+	  cases can reach the internal helpers declared in hyperv_net.h
+	  without exporting them.
+
+	  If unsure, say N.
drivers/net/hyperv/Makefile +1 -0
index 0db7ccaec4a4..6f1abc756fde 100644
@@ -2,3 +2,4 @@
 obj-$(CONFIG_HYPERV_NET) += hv_netvsc.o
 
 hv_netvsc-y := netvsc_drv.o netvsc.o rndis_filter.o netvsc_trace.o netvsc_bpf.o
+hv_netvsc-$(CONFIG_HYPERV_NET_KUNIT_TEST) += rndis_request_test.o
drivers/net/hyperv/hyperv_net.h +42 -1

62 lines not on this page · raw message

drivers/net/hyperv/rndis_filter.c +78 -39

173 lines not on this page · raw message

drivers/net/hyperv/rndis_request_test.c new file +216 -0

216 lines not on this page · raw message

Signature · 1 line
2.43.0
#21 lore raw

Re: [PATCH v2 12/14] hv: netvsc: allocate RNDIS request descriptors with kvzalloc_obj()

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [Critical] hv_netvsc: Double-free and UAF on duplicate RNDIS response - [Medium] selftests…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Critical] hv_netvsc: Double-free and UAF on duplicate RNDIS response
- [Medium] selftests: rndis_request_size_premise_test fails unconditionally on architectures with >4KB pages
- [Medium] netvsc: netvsc_dma_map() leaks earlier DMA mappings when dma_map_single() fails
- [Medium] hyperv: netvsc: DMA mapping leak in RNDIS_MSG_HALT control message
- [Low] kconfig: HYPERV_NET_KUNIT_TEST cannot be enabled when driver is built as a module --

commit 91156bed3a78e0ac932d5c6bf8e50ef88aa52fa1
Author: Emerson Busson <[email protected]>

hv: netvsc: allocate RNDIS request descriptors with kvzalloc_obj()

This commit changes the allocation of RNDIS control requests from kzalloc_obj() to kvzalloc_obj() to avoid order-2 page allocation failures under buddy fragmentation. It resolves the vmalloc-backed descriptor into an array of page buffers for the DMA layout and includes KUnit test cases to cover the allocation and layout requirements.

drivers/net/hyperv/Kconfig config HYPERV_NET · line 12

Quoted 12 lines
drivers/net/hyperv/Kconfig +4 -0
index 982964c1a9fb9..226728fd77d71 100644
@@ -6,3 +6,15 @@ config HYPERV_NET
 	select NLS
 	help
 	  Select this option to enable the Hyper-V virtual network driver.
+
+config HYPERV_NET_KUNIT_TEST
+	bool "Build Hyper-V netvsc KUnit tests"
+	depends on HYPERV_NET && KUNIT

[Severity: Low]
Will this test be unselectable for modular builds?

Because HYPERV_NET_KUNIT_TEST is a bool depending on the tristate HYPERV_NET, if HYPERV_NET is built as a module (=m), this boolean symbol will be clamped to n.

Should this use depends on HYPERV_NET != n && KUNIT instead?

Quoted 3 lines
drivers/net/hyperv/Kconfig +3 -0
+	default KUNIT_ALL_TESTS
+	help
+	  Build the netvsc KUnit test suites into the hv_netvsc object.

[ ... ]

Quoted 4 lines
drivers/net/hyperv/rndis_filter.c +0 -0
index 9b6c44979b4ea..1ce40baa2d239 100644

[ ... ]

Quoted 12 lines
drivers/net/hyperv/rndis_filter.c +2 -2
@@ -115,8 +102,8 @@ static struct rndis_request *get_rndis_request(struct rndis_device *dev,
 	return request;
 }
 
-static void put_rndis_request(struct rndis_device *dev,
-			    struct rndis_request *req)
+void put_rndis_request(struct rndis_device *dev,
+		       struct rndis_request *req)
 {
 	unsigned long flags;
 

drivers/net/hyperv/rndis_filter.c static void put_rndis_request(struct rndis_device *dev, · line 116

Quoted 7 lines
drivers/net/hyperv/rndis_filter.c +2 -1
@@ -124,7 +111,8 @@ static void put_rndis_request(struct rndis_device *dev,
 	list_del(&req->list_ent);
 	spin_unlock_irqrestore(&dev->request_lock, flags);
 
-	kfree(req);
+	/* Paired with the kvzalloc_obj() in get_rndis_request(). */
+	kvfree(req);
 }

[Severity: Medium]
Does freeing the request here permanently leak its DMA mapping when the device is halted?

When rndis_filter_halt_device() sends an RNDIS_MSG_HALT request, it gets mapped via netvsc_dma_map(). Because it expects no response, rndis_filter_receive_response() is never executed to unmap it.

Additionally, the TX completion path in netvsc_send_tx_complete() skips unmapping for control messages since skb is NULL.

When rndis_filter_halt_device() subsequently calls put_rndis_request(), the request and its req->pkt.dma_range array are freed, but dma_unmap_single() is never called, leaking the SWIOTLB mappings.

[Severity: Critical]
Can a duplicate response from the host cause a double-free and use-after-free here?

When rndis_filter_receive_response() processes a response, it looks up the request in dev->req_list but does not remove it:

rndis_filter_receive_response() {
    spin_lock_irqsave(&dev->request_lock, flags);
    list_for_each_entry(request, &dev->req_list, list_ent) {
        if (request->request_msg.msg.init_req.req_id == *req_id) {
            found = true;
            break;
        }
    }
    spin_unlock_irqrestore(&dev->request_lock, flags);
    ...
}

If the host sends a duplicate RNDIS response with the same req_id, and the first response has already woken the waiting thread, the waiting thread can call put_rndis_request() to remove and free the request.

The duplicate response RX thread will then use the freed request pointer and call netvsc_dma_unmap(), which calls kfree(packet->dma_range) without checking for NULL.

For isolated VMs (like AMD SEV-SNP or Intel TDX), could an untrusted Hyper-V host use this to compromise the guest?

Quoted 1 line
drivers/net/hyperv/rndis_filter.c +0 -0
 static void dump_rndis_message(struct net_device *netdev,

[ ... ]

Quoted 7 lines
drivers/net/hyperv/rndis_filter.c +3 -0
@@ -221,27 +209,78 @@ static void dump_rndis_message(struct net_device *netdev,
 	}
 }
 
+int rndis_build_page_buffers(const void *data, u32 len,
+			     struct hv_page_buffer *page_bufs,
+			     u32 *page_buf_cnt)

[ ... ]

Quoted 21 lines

static int rndis_filter_send_request(struct rndis_device *dev,

drivers/net/hyperv/rndis_filter.c +5 -6
 				  struct rndis_request *req)
 {
 	struct hv_netvsc_packet *packet;
-	struct hv_page_buffer pb;
+	struct hv_page_buffer page_bufs[MAX_PAGE_BUFFER_COUNT];
+	u32 page_buf_cnt;
 	int ret;
 
 	/* Setup the packet to send it */
 	packet = &req->pkt;
 
 	packet->total_data_buflen = req->request_msg.msg_len;
-	packet->page_buf_cnt = 1;
-
-	pb.pfn = virt_to_phys(&req->request_msg) >> HV_HYP_PAGE_SHIFT;
-	pb.len = req->request_msg.msg_len;
-	pb.offset = offset_in_hvpage(&req->request_msg);
+	ret = rndis_build_page_buffers(&req->request_msg,
+				       req->request_msg.msg_len,
+				       page_bufs, &page_buf_cnt);

drivers/net/hyperv/rndis_filter.c static void dump_rndis_message(struct net_device *netdev, · line 284

Quoted 10 lines
drivers/net/hyperv/rndis_filter.c +4 -1
+	if (ret)
+		return ret;
+	packet->page_buf_cnt = page_buf_cnt;
 
 	trace_rndis_send(dev->ndev, 0, &req->request_msg);
 
 	rcu_read_lock_bh();
-	ret = netvsc_send(dev->ndev, packet, NULL, &pb, NULL, false);
+	ret = netvsc_send(dev->ndev, packet, NULL, page_bufs, NULL, false);
 	rcu_read_unlock_bh();

[Severity: Medium]
Because page_buf_cnt can now be greater than 1, does this introduce a resource leak if DMA mapping partially fails?

Inside netvsc_dma_map(), it iterates over page_buf_cnt to map the pages:

netvsc_dma_map() {
    ...
    for (i = 0; i < page_count; i++) {
        ...
        dma = dma_map_single(&hv_dev->device, src, len, DMA_TO_DEVICE);
        if (dma_mapping_error(&hv_dev->device, dma)) {
            kfree(packet->dma_range);
            return -ENOMEM;
        }
    }
    ...
}

If dma_map_single() fails on a later iteration (when i > 0), it returns -ENOMEM but neglects to call dma_unmap_single() for the pages 0 to i - 1 that were successfully mapped in previous loop iterations.

Quoted 5 lines
drivers/net/hyperv/rndis_request_test.c new file +0 -0
new file mode 100644
index 0000000000000..6affa916e74e3

[ ... ]

drivers/net/hyperv/rndis_request_test.c line 38

Quoted 4 lines
drivers/net/hyperv/rndis_request_test.c new file +4 -0
+static void rndis_request_size_premise_test(struct kunit *test)
+{
+	KUNIT_EXPECT_GT(test, sizeof(struct rndis_request),
+			(size_t)KMALLOC_MAX_CACHE_SIZE);

[Severity: Medium]
Will this assertion unconditionally fail on architectures with page sizes larger than 4KB?

KMALLOC_MAX_CACHE_SIZE scales with PAGE_SIZE (typically PAGE_SIZE * 2). On architectures like ARM64 or PPC64 configured with 64KB pages, KMALLOC_MAX_CACHE_SIZE is at least 64 KiB.

Since sizeof(struct rndis_request) is slightly larger than 8 KiB (because RNDIS_EXT_LEN is fixed at 4096), this check will evaluate to roughly 8272 > 65536 on those platforms, causing the test suite to spuriously fail.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#22 lore raw

PATCH v2 13/14 hv: netvsc: handle a NULL request address on empty completions

In reply to Emerson Busson

netvsc_send_pkt() registers (ulong)skb as the VMBus request address. Control RNDIS sends carry no skb -- rndis_filter.c calls netvsc_send() with skb == NULL -- so the registered address is NULL. That is
intentional: there is no guest object to hand back, and the request slot is still allocated so the completion can reclaim it.

netvsc_send_tx_complete() already tolerates that with if (likely(skb)). netvsc_send_completion()'s empty-payload branch does not. It casts the request address to struct nvsp_message * and reads hdr.msg_type unconditionally, so a completion that resolves to NULL is a fatal NULL dereference in NAPI/softirq context.

The empty-payload branch exists for NVSP_MSG4_TYPE_SWITCH_DATA_PATH, which netvsc_switch_datapath() sends with a real nvsp_message address. A NULL request address is not that message and must not be dereferenced. Validate VMBUS_NO_RQSTOR alongside VMBUS_RQST_ERROR in both completion paths -- request_addr_callback() returns it when the channel has no requestor -- and account a NULL-address completion the same way the payload path accounts a NULL skb. The request id is consumed by the lookup, so that completion is the one that owns the queue_sends decrement and the possible queue wake.

This is reached by the runtime drill in this series once channel open survives buddy fragmentation: control RNDIS traffic proceeds where it used to fail with -ENOMEM, and an empty completion for one of those requests takes the unguarded path.

Revert this patch if an empty completion with a NULL request address dereferences again, if a netvsc TX stall or an "Invalid transaction ID" flood appears under this patch, or if a SWITCH_DATA_PATH completion is shown to be dropped instead of taken through its nvsp_message path.

Adds eleven named netvsc completion KUnit cases covering the decision layer of the empty-payload branch: a NULL request address owning the queue_sends decrement, both invalid sentinels rejected without accounting, SWITCH_DATA_PATH completing channel_init_wait without accounting, an unexpected message type taking neither path, a replayed transaction id accounting exactly once, N completions decrementing the queue exactly N times, the destroy drain wait waking only at zero, and netvsc_send_tx_complete() applying the same sentinel rejection while still accounting a NULL skb. Two skb-backed payload cases exercise the production completion entry with success and error status, a published send slot and queue 1. They verify synchronous skb consumption, exact packet/byte statistics, selected queue accounting and duplicate transaction rejection. Confidential DMA unmapping remains platform-specific and is not exercised here.

netvsc_send_acct() is extracted so a test can observe the decrement and the drain wake directly; it is not a behaviour change. The helpers lose static and are declared in hyperv_net.h so the cases reach them without a new EXPORT_SYMBOL_GPL, matching how the VMBus buffer tests are built into hv_vmbus.

Fixes 8b31f8c982b7 ("hv_netvsc: Wait for completion on request SWITCH_DATA_PATH")
---
 drivers/net/hyperv/Makefile                 |   1 +
 drivers/net/hyperv/hyperv_net.h             |  15 +
 drivers/net/hyperv/netvsc.c                 |  81 ++--
 drivers/net/hyperv/netvsc_completion_test.c | 439 ++++++++++++++++++++
 4 files changed, 507 insertions(+), 29 deletions(-)
 create mode 100644 drivers/net/hyperv/netvsc_completion_test.c
drivers/net/hyperv/Makefile +1 -0
index 6f1abc756fde..b2d22855fd8a 100644
@@ -2,4 +2,5 @@
 obj-$(CONFIG_HYPERV_NET) += hv_netvsc.o
 
 hv_netvsc-y := netvsc_drv.o netvsc.o rndis_filter.o netvsc_trace.o netvsc_bpf.o
+hv_netvsc-$(CONFIG_HYPERV_NET_KUNIT_TEST) += netvsc_completion_test.o
 hv_netvsc-$(CONFIG_HYPERV_NET_KUNIT_TEST) += rndis_request_test.o
drivers/net/hyperv/hyperv_net.h +15 -0
index 6492e7e93ded..be3a63a168cf 100644
@@ -229,6 +229,21 @@ int rndis_build_page_buffers(const void *data, u32 len,
 			     struct hv_page_buffer *page_bufs,
 			     u32 *page_buf_cnt);
 
+void netvsc_send_acct(struct net_device *ndev,
+		      struct netvsc_device *net_device,
+		      struct vmbus_channel *channel,
+		      u16 q_idx);
+void netvsc_send_tx_complete(struct net_device *ndev,
+			     struct netvsc_device *net_device,
+			     struct vmbus_channel *channel,
+			     const struct vmpacket_descriptor *desc,
+			     int budget);
+void netvsc_send_completion(struct net_device *ndev,
+			    struct netvsc_device *net_device,
+			    struct vmbus_channel *incoming_channel,
+			    const struct vmpacket_descriptor *desc,
+			    int budget);
+
 extern u32 netvsc_ring_bytes;
 
 int netvsc_workqueue_init(void);
drivers/net/hyperv/netvsc.c +52 -29

112 lines not on this page · raw message

drivers/net/hyperv/netvsc_completion_test.c new file +439 -0

439 lines not on this page · raw message

Signature · 1 line
2.43.0
#23 lore raw

Re: [PATCH v2 13/14] hv: netvsc: handle a NULL request address on empty completions

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] netvsc: Type confusion and memory corruption via untrusted host msglen mismatch - [Low]…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] netvsc: Type confusion and memory corruption via untrusted host msglen mismatch
- [Low] netvsc: data race on global wake_queue ethtool statistic
--

commit cc27953d7c3e5380170944c920266d1ad5b66616
Author: Emerson Busson <[email protected]>
Subject: hv: netvsc: handle a NULL request address on empty completions

This commit introduces a new check in the empty-payload branch of the netvsc send completion path to tolerate NULL request addresses, which occur during control RNDIS sends. It extracts the queue wake and accounting logic into a new helper function and provides associated KUnit tests.

[Severity: Critical]
In drivers/net/hyperv/netvsc.c, within the netvsc_send_completion and netvsc_send_tx_complete functions, is there a potential type confusion regression? The empty-payload branch relies on the untrusted host msglen == 0 to cast the context pointer to an nvsp_message. If the pointer is actually an sk_buff, does this result in a memory leak? Conversely, if the host sends a msglen > 0 for a channel_init_pkt transaction, the pointer is cast to an sk_buff in netvsc_send_tx_complete. Since the pointer is an interior struct member rather than an sk_buff, could this cause out-of-bounds reads and slab memory corruption when napi_consume_skb is called on it? This sequence is reachable by an untrusted host, which violates the security boundary in confidential virtual machine environments where the host is untrusted.

[Severity: Low]
In drivers/net/hyperv/netvsc.c, at line 788 within the newly extracted netvsc_send_acct function, does this code introduce a data race on the wake_queue ethtool statistic? The increment operation on ndev_ctx->eth_stats.wake_queue is performed non-atomically. When multiple VMBus channels process completions in concurrent NAPI softirq contexts on different CPUs, and both channels need to wake their respective stopped transmit queues, could they simultaneously evaluate the queue state and update the shared global counter without synchronization, resulting in lost increments?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#24 lore raw

PATCH v2 14/14 hv: netvsc: use kvzalloc for device state

In reply to Emerson Busson

alloc_net_device() allocates the fixed-channel netvsc_device with kzalloc_obj(). The runtime fragmentation drill reaches this allocation from netvsc_device_add(): windows-2025 reports an order-7 allocation failure with about 99 MiB free, while windows-latest stalls at channel open until the guest timeout.

This object is guest-private control-plane metadata, not DMA backing. Use kvzalloc_obj() so the allocation can fall back to vmalloc when a high-order kmalloc cannot be satisfied. Zero initialization is preserved. The RCU workqueue cleanup uses kvfree() to release either backing.

Rollback trigger: revert if channel setup fails with vmalloc capacity available or teardown leaves netvsc_device allocations outstanding.

---
 drivers/net/hyperv/netvsc.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/hyperv/netvsc.c +2 -2
index 0d017f836b9e..8ea7c993baac 100644
@@ -144,7 +144,7 @@ static void __free_netvsc_device(struct netvsc_device *nvdev)
 		vfree(nvdev->chan_table[i].mrc.slots);
 	}
 
-	kfree(nvdev);
+	kvfree(nvdev);
 }
 
 static void free_netvsc_device(struct work_struct *w)
@@ -171,7 +171,7 @@ static struct netvsc_device *alloc_net_device(void)
 {
 	struct netvsc_device *net_device;
 
-	net_device = kzalloc_obj(struct netvsc_device);
+	net_device = kvzalloc_obj(struct netvsc_device);
 	if (!net_device)
 		return NULL;
 
Signature · 1 line
2.43.0
#25 lore raw

Re: [PATCH v2 14/14] hv: netvsc: use kvzalloc for device state

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] netvsc: unconditional xdp_rxq_info_unreg() on uninitialized structs triggers WARN --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] netvsc: unconditional xdp_rxq_info_unreg() on uninitialized structs triggers WARN --

commit 961e2b6c1ed96f0ba554ff4b714af09658ea0cc8
Author: Emerson Busson <[email protected]>

hv: netvsc: use kvzalloc for device state

This commit modifies alloc_net_device() to use kvzalloc_obj() instead of kzalloc_obj() for allocating the netvsc_device. It updates the cleanup path in __free_netvsc_device() to use kvfree() for releasing the memory, allowing allocations to safely fall back to vmalloc.

drivers/net/hyperv/netvsc.c static void __free_netvsc_device(struct netvsc_device *nvdev) · line 141

Quoted 7 lines
drivers/net/hyperv/netvsc.c +0 -0
index 0d017f836b9eb..8ea7c993baac0 100644
@@ -140,8 +140,8 @@ static void __free_netvsc_device(struct netvsc_device *nvdev)
 	for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
 		xdp_rxq_info_unreg(&nvdev->chan_table[i].xdp_rxq);

[Severity: Medium]
Does this loop unconditionally call xdp_rxq_info_unreg() on uninitialized structs during error cleanup, triggering a warning splat?

If channel setup fails after alloc_net_device() zero-initializes the device, __free_netvsc_device() loops over all channels and calls xdp_rxq_info_unreg().

Because the uninitialized structs have a state of REG_STATE_NEW (0), passing them to xdp_rxq_info_unreg() bypasses the registered state check and triggers the following warning in xdp_rxq_info_unreg_mem_model() in net/core/xdp.c:

WARN(1, "Missing register, driver bug");

Quoted 7 lines
drivers/net/hyperv/netvsc.c +1 -1
 		kfree(nvdev->chan_table[i].recv_buf);
 		vfree(nvdev->chan_table[i].mrc.slots);
 	}
 
-	kfree(nvdev);
+	kvfree(nvdev);
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#26 lore raw
In reply to Emerson Busson
Quoted 11 lines · Emerson Busson

This series moves VMBus ring backing to the chunk allocator and keeps the allocation, GPADL ownership, and mapping references together. It preserves the exported four-argument interfaces while allowing the private allocation paths to carry ownership and sharing policy.

A review of the original vzalloc fallback noted that CCA and TDX guests without a paravisor need direct-map page transitions. This revision uses contiguous chunks for buffers that must be host-shared, transitions each page through page_address(), and combines the chunks with vmap(). Ordinary guest-private buffers retain vzalloc-style allocation.

Can you provide a link to the v1 of this changeset and this "original vzalloc fallback" review? And a changelog and motivation for this series?

<snip>

Thanks,
Easwar (he/him)

maintainer
#27 lore raw
Quoted 13 lines · Easwar Hariharan
Quoted 11 lines · Emerson Busson

This series moves VMBus ring backing to the chunk allocator and keeps the allocation, GPADL ownership, and mapping references together. It preserves the exported four-argument interfaces while allowing the private allocation paths to carry ownership and sharing policy.

A review of the original vzalloc fallback noted that CCA and TDX guests without a paravisor need direct-map page transitions. This revision uses contiguous chunks for buffers that must be host-shared, transitions each page through page_address(), and combines the chunks with vmap(). Ordinary guest-private buffers retain vzalloc-style allocation.

Quoted 2 lines

Can you provide a link to the v1 of this changeset and this "original vzalloc fallback" review? And a changelog and motivation for this series?

The title is

[PATCH 0/2] hv: vmbus: prevent control-plane starvation and order-7 ring deadlocks under memory pressure

Wei

#28 lore raw
In reply to Emerson Busson

From: Emerson Busson <[email protected]> Sent: Wednesday, October 7, 2026 12:08 PM

Quoted 117 lines

This series moves VMBus ring backing to the chunk allocator and keeps the allocation, GPADL ownership, and mapping references together. It preserves the exported four-argument interfaces while allowing the private allocation paths to carry ownership and sharing policy.

A review of the original vzalloc fallback noted that CCA and TDX guests without a paravisor need direct-map page transitions. This revision uses contiguous chunks for buffers that must be host-shared, transitions each page through page_address(), and combines the chunks with vmap(). Ordinary guest-private buffers retain vzalloc-style allocation.

Allocation and compatibility
----------------------------

Every ring allocation uses the chunk allocator. Ordinary guests and buffers kept private by channel policy use vzalloc(). For host-shared buffers in an encrypted or isolated guest, the allocator uses contiguous chunks and transitions them page by page. Guest-memory encryption is selected independently of Hyper-V isolation.

Ring consumers select co_ring_buffer. External buffers and the legacy allocator select co_external_memory. The exported allocator and caller- decrypted GPADL prototypes retain four arguments throughout all fourteen patches. UIO migration follows its release support.

The address, page and chunk arrays, and embedded GPADL belong to one buffer. The allocation extent, host-described GPADL extent, and retained allocation extent remain distinct. Interior GPADL duplication preserves the existing exported interfaces. Prepared owned buffers avoid repeat decryption, and HV_GPADL_BUFFER_DECRYPTED is removed.

Lifetime and host acknowledgement
---------------------------------

A host rescind alone does not prove GPADL revocation. For a known-live GPADL whose channel identifier is still held, teardown posts a request and waits for a matching GPADL_TORNDOWN message before clearing ownership. Synthetic rescind notification cannot replace this acknowledgement. Unknown creates, local removal, invalid identifiers, failed posting, and timeouts retain ownership.

Waiter removal shares the response-list lock with matching replies so a late acknowledgement cannot use a freed waiter. Released owners retain pages across mapping references and failed page-state restoration. Reclaimer shutdown cancels pending timers under the owner lock and requeues only work that was actually canceled; running callbacks drain through workqueue destruction without re-executing freed embedded work.

Sysfs mappings install no vm_ops and release the bridge pin on every setup outcome. UIO mappings hold their pin through VMA close. Page, count, and protection snapshots share the owner-lock boundary. New tests call the real sysfs wrapper, insert actual PTEs, and check readable bytes and page references through success and partial -EBUSY. They do not execute a full kernfs syscall or full device destruction.

The final four fixes use vzalloc() for guest-private requestor arrays and bitmaps, kvzalloc_obj() for guest-private RNDIS descriptors, handle NULL control requests on empty NetVSC completions, and use kvzalloc_obj()/kvfree() for the large guest-private NetVSC device object.

Qualification on the exact fourteen-patch series
------------------------------------------------

The code mails are pinned by series/SHA256SUMS. Applying all fourteen to 93f51579e7df248780214094418f205253383cc5 produces source tree e6fe523ca92ce30ea7edb265b8a26bf20a867c47.

The VMBus workflow builds x86_64 and arm64 with W=1 and C=2, passes sparse, and passes all 69 linked x86_64 QEMU KUnit cases. The distinct WSL backport passes all 26 of its KUnit cases. CoCo source invariants pass on both architectures; these are necessary static checks, not confidential-hardware qualification.

Exact-source Hyper-V runtime, including controlled host rescind:
https://github.com/emersonbusson/WSL2-Linux-Kernel/actions/runs/37650468077

On both windows-2025 and windows-latest, the candidate passes 100 bind/unbind cycles, bounded buddy fragmentation, channel rebind, UIO mapping teardown, and the controlled host-origin NIC removal. Each report records HYPERV_DRILL_HOST_RESCIND status=PASS, target_absent=yes, matching_events=1. Both report zero splats and faults, restore the measured kernel settings, and return lifecycle map accounting to the settled operational baseline. Captured owner accounting reports 722 created, zero unobserved creates, 715 reclaimed, and seven still active; active owners are not classified as leaks. Trace capture has no overruns or dropped events, and the disposable VM, VHD, and switch cleanup passes.

The baseline is an intentional negative control. It reproduces the expected fragmented-allocation failure without guest faults; the workflow accepts that exact signature as a passing control. It is not a candidate result.

WSL backport runtime matrix:
https://github.com/emersonbusson/WSL2-Linux-Kernel/actions/runs/37645708153

That separate backport passes the actual Windows candidate matrix. Each runner completes 64 commands with matching teardown acknowledgements, zero unacknowledged requests, no backing or tail growth, and all six shutdown checks. The shutdown retry path is covered by 40 local parser and refusal regressions; the live candidate runs required zero retries. These results qualify the WSL backport's measured ordinary behavior, not the mainline mail series.

Qualification limits
--------------------

The Hyper-V runtime uses the ordinary x86_64 vzalloc path. It does not execute confidential chunk transitions. Full memory saturation, the chunked CoCo fallback on hardware, SEV-SNP, TDX without a paravisor, Arm CCA, and complete VMBus module unload and retained-owner destruction remain unqualified. The exact mainline series has not been installed or booted on the daily WSL host; the installed kernel and Windows WSL matrix are a separate backport. The baseline is one intentional fragmentation negative control, not a matched same-configuration diagnostic-count comparison for every patch. No confidential-platform result is inferred from ordinary Hyper-V or static checks.

Quoted 16 lines

---
Emerson Busson (14):
hv: vmbus: convert ring backing through the chunk allocator
hv: vmbus: validate chunk buffer allocation and cleanup
uio: hv_generic: describe buffers for owned allocation
hv: vmbus: add KUnit tests for GPADL post failure injection
hv: vmbus: add KUnit test for order-zero allocation fallback
hv: vmbus: cover all shared-page policy combinations
hv: vmbus: distinguish host rescind from local channel unload
hv: vmbus: retain backing until ownership and references clear
hv: use owned VMBus buffers in NetVSC and UIO
hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race
hv: vmbus: vmalloc requestor metadata
hv: netvsc: allocate RNDIS request descriptors with kvzalloc_obj()
hv: netvsc: handle a NULL request address on empty completions
hv: netvsc: use kvzalloc for device state

This patch set has become huge in going from your original v1 to this v2. The v1 diffstat was 101 insertions and 12 deletions. This v2 has 4515 insertions and 427 deletions, which is too big to be effectively reviewed. (For some reason this v2 cover letter doesn't have the diffstat, while your v1 series did.) The elapsed time from my comments on v1 to this v2 is a little over 2 weeks, so it's clear that most of this code must be AI generated, which is itself a red flag. I'll also comment further down on the commit messages and this cover page summary, which I find difficult to comprehend and assume must have been mostly AI-generated as well.

At a top level, I think this needs to be broken into multiple patch sets, each with a clear focus. I can see these areas:

1) Ensure ring buffer allocations don't fail when memory is fragmented

2) Ensure other allocations by VMBus infrastructure and drivers (netvsc) don't fail when memory is fragmented

3) Deal with failures in GPADL teardown, ensuring that the memory is leaked (I think this is what you are calling "ownership"). This can be a tricky area, especially if the host doesn't respond within the guest's timeout period. There's an existing VMBus mechanism to help with this case but it has not been applied widely. The VMBus code mostly just assumes that if there's no response in the timeout period, there will never be a response. Handling a "late" response is a separate issue that already exists, and could be dealt with in a separate patch set if it's judged to be worth the trouble.

4) It looks like there are other bugs you are also fixing (UIO mmap and reclaim race?). If such bugs already existed, it's usually better to fix them as a separate patch or patch set, rather than folding the fixes into a patch set that is focused on a different issue. That's particularly true if the complexity of the fix is moderate to high.

5) Kunit tests. There are 2651 lines added in the new *test.c files, plus there are hooks and supporting infrastructure in the main source code files. So over half the code in this patch set is for tests. I'm rather ambivalent about this. Having unit tests is good. But as you can tell, not much effort has been invested to date in doing VMBus unit tests, with one reason being that it requires a relatively high level of invasiveness. As a result, it's a lot of test code that adds to the maintenance burden over time. Probably should get a read from the Hyper-V maintainers on whether they want to take on that burden.

There may be some interdependencies between the above areas. The trick is to figure out a sequencing that makes conceptual sense while allowing the code to be added incrementally. It's OK to design an earlier step in the sequence with a later step in mind but hopefully not add the code until the later step. Caveat: My list of 5 areas above is based on my high-level read of your v2 patch set. As the author, you have to deal with the details, and there may be reasons that combining two of the areas actually does make sense. Feel free to make that such a case -- don't take my statement as absolute truth.

Commit messages (and this cover letter) must focus on the "Why?" question. What is the problem scenario? Has the problem been seen in the real world, or it is the result of code inspection or an AI report? And then, what is the proposed fix? I know that memory allocation failure due to fragmentation has happened in the real world, so I'm on-board with the general approach to fixing it. Alternatively, if the patch set is adding a new feature/function, why is it needed? What problem is solved or new capability is provided, and why is that valuable?

For large patch sets, cover letters also often explain the sequencing and purpose of the patches in the patch set. E.g., Patches 1 thru 3 do some preliminary code reorganization; patches 4 thru 8 are the core of the patch set and fix the core XXXXX issue; patches 9 and 10 remove XXXXX existing functionality that was made obsolete by the new code. The goal is to give the reviewer a roadmap.

Read through postings to the linux-hyperv and linux-kernel mailing lists to get a feel for how commit messages read. You want yours to fit in with existing style and terminology (e.g., use "testing", not "qualification"). I could provide more detailed feedback on the commit messages, but would prefer to spend my time on a closer review once they are more in alignment with typical practices.

Bottom-line: My recommendation is to go back to the original problem from v1 of your patch set, and provide a good solution to that problem, with modest refactoring so it fits naturally in the existing code base and hopefully simplifies some of the complexity that has built-up over time. Skip the Kunit tests for now. Separately (and perhaps in parallel), deal with my #2, which is other high-order allocations that could fail when memory is fragmented. Feel free to use AI as an assistant, but don't just pass-thru AI-generated code and commit messages. Put effort into making sure the code is good and tight -- don't push that effort onto reviewers from the mailing list. You've got to "own" the result before submitting it.

Michael

maintainer
#29 lore raw
In reply to Emerson Busson

Hi Emerson

I find the wall of text in the cover letter, commit messages and code comments extremely difficult to parse.

With AI, generating code is cheap, reviewing is expensive. I don't think anyone on the list can or should review a patch series like this.

Please make sure you understand the code and deslop the AI-generated content before posting.

After reading v1, I think I know what you try to solve, but I'm not going to accept a patch series like this. A lot of the patches don't seem to be related to the problem you want to solve.

Thanks,
Wei

Quoted 132 lines · Emerson Busson

This series moves VMBus ring backing to the chunk allocator and keeps the allocation, GPADL ownership, and mapping references together. It preserves the exported four-argument interfaces while allowing the private allocation paths to carry ownership and sharing policy.

A review of the original vzalloc fallback noted that CCA and TDX guests without a paravisor need direct-map page transitions. This revision uses contiguous chunks for buffers that must be host-shared, transitions each page through page_address(), and combines the chunks with vmap(). Ordinary guest-private buffers retain vzalloc-style allocation.

Allocation and compatibility
----------------------------

Every ring allocation uses the chunk allocator. Ordinary guests and buffers kept private by channel policy use vzalloc(). For host-shared buffers in an encrypted or isolated guest, the allocator uses contiguous chunks and transitions them page by page. Guest-memory encryption is selected independently of Hyper-V isolation.

Ring consumers select co_ring_buffer. External buffers and the legacy allocator select co_external_memory. The exported allocator and caller- decrypted GPADL prototypes retain four arguments throughout all fourteen patches. UIO migration follows its release support.

The address, page and chunk arrays, and embedded GPADL belong to one buffer. The allocation extent, host-described GPADL extent, and retained allocation extent remain distinct. Interior GPADL duplication preserves the existing exported interfaces. Prepared owned buffers avoid repeat decryption, and HV_GPADL_BUFFER_DECRYPTED is removed.

Lifetime and host acknowledgement
---------------------------------

A host rescind alone does not prove GPADL revocation. For a known-live GPADL whose channel identifier is still held, teardown posts a request and waits for a matching GPADL_TORNDOWN message before clearing ownership. Synthetic rescind notification cannot replace this acknowledgement. Unknown creates, local removal, invalid identifiers, failed posting, and timeouts retain ownership.

Waiter removal shares the response-list lock with matching replies so a late acknowledgement cannot use a freed waiter. Released owners retain pages across mapping references and failed page-state restoration. Reclaimer shutdown cancels pending timers under the owner lock and requeues only work that was actually canceled; running callbacks drain through workqueue destruction without re-executing freed embedded work.

Sysfs mappings install no vm_ops and release the bridge pin on every setup outcome. UIO mappings hold their pin through VMA close. Page, count, and protection snapshots share the owner-lock boundary. New tests call the real sysfs wrapper, insert actual PTEs, and check readable bytes and page references through success and partial -EBUSY. They do not execute a full kernfs syscall or full device destruction.

The final four fixes use vzalloc() for guest-private requestor arrays and bitmaps, kvzalloc_obj() for guest-private RNDIS descriptors, handle NULL control requests on empty NetVSC completions, and use kvzalloc_obj()/kvfree() for the large guest-private NetVSC device object.

Qualification on the exact fourteen-patch series
------------------------------------------------

The code mails are pinned by series/SHA256SUMS. Applying all fourteen to 93f51579e7df248780214094418f205253383cc5 produces source tree e6fe523ca92ce30ea7edb265b8a26bf20a867c47.

The VMBus workflow builds x86_64 and arm64 with W=1 and C=2, passes sparse, and passes all 69 linked x86_64 QEMU KUnit cases. The distinct WSL backport passes all 26 of its KUnit cases. CoCo source invariants pass on both architectures; these are necessary static checks, not confidential-hardware qualification.

Exact-source Hyper-V runtime, including controlled host rescind:
https://github.com/emersonbusson/WSL2-Linux-Kernel/actions/runs/37650468077

On both windows-2025 and windows-latest, the candidate passes 100 bind/unbind cycles, bounded buddy fragmentation, channel rebind, UIO mapping teardown, and the controlled host-origin NIC removal. Each report records HYPERV_DRILL_HOST_RESCIND status=PASS, target_absent=yes, matching_events=1. Both report zero splats and faults, restore the measured kernel settings, and return lifecycle map accounting to the settled operational baseline. Captured owner accounting reports 722 created, zero unobserved creates, 715 reclaimed, and seven still active; active owners are not classified as leaks. Trace capture has no overruns or dropped events, and the disposable VM, VHD, and switch cleanup passes.

The baseline is an intentional negative control. It reproduces the expected fragmented-allocation failure without guest faults; the workflow accepts that exact signature as a passing control. It is not a candidate result.

WSL backport runtime matrix:
https://github.com/emersonbusson/WSL2-Linux-Kernel/actions/runs/37645708153

That separate backport passes the actual Windows candidate matrix. Each runner completes 64 commands with matching teardown acknowledgements, zero unacknowledged requests, no backing or tail growth, and all six shutdown checks. The shutdown retry path is covered by 40 local parser and refusal regressions; the live candidate runs required zero retries. These results qualify the WSL backport's measured ordinary behavior, not the mainline mail series.

Qualification limits
--------------------

The Hyper-V runtime uses the ordinary x86_64 vzalloc path. It does not execute confidential chunk transitions. Full memory saturation, the chunked CoCo fallback on hardware, SEV-SNP, TDX without a paravisor, Arm CCA, and complete VMBus module unload and retained-owner destruction remain unqualified. The exact mainline series has not been installed or booted on the daily WSL host; the installed kernel and Windows WSL matrix are a separate backport. The baseline is one intentional fragmentation negative control, not a matched same-configuration diagnostic-count comparison for every patch. No confidential-platform result is inferred from ordinary Hyper-V or static checks.

---
Emerson Busson (14):
hv: vmbus: convert ring backing through the chunk allocator
hv: vmbus: validate chunk buffer allocation and cleanup
uio: hv_generic: describe buffers for owned allocation
hv: vmbus: add KUnit tests for GPADL post failure injection
hv: vmbus: add KUnit test for order-zero allocation fallback
hv: vmbus: cover all shared-page policy combinations
hv: vmbus: distinguish host rescind from local channel unload
hv: vmbus: retain backing until ownership and references clear
hv: use owned VMBus buffers in NetVSC and UIO
hv: vmbus: pin buffer pages across UIO mmap to close the reclaim race
hv: vmbus: vmalloc requestor metadata
hv: netvsc: allocate RNDIS request descriptors with kvzalloc_obj()
hv: netvsc: handle a NULL request address on empty completions
hv: netvsc: use kvzalloc for device state