AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/07 21:53 flow patch-triage
9m Args:
null

Results:
{
  "EnableConfigs": [
    "UIO",
    "TARGET_CORE",
    "TCM_USER2",
    "HYPERV",
    "HYPERV_VMBUS",
    "HYPERV_NET",
    "UIO_HV_GENERIC"
  ],
  "FocusSymbols": [
    "uio_mmap",
    "hv_uio_mmap_prepare",
    "hv_uio_ring_mmap_prepare",
    "vmbus_alloc_buffer_owned",
    "vmbus_release_buffer",
    "vmbus_buffer_pin_pages",
    "vmbus_buffer_unpin_pages",
    "vmbus_buffer_reclaim_work",
    "vmbus_gpadl_teardown_request",
    "vmbus_teardown_gpadl_owned",
    "vmbus_establish_gpadl_owned",
    "hv_mmap_ring_buffer_wrapper",
    "netvsc_send_completion",
    "netvsc_send_tx_complete",
    "netvsc_send_acct",
    "rndis_build_page_buffers",
    "get_rndis_request"
  ],
  "KMSANReasoning": "The patch series enhances memory lifetime and GPADL management across Hyper-V VMBus (hv_vmbus), NetVSC (hv_netvsc), and UIO (uio_hv_generic) drivers, addressing use-after-free and synchronization issues when buffer pages are reclaimed while mapped into user space or pending host teardown. It also updates high-order allocations to use kvzalloc_obj() and adds KUnit unit test suites.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory / Info-leak Risk (KMSAN):\n   - All newly introduced or modified heap and stack data structures (e.g. struct vmbus_buffer, struct vmbus_buffer_retained, struct vmbus_buffer_pin, struct hv_uio_pin, struct rndis_request, requestor arrays, bitmaps) are explicitly zero-initialized upon allocation using kzalloc_obj(), kvzalloc_obj(), vzalloc(), memset(), or {0} initializers.\n   - Memory mapped to user space via UIO / sysfs mmap interfaces uses vzalloc() or zero-initialized pages (__GFP_ZERO and memset()), preventing uninitialized memory disclosure to userspace.\n   - No kernel data structures or uninitialized paddings are copied to user space via copy_to_user, put_user, ioctl outputs, or netlink messages.\n   - No conditional branches or control flow rely on uninitialized values.\n\n2. Memory Safety / Concurrency Risks (KASAN, LOCKDEP):\n   - The primary hazards addressed and introduced by the changes involve page lifetime, reference counting (folio/page refcounts), race conditions between buffer release and mmap pinning, delayed workqueue teardown, and potential use-after-free on reclaim.\n   - These bugs are comprehensively monitored by standard sanitizers and debuggers already enabled in standard builds (KASAN for use-after-free and out-of-bounds accesses, LOCKDEP for vmbus_buffer_owners_lock locking correctness).\n\nBecause the changes introduce no uninitialized memory hazards or info-leak vectors that would require KMSAN, a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch modifies core UIO subsystem mmap logic in drivers/uio/uio.c (uio_mmap), changing VMA state installation and invoking vma-\u003evm_ops-\u003eclose() on mmap failure for drivers providing mmap_prepare (which directly affects reachable virtual subsystems like TCMU / target_core_user). It also significantly refactors buffer allocation, page pinning, asynchronous deferred page reclaim, and GPADL lifecycle management across Hyper-V VMBus and netvsc. These logic alterations and error-path cleanups warrant fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/10/07 21:53 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit b46a7f3a76fb605ed8bbd8f5217b7a13200e774b\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Oct 7 21:53:22 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/drivers/hv/Kconfig b/drivers/hv/Kconfig\nindex aa11bcefddf2c..d44dd60fbc237 100644\n--- a/drivers/hv/Kconfig\n+++ b/drivers/hv/Kconfig\n@@ -65,6 +65,17 @@ config HYPERV_VMBUS\n \thelp\n \t  Select this option to enable Hyper-V Vmbus driver.\n \n+config HYPERV_VMBUS_KUNIT_TEST\n+\tbool \"Build Hyper-V VMBus buffer KUnit tests\"\n+\tdepends on HYPERV_VMBUS \u0026\u0026 KUNIT\n+\tdefault KUNIT_ALL_TESTS\n+\thelp\n+\t  Build the vmbus buffer sizing, GPADL lifetime and reclaim KUnit\n+\t  cases into the hv_vmbus object. The cases reach internal helpers\n+\t  that are not exported, so they cannot live in a separate module.\n+\n+\t  If unsure, say N.\n+\n config MSHV_ROOT\n \ttristate \"Microsoft Hyper-V root partition support\"\n \tdepends on HYPERV \u0026\u0026 (X86_64 || ARM64)\ndiff --git a/drivers/hv/Makefile b/drivers/hv/Makefile\nindex 888a748cc7cb9..80d33e9c0e572 100644\n--- a/drivers/hv/Makefile\n+++ b/drivers/hv/Makefile\n@@ -12,6 +12,7 @@ hv_vmbus-y := vmbus_drv.o \\\n \t\t hv.o connection.o channel.o \\\n \t\t channel_mgmt.o ring_buffer.o hv_trace.o\n hv_vmbus-$(CONFIG_HYPERV_TESTING)\t+= hv_debugfs.o\n+hv_vmbus-$(CONFIG_HYPERV_VMBUS_KUNIT_TEST) += vmbus_buffer_test.o\n hv_utils-y := hv_util.o hv_kvp.o hv_snapshot.o hv_utils_transport.o\n mshv_root-y := mshv_root_main.o mshv_synic.o mshv_eventfd.o mshv_irq.o \\\n \t       mshv_root_hv_call.o mshv_portid_table.o mshv_regions.o\ndiff --git a/drivers/hv/channel.c b/drivers/hv/channel.c\nindex 7e4cc6f55237a..c7f3f5c6c0d28 100644\n--- a/drivers/hv/channel.c\n+++ b/drivers/hv/channel.c\n@@ -12,6 +12,8 @@\n #include \u003clinux/sched.h\u003e\n #include \u003clinux/wait.h\u003e\n #include \u003clinux/mm.h\u003e\n+#include \u003clinux/cc_platform.h\u003e\n+#include \u003clinux/overflow.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/log2.h\u003e\n #include \u003clinux/module.h\u003e\n@@ -21,11 +23,378 @@\n #include \u003clinux/set_memory.h\u003e\n #include \u003clinux/vmalloc.h\u003e\n #include \u003clinux/export.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/workqueue.h\u003e\n #include \u003casm/page.h\u003e\n #include \u003casm/mshyperv.h\u003e\n \n #include \"hyperv_vmbus.h\"\n \n+static LIST_HEAD(vmbus_buffer_owners);\n+static DEFINE_MUTEX(vmbus_buffer_owners_lock);\n+static struct workqueue_struct *vmbus_buffer_reclaim_wq;\n+static bool vmbus_buffer_reclaimer_stopping;\n+static atomic64_t vmbus_buffer_owner_sequence = ATOMIC64_INIT(0);\n+\n+/*\n+ * Reclaim scheduling. VMBUS_BUFFER_RECLAIM_SCHEDULE_MS is the delay\n+ * before the first reclaim attempt after ownership state changes;\n+ * it is kept at one jiffy so a completed GPADL teardown frees the\n+ * buffer promptly. VMBUS_BUFFER_RECLAIM_RETRY_MS is the steady-state\n+ * retry while a guest mapping still holds the pages. The workqueue\n+ * is unbound so reclaim never runs in the caller's context, and\n+ * WQ_MEM_RECLAIM so the free path is not blocked by the very\n+ * pressure it is relieving. max_active stays at one: re-encryption\n+ * is serialized and the cost of a second concurrent worker is not\n+ * worth the ordering questions it would raise.\n+ */\n+#define VMBUS_BUFFER_RECLAIM_SCHEDULE_MS\t1\n+#define VMBUS_BUFFER_RECLAIM_RETRY_MS\t\t1000\n+#define VMBUS_BUFFER_RECLAIM_WQ_FLAGS\t\t(WQ_UNBOUND | WQ_MEM_RECLAIM)\n+#define VMBUS_BUFFER_RECLAIM_WQ_MAX_ACTIVE\t1\n+\n+/*\n+ * vmbus_buffer_round_size() and the order-descent helpers are also called\n+ * from vmbus_buffer_test.c, which is built into this same object. They are\n+ * therefore not static; nothing outside hv_vmbus links against them.\n+ */\n+int vmbus_buffer_round_size(u32 size, u32 *rounded_size)\n+{\n+\tif (!size)\n+\t\treturn -EINVAL;\n+\n+\tif (size \u003e U32_MAX - (u32)PAGE_SIZE + 1)\n+\t\treturn -EOVERFLOW;\n+\n+\t*rounded_size = round_up(size, (u32)PAGE_SIZE);\n+\treturn 0;\n+}\n+\n+bool\n+vmbus_needs_shared_pages(bool hv_isolation, bool guest_mem_encrypted,\n+\t\t\t bool confidential)\n+{\n+\treturn !confidential \u0026\u0026 (hv_isolation || guest_mem_encrypted);\n+}\n+\n+unsigned int vmbus_buffer_order(unsigned long remaining,\n+\t\t\t\tunsigned int max_order)\n+{\n+\treturn min_t(unsigned int, max_order, ilog2(remaining));\n+}\n+\n+bool vmbus_buffer_lower_order(unsigned int *order)\n+{\n+\tif (!*order)\n+\t\treturn false;\n+\n+\t(*order)--;\n+\treturn true;\n+}\n+\n+struct page *vmbus_alloc_pages_with_fallback(int nid, gfp_t gfp,\n+\t\t\t\t\t     unsigned int *order,\n+\t\t\t\t\t     vmbus_alloc_pages_fn alloc,\n+\t\t\t\t\t     void *context)\n+{\n+\tstruct page *page;\n+\n+\tdo {\n+\t\tgfp_t try_gfp = gfp;\n+\n+\t\t/*\n+\t\t * Use __GFP_NORETRY | __GFP_NOWARN to avoid OOM-killing,\n+\t\t * but try harder at order 0 since that is the final\n+\t\t * fallback.\n+\t\t * __GFP_COMP stores order information in the page folio.\n+\t\t */\n+\t\tif (*order)\n+\t\t\ttry_gfp |= __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN;\n+\n+\t\tpage = alloc(context, nid, try_gfp, *order);\n+\t\tif (page || !vmbus_buffer_lower_order(order))\n+\t\t\treturn page;\n+\t} while (true);\n+}\n+\n+bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer)\n+{\n+\treturn !buffer-\u003eleak \u0026\u0026 !buffer-\u003egpadl.leak \u0026\u0026\n+\t       !buffer-\u003egpadl.gpadl_handle;\n+}\n+\n+/* Caller holds the owner lock or exclusive custody of this owner. */\n+static void vmbus_buffer_trace_owner(const struct vmbus_buffer_retained *owner,\n+\t\t\t\t     const char *action)\n+{\n+\t/* Bit 0: host uncertainty; bit 1: page state; bit 2: permanent retain. */\n+\tu8 state = owner-\u003ehost_may_own | (owner-\u003eencryption_unknown \u003c\u003c 1) |\n+\t\t   (owner-\u003epermanent_leak \u003c\u003c 2);\n+\n+\ttrace_vmbus_buffer_owner(owner-\u003eowner_id, owner-\u003echannel_id, action,\n+\t\t\t\t owner-\u003esize, owner-\u003epage_cnt, state);\n+}\n+\n+bool\n+vmbus_buffer_owner_can_reclaim(const struct vmbus_buffer_retained *owner)\n+{\n+\treturn owner-\u003ereleased \u0026\u0026 !owner-\u003epermanent_leak \u0026\u0026\n+\t       !owner-\u003eencryption_unknown \u0026\u0026\n+\t       !owner-\u003ehost_may_own;\n+}\n+\n+bool\n+vmbus_buffer_owner_should_schedule(const struct vmbus_buffer_retained *owner,\n+\t\t\t\t   bool stopping, bool queue_live)\n+{\n+\treturn !owner-\u003ework_active \u0026\u0026 !owner-\u003ereclaiming \u0026\u0026\n+\t       vmbus_buffer_owner_can_reclaim(owner) \u0026\u0026 !stopping \u0026\u0026 queue_live;\n+}\n+\n+static void\n+vmbus_buffer_schedule_reclaim_locked(struct vmbus_buffer_retained *owner)\n+{\n+\tif (!vmbus_buffer_owner_should_schedule(owner,\n+\t\t\t\t\t\tvmbus_buffer_reclaimer_stopping,\n+\t\t\t\t\t\tvmbus_buffer_reclaim_wq))\n+\t\treturn;\n+\n+\towner-\u003ework_active = true;\n+\tmod_delayed_work(vmbus_buffer_reclaim_wq, \u0026owner-\u003ereclaim_work,\n+\t\t\t msecs_to_jiffies(VMBUS_BUFFER_RECLAIM_SCHEDULE_MS));\n+}\n+\n+static void\n+vmbus_buffer_update_host_ownership(struct vmbus_buffer_retained *owner,\n+\t\t\t\t   bool host_may_own)\n+{\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\towner-\u003ehost_may_own = host_may_own;\n+\tvmbus_buffer_schedule_reclaim_locked(owner);\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+}\n+\n+/*\n+ * Declared before vmbus_buffer_owner_alloc() hands the callback pointer\n+ * to INIT_DELAYED_WORK(); defined below with the rest of the reclaim\n+ * machinery.\n+ */\n+static void vmbus_buffer_reclaim_work(struct work_struct *work);\n+\n+struct vmbus_buffer_retained *\n+vmbus_buffer_owner_alloc(struct vmbus_channel *channel)\n+{\n+\tstruct vmbus_buffer_retained *owner;\n+\n+\towner = kzalloc_obj(*owner);\n+\tif (!owner)\n+\t\treturn NULL;\n+\n+\tINIT_LIST_HEAD(\u0026owner-\u003elist);\n+\tINIT_DELAYED_WORK(\u0026owner-\u003ereclaim_work, vmbus_buffer_reclaim_work);\n+\towner-\u003echannel_id = channel-\u003elifetime_id;\n+\towner-\u003eowner_id = atomic64_inc_return(\u0026vmbus_buffer_owner_sequence);\n+\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\tif (vmbus_buffer_reclaimer_stopping)\n+\t\tgoto err_unlock;\n+\tif (!vmbus_buffer_reclaim_wq) {\n+\t\tvmbus_buffer_reclaim_wq =\n+\t\t\talloc_workqueue(\"vmbus-buffer-reclaim\",\n+\t\t\t\t\tVMBUS_BUFFER_RECLAIM_WQ_FLAGS,\n+\t\t\t\t\tVMBUS_BUFFER_RECLAIM_WQ_MAX_ACTIVE);\n+\t\tif (!vmbus_buffer_reclaim_wq)\n+\t\t\tgoto err_unlock;\n+\t}\n+\tlist_add_tail(\u0026owner-\u003elist, \u0026vmbus_buffer_owners);\n+\tvmbus_buffer_trace_owner(owner, \"created\");\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\n+\treturn owner;\n+\n+err_unlock:\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\tkfree(owner);\n+\treturn NULL;\n+}\n+\n+static void vmbus_buffer_owner_free(struct vmbus_buffer_retained *owner)\n+{\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\tif (!list_empty(\u0026owner-\u003elist))\n+\t\tlist_del_init(\u0026owner-\u003elist);\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\n+\tkfree(owner);\n+}\n+\n+static void vmbus_buffer_owner_remove(struct vmbus_buffer_retained *owner)\n+{\n+\t/*\n+\t * The owner embeds a delayed_work and its timer may still be\n+\t * armed when an external caller drops the last reference.\n+\t * Freeing the object under an armed timer would let the\n+\t * callback reach freed memory, so stop the timer first. The\n+\t * reclaim work itself must not come through here: it would\n+\t * wait for its own completion.\n+\t */\n+\tcancel_delayed_work_sync(\u0026owner-\u003ereclaim_work);\n+\tvmbus_buffer_trace_owner(owner, \"discarded\");\n+\tvmbus_buffer_owner_free(owner);\n+}\n+\n+bool vmbus_buffer_pages_busy(struct vmbus_buffer_retained *owner)\n+{\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c owner-\u003epage_cnt; i++) {\n+\t\tif (WARN_ON_ONCE(!owner-\u003epages || !owner-\u003epages[i]))\n+\t\t\treturn true;\n+\t\tif (folio_ref_count(page_folio(owner-\u003epages[i])) != 1)\n+\t\t\treturn true;\n+\t}\n+\n+\treturn false;\n+}\n+\n+static void vmbus_buffer_reclaim_work(struct work_struct *work)\n+{\n+\tstruct vmbus_buffer_retained *owner = container_of(to_delayed_work(work),\n+\t\t\t\t\t\t\t\t   struct vmbus_buffer_retained,\n+\t\t\t\t\t\t\t\t   reclaim_work);\n+\tunsigned long delay = msecs_to_jiffies(VMBUS_BUFFER_RECLAIM_RETRY_MS);\n+\tu32 i;\n+\tint ret = 0;\n+\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\t/*\n+\t * A ready owner must still be reclaimable while the workqueue\n+\t * is being destroyed: shutdown re-queues exactly those so they\n+\t * drain before destroy_workqueue() returns. New work is never\n+\t * scheduled past that point because\n+\t * vmbus_buffer_owner_should_schedule() refuses once stopping.\n+\t */\n+\tif (!vmbus_buffer_owner_can_reclaim(owner)) {\n+\t\towner-\u003ework_active = false;\n+\t\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\t\treturn;\n+\t}\n+\n+\tif (vmbus_buffer_pages_busy(owner)) {\n+\t\tif (vmbus_buffer_reclaimer_stopping) {\n+\t\t\t/*\n+\t\t\t * A guest mapping still holds these pages as the\n+\t\t\t * workqueue goes away. Freeing them would be a\n+\t\t\t * use-after-free, so retain and say so.\n+\t\t\t */\n+\t\t\towner-\u003epermanent_leak = true;\n+\t\t\towner-\u003ework_active = false;\n+\t\t\tvmbus_buffer_trace_owner(owner, \"retained\");\n+\t\t} else {\n+\t\t\tmod_delayed_work(vmbus_buffer_reclaim_wq,\n+\t\t\t\t\t \u0026owner-\u003ereclaim_work, delay);\n+\t\t}\n+\t\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\t\treturn;\n+\t}\n+\towner-\u003ereclaiming = true;\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\n+\tif (owner-\u003eneeds_encrypt) {\n+\t\tfor (i = 0; i \u003c owner-\u003echunk_cnt; i++) {\n+\t\t\tstruct page *page = owner-\u003echunks[i];\n+\t\t\tunsigned int order = folio_order(page_folio(page));\n+\n+\t\t\tret = set_memory_encrypted((unsigned long)page_address(page),\n+\t\t\t\t\t\t   1U \u003c\u003c order);\n+\t\t\tif (ret)\n+\t\t\t\tbreak;\n+\t\t}\n+\t} else if (owner-\u003eraw_decrypted) {\n+\t\tret = set_memory_encrypted((unsigned long)owner-\u003eaddr,\n+\t\t\t\t\t   PFN_UP(owner-\u003esize));\n+\t}\n+\n+\tif (ret) {\n+\t\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\t\towner-\u003epermanent_leak = true;\n+\t\towner-\u003ework_active = false;\n+\t\towner-\u003ereclaiming = false;\n+\t\tvmbus_buffer_trace_owner(owner, \"retained\");\n+\t\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\t\tpr_warn_ratelimited(\"VMBus buffer reclaim retained pages after encryption failure: %d\\n\",\n+\t\t\t\t    ret);\n+\t\treturn;\n+\t}\n+\n+\tvmbus_buffer_trace_owner(owner, \"reclaimed\");\n+\tif (owner-\u003eaddr) {\n+\t\tif (owner-\u003echunks)\n+\t\t\tvunmap(owner-\u003eaddr);\n+\t\telse\n+\t\t\tvfree(owner-\u003eaddr);\n+\t}\n+\n+\tfor (i = 0; i \u003c owner-\u003echunk_cnt; i++) {\n+\t\tstruct page *page = owner-\u003echunks[i];\n+\t\tunsigned int order = folio_order(page_folio(page));\n+\n+\t\t__free_pages(page, order);\n+\t}\n+\n+\tkvfree(owner-\u003echunks);\n+\tkvfree(owner-\u003epages);\n+\tvmbus_buffer_owner_free(owner);\n+}\n+\n+/* Caller holds the owner lock or exclusive custody of this owner. */\n+void vmbus_buffer_owner_drain(struct vmbus_buffer_retained *owner,\n+\t\t\t      struct workqueue_struct *wq)\n+{\n+\tif (!cancel_delayed_work(\u0026owner-\u003ereclaim_work))\n+\t\treturn;\n+\n+\towner-\u003ework_active = false;\n+\tif (wq \u0026\u0026 vmbus_buffer_owner_can_reclaim(owner)) {\n+\t\towner-\u003ework_active = true;\n+\t\tmod_delayed_work(wq, \u0026owner-\u003ereclaim_work, 0);\n+\t}\n+}\n+\n+void vmbus_buffer_reclaimer_shutdown(void)\n+{\n+\tstruct workqueue_struct *wq;\n+\tstruct vmbus_buffer_retained *owner;\n+\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\tvmbus_buffer_reclaimer_stopping = true;\n+\twq = vmbus_buffer_reclaim_wq;\n+\tvmbus_buffer_reclaim_wq = NULL;\n+\n+\t/*\n+\t * destroy_workqueue() drains work that is queued or already\n+\t * running. A delayed_work still waiting on its timer is not\n+\t * on the workqueue yet, so cancel those timers here or they\n+\t * fire against a workqueue that is about to be freed.\n+\t * cancel_delayed_work() rather than _sync: reclaim work that\n+\t * is already running blocks on this same lock, and\n+\t * destroy_workqueue() below waits for it to finish.\n+\t *\n+\t * An owner that is already ready to reclaim must not be lost\n+\t * with its cancelled timer. Requeue only work that was actually\n+\t * cancelled: a running callback owns its embedded work item and\n+\t * may free the owner before a second queued execution can run.\n+\t * destroy_workqueue() drains that running callback itself.\n+\t */\n+\tlist_for_each_entry(owner, \u0026vmbus_buffer_owners, list)\n+\t\tvmbus_buffer_owner_drain(owner, wq);\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\n+\tif (wq)\n+\t\tdestroy_workqueue(wq);\n+}\n+\n /*\n  * hv_gpadl_size - Return the real size of a gpadl, the size that Hyper-V uses\n  *\n@@ -42,7 +411,6 @@ static inline u32 hv_gpadl_size(enum hv_gpadl_type type, u32 size)\n {\n \tswitch (type) {\n \tcase HV_GPADL_BUFFER:\n-\tcase HV_GPADL_BUFFER_DECRYPTED:\n \t\treturn size;\n \tcase HV_GPADL_RING:\n \t\t/* The size of a ringbuffer must be page-aligned */\n@@ -103,7 +471,6 @@ static inline u64 hv_gpadl_hvpfn(enum hv_gpadl_type type, void *kbuffer,\n \n \tswitch (type) {\n \tcase HV_GPADL_BUFFER:\n-\tcase HV_GPADL_BUFFER_DECRYPTED:\n \t\tbreak;\n \tcase HV_GPADL_RING:\n \t\tif (i == 0)\n@@ -154,17 +521,15 @@ EXPORT_SYMBOL_GPL(vmbus_setevent);\n /* vmbus_free_ring - drop mapping of ring buffer */\n void vmbus_free_ring(struct vmbus_channel *channel)\n {\n+\tstruct vmbus_buffer *buffer = \u0026channel-\u003eringbuffer;\n+\n \thv_ringbuffer_cleanup(\u0026channel-\u003eoutbound);\n \thv_ringbuffer_cleanup(\u0026channel-\u003einbound);\n \n-\tif (channel-\u003eringbuffer_page) {\n-\t\t/* In a CoCo VM leak the memory if it didn't get re-encrypted */\n-\t\tif (!channel-\u003eringbuffer_gpadlhandle.decrypted)\n-\t\t\t__free_pages(channel-\u003eringbuffer_page,\n-\t\t\t     get_order(channel-\u003eringbuffer_pagecount\n-\t\t\t\t       \u003c\u003c PAGE_SHIFT));\n-\t\tchannel-\u003eringbuffer_page = NULL;\n-\t}\n+\tif (!buffer-\u003eaddr)\n+\t\treturn;\n+\n+\tvmbus_release_buffer(buffer);\n }\n EXPORT_SYMBOL_GPL(vmbus_free_ring);\n \n@@ -172,25 +537,21 @@ EXPORT_SYMBOL_GPL(vmbus_free_ring);\n int vmbus_alloc_ring(struct vmbus_channel *newchannel,\n \t\t     u32 send_size, u32 recv_size)\n {\n-\tstruct page *page;\n-\tint order;\n+\tstruct vmbus_buffer *buffer = \u0026newchannel-\u003eringbuffer;\n+\tu32 size;\n+\tint ret;\n \n-\tif (send_size % PAGE_SIZE || recv_size % PAGE_SIZE)\n+\tif (!send_size || !recv_size ||\n+\t    send_size % PAGE_SIZE || recv_size % PAGE_SIZE ||\n+\t    check_add_overflow(send_size, recv_size, \u0026size))\n \t\treturn -EINVAL;\n \n-\t/* Allocate the ring buffer */\n-\torder = get_order(send_size + recv_size);\n-\tpage = alloc_pages_node(cpu_to_node(newchannel-\u003etarget_cpu),\n-\t\t\t\tGFP_KERNEL|__GFP_ZERO, order);\n-\n-\tif (!page)\n-\t\tpage = alloc_pages(GFP_KERNEL|__GFP_ZERO, order);\n-\n-\tif (!page)\n-\t\treturn -ENOMEM;\n+\tret = vmbus_alloc_buffer_owned(newchannel, size,\n+\t\t\t\t       newchannel-\u003eco_ring_buffer, buffer);\n+\tif (ret)\n+\t\treturn ret;\n \n-\tnewchannel-\u003eringbuffer_page = page;\n-\tnewchannel-\u003eringbuffer_pagecount = (send_size + recv_size) \u003e\u003e PAGE_SHIFT;\n+\tnewchannel-\u003eringbuffer_pagecount = size \u003e\u003e PAGE_SHIFT;\n \tnewchannel-\u003eringbuffer_send_offset = send_size \u003e\u003e PAGE_SHIFT;\n \n \treturn 0;\n@@ -440,20 +801,106 @@ static void vmbus_free_channel_msginfo(struct vmbus_channel_msginfo *msginfo)\n  *              should be 0 for BUFFER type gpadl\n  * @gpadl_handle: some funky thing\n  */\n+static int vmbus_gpadl_post_real(void *context, void *buffer,\n+\t\t\t\t size_t buflen, bool can_sleep)\n+{\n+\t(void)context;\n+\treturn vmbus_post_msg(buffer, buflen, can_sleep);\n+}\n+\n+int vmbus_post_gpadl_messages(struct vmbus_channel_msginfo *msginfo,\n+\t\t\t      u32 gpadl, bool *posted,\n+\t\t\t      vmbus_gpadl_post_fn post_msg,\n+\t\t\t      void *context)\n+{\n+\tstruct vmbus_channel_gpadl_header *gpadl_header;\n+\tstruct vmbus_channel_msginfo *submsginfo;\n+\tstruct list_head *curr;\n+\tint ret;\n+\n+\tgpadl_header = (struct vmbus_channel_gpadl_header *)msginfo-\u003emsg;\n+\tgpadl_header-\u003eheader.msgtype = CHANNELMSG_GPADL_HEADER;\n+\tgpadl_header-\u003egpadl = gpadl;\n+\n+\t/* A failed post may still have reached the host. */\n+\t*posted = true;\n+\tret = post_msg(context, gpadl_header,\n+\t\t       msginfo-\u003emsgsize - sizeof(*msginfo), true);\n+\ttrace_vmbus_establish_gpadl_header(gpadl_header, ret);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tlist_for_each(curr, \u0026msginfo-\u003esubmsglist) {\n+\t\tstruct vmbus_channel_gpadl_body *gpadl_body;\n+\n+\t\tsubmsginfo = list_entry(curr, struct vmbus_channel_msginfo,\n+\t\t\t\t\tmsglistentry);\n+\t\tgpadl_body = (struct vmbus_channel_gpadl_body *)submsginfo-\u003emsg;\n+\t\tgpadl_body-\u003eheader.msgtype = CHANNELMSG_GPADL_BODY;\n+\t\tgpadl_body-\u003egpadl = gpadl;\n+\n+\t\tret = post_msg(context, gpadl_body,\n+\t\t\t       submsginfo-\u003emsgsize - sizeof(*submsginfo), true);\n+\t\ttrace_vmbus_establish_gpadl_body(gpadl_body, ret);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+int vmbus_gpadl_response_status(u32 creation_status, bool rescind,\n+\t\t\t\tbool *posted)\n+{\n+\tif (creation_status) {\n+\t\t*posted = false;\n+\t\treturn -EDQUOT;\n+\t}\n+\tif (rescind)\n+\t\treturn -ENODEV;\n+\n+\t/* A response resolved the request; a successful GPADL is tracked by handle. */\n+\t*posted = false;\n+\treturn 0;\n+}\n+\n+int vmbus_post_gpadl_teardown(u32 child_relid,\n+\t\t\t      struct vmbus_channel_gpadl_teardown *msg,\n+\t\t\t      u32 gpadl,\n+\t\t\t      vmbus_gpadl_post_fn post_msg,\n+\t\t\t      void *context)\n+{\n+\tint ret;\n+\n+\tmsg-\u003eheader.msgtype = CHANNELMSG_GPADL_TEARDOWN;\n+\tmsg-\u003echild_relid = child_relid;\n+\tmsg-\u003egpadl = gpadl;\n+\n+\tret = post_msg(context, msg, sizeof(*msg), true);\n+\ttrace_vmbus_teardown_gpadl(msg, ret);\n+\n+\treturn ret;\n+}\n+\n static int __vmbus_establish_gpadl(struct vmbus_channel *channel,\n-\t\t\t\t   enum hv_gpadl_type type, void *kbuffer,\n-\t\t\t\t   u32 size, u32 send_offset,\n-\t\t\t\t   struct vmbus_gpadl *gpadl)\n+\t\t\t\t   enum hv_gpadl_type type,\n+\t\t\t\t   struct vmbus_buffer *buffer,\n+\t\t\t\t   u32 send_offset, bool memory_prepared)\n {\n \tstruct vmbus_channel_gpadl_header *gpadlmsg;\n-\tstruct vmbus_channel_gpadl_body *gpadl_body;\n \tstruct vmbus_channel_msginfo *msginfo = NULL;\n-\tstruct vmbus_channel_msginfo *submsginfo;\n-\tstruct list_head *curr;\n+\tstruct vmbus_buffer_retained *owner = buffer-\u003eowner;\n+\tstruct vmbus_gpadl *gpadl = \u0026buffer-\u003egpadl;\n+\tvoid *kbuffer = buffer-\u003eaddr;\n+\tu32 size = buffer-\u003esize;\n \tu32 next_gpadl_handle;\n+\tu32 creation_status;\n \tunsigned long flags;\n+\tbool posted = false;\n \tint ret = 0;\n \n+\tgpadl-\u003eleak = false;\n+\n \tnext_gpadl_handle =\n \t\t(atomic_inc_return(\u0026vmbus_connection.next_gpadl_handle) - 1);\n \n@@ -463,9 +910,9 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,\n \t\treturn ret;\n \t}\n \n-\tgpadl-\u003edecrypted = !((channel-\u003eco_external_memory \u0026\u0026 type == HV_GPADL_BUFFER) ||\n-\t\t(channel-\u003eco_ring_buffer \u0026\u0026 type == HV_GPADL_RING) ||\n-\t\t(type == HV_GPADL_BUFFER_DECRYPTED));\n+\tgpadl-\u003edecrypted = !memory_prepared \u0026\u0026\n+\t\t!((channel-\u003eco_external_memory \u0026\u0026 type == HV_GPADL_BUFFER) ||\n+\t\t  (channel-\u003eco_ring_buffer \u0026\u0026 type == HV_GPADL_RING));\n \tif (gpadl-\u003edecrypted) {\n \t\t/*\n \t\t * The \"decrypted\" flag being true assumes that set_memory_decrypted() succeeds.\n@@ -479,6 +926,9 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,\n \t\t\tdev_warn(\u0026channel-\u003edevice_obj-\u003edevice,\n \t\t\t\t\"Failed to set host visibility for new GPADL %d.\\n\",\n \t\t\t\tret);\n+\t\t\tif (owner)\n+\t\t\t\towner-\u003eencryption_unknown = true;\n+\t\t\tgpadl-\u003eleak = true;\n \t\t\tvmbus_free_channel_msginfo(msginfo);\n \t\t\treturn ret;\n \t\t}\n@@ -504,45 +954,22 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,\n \t\tgoto cleanup;\n \t}\n \n-\tret = vmbus_post_msg(gpadlmsg, msginfo-\u003emsgsize -\n-\t\t\t     sizeof(*msginfo), true);\n-\n-\ttrace_vmbus_establish_gpadl_header(gpadlmsg, ret);\n-\n-\tif (ret != 0)\n+\tret = vmbus_post_gpadl_messages(msginfo, next_gpadl_handle, \u0026posted,\n+\t\t\t\t\tvmbus_gpadl_post_real, NULL);\n+\tif (posted \u0026\u0026 owner)\n+\t\tvmbus_buffer_update_host_ownership(owner, true);\n+\tif (ret)\n \t\tgoto cleanup;\n \n-\tlist_for_each(curr, \u0026msginfo-\u003esubmsglist) {\n-\t\tsubmsginfo = (struct vmbus_channel_msginfo *)curr;\n-\t\tgpadl_body =\n-\t\t\t(struct vmbus_channel_gpadl_body *)submsginfo-\u003emsg;\n-\n-\t\tgpadl_body-\u003eheader.msgtype =\n-\t\t\tCHANNELMSG_GPADL_BODY;\n-\t\tgpadl_body-\u003egpadl = next_gpadl_handle;\n-\n-\t\tret = vmbus_post_msg(gpadl_body,\n-\t\t\t\t     submsginfo-\u003emsgsize - sizeof(*submsginfo),\n-\t\t\t\t     true);\n-\n-\t\ttrace_vmbus_establish_gpadl_body(gpadl_body, ret);\n-\n-\t\tif (ret != 0)\n-\t\t\tgoto cleanup;\n-\n-\t}\n \twait_for_completion(\u0026msginfo-\u003ewaitevent);\n \n-\tif (msginfo-\u003eresponse.gpadl_created.creation_status != 0) {\n-\t\tpr_err(\"Failed to establish GPADL: err = 0x%x\\n\",\n-\t\t       msginfo-\u003eresponse.gpadl_created.creation_status);\n-\n-\t\tret = -EDQUOT;\n-\t\tgoto cleanup;\n-\t}\n-\n-\tif (channel-\u003erescind) {\n-\t\tret = -ENODEV;\n+\tcreation_status = msginfo-\u003eresponse.gpadl_created.creation_status;\n+\tret = vmbus_gpadl_response_status(creation_status, channel-\u003erescind,\n+\t\t\t\t\t  \u0026posted);\n+\tif (ret) {\n+\t\tif (creation_status)\n+\t\t\tpr_err(\"Failed to establish GPADL: err = 0x%x\\n\",\n+\t\t\t       creation_status);\n \t\tgoto cleanup;\n \t}\n \n@@ -550,7 +977,8 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,\n \tgpadl-\u003egpadl_handle = gpadlmsg-\u003egpadl;\n \tgpadl-\u003ebuffer = kbuffer;\n \tgpadl-\u003esize = size;\n-\n+\tif (owner)\n+\t\tvmbus_buffer_update_host_ownership(owner, true);\n \n cleanup:\n \tspin_lock_irqsave(\u0026vmbus_connection.channelmsg_lock, flags);\n@@ -559,34 +987,44 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,\n \n \tvmbus_free_channel_msginfo(msginfo);\n \n-\tif (ret) {\n-\t\t/*\n-\t\t * If set_memory_encrypted() fails, the decrypted flag is\n-\t\t * left as true so the memory is leaked instead of being\n-\t\t * put back on the free list.\n-\t\t */\n-\t\tif (gpadl-\u003edecrypted) {\n-\t\t\tif (!set_memory_encrypted((unsigned long)kbuffer, PFN_UP(size)))\n-\t\t\t\tgpadl-\u003edecrypted = false;\n-\t\t}\n-\t}\n+\tif (ret \u0026\u0026 posted)\n+\t\tgpadl-\u003eleak = true;\n+\telse if (ret \u0026\u0026 owner)\n+\t\tvmbus_buffer_update_host_ownership(owner, false);\n \n \treturn ret;\n }\n \n /*\n- * vmbus_establish_gpadl - Establish a GPADL for the specified buffer\n+ * vmbus_establish_gpadl_owned - Establish a GPADL for an owned buffer whose\n+ * memory has already been prepared by the allocator.\n  *\n  * @channel: a channel\n- * @kbuffer: from kmalloc or vmalloc\n- * @size: page-size multiple\n- * @gpadl: output gpadl\n+ * @buffer: allocated by vmbus_alloc_buffer_owned()\n  */\n+int vmbus_establish_gpadl_owned(struct vmbus_channel *channel,\n+\t\t\t\tstruct vmbus_buffer *buffer)\n+{\n+\treturn __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, buffer,\n+\t\t\t\t       0U, true);\n+}\n+EXPORT_SYMBOL_GPL(vmbus_establish_gpadl_owned);\n+\n+/* Preserve the established exported API for non-owned caller buffers. */\n int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,\n \t\t\t  u32 size, struct vmbus_gpadl *gpadl)\n {\n-\treturn __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, kbuffer, size,\n-\t\t\t\t       0U, gpadl);\n+\tstruct vmbus_buffer buffer = {\n+\t\t.addr = kbuffer,\n+\t\t.size = size,\n+\t\t.gpadl = *gpadl,\n+\t};\n+\tint ret;\n+\n+\tret = __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, \u0026buffer,\n+\t\t\t\t      0U, false);\n+\t*gpadl = buffer.gpadl;\n+\treturn ret;\n }\n EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);\n \n@@ -600,13 +1038,23 @@ EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);\n  * @gpadl: output gpadl\n  *\n  * The caller is responsible for re-encrypting the buffer before freeing it.\n+ * Ownership of the backing pages stays with the caller's vmbus_buffer.\n  */\n int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,\n-\t\t\t\t\t   void *kbuffer, u32 size,\n-\t\t\t\t\t   struct vmbus_gpadl *gpadl)\n+\t\t\t\t\t  void *kbuffer, u32 size,\n+\t\t\t\t\t  struct vmbus_gpadl *gpadl)\n {\n-\treturn __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER_DECRYPTED,\n-\t\t\t\t       kbuffer, size, 0U, gpadl);\n+\tstruct vmbus_buffer buffer = {\n+\t\t.addr = kbuffer,\n+\t\t.size = size,\n+\t\t.gpadl = *gpadl,\n+\t};\n+\tint ret;\n+\n+\tret = __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, \u0026buffer,\n+\t\t\t\t      0U, true);\n+\t*gpadl = buffer.gpadl;\n+\treturn ret;\n }\n EXPORT_SYMBOL_GPL(vmbus_establish_gpadl_caller_decrypted);\n \n@@ -632,7 +1080,8 @@ void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt)\n \t\treturn;\n \t}\n \n-\tvunmap(addr);\n+\tif (addr)\n+\t\tvunmap(addr);\n \n \tfor (i = 0; i \u003c chunk_cnt; i++) {\n \t\tunsigned long vaddr =\n@@ -648,14 +1097,162 @@ void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt)\n }\n EXPORT_SYMBOL_GPL(vmbus_free_buffer);\n \n+/* Retain backing until the host and any guest mappings have released it. */\n+void vmbus_release_buffer(struct vmbus_buffer *buffer)\n+{\n+\tstruct vmbus_buffer_retained *owner = buffer-\u003eowner;\n+\n+\tif (!buffer-\u003eaddr \u0026\u0026 !buffer-\u003echunks \u0026\u0026 !buffer-\u003epages) {\n+\t\tif (owner)\n+\t\t\tvmbus_buffer_owner_remove(owner);\n+\t\tmemset(buffer, 0, sizeof(*buffer));\n+\t\treturn;\n+\t}\n+\n+\tif (!owner) {\n+\t\tif (vmbus_buffer_should_free(buffer)) {\n+\t\t\tif (buffer-\u003echunks)\n+\t\t\t\tvmbus_free_buffer(buffer-\u003eaddr, buffer-\u003echunks,\n+\t\t\t\t\t\t  buffer-\u003echunk_cnt);\n+\t\t\telse\n+\t\t\t\tvfree(buffer-\u003eaddr);\n+\t\t} else {\n+\t\t\tpr_warn_ratelimited(\"VMBus buffer has no ownership record; retaining backing pages\\n\");\n+\t\t}\n+\t\tmemset(buffer, 0, sizeof(*buffer));\n+\t\treturn;\n+\t}\n+\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\towner-\u003eaddr = buffer-\u003eaddr;\n+\towner-\u003echunks = buffer-\u003echunks;\n+\towner-\u003epages = buffer-\u003epages;\n+\towner-\u003echunk_cnt = buffer-\u003echunk_cnt;\n+\towner-\u003epage_cnt = buffer-\u003epage_cnt;\n+\towner-\u003esize = buffer-\u003esize;\n+\towner-\u003ehost_may_own |= buffer-\u003egpadl.gpadl_handle ||\n+\t\t\t       buffer-\u003egpadl.leak;\n+\towner-\u003eraw_decrypted |= buffer-\u003egpadl.decrypted;\n+\towner-\u003epermanent_leak |= buffer-\u003eleak;\n+\towner-\u003ereleased = true;\n+\tvmbus_buffer_trace_owner(owner, \"released\");\n+\tif (!vmbus_buffer_owner_can_reclaim(owner))\n+\t\tvmbus_buffer_trace_owner(owner, \"retained\");\n+\n+\tmemset(buffer, 0, sizeof(*buffer));\n+\tvmbus_buffer_schedule_reclaim_locked(owner);\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+}\n+EXPORT_SYMBOL_GPL(vmbus_release_buffer);\n+\n /**\n- * vmbus_alloc_buffer - allocate a host-visible, virtually-contiguous buffer.\n+ * vmbus_buffer_pin_pages - snapshot a buffer's pages and hold references\n+ * @buffer: buffer whose pages the caller is about to map\n+ * @pin: out parameter filled entirely under the owners lock\n+ *\n+ * Take a reference on every page of @buffer and fill @pin with the page\n+ * array, the page count and the mapping-protection state that describe\n+ * them. The references close the window between the snapshot and the\n+ * point where a new mapping holds its own: the reclaim worker refuses to\n+ * free pages whose folio reference count is above one, and refuses to\n+ * start at all once it has begun reclaiming. Call\n+ * vmbus_buffer_unpin_pages() after the mapping holds its own references.\n+ *\n+ * Every field of @pin is read under vmbus_buffer_owners_lock so the\n+ * caller never has to look at @buffer again. In particular @pin-\u003edecrypted\n+ * is the protection state of the pages being pinned, not of whatever\n+ * @buffer looks like after a concurrent vmbus_release_buffer() has\n+ * cleared it.\n+ *\n+ * Return: 0 on success, -ENODEV if the pages are gone or reclaim\n+ * has already taken ownership of them.\n+ */\n+int vmbus_buffer_pin_pages(struct vmbus_buffer *buffer,\n+\t\t\t   struct vmbus_buffer_pin *pin)\n+{\n+\tstruct vmbus_buffer_retained *owner;\n+\tu32 i;\n+\n+\t/*\n+\t * The owner and page array are published and cleared under\n+\t * vmbus_buffer_owners_lock (see vmbus_release_buffer()). Reading\n+\t * either outside that lock lets a concurrent release free the array\n+\t * while this loop still walks it.\n+\t */\n+\tmutex_lock(\u0026vmbus_buffer_owners_lock);\n+\towner = buffer-\u003eowner;\n+\tif (!buffer-\u003epages || !buffer-\u003epage_cnt) {\n+\t\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\t\treturn -ENODEV;\n+\t}\n+\n+\tif (owner \u0026\u0026 (owner-\u003ereclaiming || owner-\u003epermanent_leak)) {\n+\t\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\t\treturn -ENODEV;\n+\t}\n+\n+\tfor (i = 0; i \u003c buffer-\u003epage_cnt; i++) {\n+\t\tif (WARN_ON_ONCE(!buffer-\u003epages[i])) {\n+\t\t\twhile (i--)\n+\t\t\t\tput_page(buffer-\u003epages[i]);\n+\t\t\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\t\t\treturn -ENODEV;\n+\t\t}\n+\t\tget_page(buffer-\u003epages[i]);\n+\t}\n+\n+\tpin-\u003epages = buffer-\u003epages;\n+\tpin-\u003epage_count = buffer-\u003epage_cnt;\n+\t/*\n+\t * Only the shared-page path populates the chunk array, and that is\n+\t * the path that decrypts each chunk before mapping it. Read it here\n+\t * so the protection state cannot disagree with the pages pinned.\n+\t */\n+\tpin-\u003edecrypted = !!buffer-\u003echunks;\n+\tmutex_unlock(\u0026vmbus_buffer_owners_lock);\n+\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_GPL(vmbus_buffer_pin_pages);\n+\n+/**\n+ * vmbus_buffer_unpin_pages - drop references taken by vmbus_buffer_pin_pages\n+ * @pin: pin filled by vmbus_buffer_pin_pages(), or NULL\n+ *\n+ * Idempotent: a pin that has already been released, or a NULL pin, is a\n+ * no-op. Release is one-shot because a VMA can be established and then\n+ * torn down, and the abandon path must not put the same pages twice.\n+ */\n+void vmbus_buffer_unpin_pages(struct vmbus_buffer_pin *pin)\n+{\n+\tunsigned long i;\n+\n+\tif (!pin || !pin-\u003epages)\n+\t\treturn;\n+\n+\tfor (i = 0; i \u003c pin-\u003epage_count; i++)\n+\t\tput_page(pin-\u003epages[i]);\n+\tpin-\u003epages = NULL;\n+\tpin-\u003epage_count = 0;\n+}\n+EXPORT_SYMBOL_GPL(vmbus_buffer_unpin_pages);\n+\n+static struct page *vmbus_alloc_pages_node(void *context, int nid,\n+\t\t\t\t\t   gfp_t gfp,\n+\t\t\t\t\t   unsigned int order)\n+{\n+\t(void)context;\n+\treturn alloc_pages_node(nid, gfp, order);\n+}\n+\n+/**\n+ * vmbus_alloc_buffer_owned - allocate a host-visible, virtually-contiguous\n+ * buffer with VMBus-managed backing-page lifetime.\n  *\n  * @channel: the channel the buffer will be attached to\n  * @size: requested buffer size in bytes (will be rounded up to PAGE_SIZE)\n- * @chunks_out: on success, set to the array of underlying chunks, or NULL when\n- *              the buffer was allocated with vzalloc()\n- * @chunk_cnt_out: on success, set to the number of chunks\n+ * @confidential: keep the buffer private to the guest\n+ * @buffer: output descriptor that owns the allocation and its backing pages\n  *\n  * Buffers not requiring decryption are allocated with vzalloc().\n  *\n@@ -665,66 +1262,88 @@ EXPORT_SYMBOL_GPL(vmbus_free_buffer);\n  * host-visible via set_memory_decrypted() on its direct-map address, then all\n  * chunks are combined into a virtually-contiguous range via vmap().\n  *\n- * Return: the buffer's virtual address, or NULL on failure.\n+ * Return: 0 on success, or a negative error code.\n  */\n-void *vmbus_alloc_buffer(struct vmbus_channel *channel,\n-\t\t\t u32 size,\n-\t\t\t struct page ***chunks_out,\n-\t\t\t u32 *chunk_cnt_out)\n+int vmbus_alloc_buffer_owned(struct vmbus_channel *channel, u32 size,\n+\t\t\t     bool confidential, struct vmbus_buffer *buffer)\n {\n-\tunsigned long nr_pages = PFN_UP(size);\n-\tunsigned long remaining = nr_pages;\n+\tu32 rounded_size;\n+\tunsigned long nr_pages;\n+\tunsigned long remaining;\n \tunsigned long page_idx = 0;\n-\tstruct page **chunks = NULL;\n-\tstruct page **pages = NULL;\n-\tint order = MAX_PAGE_ORDER;\n-\tu32 chunk_cnt = 0;\n-\tvoid *addr;\n+\tstruct vmbus_buffer_retained *owner;\n+\tunsigned int order = MAX_PAGE_ORDER;\n+\tbool hv_isolation;\n+\tbool guest_mem_encrypted;\n \tu32 i;\n \tint ret;\n \n-\t*chunks_out = NULL;\n-\t*chunk_cnt_out = 0;\n+\tmemset(buffer, 0, sizeof(*buffer));\n \n-\tif (!nr_pages)\n-\t\treturn NULL;\n+\tret = vmbus_buffer_round_size(size, \u0026rounded_size);\n+\tif (ret)\n+\t\treturn ret;\n+\tnr_pages = rounded_size \u003e\u003e PAGE_SHIFT;\n+\tremaining = nr_pages;\n+\towner = vmbus_buffer_owner_alloc(channel);\n+\tif (!owner)\n+\t\treturn -ENOMEM;\n+\tbuffer-\u003eowner = owner;\n+\tbuffer-\u003esize = rounded_size;\n+\towner-\u003esize = rounded_size;\n+\thv_isolation = hv_is_isolation_supported();\n+\tguest_mem_encrypted = cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT);\n \n \t/* If the buffer does not need to be decrypted, just use vzalloc() */\n-\tif (!hv_is_isolation_supported() || channel-\u003eco_external_memory)\n-\t\treturn vzalloc(nr_pages \u003c\u003c PAGE_SHIFT);\n+\tif (!vmbus_needs_shared_pages(hv_isolation, guest_mem_encrypted,\n+\t\t\t\t      confidential)) {\n+\t\tbuffer-\u003eaddr = vzalloc(rounded_size);\n+\t\tif (!buffer-\u003eaddr) {\n+\t\t\tvmbus_release_buffer(buffer);\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t\tbuffer-\u003epages = kvcalloc(nr_pages, sizeof(*buffer-\u003epages), GFP_KERNEL);\n+\t\tif (!buffer-\u003epages) {\n+\t\t\tvmbus_release_buffer(buffer);\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t\tfor (page_idx = 0; page_idx \u003c nr_pages; page_idx++)\n+\t\t\tbuffer-\u003epages[page_idx] =\n+\t\t\t\tvmalloc_to_page(buffer-\u003eaddr +\n+\t\t\t\t\t\t(page_idx \u003c\u003c PAGE_SHIFT));\n+\t\tbuffer-\u003epage_cnt = nr_pages;\n+\t\treturn 0;\n+\t}\n \n \t/* Worst case: every chunk is a single page. */\n-\tchunks = kvmalloc_objs(*chunks, nr_pages, GFP_KERNEL | __GFP_ZERO);\n-\tif (!chunks)\n+\tbuffer-\u003echunks = kvmalloc_array(nr_pages, sizeof(*buffer-\u003echunks),\n+\t\t\t\t\tGFP_KERNEL | __GFP_ZERO);\n+\tif (!buffer-\u003echunks)\n \t\tgoto err;\n \n-\tpages = kvmalloc_objs(*pages, nr_pages);\n-\tif (!pages)\n+\tbuffer-\u003epages = kvmalloc_array(nr_pages, sizeof(*buffer-\u003epages), GFP_KERNEL);\n+\tif (!buffer-\u003epages)\n \t\tgoto err;\n \n \twhile (remaining) {\n \t\tstruct page *page;\n \t\tgfp_t gfp;\n+\t\tint nid;\n \n-\t\torder = min(order, ilog2(remaining));\n+\t\torder = vmbus_buffer_order(remaining, order);\n \n-\t\t/*\n-\t\t * Use __GFP_NORETRY | __GFP_NOWARN to avoid OOM-killing,\n-\t\t * but try harder at order 0 since that is the final\n-\t\t * fallback.\n-\t\t * __GFP_COMP stores order information in the page folio.\n-\t\t */\n \t\tgfp = GFP_KERNEL | __GFP_ZERO;\n-\t\tif (order)\n-\t\t\tgfp |= __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN;\n-\n-\t\tpage = alloc_pages_node(cpu_to_node(channel-\u003etarget_cpu),\n-\t\t\t\t\tgfp, order);\n-\t\tif (!page) {\n-\t\t\tif (!order--)\n-\t\t\t\tgoto err;\n-\t\t\tcontinue;\n-\t\t}\n+\n+\t\tnid = cpu_to_node(channel-\u003etarget_cpu);\n+\t\tpage = vmbus_alloc_pages_with_fallback(nid, gfp, \u0026order,\n+\t\t\t\t\t\t       vmbus_alloc_pages_node, NULL);\n+\t\tif (!page)\n+\t\t\tgoto err;\n+\n+\t\tbuffer-\u003echunks[buffer-\u003echunk_cnt++] = page;\n+\t\tfor (i = 0; i \u003c (1U \u003c\u003c order); i++)\n+\t\t\tbuffer-\u003epages[page_idx++] = page + i;\n+\t\tbuffer-\u003epage_cnt = page_idx;\n \n \t\tret = set_memory_decrypted((unsigned long)page_address(page),\n \t\t\t\t\t   1U \u003c\u003c order);\n@@ -733,32 +1352,57 @@ void *vmbus_alloc_buffer(struct vmbus_channel *channel,\n \t\t\t * set_memory_decrypted() failed; the page state is\n \t\t\t * unknown so it must be leaked rather than freed.\n \t\t\t */\n+\t\t\towner-\u003eencryption_unknown = true;\n \t\t\tgoto err;\n \t\t}\n-\n-\t\tchunks[chunk_cnt++] = page;\n-\n-\t\tfor (i = 0; i \u003c (1U \u003c\u003c order); i++)\n-\t\t\tpages[page_idx++] = page + i;\n+\t\towner-\u003eneeds_encrypt = true;\n \n \t\tremaining -= 1U \u003c\u003c order;\n \t}\n \n-\taddr = vmap(pages, nr_pages, VM_MAP, pgprot_decrypted(PAGE_KERNEL));\n-\tif (!addr)\n+\tbuffer-\u003eaddr = vmap(buffer-\u003epages, nr_pages, VM_MAP,\n+\t\t\t    pgprot_decrypted(PAGE_KERNEL));\n+\tif (!buffer-\u003eaddr)\n \t\tgoto err;\n \n-\tmemset(addr, 0, nr_pages \u003c\u003c PAGE_SHIFT);\n-\n-\tkvfree(pages);\n-\t*chunks_out = chunks;\n-\t*chunk_cnt_out = chunk_cnt;\n-\treturn addr;\n+\tmemset(buffer-\u003eaddr, 0, rounded_size);\n+\treturn 0;\n \n err:\n-\tkvfree(pages);\n-\tvmbus_free_buffer(NULL, chunks, chunk_cnt);\n-\treturn NULL;\n+\tvmbus_release_buffer(buffer);\n+\treturn -ENOMEM;\n+}\n+EXPORT_SYMBOL_GPL(vmbus_alloc_buffer_owned);\n+\n+/*\n+ * vmbus_alloc_buffer - compatibility allocator for callers managing lifetime.\n+ * New callers that need retained GPADL and mmap ownership should use\n+ * vmbus_alloc_buffer_owned().\n+ */\n+void *vmbus_alloc_buffer(struct vmbus_channel *channel, u32 size,\n+\t\t\t struct page ***chunks_out, u32 *chunk_cnt_out)\n+{\n+\tstruct vmbus_buffer buffer = {};\n+\tvoid *addr;\n+\tint ret;\n+\n+\tif (!chunks_out || !chunk_cnt_out)\n+\t\treturn NULL;\n+\n+\t*chunks_out = NULL;\n+\t*chunk_cnt_out = 0;\n+\tret = vmbus_alloc_buffer_owned(channel, size,\n+\t\t\t\t       channel-\u003eco_external_memory, \u0026buffer);\n+\tif (ret)\n+\t\treturn NULL;\n+\n+\taddr = buffer.addr;\n+\t*chunks_out = buffer.chunks;\n+\t*chunk_cnt_out = buffer.chunk_cnt;\n+\tkvfree(buffer.pages);\n+\tvmbus_buffer_owner_remove(buffer.owner);\n+\n+\treturn addr;\n }\n EXPORT_SYMBOL_GPL(vmbus_alloc_buffer);\n \n@@ -767,14 +1411,26 @@ EXPORT_SYMBOL_GPL(vmbus_alloc_buffer);\n  * keeps track of the next available slot in the array. Initially, each\n  * slot points to the next one (as in a Linked List). The last slot\n  * does not point to anything, so its value is U64_MAX by default.\n+ *\n+ * Allocated with vzalloc() rather than kvcalloc(). kvcalloc() can use a\n+ * higher-order kmalloc allocation for arrays up to KMALLOC_MAX_SIZE, so\n+ * both small requestor arrays and the default 128-page ring array may need\n+ * contiguous pages while opening a channel under buddy fragmentation. The\n+ * array is guest-private request bookkeeping -- the host never sees the\n+ * slot values -- so a vmalloc-backed mapping carries no Confidential\n+ * Computing implication and needs no set_memory_decrypted().\n  * @size: The size of the array\n  */\n-static u64 *request_arr_init(u32 size)\n+u64 *request_arr_init(u32 size)\n {\n-\tint i;\n+\tsize_t bytes;\n+\tu32 i;\n \tu64 *req_arr;\n \n-\treq_arr = kcalloc(size, sizeof(u64), GFP_KERNEL);\n+\tif (!size || check_mul_overflow((size_t)size, sizeof(*req_arr), \u0026bytes))\n+\t\treturn NULL;\n+\n+\treq_arr = vzalloc(bytes);\n \tif (!req_arr)\n \t\treturn NULL;\n \n@@ -792,8 +1448,9 @@ static u64 *request_arr_init(u32 size)\n  * Index 0 is the first free slot\n  * @size: Size of the requestor array\n  */\n-static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)\n+int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)\n {\n+\tsize_t bitmap_longs, bitmap_bytes;\n \tu64 *rqst_arr;\n \tunsigned long *bitmap;\n \n@@ -801,9 +1458,17 @@ static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)\n \tif (!rqst_arr)\n \t\treturn -ENOMEM;\n \n-\tbitmap = bitmap_zalloc(size, GFP_KERNEL);\n+\tbitmap_longs = size / BITS_PER_LONG;\n+\tif (size % BITS_PER_LONG)\n+\t\tbitmap_longs++;\n+\tif (check_mul_overflow(bitmap_longs, sizeof(*bitmap), \u0026bitmap_bytes)) {\n+\t\tvfree(rqst_arr);\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\tbitmap = vzalloc(bitmap_bytes);\n \tif (!bitmap) {\n-\t\tkfree(rqst_arr);\n+\t\tvfree(rqst_arr);\n \t\treturn -ENOMEM;\n \t}\n \n@@ -820,10 +1485,10 @@ static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)\n  * vmbus_free_requestor - Frees memory allocated for @rqstor\n  * @rqstor: Pointer to the requestor struct\n  */\n-static void vmbus_free_requestor(struct vmbus_requestor *rqstor)\n+void vmbus_free_requestor(struct vmbus_requestor *rqstor)\n {\n-\tkfree(rqstor-\u003ereq_arr);\n-\tbitmap_free(rqstor-\u003ereq_bitmap);\n+\tvfree(rqstor-\u003ereq_arr);\n+\tvfree(rqstor-\u003ereq_bitmap);\n }\n \n static int __vmbus_open(struct vmbus_channel *newchannel,\n@@ -832,7 +1497,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,\n {\n \tstruct vmbus_channel_open_channel *open_msg;\n \tstruct vmbus_channel_msginfo *open_info = NULL;\n-\tstruct page *page = newchannel-\u003eringbuffer_page;\n+\tstruct vmbus_buffer *buffer = \u0026newchannel-\u003eringbuffer;\n \tu32 send_pages, recv_pages;\n \tunsigned long flags;\n \tint err;\n@@ -860,22 +1525,22 @@ static int __vmbus_open(struct vmbus_channel *newchannel,\n \t\tnewchannel-\u003emax_pkt_size = VMBUS_DEFAULT_MAX_PKT_SIZE;\n \n \t/* Establish the gpadl for the ring buffer */\n-\tnewchannel-\u003eringbuffer_gpadlhandle.gpadl_handle = 0;\n+\tbuffer-\u003egpadl.gpadl_handle = 0;\n \n-\terr = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING,\n-\t\t\t\t      page_address(newchannel-\u003eringbuffer_page),\n-\t\t\t\t      (send_pages + recv_pages) \u003c\u003c PAGE_SHIFT,\n+\terr = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING, buffer,\n \t\t\t\t      newchannel-\u003eringbuffer_send_offset \u003c\u003c PAGE_SHIFT,\n-\t\t\t\t      \u0026newchannel-\u003eringbuffer_gpadlhandle);\n+\t\t\t\t      true);\n \tif (err)\n \t\tgoto error_clean_ring;\n \n \terr = hv_ringbuffer_init(\u0026newchannel-\u003eoutbound,\n-\t\t\t\t page, send_pages, 0, newchannel-\u003eco_ring_buffer);\n+\t\t\t\t buffer-\u003eaddr, send_pages, 0,\n+\t\t\t\t newchannel-\u003eco_ring_buffer);\n \tif (err)\n \t\tgoto error_free_gpadl;\n \n-\terr = hv_ringbuffer_init(\u0026newchannel-\u003einbound, \u0026page[send_pages],\n+\terr = hv_ringbuffer_init(\u0026newchannel-\u003einbound,\n+\t\t\t\t buffer-\u003eaddr + (send_pages \u003c\u003c PAGE_SHIFT),\n \t\t\t\t recv_pages, newchannel-\u003emax_pkt_size,\n \t\t\t\t newchannel-\u003eco_ring_buffer);\n \tif (err)\n@@ -897,8 +1562,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,\n \topen_msg-\u003eheader.msgtype = CHANNELMSG_OPENCHANNEL;\n \topen_msg-\u003eopenid = newchannel-\u003eoffermsg.child_relid;\n \topen_msg-\u003echild_relid = newchannel-\u003eoffermsg.child_relid;\n-\topen_msg-\u003eringbuffer_gpadlhandle\n-\t\t= newchannel-\u003eringbuffer_gpadlhandle.gpadl_handle;\n+\topen_msg-\u003eringbuffer_gpadlhandle = buffer-\u003egpadl.gpadl_handle;\n \t/*\n \t * The unit of -\u003edownstream_ringbuffer_pageoffset is HV_HYP_PAGE and\n \t * the unit of -\u003eringbuffer_send_offset (i.e. send_pages) is PAGE, so\n@@ -956,7 +1620,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,\n error_free_info:\n \tkfree(open_info);\n error_free_gpadl:\n-\tvmbus_teardown_gpadl(newchannel, \u0026newchannel-\u003eringbuffer_gpadlhandle);\n+\tvmbus_teardown_gpadl_owned(newchannel, buffer);\n error_clean_ring:\n \thv_ringbuffer_cleanup(\u0026newchannel-\u003eoutbound);\n \thv_ringbuffer_cleanup(\u0026newchannel-\u003einbound);\n@@ -1002,71 +1666,164 @@ EXPORT_SYMBOL_GPL(vmbus_open);\n /*\n  * vmbus_teardown_gpadl -Teardown the specified GPADL handle\n  */\n-int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpadl)\n+int vmbus_gpadl_teardown_request(struct vmbus_channel *channel,\n+\t\t\t\t struct vmbus_buffer *buffer,\n+\t\t\t\t vmbus_gpadl_info_alloc_fn alloc_info,\n+\t\t\t\t struct vmbus_connection *connection,\n+\t\t\t\t vmbus_gpadl_teardown_post_fn post,\n+\t\t\t\t unsigned long timeout)\n {\n \tstruct vmbus_channel_gpadl_teardown *msg;\n \tstruct vmbus_channel_msginfo *info;\n+\tstruct vmbus_gpadl *gpadl = \u0026buffer-\u003egpadl;\n+\tstruct vmbus_buffer_retained *owner = buffer-\u003eowner;\n \tunsigned long flags;\n-\tint ret;\n+\tint ret = -ENODEV;\n+\tu32 handle = gpadl-\u003egpadl_handle;\n+\tu32 relid = channel-\u003eoffermsg.child_relid;\n+\n+\tif (!handle \u0026\u0026 !gpadl-\u003eleak)\n+\t\treturn 0;\n+\n+\t/* Host rescind permits a request, but only the actual ACK releases it. */\n+\tif (relid == INVALID_RELID ||\n+\t    (READ_ONCE(channel-\u003erescind) \u0026\u0026\n+\t     !READ_ONCE(channel-\u003erescind_from_host)))\n+\t\tgoto retain;\n+\n+\tif (!handle) {\n+\t\tret = -EINPROGRESS;\n+\t\tgoto retain;\n+\t}\n \n-\tinfo = kzalloc(sizeof(*info) +\n-\t\t       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);\n-\tif (!info)\n-\t\treturn -ENOMEM;\n+\tinfo = alloc_info();\n+\tif (!info) {\n+\t\tret = -ENOMEM;\n+\t\tgoto retain;\n+\t}\n \n \tinit_completion(\u0026info-\u003ewaitevent);\n-\tinfo-\u003ewaiting_channel = channel;\n+\t/* A synthetic rescind completion must not stand in for the host reply. */\n+\tinfo-\u003ewaiting_channel = NULL;\n \n \tmsg = (struct vmbus_channel_gpadl_teardown *)info-\u003emsg;\n-\n \tmsg-\u003eheader.msgtype = CHANNELMSG_GPADL_TEARDOWN;\n-\tmsg-\u003echild_relid = channel-\u003eoffermsg.child_relid;\n-\tmsg-\u003egpadl = gpadl-\u003egpadl_handle;\n+\tmsg-\u003echild_relid = relid;\n+\tmsg-\u003egpadl = handle;\n \n-\tspin_lock_irqsave(\u0026vmbus_connection.channelmsg_lock, flags);\n-\tlist_add_tail(\u0026info-\u003emsglistentry,\n-\t\t      \u0026vmbus_connection.chn_msg_list);\n-\tspin_unlock_irqrestore(\u0026vmbus_connection.channelmsg_lock, flags);\n \n-\tif (channel-\u003erescind)\n-\t\tgoto post_msg_err;\n+\tspin_lock_irqsave(\u0026connection-\u003echannelmsg_lock, flags);\n+\tlist_add_tail(\u0026info-\u003emsglistentry, \u0026connection-\u003echn_msg_list);\n+\tspin_unlock_irqrestore(\u0026connection-\u003echannelmsg_lock, flags);\n \n-\tret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),\n-\t\t\t     true);\n+\tif (channel-\u003eoffermsg.child_relid != relid ||\n+\t    (READ_ONCE(channel-\u003erescind) \u0026\u0026\n+\t     !READ_ONCE(channel-\u003erescind_from_host)))\n+\t\tgoto cleanup;\n \n-\ttrace_vmbus_teardown_gpadl(msg, ret);\n+\tret = post(connection, info);\n \n \tif (ret)\n-\t\tgoto post_msg_err;\n-\n-\twait_for_completion(\u0026info-\u003ewaitevent);\n+\t\tgoto cleanup;\n \n-\tgpadl-\u003egpadl_handle = 0;\n+\t/* A lost transport is bounded; expiry retains unknown host ownership. */\n+\tif (!wait_for_completion_timeout(\u0026info-\u003ewaitevent, timeout)) {\n+\t\tret = -ETIMEDOUT;\n+\t\tgoto cleanup;\n+\t}\n \n-post_msg_err:\n-\t/*\n-\t * If the channel has been rescinded;\n-\t * we will be awakened by the rescind\n-\t * handler; set the error code to zero so we don't leak memory.\n-\t */\n-\tif (channel-\u003erescind)\n+\tif (info-\u003eresponse.gpadl_torndown.header.msgtype ==\n+\t    CHANNELMSG_GPADL_TORNDOWN \u0026\u0026\n+\t    info-\u003eresponse.gpadl_torndown.gpadl == handle) {\n \t\tret = 0;\n+\t\tgpadl-\u003egpadl_handle = 0;\n+\t\tgpadl-\u003eleak = false;\n+\t\tif (owner)\n+\t\t\tvmbus_buffer_update_host_ownership(owner, false);\n+\t\tgoto cleanup;\n+\t}\n \n-\tspin_lock_irqsave(\u0026vmbus_connection.channelmsg_lock, flags);\n+\tret = -ENODEV;\n+\n+cleanup:\n+\tspin_lock_irqsave(\u0026connection-\u003echannelmsg_lock, flags);\n \tlist_del(\u0026info-\u003emsglistentry);\n-\tspin_unlock_irqrestore(\u0026vmbus_connection.channelmsg_lock, flags);\n+\tspin_unlock_irqrestore(\u0026connection-\u003echannelmsg_lock, flags);\n \n \tkfree(info);\n \n-\tif (gpadl-\u003edecrypted)\n-\t\tret = set_memory_encrypted((unsigned long)gpadl-\u003ebuffer,\n-\t\t\t\t\tPFN_UP(gpadl-\u003esize));\n-\telse\n-\t\tret = 0;\n-\tif (ret)\n-\t\tpr_warn(\"Fail to set mem host visibility in GPADL teardown %d.\\n\", ret);\n+retain:\n+\tif (ret) {\n+\t\tgpadl-\u003eleak = true;\n+\t\tif (owner)\n+\t\t\tvmbus_buffer_update_host_ownership(owner, true);\n+\t}\n \n-\tgpadl-\u003edecrypted = ret;\n+\treturn ret;\n+}\n+\n+static struct vmbus_channel_msginfo *vmbus_alloc_teardown_info(void)\n+{\n+\treturn kzalloc(sizeof(struct vmbus_channel_msginfo) +\n+\t\t       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);\n+}\n+\n+static int vmbus_gpadl_teardown_post_real(struct vmbus_connection *connection,\n+\t\t\t\t\t  struct vmbus_channel_msginfo *info)\n+{\n+\tstruct vmbus_channel_gpadl_teardown *msg = (void *)info-\u003emsg;\n+\n+\treturn vmbus_post_gpadl_teardown(msg-\u003echild_relid, msg, msg-\u003egpadl,\n+\t\t\t\t\tvmbus_gpadl_post_real, NULL);\n+}\n+\n+static int __vmbus_teardown_gpadl_buffer(struct vmbus_channel *channel,\n+\t\t\t\t\t struct vmbus_buffer *buffer)\n+{\n+\treturn vmbus_gpadl_teardown_request(channel, buffer,\n+\t\t\t\t\t  vmbus_alloc_teardown_info,\n+\t\t\t\t\t  \u0026vmbus_connection,\n+\t\t\t\t\t  vmbus_gpadl_teardown_post_real, 5 * HZ);\n+}\n+\n+int vmbus_teardown_gpadl_owned(struct vmbus_channel *channel,\n+\t\t\t       struct vmbus_buffer *buffer)\n+{\n+\treturn __vmbus_teardown_gpadl_buffer(channel, buffer);\n+}\n+EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl_owned);\n+\n+int vmbus_teardown_gpadl(struct vmbus_channel *channel,\n+\t\t\t struct vmbus_gpadl *gpadl)\n+{\n+\tstruct vmbus_buffer buffer = {\n+\t\t.gpadl = *gpadl,\n+\t};\n+\tint encrypt_ret;\n+\tint ret;\n+\n+\tret = __vmbus_teardown_gpadl_buffer(channel, \u0026buffer);\n+\t*gpadl = buffer.gpadl;\n+\n+\t/*\n+\t * The compat entry point builds an owner-less buffer, so the\n+\t * reclaim path never sees it and cannot re-encrypt on its\n+\t * behalf. Restore the synchronous re-encryption this symbol\n+\t * has always performed: the caller is about to release the\n+\t * range, and returning it decrypted would put shared pages\n+\t * back on the free list. The owned path defers the same work\n+\t * to reclaim through owner-\u003eraw_decrypted.\n+\t */\n+\tif (!ret \u0026\u0026 gpadl-\u003edecrypted) {\n+\t\tencrypt_ret = set_memory_encrypted((unsigned long)gpadl-\u003ebuffer,\n+\t\t\t\t\t\t   PFN_UP(gpadl-\u003esize));\n+\t\tif (encrypt_ret) {\n+\t\t\tpr_warn(\"Failed to re-encrypt GPADL buffer: %d\\n\",\n+\t\t\t\tencrypt_ret);\n+\t\t\tret = encrypt_ret;\n+\t\t}\n+\t\tgpadl-\u003edecrypted = !!encrypt_ret;\n+\t}\n \n \treturn ret;\n }\n@@ -1142,8 +1899,8 @@ static int vmbus_close_internal(struct vmbus_channel *channel)\n \t}\n \n \t/* Tear down the gpadl for the channel's ring buffer */\n-\telse if (channel-\u003eringbuffer_gpadlhandle.gpadl_handle) {\n-\t\tret = vmbus_teardown_gpadl(channel, \u0026channel-\u003eringbuffer_gpadlhandle);\n+\telse if (channel-\u003eringbuffer.gpadl.gpadl_handle) {\n+\t\tret = vmbus_teardown_gpadl_owned(channel, \u0026channel-\u003eringbuffer);\n \t\tif (ret) {\n \t\t\tpr_err(\"Close failed: teardown gpadl return %d\\n\", ret);\n \t\t\t/*\ndiff --git a/drivers/hv/channel_mgmt.c b/drivers/hv/channel_mgmt.c\nindex a044fd3b3c4e7..be0f70a3541cd 100644\n--- a/drivers/hv/channel_mgmt.c\n+++ b/drivers/hv/channel_mgmt.c\n@@ -26,6 +26,8 @@\n \n #include \"hyperv_vmbus.h\"\n \n+static atomic64_t vmbus_channel_lifetime_id = ATOMIC64_INIT(0);\n+\n static void init_vp_index(struct vmbus_channel *channel);\n \n const struct vmbus_device vmbus_devs[] = {\n@@ -170,14 +172,17 @@ static const struct {\n  * The rescinded channel may be blocked waiting for a response from the host;\n  * take care of that.\n  */\n-static void vmbus_rescind_cleanup(struct vmbus_channel *channel)\n+static void vmbus_rescind_cleanup(struct vmbus_channel *channel,\n+\t\t\t\t  bool host_generated)\n {\n \tstruct vmbus_channel_msginfo *msginfo;\n \tunsigned long flags;\n \n \n \tspin_lock_irqsave(\u0026vmbus_connection.channelmsg_lock, flags);\n-\tchannel-\u003erescind = true;\n+\tif (host_generated)\n+\t\tWRITE_ONCE(channel-\u003erescind_from_host, true);\n+\tWRITE_ONCE(channel-\u003erescind, true);\n \tlist_for_each_entry(msginfo, \u0026vmbus_connection.chn_msg_list,\n \t\t\t\tmsglistentry) {\n \n@@ -955,6 +960,10 @@ EXPORT_SYMBOL_GPL(vmbus_initiate_unload);\n static void vmbus_setup_channel_state(struct vmbus_channel *channel,\n \t\t\t\t      struct vmbus_channel_offer_channel *offer)\n {\n+\tchannel-\u003elifetime_id = atomic64_inc_return(\u0026vmbus_channel_lifetime_id);\n+\tWRITE_ONCE(channel-\u003erescind, false);\n+\tWRITE_ONCE(channel-\u003erescind_from_host, false);\n+\n \t/*\n \t * Setup state for signalling the host.\n \t */\n@@ -1159,7 +1168,8 @@ static void check_ready_for_suspend_event(void)\n  *\n  * We queue a work item to process this offer synchronously\n  */\n-static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr)\n+static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr,\n+\t\t\t\t  bool host_generated)\n {\n \tstruct vmbus_channel_rescind_offer *rescind;\n \tstruct vmbus_channel *channel;\n@@ -1238,7 +1248,7 @@ static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr)\n \t/*\n \t * Now wait for offer handling to complete.\n \t */\n-\tvmbus_rescind_cleanup(channel);\n+\tvmbus_rescind_cleanup(channel, host_generated);\n \twhile (READ_ONCE(channel-\u003eprobe_done) == false) {\n \t\t/*\n \t\t * We wait here until any channel offer is currently\n@@ -1477,26 +1487,23 @@ static void vmbus_onmodifychannel_response(struct vmbus_channel_message_header *\n  * Find the matching request, copy the response and signal the requesting\n  * thread.\n  */\n-static void vmbus_ongpadl_torndown(\n-\t\t\tstruct vmbus_channel_message_header *hdr)\n+void vmbus_complete_gpadl_teardown(struct vmbus_connection *connection,\n+\t\t\t\t   struct vmbus_channel_gpadl_torndown *gpadl_torndown)\n {\n-\tstruct vmbus_channel_gpadl_torndown *gpadl_torndown;\n \tstruct vmbus_channel_msginfo *msginfo;\n \tstruct vmbus_channel_message_header *requestheader;\n \tstruct vmbus_channel_gpadl_teardown *gpadl_teardown;\n \tunsigned long flags;\n \n-\tgpadl_torndown = (struct vmbus_channel_gpadl_torndown *)hdr;\n-\n \ttrace_vmbus_ongpadl_torndown(gpadl_torndown);\n \n \t/*\n \t * Find the open msg, copy the result and signal/unblock the wait event\n \t */\n-\tspin_lock_irqsave(\u0026vmbus_connection.channelmsg_lock, flags);\n+\tspin_lock_irqsave(\u0026connection-\u003echannelmsg_lock, flags);\n \n-\tlist_for_each_entry(msginfo, \u0026vmbus_connection.chn_msg_list,\n-\t\t\t\tmsglistentry) {\n+\tlist_for_each_entry(msginfo, \u0026connection-\u003echn_msg_list,\n+\t\t\t    msglistentry) {\n \t\trequestheader =\n \t\t\t(struct vmbus_channel_message_header *)msginfo-\u003emsg;\n \n@@ -1514,7 +1521,13 @@ static void vmbus_ongpadl_torndown(\n \t\t\t}\n \t\t}\n \t}\n-\tspin_unlock_irqrestore(\u0026vmbus_connection.channelmsg_lock, flags);\n+\tspin_unlock_irqrestore(\u0026connection-\u003echannelmsg_lock, flags);\n+}\n+\n+static void vmbus_ongpadl_torndown(struct vmbus_channel_message_header *hdr)\n+{\n+\tvmbus_complete_gpadl_teardown(\u0026vmbus_connection,\n+\t\t\t\t      (struct vmbus_channel_gpadl_torndown *)hdr);\n }\n \n /*\n@@ -1555,12 +1568,18 @@ static void vmbus_onversion_response(\n }\n \n /* Channel message dispatch table */\n+static void\n+vmbus_onoffer_rescind_from_table(struct vmbus_channel_message_header *hdr)\n+{\n+\tvmbus_onoffer_rescind(hdr, true);\n+}\n+\n const struct vmbus_channel_message_table_entry\n channel_message_table[CHANNELMSG_COUNT] = {\n \t{ CHANNELMSG_INVALID,\t\t\t0, NULL, 0},\n \t{ CHANNELMSG_OFFERCHANNEL,\t\t0, vmbus_onoffer,\n \t\tsizeof(struct vmbus_channel_offer_channel)},\n-\t{ CHANNELMSG_RESCIND_CHANNELOFFER,\t0, vmbus_onoffer_rescind,\n+\t{ CHANNELMSG_RESCIND_CHANNELOFFER,\t0, vmbus_onoffer_rescind_from_table,\n \t\tsizeof(struct vmbus_channel_rescind_offer) },\n \t{ CHANNELMSG_REQUESTOFFERS,\t\t0, NULL, 0},\n \t{ CHANNELMSG_ALLOFFERS_DELIVERED,\t1, vmbus_onoffers_delivered, 0},\n@@ -1596,7 +1615,8 @@ channel_message_table[CHANNELMSG_COUNT] = {\n  *\n  * This is invoked in the vmbus worker thread context.\n  */\n-void vmbus_onmessage(struct vmbus_channel_message_header *hdr)\n+void vmbus_onmessage(struct vmbus_channel_message_header *hdr,\n+\t\t     bool host_generated)\n {\n \ttrace_vmbus_on_message(hdr);\n \n@@ -1604,6 +1624,11 @@ void vmbus_onmessage(struct vmbus_channel_message_header *hdr)\n \t * vmbus_on_msg_dpc() makes sure the hdr-\u003emsgtype here can not go\n \t * out of bound and the message_handler pointer can not be NULL.\n \t */\n+\tif (hdr-\u003emsgtype == CHANNELMSG_RESCIND_CHANNELOFFER) {\n+\t\tvmbus_onoffer_rescind(hdr, host_generated);\n+\t\treturn;\n+\t}\n+\n \tchannel_message_table[hdr-\u003emsgtype].message_handler(hdr);\n }\n \ndiff --git a/drivers/hv/hv_trace.h b/drivers/hv/hv_trace.h\nindex c02a1719e92f2..a3eeb817b00ea 100644\n--- a/drivers/hv/hv_trace.h\n+++ b/drivers/hv/hv_trace.h\n@@ -8,6 +8,30 @@\n \n #include \u003clinux/tracepoint.h\u003e\n \n+/* Opaque allocation identities; never expose a kernel pointer. */\n+TRACE_EVENT(vmbus_buffer_owner,\n+\t    TP_PROTO(u64 owner_id, u64 channel_id, const char *action,\n+\t\t     u32 size, u32 pages, u8 state),\n+\t    TP_ARGS(owner_id, channel_id, action, size, pages, state),\n+\t    TP_STRUCT__entry(__field(u64, owner_id)\n+\t\t__field(u64, channel_id)\n+\t\t__string(action, action)\n+\t\t__field(u32, size)\n+\t\t__field(u32, pages)\n+\t\t__field(u8, state)\n+\t),\n+\t    TP_fast_assign(__entry-\u003eowner_id = owner_id;\n+\t\t__entry-\u003echannel_id = channel_id;\n+\t\t__assign_str(action);\n+\t\t__entry-\u003esize = size;\n+\t\t__entry-\u003epages = pages;\n+\t\t__entry-\u003estate = state;\n+\t),\n+\t    TP_printk(\"owner_id=%llu channel_id=%llu action=%s size=%u pages=%u state=%u\",\n+\t\t      __entry-\u003eowner_id, __entry-\u003echannel_id, __get_str(action),\n+\t\t      __entry-\u003esize, __entry-\u003epages, __entry-\u003estate)\n+);\n+\n DECLARE_EVENT_CLASS(vmbus_hdr_msg,\n \tTP_PROTO(const struct vmbus_channel_message_header *hdr),\n \tTP_ARGS(hdr),\ndiff --git a/drivers/hv/hyperv_vmbus.h b/drivers/hv/hyperv_vmbus.h\nindex 33923621a5a3f..9819a6b686cec 100644\n--- a/drivers/hv/hyperv_vmbus.h\n+++ b/drivers/hv/hyperv_vmbus.h\n@@ -204,8 +204,8 @@ extern int hv_synic_cleanup(unsigned int cpu);\n void hv_ringbuffer_pre_init(struct vmbus_channel *channel);\n \n int hv_ringbuffer_init(struct hv_ring_buffer_info *ring_info,\n-\t\t       struct page *pages, u32 pagecnt, u32 max_pkt_size,\n-\t\t\t   bool confidential);\n+\t\t       void *addr, u32 pagecnt, u32 max_pkt_size,\n+\t\t       bool confidential);\n \n void hv_ringbuffer_cleanup(struct hv_ring_buffer_info *ring_info);\n \n@@ -354,6 +354,7 @@ struct vmbus_channel_message_table_entry {\n extern const struct vmbus_channel_message_table_entry\n \tchannel_message_table[CHANNELMSG_COUNT];\n \n+void vmbus_buffer_reclaimer_shutdown(void);\n \n /* General vmbus interface */\n \n@@ -551,4 +552,111 @@ int hv_create_ring_sysfs(struct vmbus_channel *channel,\n \t\t\t\t\t\t\t    struct vm_area_desc *desc));\n int hv_remove_ring_sysfs(struct vmbus_channel *channel);\n \n+/*\n+ * Retained buffer owner. One per channel-keyed allocation; freed only\n+ * after GPADL, page-state and mapping-reference gates all clear.\n+ */\n+struct vmbus_buffer_retained {\n+\tstruct list_head list;\n+\tstruct delayed_work reclaim_work;\n+\tu64 channel_id;\n+\tu64 owner_id;\n+\tvoid *addr;\n+\tstruct page **chunks;\n+\tstruct page **pages;\n+\tu32 chunk_cnt;\n+\tu32 page_cnt;\n+\tu32 size;\n+\tbool released;\n+\tbool host_may_own;\n+\tbool needs_encrypt;\n+\tbool raw_decrypted;\n+\tbool encryption_unknown;\n+\tbool permanent_leak;\n+\tbool work_active;\n+\tbool reclaiming;\n+};\n+\n+/*\n+ * vmbus buffer sizing, order-descent and free-decision helpers.\n+ *\n+ * These are shared with vmbus_buffer_test.c, which is built into the\n+ * hv_vmbus object alongside channel.c. They stay unexported.\n+ */\n+bool vmbus_needs_shared_pages(bool hv_isolation, bool guest_mem_encrypted,\n+\t\t\t      bool confidential);\n+int vmbus_buffer_round_size(u32 size, u32 *rounded_size);\n+unsigned int vmbus_buffer_order(unsigned long remaining,\n+\t\t\t\tunsigned int max_order);\n+bool vmbus_buffer_lower_order(unsigned int *order);\n+bool vmbus_buffer_should_free(const struct vmbus_buffer *buffer);\n+\n+/*\n+ * Order-descent allocation, shared with vmbus_buffer_test.c so the\n+ * cases can inject per-order failures. Defined in channel.c, built\n+ * into the hv_vmbus object, never exported.\n+ */\n+typedef struct page *(*vmbus_alloc_pages_fn)(void *context, int nid,\n+\t\t\t\t\t     gfp_t gfp,\n+\t\t\t\t\t     unsigned int order);\n+struct page *vmbus_alloc_pages_with_fallback(int nid, gfp_t gfp,\n+\t\t\t\t\t     unsigned int *order,\n+\t\t\t\t\t     vmbus_alloc_pages_fn alloc,\n+\t\t\t\t\t     void *context);\n+\n+/*\n+ * Owner lifetime and reclaim-gate helpers, shared with\n+ * vmbus_buffer_test.c for the same reason as the sizing helpers.\n+ * Defined in channel.c, unexported.\n+ */\n+bool vmbus_buffer_owner_can_reclaim(const struct vmbus_buffer_retained *owner);\n+bool vmbus_buffer_owner_should_schedule(const struct vmbus_buffer_retained *owner,\n+\t\t\t\t\tbool stopping, bool queue_live);\n+bool vmbus_buffer_pages_busy(struct vmbus_buffer_retained *owner);\n+void vmbus_buffer_owner_drain(struct vmbus_buffer_retained *owner,\n+\t\t\t      struct workqueue_struct *wq);\n+struct vmbus_buffer_retained *\n+vmbus_buffer_owner_alloc(struct vmbus_channel *channel);\n+\n+/*\n+ * GPADL post and response helpers, also shared with vmbus_buffer_test.c.\n+ * Same deal as the sizing helpers above: defined in channel.c, built into\n+ * the hv_vmbus object, never exported.\n+ */\n+typedef int (*vmbus_gpadl_post_fn)(void *context, void *buffer,\n+\t\t\t\t   size_t buflen, bool can_sleep);\n+int vmbus_post_gpadl_messages(struct vmbus_channel_msginfo *msginfo,\n+\t\t\t      u32 gpadl, bool *posted,\n+\t\t\t      vmbus_gpadl_post_fn post_msg,\n+\t\t\t      void *context);\n+int vmbus_gpadl_response_status(u32 creation_status, bool rescind,\n+\t\t\t\tbool *posted);\n+int vmbus_post_gpadl_teardown(u32 child_relid,\n+\t\t\t      struct vmbus_channel_gpadl_teardown *msg,\n+\t\t\t      u32 gpadl,\n+\t\t\t      vmbus_gpadl_post_fn post_msg,\n+\t\t\t      void *context);\n+typedef struct vmbus_channel_msginfo *(*vmbus_gpadl_info_alloc_fn)(void);\n+typedef int (*vmbus_gpadl_teardown_post_fn)(struct vmbus_connection *connection,\n+\t\t\t\t\t struct vmbus_channel_msginfo *info);\n+int vmbus_gpadl_teardown_request(struct vmbus_channel *channel,\n+\t\t\t\t struct vmbus_buffer *buffer,\n+\t\t\t\t vmbus_gpadl_info_alloc_fn alloc_info,\n+\t\t\t\t struct vmbus_connection *connection,\n+\t\t\t\t vmbus_gpadl_teardown_post_fn post,\n+\t\t\t\t unsigned long timeout);\n+void vmbus_complete_gpadl_teardown(struct vmbus_connection *connection,\n+\t\t\t\t   struct vmbus_channel_gpadl_torndown *response);\n+\n+/*\n+ * Requestor array lifetime helpers, shared with vmbus_buffer_test.c for\n+ * the same reason as the sizing helpers. Defined in channel.c, unexported.\n+ * request_arr_init() returns a vmalloc-backed array the caller must vfree();\n+ * vmbus_alloc_requestor() owns both vmalloc-backed objects on success, and\n+ * vmbus_free_requestor() releases them.\n+ */\n+u64 *request_arr_init(u32 size);\n+int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size);\n+void vmbus_free_requestor(struct vmbus_requestor *rqstor);\n+\n #endif /* _HYPERV_VMBUS_H */\ndiff --git a/drivers/hv/ring_buffer.c b/drivers/hv/ring_buffer.c\nindex 592a9601faaaf..16b1c29107890 100644\n--- a/drivers/hv/ring_buffer.c\n+++ b/drivers/hv/ring_buffer.c\n@@ -184,8 +184,8 @@ void hv_ringbuffer_pre_init(struct vmbus_channel *channel)\n \n /* Initialize the ring buffer. */\n int hv_ringbuffer_init(struct hv_ring_buffer_info *ring_info,\n-\t\t       struct page *pages, u32 page_cnt, u32 max_pkt_size,\n-\t\t\t   bool confidential)\n+\t\t       void *addr, u32 page_cnt, u32 max_pkt_size,\n+\t\t       bool confidential)\n {\n \tstruct page **pages_wraparound;\n \tint i;\n@@ -200,10 +200,11 @@ int hv_ringbuffer_init(struct hv_ring_buffer_info *ring_info,\n \tif (!pages_wraparound)\n \t\treturn -ENOMEM;\n \n-\tpages_wraparound[0] = pages;\n+\tpages_wraparound[0] = vmalloc_to_page(addr);\n \tfor (i = 0; i \u003c 2 * (page_cnt - 1); i++)\n \t\tpages_wraparound[i + 1] =\n-\t\t\t\u0026pages[i % (page_cnt - 1) + 1];\n+\t\t\tvmalloc_to_page(addr +\n+\t\t\t\t((i % (page_cnt - 1) + 1) \u003c\u003c PAGE_SHIFT));\n \n \tring_info-\u003ering_buffer = (struct hv_ring_buffer *)\n \t\tvmap(pages_wraparound, page_cnt * 2 - 1, VM_MAP,\ndiff --git a/drivers/hv/vmbus_buffer_test.c b/drivers/hv/vmbus_buffer_test.c\nnew file mode 100644\nindex 0000000000000..d0102dabef737\n--- /dev/null\n+++ b/drivers/hv/vmbus_buffer_test.c\n@@ -0,0 +1,976 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * KUnit tests for Hyper-V VMBus buffer allocation and GPADL lifetime.\n+ *\n+ * Built into the hv_vmbus object rather than a separate module so the\n+ * cases can reach the internal helpers declared in hyperv_vmbus.h\n+ * without exporting them.\n+ */\n+#include \u003ckunit/test.h\u003e\n+#include \u003clinux/completion.h\u003e\n+#include \u003clinux/hyperv.h\u003e\n+#include \u003clinux/mm.h\u003e\n+#include \u003clinux/sizes.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/vmalloc.h\u003e\n+\n+#include \"hyperv_vmbus.h\"\n+\n+static void vmbus_buffer_size_rounding_test(struct kunit *test)\n+{\n+\tu32 rounded_size;\n+\n+\tKUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(1, \u0026rounded_size), 0);\n+\tKUNIT_EXPECT_EQ(test, rounded_size, (u32)PAGE_SIZE);\n+\tKUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(PAGE_SIZE, \u0026rounded_size), 0);\n+\tKUNIT_EXPECT_EQ(test, rounded_size, (u32)PAGE_SIZE);\n+}\n+\n+static void vmbus_buffer_size_overflow_test(struct kunit *test)\n+{\n+\tu32 rounded_size = 0;\n+\tint ret;\n+\n+\tKUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(0, \u0026rounded_size), -EINVAL);\n+\tret = vmbus_buffer_round_size(U32_MAX, \u0026rounded_size);\n+\tKUNIT_EXPECT_EQ(test, ret, -EOVERFLOW);\n+\tret = vmbus_buffer_round_size(U32_MAX - PAGE_SIZE + 1, \u0026rounded_size);\n+\tKUNIT_EXPECT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_EQ(test, rounded_size,\n+\t\t\t(u32)(U32_MAX - PAGE_SIZE + 1));\n+}\n+\n+static void vmbus_buffer_private_shared_selection_test(struct kunit *test)\n+{\n+\tstatic const struct {\n+\t\tbool isolation;\n+\t\tbool encrypted;\n+\t\tbool confidential;\n+\t\tbool shared;\n+\t} cases[] = {\n+\t\t{ false, false, false, false },\n+\t\t{ false, false, true, false },\n+\t\t{ false, true, false, true },\n+\t\t{ false, true, true, false },\n+\t\t{ true, false, false, true },\n+\t\t{ true, false, true, false },\n+\t\t{ true, true, false, true },\n+\t\t{ true, true, true, false },\n+\t};\n+\tunsigned int i;\n+\n+\t/* Either platform signal requires visibility; confidential stays private. */\n+\tfor (i = 0; i \u003c ARRAY_SIZE(cases); i++)\n+\t\tKUNIT_EXPECT_EQ(test,\n+\t\t\t\tvmbus_needs_shared_pages(cases[i].isolation,\n+\t\t\t\t\t\t\t cases[i].encrypted,\n+\t\t\t\t\t\t\t cases[i].confidential),\n+\t\t\t\tcases[i].shared);\n+}\n+\n+static void vmbus_buffer_owner_reclaim_gate_test(struct kunit *test)\n+{\n+\tstruct vmbus_buffer_retained owner = {\n+\t\t.released = false,\n+\t};\n+\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+\towner.released = true;\n+\tKUNIT_EXPECT_TRUE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+\n+\towner.host_may_own = true;\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+\n+\towner.host_may_own = false;\t/* GPADL teardown acknowledgment */\n+\tKUNIT_EXPECT_TRUE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+\n+\towner.permanent_leak = true;\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+\n+\towner.permanent_leak = false;\n+\towner.encryption_unknown = true;\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+}\n+\n+static void vmbus_buffer_reclaim_schedule_gate_test(struct kunit *test)\n+{\n+\tstruct vmbus_buffer_retained owner = {\n+\t\t.released = true,\n+\t};\n+\n+\tKUNIT_EXPECT_TRUE(test,\n+\t\t\t  vmbus_buffer_owner_should_schedule(\u0026owner, false, true));\n+\towner.work_active = true;\n+\tKUNIT_EXPECT_FALSE(test,\n+\t\t\t   vmbus_buffer_owner_should_schedule(\u0026owner, false, true));\n+\towner.work_active = false;\n+\towner.reclaiming = true;\n+\tKUNIT_EXPECT_FALSE(test,\n+\t\t\t   vmbus_buffer_owner_should_schedule(\u0026owner, false, true));\n+\towner.reclaiming = false;\n+\tKUNIT_EXPECT_FALSE(test,\n+\t\t\t   vmbus_buffer_owner_should_schedule(\u0026owner, true, true));\n+\tKUNIT_EXPECT_FALSE(test,\n+\t\t\t   vmbus_buffer_owner_should_schedule(\u0026owner, false, false));\n+}\n+\n+struct vmbus_reclaim_test_work {\n+\tstruct vmbus_buffer_retained owner;\n+\tstruct workqueue_struct *wq;\n+\tstruct completion entered;\n+\tstruct completion proceed;\n+\tatomic_t calls;\n+\tbool claim_owner;\n+};\n+\n+static void vmbus_reclaim_test_callback(struct work_struct *work)\n+{\n+\tstruct vmbus_buffer_retained *owner =\n+\t\tcontainer_of(to_delayed_work(work),\n+\t\t\t     struct vmbus_buffer_retained, reclaim_work);\n+\tstruct vmbus_reclaim_test_work *ctx =\n+\t\tcontainer_of(owner, struct vmbus_reclaim_test_work, owner);\n+\n+\tatomic_inc(\u0026ctx-\u003ecalls);\n+\tif (ctx-\u003eclaim_owner)\n+\t\towner-\u003ereclaiming = true;\n+\tcomplete(\u0026ctx-\u003eentered);\n+\twait_for_completion(\u0026ctx-\u003eproceed);\n+}\n+\n+static void vmbus_reclaim_test_cleanup(void *data)\n+{\n+\tstruct vmbus_reclaim_test_work *ctx = data;\n+\n+\tcomplete_all(\u0026ctx-\u003eproceed);\n+\tcancel_delayed_work_sync(\u0026ctx-\u003eowner.reclaim_work);\n+\tdestroy_workqueue(ctx-\u003ewq);\n+}\n+\n+static struct vmbus_reclaim_test_work *\n+vmbus_reclaim_test_init(struct kunit *test)\n+{\n+\tstruct vmbus_reclaim_test_work *ctx;\n+\n+\tctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);\n+\tif (!ctx)\n+\t\treturn NULL;\n+\tinit_completion(\u0026ctx-\u003eentered);\n+\tinit_completion(\u0026ctx-\u003eproceed);\n+\tatomic_set(\u0026ctx-\u003ecalls, 0);\n+\tctx-\u003eowner.released = true;\n+\tctx-\u003eowner.work_active = true;\n+\tINIT_DELAYED_WORK(\u0026ctx-\u003eowner.reclaim_work,\n+\t\t\t  vmbus_reclaim_test_callback);\n+\tctx-\u003ewq = alloc_workqueue(\"vmbus-reclaim-test\",\n+\t\t\t\t  WQ_UNBOUND | WQ_MEM_RECLAIM, 1);\n+\tif (!ctx-\u003ewq)\n+\t\treturn NULL;\n+\tif (kunit_add_action_or_reset(test, vmbus_reclaim_test_cleanup, ctx))\n+\t\treturn NULL;\n+\treturn ctx;\n+}\n+\n+static void vmbus_reclaim_running_test(struct kunit *test, bool claim_owner)\n+{\n+\tstruct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tctx-\u003eclaim_owner = claim_owner;\n+\tKUNIT_ASSERT_TRUE(test,\n+\t\t\t  queue_delayed_work(ctx-\u003ewq, \u0026ctx-\u003eowner.reclaim_work, 0));\n+\tKUNIT_ASSERT_NE(test,\n+\t\t\twait_for_completion_timeout(\u0026ctx-\u003eentered,\n+\t\t\t\t\t\t    msecs_to_jiffies(1000)), 0UL);\n+\n+\t/*\n+\t * The native workqueue cleared pending before entering the callback.\n+\t * Test both windows around the callback taking ownership. Keep the\n+\t * fixture alive so an incorrect second queue fails without a UAF.\n+\t */\n+\tvmbus_buffer_owner_drain(\u0026ctx-\u003eowner, ctx-\u003ewq);\n+\tKUNIT_EXPECT_FALSE(test, delayed_work_pending(\u0026ctx-\u003eowner.reclaim_work));\n+\tKUNIT_EXPECT_TRUE(test, ctx-\u003eowner.work_active);\n+\tcomplete_all(\u0026ctx-\u003eproceed);\n+\tflush_workqueue(ctx-\u003ewq);\n+\tKUNIT_EXPECT_EQ(test, atomic_read(\u0026ctx-\u003ecalls), 1);\n+}\n+\n+static void vmbus_reclaim_shutdown_before_claim_test(struct kunit *test)\n+{\n+\tvmbus_reclaim_running_test(test, false);\n+}\n+\n+static void vmbus_reclaim_shutdown_during_reclaim_test(struct kunit *test)\n+{\n+\tvmbus_reclaim_running_test(test, true);\n+}\n+\n+static void vmbus_reclaim_shutdown_pending_test(struct kunit *test)\n+{\n+\tstruct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tKUNIT_ASSERT_TRUE(test,\n+\t\t\t  queue_delayed_work(ctx-\u003ewq, \u0026ctx-\u003eowner.reclaim_work,\n+\t\t\t\t\t     msecs_to_jiffies(60000)));\n+\tcomplete_all(\u0026ctx-\u003eproceed);\n+\tvmbus_buffer_owner_drain(\u0026ctx-\u003eowner, ctx-\u003ewq);\n+\tflush_workqueue(ctx-\u003ewq);\n+\tKUNIT_EXPECT_EQ(test, atomic_read(\u0026ctx-\u003ecalls), 1);\n+}\n+\n+static void vmbus_reclaim_shutdown_unsafe_pending_test(struct kunit *test)\n+{\n+\tstruct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tctx-\u003eowner.host_may_own = true;\n+\tKUNIT_ASSERT_TRUE(test,\n+\t\t\t  queue_delayed_work(ctx-\u003ewq, \u0026ctx-\u003eowner.reclaim_work,\n+\t\t\t\t\t     msecs_to_jiffies(60000)));\n+\tvmbus_buffer_owner_drain(\u0026ctx-\u003eowner, ctx-\u003ewq);\n+\tKUNIT_EXPECT_FALSE(test, delayed_work_pending(\u0026ctx-\u003eowner.reclaim_work));\n+\tKUNIT_EXPECT_FALSE(test, ctx-\u003eowner.work_active);\n+\tflush_workqueue(ctx-\u003ewq);\n+\tKUNIT_EXPECT_EQ(test, atomic_read(\u0026ctx-\u003ecalls), 0);\n+}\n+\n+static struct vmbus_channel_msginfo *vmbus_test_alloc_teardown_fail(void)\n+{\n+\treturn NULL;\n+}\n+\n+static void vmbus_buffer_rescind_retains_gpadl_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = { .rescind = true };\n+\tstruct vmbus_buffer_retained owner = {\n+\t\t.released = true,\n+\t\t.host_may_own = true,\n+\t};\n+\tstruct vmbus_buffer buffer = { .owner = \u0026owner };\n+\tunsigned int origin, pending;\n+\tu32 handle;\n+\tint ret;\n+\n+\t/* Exercise the request core without touching the live connection. */\n+\tfor (origin = 0; origin \u003c 2; origin++) {\n+\t\tchannel.rescind_from_host = origin;\n+\t\tfor (pending = 0; pending \u003c 2; pending++) {\n+\t\t\tbuffer.gpadl.gpadl_handle = pending ? 0 : 17;\n+\t\t\tbuffer.gpadl.leak = pending;\n+\t\t\thandle = buffer.gpadl.gpadl_handle;\n+\t\t\tret = vmbus_gpadl_teardown_request(\u0026channel, \u0026buffer,\n+\t\t\t\t\t\t\t   vmbus_test_alloc_teardown_fail,\n+\t\t\t\t\t\t\t   NULL, NULL, 1);\n+\t\t\tKUNIT_EXPECT_EQ(test, ret, !origin ? -ENODEV :\n+\t\t\t\t\t  pending ? -EINPROGRESS : -ENOMEM);\n+\t\t\tKUNIT_EXPECT_EQ(test, buffer.gpadl.gpadl_handle, handle);\n+\t\t\tKUNIT_EXPECT_TRUE(test, buffer.gpadl.leak);\n+\t\t\tKUNIT_EXPECT_TRUE(test, owner.host_may_own);\n+\t\t\tKUNIT_EXPECT_FALSE(test, owner.work_active);\n+\t\t\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(\u0026buffer));\n+\t\t\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(\u0026owner));\n+\t\t}\n+\t}\n+}\n+\n+enum vmbus_test_teardown_reply {\n+\tVMBUS_TEST_REPLY_ACK,\n+\tVMBUS_TEST_REPLY_NONE,\n+\tVMBUS_TEST_REPLY_WRONG_HANDLE,\n+\tVMBUS_TEST_REPLY_WRONG_TYPE,\n+\tVMBUS_TEST_REPLY_POST_FAILURE,\n+};\n+\n+struct vmbus_teardown_test_context {\n+\tstruct vmbus_connection connection;\n+\tstruct vmbus_channel channel;\n+\tstruct vmbus_buffer buffer;\n+\tstruct vmbus_buffer_retained owner;\n+\tstruct kunit *test;\n+\tenum vmbus_test_teardown_reply reply;\n+\tunsigned int post_calls;\n+};\n+\n+static struct vmbus_channel_msginfo *vmbus_test_alloc_teardown(void)\n+{\n+\treturn kzalloc(sizeof(struct vmbus_channel_msginfo) +\n+\t\t       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);\n+}\n+\n+static int vmbus_test_post_teardown(struct vmbus_connection *connection,\n+\t\t\t\t    struct vmbus_channel_msginfo *info)\n+{\n+\tstruct vmbus_teardown_test_context *ctx =\n+\t\tcontainer_of(connection, struct vmbus_teardown_test_context,\n+\t\t\t     connection);\n+\tstruct vmbus_channel_gpadl_teardown *msg = (void *)info-\u003emsg;\n+\tstruct vmbus_channel_gpadl_torndown response = {\n+\t\t.header.msgtype = CHANNELMSG_GPADL_TORNDOWN,\n+\t\t.gpadl = msg-\u003egpadl,\n+\t};\n+\n+\tctx-\u003epost_calls++;\n+\tKUNIT_EXPECT_EQ(ctx-\u003etest, msg-\u003eheader.msgtype, CHANNELMSG_GPADL_TEARDOWN);\n+\tKUNIT_EXPECT_EQ(ctx-\u003etest, msg-\u003echild_relid, 71U);\n+\tKUNIT_EXPECT_EQ(ctx-\u003etest, msg-\u003egpadl, 51U);\n+\tKUNIT_EXPECT_PTR_EQ(ctx-\u003etest, info-\u003ewaiting_channel, NULL);\n+\tif (ctx-\u003ereply == VMBUS_TEST_REPLY_POST_FAILURE)\n+\t\treturn -EIO;\n+\tif (ctx-\u003ereply == VMBUS_TEST_REPLY_NONE)\n+\t\treturn 0;\n+\tif (ctx-\u003ereply == VMBUS_TEST_REPLY_WRONG_HANDLE)\n+\t\tresponse.gpadl++;\n+\tif (ctx-\u003ereply == VMBUS_TEST_REPLY_WRONG_TYPE)\n+\t\tresponse.header.msgtype = CHANNELMSG_GPADL_CREATED;\n+\tvmbus_complete_gpadl_teardown(connection, \u0026response);\n+\treturn 0;\n+}\n+\n+static struct vmbus_teardown_test_context *\n+vmbus_test_teardown_context(struct kunit *test)\n+{\n+\tstruct vmbus_teardown_test_context *ctx;\n+\n+\tctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);\n+\tif (!ctx)\n+\t\treturn NULL;\n+\tctx-\u003etest = test;\n+\tctx-\u003ebuffer.gpadl.gpadl_handle = 51;\n+\tctx-\u003ebuffer.owner = \u0026ctx-\u003eowner;\n+\tctx-\u003eowner.host_may_own = true;\n+\tctx-\u003echannel.rescind = true;\n+\tctx-\u003echannel.rescind_from_host = true;\n+\tctx-\u003echannel.offermsg.child_relid = 71;\n+\tINIT_LIST_HEAD(\u0026ctx-\u003econnection.chn_msg_list);\n+\tspin_lock_init(\u0026ctx-\u003econnection.channelmsg_lock);\n+\treturn ctx;\n+}\n+\n+static int vmbus_test_teardown_request(struct vmbus_teardown_test_context *ctx)\n+{\n+\treturn vmbus_gpadl_teardown_request(\u0026ctx-\u003echannel, \u0026ctx-\u003ebuffer,\n+\t\t\t\t\t  vmbus_test_alloc_teardown,\n+\t\t\t\t\t  \u0026ctx-\u003econnection,\n+\t\t\t\t\t  vmbus_test_post_teardown, 1);\n+}\n+\n+static void vmbus_host_rescind_teardown_ack_test(struct kunit *test)\n+{\n+\tstruct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tKUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), 0);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003epost_calls, 1U);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003ebuffer.gpadl.gpadl_handle, 0U);\n+\tKUNIT_EXPECT_FALSE(test, ctx-\u003ebuffer.gpadl.leak);\n+\tKUNIT_EXPECT_FALSE(test, ctx-\u003eowner.host_may_own);\n+\tKUNIT_EXPECT_TRUE(test, vmbus_buffer_should_free(\u0026ctx-\u003ebuffer));\n+\tKUNIT_EXPECT_TRUE(test, list_empty(\u0026ctx-\u003econnection.chn_msg_list));\n+}\n+\n+static void vmbus_test_teardown_failure(struct kunit *test,\n+\t\t\t\t\tenum vmbus_test_teardown_reply reply,\n+\t\t\t\t\tint expected)\n+{\n+\tstruct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tctx-\u003ereply = reply;\n+\tKUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), expected);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003epost_calls, 1U);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003ebuffer.gpadl.gpadl_handle, 51U);\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(\u0026ctx-\u003ebuffer));\n+\tKUNIT_EXPECT_TRUE(test, ctx-\u003eowner.host_may_own);\n+\tKUNIT_EXPECT_TRUE(test, list_empty(\u0026ctx-\u003econnection.chn_msg_list));\n+}\n+\n+static void vmbus_host_rescind_teardown_timeout_test(struct kunit *test)\n+{\n+\tvmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_NONE, -ETIMEDOUT);\n+}\n+\n+static void vmbus_host_rescind_teardown_wrong_handle_test(struct kunit *test)\n+{\n+\tvmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_WRONG_HANDLE,\n+\t\t\t\t    -ETIMEDOUT);\n+}\n+\n+static void vmbus_host_rescind_teardown_wrong_type_test(struct kunit *test)\n+{\n+\tvmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_WRONG_TYPE, -ENODEV);\n+}\n+\n+static void vmbus_host_rescind_teardown_post_failure_test(struct kunit *test)\n+{\n+\tvmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_POST_FAILURE, -EIO);\n+}\n+\n+static void vmbus_local_rescind_skips_teardown_test(struct kunit *test)\n+{\n+\tstruct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tctx-\u003echannel.rescind_from_host = false;\n+\tKUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), -ENODEV);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003epost_calls, 0U);\n+\tKUNIT_EXPECT_TRUE(test, ctx-\u003ebuffer.gpadl.leak);\n+\tKUNIT_EXPECT_TRUE(test, ctx-\u003eowner.host_may_own);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003ebuffer.gpadl.gpadl_handle, 51U);\n+}\n+\n+static void vmbus_invalid_relid_skips_teardown_test(struct kunit *test)\n+{\n+\tstruct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tctx-\u003echannel.offermsg.child_relid = INVALID_RELID;\n+\tKUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), -ENODEV);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003epost_calls, 0U);\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003ebuffer.gpadl.gpadl_handle, 51U);\n+}\n+\n+static void vmbus_host_rescind_teardown_late_ack_test(struct kunit *test)\n+{\n+\tstruct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);\n+\tstruct vmbus_channel_gpadl_torndown response = {\n+\t\t.header.msgtype = CHANNELMSG_GPADL_TORNDOWN,\n+\t\t.gpadl = 51,\n+\t};\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tctx-\u003ereply = VMBUS_TEST_REPLY_NONE;\n+\tKUNIT_ASSERT_EQ(test, vmbus_test_teardown_request(ctx), -ETIMEDOUT);\n+\t/* Run the production response matcher after its waiter has been freed. */\n+\tvmbus_complete_gpadl_teardown(\u0026ctx-\u003econnection, \u0026response);\n+\tKUNIT_EXPECT_TRUE(test, list_empty(\u0026ctx-\u003econnection.chn_msg_list));\n+\tKUNIT_EXPECT_EQ(test, ctx-\u003ebuffer.gpadl.gpadl_handle, 51U);\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(\u0026ctx-\u003ebuffer));\n+\tKUNIT_EXPECT_TRUE(test, ctx-\u003eowner.host_may_own);\n+}\n+\n+static void vmbus_buffer_mapping_reference_test(struct kunit *test)\n+{\n+\tstruct vmbus_buffer_retained owner = {};\n+\tstruct page *page;\n+\tstruct page *pages[1];\n+\n+\tpage = alloc_page(GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, page);\n+\tpages[0] = page;\n+\towner.pages = pages;\n+\towner.page_cnt = ARRAY_SIZE(pages);\n+\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_pages_busy(\u0026owner));\n+\tget_page(page); /* vm_insert_pages() holds one reference per mapping */\n+\tKUNIT_EXPECT_TRUE(test, vmbus_buffer_pages_busy(\u0026owner));\n+\tput_page(page);\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_pages_busy(\u0026owner));\n+\t__free_page(page);\n+}\n+\n+static void vmbus_buffer_repeated_owner_release_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {};\n+\tstruct vmbus_buffer buffer = {};\n+\tstruct vmbus_buffer empty = {};\n+\n+\tbuffer.addr = vzalloc(PAGE_SIZE);\n+\tKUNIT_ASSERT_NOT_NULL(test, buffer.addr);\n+\tbuffer.owner = vmbus_buffer_owner_alloc(\u0026channel);\n+\tif (!buffer.owner) {\n+\t\tvfree(buffer.addr);\n+\t\tKUNIT_FAIL(test, \"failed to allocate a VMBus buffer owner\");\n+\t\treturn;\n+\t}\n+\tbuffer.size = PAGE_SIZE;\n+\tempty.owner = vmbus_buffer_owner_alloc(\u0026channel);\n+\tif (!empty.owner) {\n+\t\tvmbus_release_buffer(\u0026buffer);\n+\t\tKUNIT_FAIL(test, \"failed to allocate a second VMBus buffer owner\");\n+\t\treturn;\n+\t}\n+\tKUNIT_EXPECT_TRUE(test, empty.owner-\u003eowner_id != buffer.owner-\u003eowner_id);\n+\tvmbus_release_buffer(\u0026empty);\n+\tKUNIT_EXPECT_PTR_EQ(test, empty.owner, NULL);\n+\n+\tvmbus_release_buffer(\u0026buffer);\n+\tKUNIT_EXPECT_PTR_EQ(test, buffer.addr, NULL);\n+\tKUNIT_EXPECT_PTR_EQ(test, buffer.owner, NULL);\n+\tvmbus_release_buffer(\u0026buffer);\n+}\n+\n+static void vmbus_ring_fallback_order_zero_test(struct kunit *test)\n+{\n+\tunsigned int order;\n+\n+\torder = vmbus_buffer_order(1UL \u003c\u003c MAX_PAGE_ORDER, MAX_PAGE_ORDER);\n+\tKUNIT_EXPECT_EQ(test, order, (unsigned int)MAX_PAGE_ORDER);\n+\twhile (order)\n+\t\tKUNIT_ASSERT_TRUE(test, vmbus_buffer_lower_order(\u0026order));\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_lower_order(\u0026order));\n+\tKUNIT_EXPECT_EQ(test, order, 0U);\n+\tKUNIT_EXPECT_EQ(test, vmbus_buffer_order(3, MAX_PAGE_ORDER), 1U);\n+}\n+\n+static void vmbus_buffer_failed_teardown_leaks_test(struct kunit *test)\n+{\n+\tstruct vmbus_buffer buffer = {\n+\t\t.addr = (void *)1,\n+\t\t.gpadl.gpadl_handle = 1,\n+\t};\n+\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(\u0026buffer));\n+\tbuffer.gpadl.gpadl_handle = 0;\n+\tbuffer.gpadl.leak = true;\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(\u0026buffer));\n+\tbuffer.gpadl.leak = false;\n+\tbuffer.leak = true;\n+\tKUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(\u0026buffer));\n+\tbuffer.leak = false;\n+\tKUNIT_EXPECT_TRUE(test, vmbus_buffer_should_free(\u0026buffer));\n+}\n+\n+static void vmbus_buffer_partial_allocation_cleanup_test(struct kunit *test)\n+{\n+\tstruct page **chunks;\n+\tstruct vmbus_buffer buffer = {};\n+\n+\tchunks = kmalloc_obj(*chunks, GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, chunks);\n+\tvmbus_free_buffer(NULL, chunks, 0);\n+\n+\tbuffer.addr = vzalloc(PAGE_SIZE);\n+\tKUNIT_ASSERT_NOT_NULL(test, buffer.addr);\n+\tvmbus_release_buffer(\u0026buffer);\n+\tKUNIT_EXPECT_PTR_EQ(test, buffer.addr, NULL);\n+\tvmbus_release_buffer(\u0026buffer);\n+}\n+\n+struct vmbus_gpadl_post_test_context {\n+\tstruct kunit *test;\n+\tunsigned int call_count;\n+\tunsigned int fail_call;\n+\tu32 first_msgtype;\n+\tu32 expected_gpadl;\n+};\n+\n+static int vmbus_gpadl_test_post(void *context, void *buffer,\n+\t\t\t\t size_t buflen, bool can_sleep)\n+{\n+\tstruct vmbus_gpadl_post_test_context *test_context = context;\n+\tstruct vmbus_channel_message_header *header = buffer;\n+\n+\tKUNIT_EXPECT_TRUE(test_context-\u003etest, can_sleep);\n+\tKUNIT_EXPECT_GT(test_context-\u003etest, buflen,\n+\t\t\t(size_t)sizeof(*header));\n+\ttest_context-\u003ecall_count++;\n+\tKUNIT_EXPECT_EQ(test_context-\u003etest, header-\u003emsgtype,\n+\t\t\ttest_context-\u003ecall_count == 1 ?\n+\t\t\ttest_context-\u003efirst_msgtype : CHANNELMSG_GPADL_BODY);\n+\tswitch (header-\u003emsgtype) {\n+\tcase CHANNELMSG_GPADL_HEADER: {\n+\t\tstruct vmbus_channel_gpadl_header *gpadl_header = buffer;\n+\n+\t\tKUNIT_EXPECT_EQ(test_context-\u003etest, gpadl_header-\u003egpadl,\n+\t\t\t\ttest_context-\u003eexpected_gpadl);\n+\t\tbreak;\n+\t}\n+\tcase CHANNELMSG_GPADL_BODY: {\n+\t\tstruct vmbus_channel_gpadl_body *gpadl_body = buffer;\n+\n+\t\tKUNIT_EXPECT_EQ(test_context-\u003etest, gpadl_body-\u003egpadl,\n+\t\t\t\ttest_context-\u003eexpected_gpadl);\n+\t\tbreak;\n+\t}\n+\tcase CHANNELMSG_GPADL_TEARDOWN: {\n+\t\tstruct vmbus_channel_gpadl_teardown *teardown = buffer;\n+\n+\t\tKUNIT_EXPECT_EQ(test_context-\u003etest, teardown-\u003egpadl,\n+\t\t\t\ttest_context-\u003eexpected_gpadl);\n+\t\tKUNIT_EXPECT_EQ(test_context-\u003etest, teardown-\u003echild_relid,\n+\t\t\t\t7U);\n+\t\tbreak;\n+\t}\n+\tdefault:\n+\t\tKUNIT_FAIL(test_context-\u003etest,\n+\t\t\t   \"unexpected GPADL message type: %d\",\n+\t\t\t   header-\u003emsgtype);\n+\t}\n+\tif (test_context-\u003ecall_count == test_context-\u003efail_call)\n+\t\treturn -EIO;\n+\n+\treturn 0;\n+}\n+\n+static struct vmbus_channel_msginfo *\n+vmbus_gpadl_test_msginfo(struct kunit *test, unsigned int body_count)\n+{\n+\tstruct vmbus_channel_msginfo *msginfo;\n+\tstruct vmbus_channel_msginfo *body_info;\n+\tunsigned int i;\n+\n+\tmsginfo = kunit_kzalloc(test, sizeof(*msginfo) +\n+\t\t\t       sizeof(struct vmbus_channel_gpadl_header),\n+\t\t\t       GFP_KERNEL);\n+\tif (!msginfo)\n+\t\treturn NULL;\n+\n+\tmsginfo-\u003emsgsize = sizeof(*msginfo) +\n+\t\t\t   sizeof(struct vmbus_channel_gpadl_header);\n+\tINIT_LIST_HEAD(\u0026msginfo-\u003esubmsglist);\n+\n+\tfor (i = 0; i \u003c body_count; i++) {\n+\t\tbody_info = kunit_kzalloc(test,\n+\t\t\t\t\t  sizeof(*body_info) +\n+\t\t\t\t\t  sizeof(struct vmbus_channel_gpadl_body),\n+\t\t\t\t\t  GFP_KERNEL);\n+\t\tif (!body_info)\n+\t\t\treturn NULL;\n+\n+\t\tbody_info-\u003emsgsize = sizeof(*body_info) +\n+\t\t\t\t     sizeof(struct vmbus_channel_gpadl_body);\n+\t\tINIT_LIST_HEAD(\u0026body_info-\u003emsglistentry);\n+\t\tlist_add_tail(\u0026body_info-\u003emsglistentry, \u0026msginfo-\u003esubmsglist);\n+\t}\n+\n+\treturn msginfo;\n+}\n+\n+static void vmbus_gpadl_post_failure_test(struct kunit *test)\n+{\n+\tunsigned int fail_call;\n+\n+\tfor (fail_call = 1; fail_call \u003c= 3; fail_call++) {\n+\t\tstruct vmbus_gpadl_post_test_context context = {\n+\t\t\t.test = test,\n+\t\t\t.fail_call = fail_call,\n+\t\t\t.first_msgtype = CHANNELMSG_GPADL_HEADER,\n+\t\t\t.expected_gpadl = 17,\n+\t\t};\n+\t\tstruct vmbus_channel_msginfo *msginfo;\n+\t\tbool posted = false;\n+\t\tint ret;\n+\n+\t\tmsginfo = vmbus_gpadl_test_msginfo(test, 2);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, msginfo);\n+\n+\t\tret = vmbus_post_gpadl_messages(msginfo, 17, \u0026posted,\n+\t\t\t\t\t\tvmbus_gpadl_test_post, \u0026context);\n+\t\tKUNIT_EXPECT_EQ(test, ret, -EIO);\n+\t\tKUNIT_EXPECT_EQ(test, context.call_count, fail_call);\n+\t\tKUNIT_EXPECT_TRUE(test, posted);\n+\t}\n+}\n+\n+static void vmbus_gpadl_post_success_test(struct kunit *test)\n+{\n+\tstruct vmbus_gpadl_post_test_context context = {\n+\t\t.test = test,\n+\t\t.first_msgtype = CHANNELMSG_GPADL_HEADER,\n+\t\t.expected_gpadl = 17,\n+\t};\n+\tstruct vmbus_channel_msginfo *msginfo;\n+\tbool posted = false;\n+\tint ret;\n+\n+\tmsginfo = vmbus_gpadl_test_msginfo(test, 2);\n+\tKUNIT_ASSERT_NOT_NULL(test, msginfo);\n+\n+\tret = vmbus_post_gpadl_messages(msginfo, 17, \u0026posted,\n+\t\t\t\t\tvmbus_gpadl_test_post, \u0026context);\n+\tKUNIT_EXPECT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_EQ(test, context.call_count, 3U);\n+\tKUNIT_EXPECT_TRUE(test, posted);\n+}\n+\n+static void vmbus_gpadl_response_state_test(struct kunit *test)\n+{\n+\tbool posted = true;\n+\n+\tKUNIT_EXPECT_EQ(test, vmbus_gpadl_response_status(0, false, \u0026posted), 0);\n+\tKUNIT_EXPECT_FALSE(test, posted);\n+\n+\tposted = true;\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\tvmbus_gpadl_response_status(1, false, \u0026posted), -EDQUOT);\n+\tKUNIT_EXPECT_FALSE(test, posted);\n+\n+\tposted = true;\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\tvmbus_gpadl_response_status(0, true, \u0026posted), -ENODEV);\n+\tKUNIT_EXPECT_TRUE(test, posted);\n+}\n+\n+static void vmbus_gpadl_teardown_post_failure_test(struct kunit *test)\n+{\n+\tstruct vmbus_gpadl_post_test_context context = {\n+\t\t.test = test,\n+\t\t.fail_call = 1,\n+\t\t.first_msgtype = CHANNELMSG_GPADL_TEARDOWN,\n+\t\t.expected_gpadl = 17,\n+\t};\n+\tstruct vmbus_channel_gpadl_teardown msg = {};\n+\tint ret;\n+\n+\tret = vmbus_post_gpadl_teardown(7, \u0026msg, 17,\n+\t\t\t\t\tvmbus_gpadl_test_post, \u0026context);\n+\tKUNIT_EXPECT_EQ(test, ret, -EIO);\n+\tKUNIT_EXPECT_EQ(test, context.call_count, 1U);\n+}\n+\n+struct vmbus_buffer_page_alloc_test_context {\n+\tstruct kunit *test;\n+\tunsigned int attempts;\n+\tunsigned int expected_order;\n+\tbool fail_order_zero;\n+};\n+\n+static struct page *vmbus_buffer_test_alloc_page(void *context, int nid,\n+\t\t\t\t\t\t gfp_t gfp,\n+\t\t\t\t\t\t unsigned int order)\n+{\n+\tstruct vmbus_buffer_page_alloc_test_context *test_context = context;\n+\n+\t(void)nid;\n+\tKUNIT_EXPECT_EQ(test_context-\u003etest, order,\n+\t\t\ttest_context-\u003eexpected_order);\n+\ttest_context-\u003eattempts++;\n+\tif (test_context-\u003eexpected_order)\n+\t\ttest_context-\u003eexpected_order--;\n+\n+\tif (order)\n+\t\treturn NULL;\n+\tif (test_context-\u003efail_order_zero)\n+\t\treturn NULL;\n+\n+\treturn alloc_pages(gfp, 0);\n+}\n+\n+static void vmbus_buffer_order_zero_allocation_test(struct kunit *test)\n+{\n+\tstruct vmbus_buffer_page_alloc_test_context context = {\n+\t\t.test = test,\n+\t\t.expected_order = MAX_PAGE_ORDER,\n+\t};\n+\tstruct page *page;\n+\tunsigned int order = MAX_PAGE_ORDER;\n+\n+\tpage = vmbus_alloc_pages_with_fallback(0, GFP_KERNEL, \u0026order,\n+\t\t\t\t\t       vmbus_buffer_test_alloc_page, \u0026context);\n+\tKUNIT_ASSERT_NOT_NULL(test, page);\n+\tKUNIT_EXPECT_EQ(test, order, 0U);\n+\tKUNIT_EXPECT_EQ(test, context.expected_order, 0U);\n+\tKUNIT_EXPECT_EQ(test, context.attempts, (unsigned int)MAX_PAGE_ORDER + 1);\n+\t__free_pages(page, 0);\n+\n+\tcontext.attempts = 0;\n+\tcontext.expected_order = MAX_PAGE_ORDER;\n+\tcontext.fail_order_zero = true;\n+\torder = MAX_PAGE_ORDER;\n+\tpage = vmbus_alloc_pages_with_fallback(0, GFP_KERNEL, \u0026order,\n+\t\t\t\t\t       vmbus_buffer_test_alloc_page, \u0026context);\n+\tKUNIT_EXPECT_PTR_EQ(test, page, NULL);\n+\tKUNIT_EXPECT_EQ(test, order, 0U);\n+\tKUNIT_EXPECT_EQ(test, context.expected_order, 0U);\n+\tKUNIT_EXPECT_EQ(test, context.attempts, (unsigned int)MAX_PAGE_ORDER + 1);\n+}\n+\n+/*\n+ * Requestor metadata must use vmalloc backing because both the array and its\n+ * bitmap can require multiple pages. The requestor is guest-private\n+ * bookkeeping: the host never sees the slot values, so this mapping has no\n+ * Confidential Computing implication and needs no set_memory_decrypted().\n+ * Cover a typical 8 KiB array, a requestor whose bitmap exceeds one page,\n+ * and a size beyond KMALLOC_MAX_SIZE without memory pressure.\n+ */\n+static void vmbus_requestor_alloc_free_test(struct kunit *test)\n+{\n+\tstruct vmbus_requestor rqstor = {};\n+\n+\tKUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(\u0026rqstor, 4), 0);\n+\tKUNIT_EXPECT_EQ(test, rqstor.size, 4U);\n+\tKUNIT_EXPECT_EQ(test, rqstor.next_request_id, 0U);\n+\tKUNIT_EXPECT_NOT_NULL(test, rqstor.req_arr);\n+\tKUNIT_EXPECT_NOT_NULL(test, rqstor.req_bitmap);\n+\n+\t/* The free list links 0-\u003e1-\u003e2-\u003e3 and terminates in U64_MAX. */\n+\tKUNIT_EXPECT_EQ(test, rqstor.req_arr[0], 1U);\n+\tKUNIT_EXPECT_EQ(test, rqstor.req_arr[1], 2U);\n+\tKUNIT_EXPECT_EQ(test, rqstor.req_arr[2], 3U);\n+\tKUNIT_EXPECT_EQ(test, rqstor.req_arr[3], U64_MAX);\n+\n+\tvmbus_free_requestor(\u0026rqstor);\n+}\n+\n+static void vmbus_requestor_vmalloc_backing_test(struct kunit *test)\n+{\n+\t/*\n+\t * Cover the small array, a requestor whose bitmap exceeds one page,\n+\t * and a size beyond KMALLOC_MAX_SIZE. All requestor metadata must use\n+\t * vmalloc backing regardless of size or allocator pressure.\n+\t */\n+\tu32 small_size = 1024;\n+\tu32 bitmap_size = (PAGE_SIZE / sizeof(unsigned long)) * BITS_PER_LONG + 1;\n+\tu32 size = (KMALLOC_MAX_SIZE / sizeof(u64)) + 1;\n+\tstruct vmbus_requestor rqstor = {};\n+\tu64 *req_arr;\n+\n+\tKUNIT_EXPECT_PTR_EQ(test, request_arr_init(0), NULL);\n+\n+\treq_arr = request_arr_init(small_size);\n+\tKUNIT_ASSERT_NOT_NULL(test, req_arr);\n+\tKUNIT_EXPECT_TRUE(test, is_vmalloc_addr(req_arr));\n+\tKUNIT_EXPECT_EQ(test, req_arr[0], 1U);\n+\tKUNIT_EXPECT_EQ(test, req_arr[small_size - 1], U64_MAX);\n+\tvfree(req_arr);\n+\n+\treq_arr = request_arr_init(size);\n+\tKUNIT_ASSERT_NOT_NULL(test, req_arr);\n+\tKUNIT_EXPECT_TRUE(test, is_vmalloc_addr(req_arr));\n+\tKUNIT_EXPECT_EQ(test, req_arr[0], 1U);\n+\tKUNIT_EXPECT_EQ(test, req_arr[size - 1], U64_MAX);\n+\tvfree(req_arr);\n+\n+\tKUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(\u0026rqstor, bitmap_size), 0);\n+\tKUNIT_EXPECT_TRUE(test, is_vmalloc_addr(rqstor.req_arr));\n+\tKUNIT_EXPECT_TRUE(test, is_vmalloc_addr(rqstor.req_bitmap));\n+\tvmbus_free_requestor(\u0026rqstor);\n+}\n+\n+static void vmbus_requestor_id_lifecycle_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = { .rqstor_size = 4 };\n+\tstruct vmbus_requestor *rqstor = \u0026channel.requestor;\n+\tu64 id0, id1, id2, id3, addr;\n+\n+\tKUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 4), 0);\n+\n+\t/* IDs are 1-based; 0 is reserved for unsolicited host messages. */\n+\tid0 = vmbus_next_request_id(\u0026channel, 0x1000);\n+\tKUNIT_EXPECT_EQ(test, id0, 1U);\n+\tid1 = vmbus_next_request_id(\u0026channel, 0x2000);\n+\tKUNIT_EXPECT_EQ(test, id1, 2U);\n+\n+\t/* Consumption returns the registered address and frees the slot. */\n+\taddr = vmbus_request_addr_match(\u0026channel, id0, VMBUS_RQST_ADDR_ANY);\n+\tKUNIT_EXPECT_EQ(test, addr, 0x1000U);\n+\taddr = vmbus_request_addr_match(\u0026channel, id1, 0x2000);\n+\tKUNIT_EXPECT_EQ(test, addr, 0x2000U);\n+\n+\t/*\n+\t * Consumed slots are reusable. The free list is LIFO -- each\n+\t * consume pushes its slot onto the head -- so the slot freed last\n+\t * is the one handed out first. Freeing id0 then id1 leaves slot 1\n+\t * at the head, and the next ID is therefore id1 again, not id0.\n+\t */\n+\tid2 = vmbus_next_request_id(\u0026channel, 0x3000);\n+\tKUNIT_EXPECT_EQ(test, id2, id1);\n+\tid3 = vmbus_next_request_id(\u0026channel, 0x4000);\n+\tKUNIT_EXPECT_EQ(test, id3, id0);\n+\n+\tvmbus_free_requestor(rqstor);\n+}\n+\n+static void vmbus_requestor_invalid_ids_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = { .rqstor_size = 4 };\n+\tstruct vmbus_requestor *rqstor = \u0026channel.requestor;\n+\tu64 id, addr;\n+\n+\tKUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 4), 0);\n+\n+\t/* ID 0 is the unsolicited-message sentinel and is never in the set. */\n+\tKUNIT_EXPECT_EQ(test, vmbus_request_addr_match(\u0026channel, 0, 0),\n+\t\t\tVMBUS_RQST_ERROR);\n+\n+\t/* Out-of-range IDs are refused, not wrapped. */\n+\tKUNIT_EXPECT_EQ(test, vmbus_request_addr_match(\u0026channel, 5, 0),\n+\t\t\tVMBUS_RQST_ERROR);\n+\tKUNIT_EXPECT_EQ(test, vmbus_request_addr_match(\u0026channel, U64_MAX, 0),\n+\t\t\tVMBUS_RQST_ERROR);\n+\n+\tid = vmbus_next_request_id(\u0026channel, 0xABCD);\n+\tKUNIT_ASSERT_EQ(test, id, 1U);\n+\n+\t/* A wrong expected address does not consume the slot. */\n+\taddr = vmbus_request_addr_match(\u0026channel, id, 0x9999);\n+\tKUNIT_EXPECT_EQ(test, addr, 0xABCDU);\n+\n+\t/* The slot is still live and a matching lookup consumes it once. */\n+\taddr = vmbus_request_addr_match(\u0026channel, id, 0xABCD);\n+\tKUNIT_EXPECT_EQ(test, addr, 0xABCDU);\n+\n+\t/* Replay: the slot is gone. */\n+\taddr = vmbus_request_addr_match(\u0026channel, id, VMBUS_RQST_ADDR_ANY);\n+\tKUNIT_EXPECT_EQ(test, addr, VMBUS_RQST_ERROR);\n+\n+\tvmbus_free_requestor(rqstor);\n+}\n+\n+static void vmbus_requestor_exhaustion_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = { .rqstor_size = 2 };\n+\tstruct vmbus_requestor *rqstor = \u0026channel.requestor;\n+\n+\tKUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 2), 0);\n+\n+\tKUNIT_EXPECT_EQ(test, vmbus_next_request_id(\u0026channel, 0x1), 1U);\n+\tKUNIT_EXPECT_EQ(test, vmbus_next_request_id(\u0026channel, 0x2), 2U);\n+\n+\t/* Both slots taken: the free list is empty and the API says so. */\n+\tKUNIT_EXPECT_EQ(test, vmbus_next_request_id(\u0026channel, 0x3),\n+\t\t\tVMBUS_RQST_ERROR);\n+\n+\t/* An uninitialized requestor is not a full one. */\n+\tchannel.rqstor_size = 0;\n+\tKUNIT_EXPECT_EQ(test, vmbus_next_request_id(\u0026channel, 0x4),\n+\t\t\tVMBUS_NO_RQSTOR);\n+\n+\tvmbus_free_requestor(rqstor);\n+}\n+\n+static struct kunit_case vmbus_buffer_test_cases[] = {\n+\tKUNIT_CASE(vmbus_buffer_size_rounding_test),\n+\tKUNIT_CASE(vmbus_buffer_size_overflow_test),\n+\tKUNIT_CASE(vmbus_buffer_private_shared_selection_test),\n+\tKUNIT_CASE(vmbus_ring_fallback_order_zero_test),\n+\tKUNIT_CASE(vmbus_buffer_failed_teardown_leaks_test),\n+\tKUNIT_CASE(vmbus_buffer_owner_reclaim_gate_test),\n+\tKUNIT_CASE(vmbus_buffer_reclaim_schedule_gate_test),\n+\tKUNIT_CASE(vmbus_reclaim_shutdown_before_claim_test),\n+\tKUNIT_CASE(vmbus_reclaim_shutdown_during_reclaim_test),\n+\tKUNIT_CASE(vmbus_reclaim_shutdown_pending_test),\n+\tKUNIT_CASE(vmbus_reclaim_shutdown_unsafe_pending_test),\n+\tKUNIT_CASE(vmbus_buffer_rescind_retains_gpadl_test),\n+\tKUNIT_CASE(vmbus_host_rescind_teardown_ack_test),\n+\tKUNIT_CASE(vmbus_host_rescind_teardown_timeout_test),\n+\tKUNIT_CASE(vmbus_host_rescind_teardown_wrong_handle_test),\n+\tKUNIT_CASE(vmbus_host_rescind_teardown_wrong_type_test),\n+\tKUNIT_CASE(vmbus_host_rescind_teardown_post_failure_test),\n+\tKUNIT_CASE(vmbus_local_rescind_skips_teardown_test),\n+\tKUNIT_CASE(vmbus_invalid_relid_skips_teardown_test),\n+\tKUNIT_CASE(vmbus_host_rescind_teardown_late_ack_test),\n+\tKUNIT_CASE(vmbus_buffer_mapping_reference_test),\n+\tKUNIT_CASE(vmbus_buffer_partial_allocation_cleanup_test),\n+\tKUNIT_CASE(vmbus_buffer_repeated_owner_release_test),\n+\tKUNIT_CASE(vmbus_buffer_order_zero_allocation_test),\n+\tKUNIT_CASE(vmbus_gpadl_post_failure_test),\n+\tKUNIT_CASE(vmbus_gpadl_post_success_test),\n+\tKUNIT_CASE(vmbus_gpadl_response_state_test),\n+\tKUNIT_CASE(vmbus_gpadl_teardown_post_failure_test),\n+\tKUNIT_CASE(vmbus_requestor_alloc_free_test),\n+\tKUNIT_CASE(vmbus_requestor_vmalloc_backing_test),\n+\tKUNIT_CASE(vmbus_requestor_id_lifecycle_test),\n+\tKUNIT_CASE(vmbus_requestor_invalid_ids_test),\n+\tKUNIT_CASE(vmbus_requestor_exhaustion_test),\n+\t{}\n+};\n+\n+static struct kunit_suite vmbus_buffer_test_suite = {\n+\t.name = \"hyperv-vmbus-buffer\",\n+\t.test_cases = vmbus_buffer_test_cases,\n+};\n+\n+kunit_test_suite(vmbus_buffer_test_suite);\ndiff --git a/drivers/hv/vmbus_drv.c b/drivers/hv/vmbus_drv.c\nindex 5ebdbe24b5a1e..198b43d240510 100644\n--- a/drivers/hv/vmbus_drv.c\n+++ b/drivers/hv/vmbus_drv.c\n@@ -1022,6 +1022,7 @@ static const struct bus_type  hv_bus = {\n \n struct onmessage_work_context {\n \tstruct work_struct work;\n+\tbool host_generated;\n \tstruct {\n \t\tstruct hv_message_header header;\n \t\tu8 payload[];\n@@ -1032,14 +1033,14 @@ static void vmbus_onmessage_work(struct work_struct *work)\n {\n \tstruct onmessage_work_context *ctx;\n \n+\tctx = container_of(work, struct onmessage_work_context, work);\n \t/* Do not process messages if we're in DISCONNECTED state */\n-\tif (vmbus_connection.conn_state == DISCONNECTED)\n+\tif (vmbus_connection.conn_state == DISCONNECTED) {\n+\t\tkfree(ctx);\n \t\treturn;\n-\n-\tctx = container_of(work, struct onmessage_work_context,\n-\t\t\t   work);\n+\t}\n \tvmbus_onmessage((struct vmbus_channel_message_header *)\n-\t\t\t\u0026ctx-\u003emsg.payload);\n+\t\t\t\u0026ctx-\u003emsg.payload, ctx-\u003ehost_generated);\n \tkfree(ctx);\n }\n \n@@ -1109,6 +1110,7 @@ static void __vmbus_on_msg_dpc(void *message_page_addr)\n \t\t\treturn;\n \n \t\tINIT_WORK(\u0026ctx-\u003ework, vmbus_onmessage_work);\n+\t\tctx-\u003ehost_generated = true;\n \t\tctx-\u003emsg.header = msg_copy.header;\n \t\tmemcpy(\u0026ctx-\u003emsg.payload, msg_copy.u.payload, payload_size);\n \n@@ -1222,6 +1224,7 @@ static void vmbus_force_channel_rescinded(struct vmbus_channel *channel)\n \trescind-\u003echild_relid = channel-\u003eoffermsg.child_relid;\n \n \tINIT_WORK(\u0026ctx-\u003ework, vmbus_onmessage_work);\n+\tctx-\u003ehost_generated = false;\n \n \tqueue_work(vmbus_connection.work_queue, \u0026ctx-\u003ework);\n }\n@@ -1926,6 +1929,7 @@ static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,\n {\n \tstruct vmbus_channel *channel = container_of(kobj, struct vmbus_channel, kobj);\n \tstruct vm_area_desc desc;\n+\tstruct vmbus_buffer_pin *pin;\n \tint err;\n \n \t/*\n@@ -1937,9 +1941,55 @@ static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,\n \tif (err)\n \t\treturn err;\n \n-\treturn __compat_vma_mmap(\u0026desc, vma);\n+\t/*\n+\t * This is a kernfs bin attribute. kernfs_fop_mmap() rejects a VMA\n+\t * whose vm_ops carry .close, because kernfs has to replace the set\n+\t * with its own and cannot wrap close. So the prepare callback has\n+\t * to pick one of two ownership contracts, and this wrapper honors\n+\t * whichever it installed. Each contract has exactly one release\n+\t * site, reached on every outcome.\n+\t *\n+\t * With vm_ops, the callback handed the per-VMA state to an abandon\n+\t * path in vm_ops-\u003eclose and typically to vm_ops-\u003emapped. Install\n+\t * both before __compat_vma_mmap() so a failure in\n+\t * mmap_action_prepare() still reaches close(): that path never runs\n+\t * compat_set_vma_from_desc(), and the legacy .mmap error path frees\n+\t * the VMA without calling close() on its own. __compat_vma_mmap()\n+\t * installs the same values again on its way to the action. Note\n+\t * that such a set is rejected by kernfs after this returns, so a\n+\t * prepare callback that wants a successful mapping must not choose\n+\t * this contract.\n+\t *\n+\t * Without vm_ops, desc.private_data is a plain struct\n+\t * vmbus_buffer_pin and this wrapper is its only owner. Release it\n+\t * when __compat_vma_mmap() returns: on success insert_pages() has\n+\t * already taken a folio reference for every page the VMA maps, and\n+\t * on failure the attempt is over. Clear vma-\u003evm_private_data first\n+\t * so the freed pin is never reachable from the VMA that outlives\n+\t * this call.\n+\t */\n+\tif (desc.vm_ops) {\n+\t\tvma-\u003evm_ops = desc.vm_ops;\n+\t\tvma-\u003evm_private_data = desc.private_data;\n+\n+\t\terr = __compat_vma_mmap(\u0026desc, vma);\n+\t\tif (err \u0026\u0026 vma-\u003evm_ops \u0026\u0026 vma-\u003evm_ops-\u003eclose)\n+\t\t\tvma-\u003evm_ops-\u003eclose(vma);\n+\t\treturn err;\n+\t}\n+\n+\tpin = desc.private_data;\n+\terr = __compat_vma_mmap(\u0026desc, vma);\n+\tvma-\u003evm_private_data = NULL;\n+\tvmbus_buffer_unpin_pages(pin);\n+\tkfree(pin);\n+\treturn err;\n }\n \n+#if IS_ENABLED(CONFIG_HYPERV_VMBUS_KUNIT_TEST)\n+#include \"vmbus_mmap_test.c\"\n+#endif\n+\n static struct bin_attribute chan_attr_ring_buffer = {\n \t.attr = {\n \t\t.name = \"ring\",\n@@ -3072,6 +3122,7 @@ static void __exit vmbus_exit(void)\n \t\t\t\t\t\u0026hyperv_panic_vmbus_unload_block);\n \n \tbus_unregister(\u0026hv_bus);\n+\tvmbus_buffer_reclaimer_shutdown();\n \n \tcpuhp_remove_state(hyperv_cpuhp_online);\n \thv_synic_free();\ndiff --git a/drivers/hv/vmbus_mmap_test.c b/drivers/hv/vmbus_mmap_test.c\nnew file mode 100644\nindex 0000000000000..50b961f2b782d\n--- /dev/null\n+++ b/drivers/hv/vmbus_mmap_test.c\n@@ -0,0 +1,145 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Included beside the production sysfs wrapper; no VMBus device is touched. */\n+#include \u003ckunit/test.h\u003e\n+#include \u003clinux/mman.h\u003e\n+#include \u003clinux/uaccess.h\u003e\n+\n+struct vmbus_mmap_test_context {\n+\tstruct vmbus_channel channel;\n+\tstruct page *pages[3];\n+\tstruct page *blocker;\n+};\n+\n+static void vmbus_mmap_test_put_page(void *page)\n+{\n+\t__free_page(page);\n+}\n+\n+static struct page *vmbus_mmap_test_page(struct kunit *test, u8 value)\n+{\n+\tstruct page *page = alloc_page(GFP_KERNEL);\n+\n+\tif (!page)\n+\t\treturn NULL;\n+\tif (kunit_add_action_or_reset(test, vmbus_mmap_test_put_page, page))\n+\t\treturn NULL;\n+\tmemset(page_address(page), value, PAGE_SIZE);\n+\treturn page;\n+}\n+\n+static int vmbus_mmap_test_prepare(struct vmbus_channel *channel,\n+\t\t\t\t   struct vm_area_desc *desc)\n+{\n+\tstruct vmbus_buffer_pin *pin;\n+\tint ret;\n+\n+\tpin = kzalloc_obj(*pin);\n+\tif (!pin)\n+\t\treturn -ENOMEM;\n+\tret = vmbus_buffer_pin_pages(\u0026channel-\u003eringbuffer, pin);\n+\tif (ret) {\n+\t\tkfree(pin);\n+\t\treturn ret;\n+\t}\n+\tmmap_action_map_kernel_pages(desc, desc-\u003estart, pin-\u003epages,\n+\t\t\t\t     pin-\u003epage_count);\n+\tdesc-\u003evm_ops = NULL;\n+\tdesc-\u003eprivate_data = pin;\n+\treturn 0;\n+}\n+\n+static struct vmbus_mmap_test_context *\n+vmbus_mmap_test_context(struct kunit *test)\n+{\n+\tstruct vmbus_mmap_test_context *ctx;\n+\tunsigned int i;\n+\n+\tctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);\n+\tif (!ctx)\n+\t\treturn NULL;\n+\tfor (i = 0; i \u003c ARRAY_SIZE(ctx-\u003epages); i++) {\n+\t\tctx-\u003epages[i] = vmbus_mmap_test_page(test, 0x61 + i);\n+\t\tif (!ctx-\u003epages[i])\n+\t\t\treturn NULL;\n+\t}\n+\tctx-\u003eblocker = vmbus_mmap_test_page(test, 0xcc);\n+\tif (!ctx-\u003eblocker)\n+\t\treturn NULL;\n+\tctx-\u003echannel.mmap_prepare_ring_buffer = vmbus_mmap_test_prepare;\n+\tctx-\u003echannel.ringbuffer.pages = ctx-\u003epages;\n+\tctx-\u003echannel.ringbuffer.page_cnt = ARRAY_SIZE(ctx-\u003epages);\n+\treturn ctx;\n+}\n+\n+static void vmbus_mmap_test_action(struct kunit *test, bool partial)\n+{\n+\tstruct vmbus_mmap_test_context *ctx = vmbus_mmap_test_context(test);\n+\tstruct vm_area_struct *vma;\n+\tunsigned long start;\n+\tunsigned int i;\n+\tu8 value = 0;\n+\tint ret;\n+\n+\tKUNIT_ASSERT_NOT_NULL(test, ctx);\n+\tstart = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE,\n+\t\t\t      MAP_SHARED | MAP_ANONYMOUS, 0);\n+\tKUNIT_ASSERT_NE(test, start, 0UL);\n+\tKUNIT_ASSERT_LT(test, start, (unsigned long)TASK_SIZE);\n+\n+\tmmap_write_lock(current-\u003emm);\n+\tvma = find_vma(current-\u003emm, start);\n+\tif (!vma) {\n+\t\tmmap_write_unlock(current-\u003emm);\n+\t\tKUNIT_FAIL(test, \"managed VMA missing\");\n+\t\treturn;\n+\t}\n+\tif (partial) {\n+\t\tret = vm_insert_page(vma, start + PAGE_SIZE, ctx-\u003eblocker);\n+\t\tif (ret) {\n+\t\t\tmmap_write_unlock(current-\u003emm);\n+\t\t\tKUNIT_FAIL(test, \"owned blocking PTE could not be installed\");\n+\t\t\treturn;\n+\t\t}\n+\t}\n+\tret = hv_mmap_ring_buffer_wrapper(vma-\u003evm_file, \u0026ctx-\u003echannel.kobj,\n+\t\t\t\t\t  NULL, vma);\n+\tKUNIT_EXPECT_EQ(test, ret, partial ? -EBUSY : 0);\n+\tKUNIT_EXPECT_NULL(test, vma-\u003evm_private_data);\n+\tKUNIT_EXPECT_NULL(test, vma-\u003evm_ops);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(ctx-\u003epages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(ctx-\u003epages[i]),\n+\t\t\t\tpartial \u0026\u0026 i ? 1 : 2);\n+\tKUNIT_EXPECT_EQ(test, page_ref_count(ctx-\u003eblocker), partial ? 2 : 1);\n+\tmmap_write_unlock(current-\u003emm);\n+\n+\t/* The first insertion really happened, including on the partial error. */\n+\tKUNIT_EXPECT_EQ(test, copy_from_user(\u0026value, (void __user *)start, 1), 0UL);\n+\tKUNIT_EXPECT_EQ(test, value, (u8)0x61);\n+\tKUNIT_ASSERT_EQ(test, vm_munmap(start, 3 * PAGE_SIZE), 0);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(ctx-\u003epages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(ctx-\u003epages[i]), 1);\n+\tKUNIT_EXPECT_EQ(test, page_ref_count(ctx-\u003eblocker), 1);\n+}\n+\n+static void vmbus_sysfs_mmap_success_test(struct kunit *test)\n+{\n+\tvmbus_mmap_test_action(test, false);\n+}\n+\n+static void vmbus_sysfs_mmap_partial_insert_test(struct kunit *test)\n+{\n+\tvmbus_mmap_test_action(test, true);\n+}\n+\n+static struct kunit_case vmbus_mmap_test_cases[] = {\n+\tKUNIT_CASE(vmbus_sysfs_mmap_success_test),\n+\tKUNIT_CASE(vmbus_sysfs_mmap_partial_insert_test),\n+\t{}\n+};\n+\n+static struct kunit_suite vmbus_mmap_test_suite = {\n+\t.name = \"hyperv-vmbus-mmap\",\n+\t.test_cases = vmbus_mmap_test_cases,\n+};\n+\n+kunit_test_suite(vmbus_mmap_test_suite);\ndiff --git a/drivers/net/hyperv/Kconfig b/drivers/net/hyperv/Kconfig\nindex 982964c1a9fb9..226728fd77d71 100644\n--- a/drivers/net/hyperv/Kconfig\n+++ b/drivers/net/hyperv/Kconfig\n@@ -6,3 +6,15 @@ config HYPERV_NET\n \tselect NLS\n \thelp\n \t  Select this option to enable the Hyper-V virtual network driver.\n+\n+config HYPERV_NET_KUNIT_TEST\n+\tbool \"Build Hyper-V netvsc KUnit tests\"\n+\tdepends on HYPERV_NET \u0026\u0026 KUNIT\n+\tdefault KUNIT_ALL_TESTS\n+\thelp\n+\t  Build the netvsc KUnit test suites into the hv_netvsc object.\n+\t  Built into the module rather than as a separate one so the\n+\t  cases can reach the internal helpers declared in hyperv_net.h\n+\t  without exporting them.\n+\n+\t  If unsure, say N.\ndiff --git a/drivers/net/hyperv/Makefile b/drivers/net/hyperv/Makefile\nindex 0db7ccaec4a4c..b2d22855fd8a0 100644\n--- a/drivers/net/hyperv/Makefile\n+++ b/drivers/net/hyperv/Makefile\n@@ -2,3 +2,5 @@\n obj-$(CONFIG_HYPERV_NET) += hv_netvsc.o\n \n hv_netvsc-y := netvsc_drv.o netvsc.o rndis_filter.o netvsc_trace.o netvsc_bpf.o\n+hv_netvsc-$(CONFIG_HYPERV_NET_KUNIT_TEST) += netvsc_completion_test.o\n+hv_netvsc-$(CONFIG_HYPERV_NET_KUNIT_TEST) += rndis_request_test.o\ndiff --git a/drivers/net/hyperv/hyperv_net.h b/drivers/net/hyperv/hyperv_net.h\nindex 4841367fdab2f..be3a63a168cfa 100644\n--- a/drivers/net/hyperv/hyperv_net.h\n+++ b/drivers/net/hyperv/hyperv_net.h\n@@ -210,14 +210,40 @@ struct rndis_device {\n \tu8 rss_key[NETVSC_HASH_KEYLEN];\n };\n \n+#define RNDIS_EXT_LEN HV_HYP_PAGE_SIZE\n \n-/* Interface */\n+/* Full definitions are below, after the RNDIS message format. */\n+struct rndis_request;\n struct rndis_message;\n+\n+/* Interface */\n struct ndis_offload_params;\n struct netvsc_device;\n struct netvsc_channel;\n struct net_device_context;\n \n+struct rndis_request *get_rndis_request(struct rndis_device *dev,\n+\t\t\t\t\tu32 msg_type, u32 msg_len);\n+void put_rndis_request(struct rndis_device *dev, struct rndis_request *req);\n+int rndis_build_page_buffers(const void *data, u32 len,\n+\t\t\t     struct hv_page_buffer *page_bufs,\n+\t\t\t     u32 *page_buf_cnt);\n+\n+void netvsc_send_acct(struct net_device *ndev,\n+\t\t      struct netvsc_device *net_device,\n+\t\t      struct vmbus_channel *channel,\n+\t\t      u16 q_idx);\n+void netvsc_send_tx_complete(struct net_device *ndev,\n+\t\t\t     struct netvsc_device *net_device,\n+\t\t\t     struct vmbus_channel *channel,\n+\t\t\t     const struct vmpacket_descriptor *desc,\n+\t\t\t     int budget);\n+void netvsc_send_completion(struct net_device *ndev,\n+\t\t\t    struct netvsc_device *net_device,\n+\t\t\t    struct vmbus_channel *incoming_channel,\n+\t\t\t    const struct vmpacket_descriptor *desc,\n+\t\t\t    int budget);\n+\n extern u32 netvsc_ring_bytes;\n \n int netvsc_workqueue_init(void);\n@@ -1158,21 +1184,15 @@ struct netvsc_device {\n \tbool tx_disable; /* if true, do not wake up queue again */\n \n \t/* Receive buffer allocated by us but manages by NetVSP */\n-\tvoid *recv_buf;\n+\tstruct vmbus_buffer recv_buffer;\n \tu32 recv_buf_size; /* allocated bytes */\n-\tstruct page **recv_buf_chunks;\n-\tu32 recv_buf_chunk_cnt;\n-\tstruct vmbus_gpadl recv_buf_gpadl_handle;\n \tu32 recv_section_cnt;\n \tu32 recv_section_size;\n \tu32 recv_completion_cnt;\n \n \t/* Send buffer allocated by us */\n-\tvoid *send_buf;\n+\tstruct vmbus_buffer send_buffer;\n \tu32 send_buf_size;\n-\tstruct page **send_buf_chunks;\n-\tu32 send_buf_chunk_cnt;\n-\tstruct vmbus_gpadl send_buf_gpadl_handle;\n \tu32 send_section_cnt;\n \tu32 send_section_size;\n \tunsigned long *send_section_map;\n@@ -1785,6 +1805,36 @@ struct rndis_message {\n \tunion rndis_message_container msg;\n };\n \n+/*\n+ * RNDIS request descriptor. Declared here so the KUnit cases can reach\n+ * the layout the response-copy bound in rndis_filter_receive_resp()\n+ * relies on. The two RNDIS_EXT_LEN tails are what make the object\n+ * larger than KMALLOC_MAX_CACHE_SIZE.\n+ */\n+struct rndis_request {\n+\tstruct list_head list_ent;\n+\tstruct completion  wait_event;\n+\n+\tstruct rndis_message response_msg;\n+\t/*\n+\t * The buffer for extended info after the RNDIS response message. It's\n+\t * referenced based on the data offset in the RNDIS message. Its size\n+\t * is enough for current needs, and should be sufficient for the near\n+\t * future.\n+\t */\n+\tu8 response_ext[RNDIS_EXT_LEN];\n+\n+\t/* Simplify allocation by having a netvsc packet inline */\n+\tstruct hv_netvsc_packet\tpkt;\n+\n+\tstruct rndis_message request_msg;\n+\t/*\n+\t * The buffer for the extended info after the RNDIS request message.\n+\t * It is referenced and sized in a similar way as response_ext.\n+\t */\n+\tu8 request_ext[RNDIS_EXT_LEN];\n+};\n+\n \n /* Handy macros */\n \ndiff --git a/drivers/net/hyperv/netvsc.c b/drivers/net/hyperv/netvsc.c\nindex 5cd084e5696cd..8ea7c993baac0 100644\n--- a/drivers/net/hyperv/netvsc.c\n+++ b/drivers/net/hyperv/netvsc.c\n@@ -134,10 +134,8 @@ static void __free_netvsc_device(struct netvsc_device *nvdev)\n \n \tkfree(nvdev-\u003eextension);\n \n-\tvmbus_free_buffer(nvdev-\u003erecv_buf, nvdev-\u003erecv_buf_chunks,\n-\t\t\t  nvdev-\u003erecv_buf_chunk_cnt);\n-\tvmbus_free_buffer(nvdev-\u003esend_buf, nvdev-\u003esend_buf_chunks,\n-\t\t\t  nvdev-\u003esend_buf_chunk_cnt);\n+\tvmbus_release_buffer(\u0026nvdev-\u003erecv_buffer);\n+\tvmbus_release_buffer(\u0026nvdev-\u003esend_buffer);\n \tbitmap_free(nvdev-\u003esend_section_map);\n \n \tfor (i = 0; i \u003c VRSS_CHANNEL_MAX; i++) {\n@@ -146,7 +144,7 @@ static void __free_netvsc_device(struct netvsc_device *nvdev)\n \t\tvfree(nvdev-\u003echan_table[i].mrc.slots);\n \t}\n \n-\tkfree(nvdev);\n+\tkvfree(nvdev);\n }\n \n static void free_netvsc_device(struct work_struct *w)\n@@ -173,7 +171,7 @@ static struct netvsc_device *alloc_net_device(void)\n {\n \tstruct netvsc_device *net_device;\n \n-\tnet_device = kzalloc_obj(struct netvsc_device);\n+\tnet_device = kvzalloc_obj(struct netvsc_device);\n \tif (!net_device)\n \t\treturn NULL;\n \n@@ -308,9 +306,9 @@ static void netvsc_teardown_recv_gpadl(struct hv_device *device,\n {\n \tint ret;\n \n-\tif (net_device-\u003erecv_buf_gpadl_handle.gpadl_handle) {\n-\t\tret = vmbus_teardown_gpadl(device-\u003echannel,\n-\t\t\t\t\t   \u0026net_device-\u003erecv_buf_gpadl_handle);\n+\tif (net_device-\u003erecv_buffer.gpadl.gpadl_handle) {\n+\t\tret = vmbus_teardown_gpadl_owned(device-\u003echannel,\n+\t\t\t\t\t\t \u0026net_device-\u003erecv_buffer);\n \n \t\t/* If we failed here, we might as well return and have a leak\n \t\t * rather than continue and a bugchk\n@@ -329,9 +327,9 @@ static void netvsc_teardown_send_gpadl(struct hv_device *device,\n {\n \tint ret;\n \n-\tif (net_device-\u003esend_buf_gpadl_handle.gpadl_handle) {\n-\t\tret = vmbus_teardown_gpadl(device-\u003echannel,\n-\t\t\t\t\t   \u0026net_device-\u003esend_buf_gpadl_handle);\n+\tif (net_device-\u003esend_buffer.gpadl.gpadl_handle) {\n+\t\tret = vmbus_teardown_gpadl_owned(device-\u003echannel,\n+\t\t\t\t\t\t \u0026net_device-\u003esend_buffer);\n \n \t\t/* If we failed here, we might as well return and have a leak\n \t\t * rather than continue and a bugchk\n@@ -377,15 +375,13 @@ static int netvsc_init_buf(struct hv_device *device,\n \t\tbuf_size = min_t(unsigned int, buf_size,\n \t\t\t\t NETVSC_RECEIVE_BUFFER_SIZE_LEGACY);\n \n-\tnet_device-\u003erecv_buf =\n-\t\tvmbus_alloc_buffer(device-\u003echannel, buf_size,\n-\t\t\t\t   \u0026net_device-\u003erecv_buf_chunks,\n-\t\t\t\t   \u0026net_device-\u003erecv_buf_chunk_cnt);\n-\tif (!net_device-\u003erecv_buf) {\n+\tret = vmbus_alloc_buffer_owned(device-\u003echannel, buf_size,\n+\t\t\t\t       device-\u003echannel-\u003eco_external_memory,\n+\t\t\t\t       \u0026net_device-\u003erecv_buffer);\n+\tif (ret) {\n \t\tnetdev_err(ndev,\n \t\t\t   \"unable to allocate receive buffer of size %u\\n\",\n \t\t\t   buf_size);\n-\t\tret = -ENOMEM;\n \t\tgoto cleanup;\n \t}\n \n@@ -396,10 +392,8 @@ static int netvsc_init_buf(struct hv_device *device,\n \t * channel.  Note: This call uses the vmbus connection rather\n \t * than the channel to establish the gpadl handle.\n \t */\n-\tret = vmbus_establish_gpadl_caller_decrypted(device-\u003echannel,\n-\t\t\t\t\t\t     net_device-\u003erecv_buf,\n-\t\t\t\t\t\t     buf_size,\n-\t\t\t\t\t\t     \u0026net_device-\u003erecv_buf_gpadl_handle);\n+\tret = vmbus_establish_gpadl_owned(device-\u003echannel,\n+\t\t\t\t\t  \u0026net_device-\u003erecv_buffer);\n \tif (ret != 0) {\n \t\tnetdev_err(ndev,\n \t\t\t\"unable to establish receive buffer's gpadl\\n\");\n@@ -411,7 +405,7 @@ static int netvsc_init_buf(struct hv_device *device,\n \tmemset(init_packet, 0, sizeof(struct nvsp_message));\n \tinit_packet-\u003ehdr.msg_type = NVSP_MSG1_TYPE_SEND_RECV_BUF;\n \tinit_packet-\u003emsg.v1_msg.send_recv_buf.\n-\t\tgpadl_handle = net_device-\u003erecv_buf_gpadl_handle.gpadl_handle;\n+\t\tgpadl_handle = net_device-\u003erecv_buffer.gpadl.gpadl_handle;\n \tinit_packet-\u003emsg.v1_msg.\n \t\tsend_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;\n \n@@ -487,14 +481,12 @@ static int netvsc_init_buf(struct hv_device *device,\n \tbuf_size = device_info-\u003esend_sections * device_info-\u003esend_section_size;\n \tbuf_size = round_up(buf_size, PAGE_SIZE);\n \n-\tnet_device-\u003esend_buf =\n-\t\tvmbus_alloc_buffer(device-\u003echannel, buf_size,\n-\t\t\t\t   \u0026net_device-\u003esend_buf_chunks,\n-\t\t\t\t   \u0026net_device-\u003esend_buf_chunk_cnt);\n-\tif (!net_device-\u003esend_buf) {\n+\tret = vmbus_alloc_buffer_owned(device-\u003echannel, buf_size,\n+\t\t\t\t       device-\u003echannel-\u003eco_external_memory,\n+\t\t\t\t       \u0026net_device-\u003esend_buffer);\n+\tif (ret) {\n \t\tnetdev_err(ndev, \"unable to allocate send buffer of size %u\\n\",\n \t\t\t   buf_size);\n-\t\tret = -ENOMEM;\n \t\tgoto cleanup;\n \t}\n \tnet_device-\u003esend_buf_size = buf_size;\n@@ -503,10 +495,8 @@ static int netvsc_init_buf(struct hv_device *device,\n \t * channel.  Note: This call uses the vmbus connection rather\n \t * than the channel to establish the gpadl handle.\n \t */\n-\tret = vmbus_establish_gpadl_caller_decrypted(device-\u003echannel,\n-\t\t\t\t\t\t     net_device-\u003esend_buf,\n-\t\t\t\t\t\t     buf_size,\n-\t\t\t\t\t\t     \u0026net_device-\u003esend_buf_gpadl_handle);\n+\tret = vmbus_establish_gpadl_owned(device-\u003echannel,\n+\t\t\t\t\t  \u0026net_device-\u003esend_buffer);\n \tif (ret != 0) {\n \t\tnetdev_err(ndev,\n \t\t\t   \"unable to establish send buffer's gpadl\\n\");\n@@ -518,7 +508,7 @@ static int netvsc_init_buf(struct hv_device *device,\n \tmemset(init_packet, 0, sizeof(struct nvsp_message));\n \tinit_packet-\u003ehdr.msg_type = NVSP_MSG1_TYPE_SEND_SEND_BUF;\n \tinit_packet-\u003emsg.v1_msg.send_send_buf.gpadl_handle =\n-\t\tnet_device-\u003esend_buf_gpadl_handle.gpadl_handle;\n+\t\tnet_device-\u003esend_buffer.gpadl.gpadl_handle;\n \tinit_packet-\u003emsg.v1_msg.send_send_buf.id = NETVSC_SEND_BUFFER_ID;\n \n \ttrace_nvsp_send(ndev, init_packet);\n@@ -774,20 +764,45 @@ static inline void netvsc_free_send_slot(struct netvsc_device *net_device,\n \tsync_change_bit(index, net_device-\u003esend_section_map);\n }\n \n-static void netvsc_send_tx_complete(struct net_device *ndev,\n-\t\t\t\t    struct netvsc_device *net_device,\n-\t\t\t\t    struct vmbus_channel *channel,\n-\t\t\t\t    const struct vmpacket_descriptor *desc,\n-\t\t\t\t    int budget)\n+void netvsc_send_acct(struct net_device *ndev,\n+\t\t      struct netvsc_device *net_device,\n+\t\t      struct vmbus_channel *channel,\n+\t\t      u16 q_idx)\n+{\n+\tstruct net_device_context *ndev_ctx = netdev_priv(ndev);\n+\tint queue_sends;\n+\n+\tqueue_sends =\n+\t\tatomic_dec_return(\u0026net_device-\u003echan_table[q_idx].queue_sends);\n+\n+\tif (unlikely(net_device-\u003edestroy)) {\n+\t\tif (queue_sends == 0)\n+\t\t\twake_up(\u0026net_device-\u003ewait_drain);\n+\t} else {\n+\t\tstruct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);\n+\n+\t\tif (netif_tx_queue_stopped(txq) \u0026\u0026 !net_device-\u003etx_disable \u0026\u0026\n+\t\t    (hv_get_avail_to_write_percent(\u0026channel-\u003eoutbound) \u003e\n+\t\t     RING_AVAIL_PERCENT_HIWATER || queue_sends \u003c 1)) {\n+\t\t\tnetif_tx_wake_queue(txq);\n+\t\t\tndev_ctx-\u003eeth_stats.wake_queue++;\n+\t\t}\n+\t}\n+}\n+\n+void netvsc_send_tx_complete(struct net_device *ndev,\n+\t\t\t     struct netvsc_device *net_device,\n+\t\t\t     struct vmbus_channel *channel,\n+\t\t\t     const struct vmpacket_descriptor *desc,\n+\t\t\t     int budget)\n {\n \tstruct net_device_context *ndev_ctx = netdev_priv(ndev);\n \tstruct sk_buff *skb;\n \tu16 q_idx = 0;\n-\tint queue_sends;\n \tu64 cmd_rqst;\n \n \tcmd_rqst = channel-\u003erequest_addr_callback(channel, desc-\u003etrans_id);\n-\tif (cmd_rqst == VMBUS_RQST_ERROR) {\n+\tif (cmd_rqst == VMBUS_RQST_ERROR || cmd_rqst == VMBUS_NO_RQSTOR) {\n \t\tnetdev_err(ndev, \"Invalid transaction ID %llx\\n\", desc-\u003etrans_id);\n \t\treturn;\n \t}\n@@ -816,29 +831,14 @@ static void netvsc_send_tx_complete(struct net_device *ndev,\n \t\tnapi_consume_skb(skb, budget);\n \t}\n \n-\tqueue_sends =\n-\t\tatomic_dec_return(\u0026net_device-\u003echan_table[q_idx].queue_sends);\n-\n-\tif (unlikely(net_device-\u003edestroy)) {\n-\t\tif (queue_sends == 0)\n-\t\t\twake_up(\u0026net_device-\u003ewait_drain);\n-\t} else {\n-\t\tstruct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);\n-\n-\t\tif (netif_tx_queue_stopped(txq) \u0026\u0026 !net_device-\u003etx_disable \u0026\u0026\n-\t\t    (hv_get_avail_to_write_percent(\u0026channel-\u003eoutbound) \u003e\n-\t\t     RING_AVAIL_PERCENT_HIWATER || queue_sends \u003c 1)) {\n-\t\t\tnetif_tx_wake_queue(txq);\n-\t\t\tndev_ctx-\u003eeth_stats.wake_queue++;\n-\t\t}\n-\t}\n+\tnetvsc_send_acct(ndev, net_device, channel, q_idx);\n }\n \n-static void netvsc_send_completion(struct net_device *ndev,\n-\t\t\t\t   struct netvsc_device *net_device,\n-\t\t\t\t   struct vmbus_channel *incoming_channel,\n-\t\t\t\t   const struct vmpacket_descriptor *desc,\n-\t\t\t\t   int budget)\n+void netvsc_send_completion(struct net_device *ndev,\n+\t\t\t    struct netvsc_device *net_device,\n+\t\t\t    struct vmbus_channel *incoming_channel,\n+\t\t\t    const struct vmpacket_descriptor *desc,\n+\t\t\t    int budget)\n {\n \tconst struct nvsp_message *nvsp_packet;\n \tu32 msglen = hv_pkt_datalen(desc);\n@@ -850,11 +850,24 @@ static void netvsc_send_completion(struct net_device *ndev,\n \tif (!msglen) {\n \t\tcmd_rqst = incoming_channel-\u003erequest_addr_callback(incoming_channel,\n \t\t\t\t\t\t\t\t   desc-\u003etrans_id);\n-\t\tif (cmd_rqst == VMBUS_RQST_ERROR) {\n+\t\tif (cmd_rqst == VMBUS_RQST_ERROR || cmd_rqst == VMBUS_NO_RQSTOR) {\n \t\t\tnetdev_err(ndev, \"Invalid transaction ID %llx\\n\", desc-\u003etrans_id);\n \t\t\treturn;\n \t\t}\n \n+\t\t/*\n+\t\t * netvsc_send_pkt() registers (ulong)skb as the request\n+\t\t * address. Control RNDIS sends carry no skb, so the\n+\t\t * registered address is NULL and there is no nvsp_message\n+\t\t * to inspect. The request id is consumed above, so this\n+\t\t * completion owns the send accounting -- the same thing\n+\t\t * netvsc_send_tx_complete() does when it sees a NULL skb.\n+\t\t */\n+\t\tif (!cmd_rqst) {\n+\t\t\tnetvsc_send_acct(ndev, net_device, incoming_channel, 0);\n+\t\t\treturn;\n+\t\t}\n+\n \t\tpkt_rqst = (struct nvsp_message *)(uintptr_t)cmd_rqst;\n \t\tswitch (pkt_rqst-\u003ehdr.msg_type) {\n \t\tcase NVSP_MSG4_TYPE_SWITCH_DATA_PATH:\n@@ -968,7 +981,7 @@ static void netvsc_copy_to_send_buf(struct netvsc_device *net_device,\n \t\t\t\t    struct hv_page_buffer *pb,\n \t\t\t\t    bool xmit_more)\n {\n-\tchar *start = net_device-\u003esend_buf;\n+\tchar *start = net_device-\u003esend_buffer.addr;\n \tchar *dest = start + (section_index * net_device-\u003esend_section_size)\n \t\t     + pend_size;\n \tint i;\n@@ -1475,7 +1488,7 @@ static int netvsc_receive(struct net_device *ndev,\n \tconst struct nvsp_message *nvsp = hv_pkt_data(desc);\n \tu32 msglen = hv_pkt_datalen(desc);\n \tu16 q_idx = channel-\u003eoffermsg.offer.sub_channel_index;\n-\tchar *recv_buf = net_device-\u003erecv_buf;\n+\tchar *recv_buf = net_device-\u003erecv_buffer.addr;\n \tu32 status = NVSP_STAT_SUCCESS;\n \tint i;\n \tint count = 0;\ndiff --git a/drivers/net/hyperv/netvsc_completion_test.c b/drivers/net/hyperv/netvsc_completion_test.c\nnew file mode 100644\nindex 0000000000000..2614b1ece2327\n--- /dev/null\n+++ b/drivers/net/hyperv/netvsc_completion_test.c\n@@ -0,0 +1,439 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * KUnit tests for empty and skb-backed netvsc completion handling.\n+ *\n+ * Built into the hv_netvsc object rather than a separate module so the\n+ * cases can reach the internal helpers declared in hyperv_net.h\n+ * without exporting them.\n+ */\n+#include \u003ckunit/test.h\u003e\n+#include \u003clinux/etherdevice.h\u003e\n+#include \u003clinux/hyperv.h\u003e\n+#include \u003clinux/netdevice.h\u003e\n+#include \u003clinux/skbuff.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/wait.h\u003e\n+\n+#include \"hyperv_net.h\"\n+\n+/*\n+ * Scripted requestor. request_addr_callback() only receives the channel\n+ * and the transaction id, so the fixture is hung off a file-scope\n+ * pointer. KUnit runs suite cases serially; one active fixture is\n+ * enough and keeps the callback signature untouched.\n+ */\n+struct netvsc_completion_fixture {\n+\tstruct net_device *ndev;\n+\tstruct netvsc_device *nvdev;\n+\tstruct vmbus_channel *channel;\n+\t/* Address returned on first use, then VMBUS_NO_RQSTOR: the id is\n+\t * consumed exactly once, as vmbus_request_addr_match() does.\n+\t */\n+\tu64 once_addr;\n+\tunsigned int calls;\n+\tu64 seen_ids[8];\n+\tunsigned int skb_frees;\n+};\n+\n+static struct netvsc_completion_fixture *active_fx;\n+\n+static u64 test_request_addr(struct vmbus_channel *channel, u64 rqst_id)\n+{\n+\tstruct netvsc_completion_fixture *fx = active_fx;\n+\n+\tif (fx-\u003ecalls \u003c ARRAY_SIZE(fx-\u003eseen_ids))\n+\t\tfx-\u003eseen_ids[fx-\u003ecalls] = rqst_id;\n+\tfx-\u003ecalls++;\n+\n+\tif (fx-\u003ecalls == 1)\n+\t\treturn fx-\u003eonce_addr;\n+\treturn VMBUS_NO_RQSTOR;\n+}\n+\n+/*\n+ * A completion carrying no payload: hv_pkt_datalen() == 0. The\n+ * empty-completion path looks the request up by trans_id and reads its\n+ * message type, so the request itself is a separate object the fixture\n+ * hands back through request_addr_callback().\n+ */\n+struct netvsc_empty_desc {\n+\tstruct vmpacket_descriptor desc;\n+} __packed;\n+\n+static void make_empty_desc(struct netvsc_empty_desc *pkt, u64 trans_id)\n+{\n+\tmemset(pkt, 0, sizeof(*pkt));\n+\tpkt-\u003edesc.offset8 = sizeof(pkt-\u003edesc) / 8;\n+\tpkt-\u003edesc.len8 = pkt-\u003edesc.offset8;\n+\tpkt-\u003edesc.trans_id = trans_id;\n+}\n+\n+/*\n+ * The production path never dereferences a net_device queue while\n+ * tx_disable is set: netif_tx_queue_stopped() \u0026\u0026 !tx_disable\n+ * short-circuits before hv_get_avail_to_write_percent() reads the\n+ * ring. Set it here so a test needs no live outbound ring.\n+ */\n+static int netvsc_completion_fixture_init(struct netvsc_completion_fixture *fx)\n+{\n+\tfx-\u003endev = alloc_netdev_mqs(sizeof(struct net_device_context),\n+\t\t\t\t    \"hvcompl%d\", NET_NAME_UNKNOWN,\n+\t\t\t\t    ether_setup, 2, 2);\n+\tif (!fx-\u003endev)\n+\t\treturn -ENOMEM;\n+\n+\tfx-\u003envdev = kzalloc_obj(*fx-\u003envdev, GFP_KERNEL);\n+\tif (!fx-\u003envdev) {\n+\t\tfree_netdev(fx-\u003endev);\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\tfx-\u003echannel = kzalloc_obj(*fx-\u003echannel, GFP_KERNEL);\n+\tif (!fx-\u003echannel) {\n+\t\tkfree(fx-\u003envdev);\n+\t\tfree_netdev(fx-\u003endev);\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\tinit_waitqueue_head(\u0026fx-\u003envdev-\u003ewait_drain);\n+\tinit_completion(\u0026fx-\u003envdev-\u003echannel_init_wait);\n+\tfx-\u003envdev-\u003etx_disable = true;\n+\tfx-\u003echannel-\u003erequest_addr_callback = test_request_addr;\n+\tfx-\u003eonce_addr = 0;\n+\tfx-\u003ecalls = 0;\n+\tmemset(fx-\u003eseen_ids, 0, sizeof(fx-\u003eseen_ids));\n+\tactive_fx = fx;\n+\treturn 0;\n+}\n+\n+static void netvsc_completion_fixture_exit(struct netvsc_completion_fixture *fx)\n+{\n+\tactive_fx = NULL;\n+\tkfree(fx-\u003echannel);\n+\tkfree(fx-\u003envdev);\n+\tfree_netdev(fx-\u003endev);\n+}\n+\n+static int netvsc_send_sends(struct netvsc_completion_fixture *fx, u16 q_idx)\n+{\n+\treturn atomic_read(\u0026fx-\u003envdev-\u003echan_table[q_idx].queue_sends);\n+}\n+\n+/* Empty completion, request address NULL: owns the send accounting. */\n+static void netvsc_completion_null_address_acct_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x11);\n+\t/* once_addr = 0 is the control-path NULL skb case. */\n+\tfx.once_addr = 0;\n+\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 2);\n+\tKUNIT_EXPECT_FALSE(test, completion_done(\u0026fx.nvdev-\u003echannel_init_wait));\n+\tKUNIT_EXPECT_EQ(test, fx.calls, 1U);\n+\tKUNIT_EXPECT_EQ(test, fx.seen_ids[0], 0x11U);\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/* VMBUS_RQST_ERROR is rejected: no accounting, no completion. */\n+static void netvsc_completion_rqst_error_sentinel_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x22);\n+\tfx.once_addr = VMBUS_RQST_ERROR;\n+\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 3);\n+\tKUNIT_EXPECT_FALSE(test, completion_done(\u0026fx.nvdev-\u003echannel_init_wait));\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/* VMBUS_NO_RQSTOR is rejected the same way. */\n+static void netvsc_completion_no_rqstor_sentinel_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x33);\n+\tfx.once_addr = VMBUS_NO_RQSTOR;\n+\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 3);\n+\tKUNIT_EXPECT_FALSE(test, completion_done(\u0026fx.nvdev-\u003echannel_init_wait));\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/*\n+ * A real request address whose message type is SWITCH_DATA_PATH\n+ * completes the channel-init wait. It is not send accounting: the\n+ * control request was not a send.\n+ */\n+static void netvsc_completion_switch_data_path_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\tstruct nvsp_message req = {};\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x44);\n+\treq.hdr.msg_type = NVSP_MSG4_TYPE_SWITCH_DATA_PATH;\n+\tfx.once_addr = (u64)(unsigned long)\u0026req;\n+\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\n+\tKUNIT_EXPECT_TRUE(test, completion_done(\u0026fx.nvdev-\u003echannel_init_wait));\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 3);\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/* An unexpected message type takes neither the complete nor the acct path. */\n+static void netvsc_completion_unknown_msg_type_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\tstruct nvsp_message req = {};\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x55);\n+\treq.hdr.msg_type = 0xdead;\n+\tfx.once_addr = (u64)(unsigned long)\u0026req;\n+\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\n+\tKUNIT_EXPECT_FALSE(test, completion_done(\u0026fx.nvdev-\u003echannel_init_wait));\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 3);\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/*\n+ * A repeated completion for an already-consumed transaction id must not\n+ * account twice. The requestor returns VMBUS_NO_RQSTOR on the second\n+ * use and the empty-completion path rejects it.\n+ */\n+static void netvsc_completion_duplicate_completion_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x66);\n+\tfx.once_addr = 0;\n+\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 2);\n+\tKUNIT_EXPECT_EQ(test, fx.calls, 1U);\n+\n+\t/* Second completion for the same id: already consumed. */\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 2);\n+\tKUNIT_EXPECT_EQ(test, fx.calls, 2U);\n+\tKUNIT_EXPECT_EQ(test, fx.seen_ids[0], 0x66U);\n+\tKUNIT_EXPECT_EQ(test, fx.seen_ids[1], 0x66U);\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/* N completions decrement the queue exactly N times. */\n+static void netvsc_completion_single_decrement_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\tint i;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 5);\n+\n+\tfor (i = 0; i \u003c 5; i++) {\n+\t\tmake_empty_desc(\u0026pkt, 0x100 + i);\n+\t\tfx.once_addr = 0;\n+\t\tfx.calls = 0;\n+\t\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel,\n+\t\t\t\t       \u0026pkt.desc, 0);\n+\t\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 4 - i);\n+\t\tKUNIT_EXPECT_EQ(test, fx.calls, 1U);\n+\t}\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 0);\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+static int netvsc_test_wake(struct wait_queue_entry *wq_entry,\n+\t\t\t    unsigned int mode, int flags, void *key)\n+{\n+\tunsigned int *woken = wq_entry-\u003eprivate;\n+\n+\t(*woken)++;\n+\treturn 0;\n+}\n+\n+/* destroy + a decrement that reaches zero wakes the drain wait. */\n+static void netvsc_send_acct_drain_wake_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct wait_queue_entry entry;\n+\tunsigned int woken = 0;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tfx.nvdev-\u003edestroy = true;\n+\n+\tmemset(\u0026entry, 0, sizeof(entry));\n+\tentry.func = netvsc_test_wake;\n+\tentry.private = \u0026woken;\n+\tadd_wait_queue(\u0026fx.nvdev-\u003ewait_drain, \u0026entry);\n+\n+\t/* Non-zero remainder: the drain wait is not woken. */\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 2);\n+\tnetvsc_send_acct(fx.ndev, fx.nvdev, fx.channel, 0);\n+\tKUNIT_EXPECT_EQ(test, woken, 0U);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 1);\n+\n+\t/* Exactly zero: the drain wait is woken once. */\n+\tnetvsc_send_acct(fx.ndev, fx.nvdev, fx.channel, 0);\n+\tKUNIT_EXPECT_EQ(test, woken, 1U);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 0);\n+\n+\tremove_wait_queue(\u0026fx.nvdev-\u003ewait_drain, \u0026entry);\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+/*\n+ * netvsc_send_tx_complete() applies the same sentinel rejection and\n+ * still accounts a NULL skb.\n+ */\n+static void netvsc_tx_complete_null_skb_acct_test(struct kunit *test)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct netvsc_empty_desc pkt;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 3);\n+\tmake_empty_desc(\u0026pkt, 0x77);\n+\tfx.once_addr = 0;\n+\n+\tnetvsc_send_tx_complete(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 2);\n+\n+\t/* The sentinel is rejected before any accounting. */\n+\tmake_empty_desc(\u0026pkt, 0x78);\n+\tfx.once_addr = VMBUS_RQST_ERROR;\n+\tfx.calls = 0;\n+\tnetvsc_send_tx_complete(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 2);\n+\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+static void netvsc_test_skb_destructor(struct sk_buff *skb)\n+{\n+\tactive_fx-\u003eskb_frees++;\n+}\n+\n+static void netvsc_tx_complete_skb(struct kunit *test, u32 status)\n+{\n+\tstruct netvsc_completion_fixture fx = {};\n+\tstruct {\n+\t\tstruct vmpacket_descriptor desc;\n+\t\tstruct nvsp_message message;\n+\t} pkt = {};\n+\tunsigned long send_slots = BIT(3);\n+\tstruct hv_netvsc_packet *packet;\n+\tstruct netvsc_stats_tx *stats;\n+\tstruct sk_buff *skb;\n+\n+\tKUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(\u0026fx), 0);\n+\tskb = alloc_skb(64, GFP_KERNEL);\n+\tif (!skb) {\n+\t\tKUNIT_FAIL(test, \"skb allocation failed\");\n+\t\tgoto out;\n+\t}\n+\tskb-\u003edestructor = netvsc_test_skb_destructor;\n+\tpacket = (struct hv_netvsc_packet *)skb-\u003ecb;\n+\tmemset(packet, 0, sizeof(*packet));\n+\tpacket-\u003esend_buf_index = 3;\n+\tpacket-\u003eq_idx = 1;\n+\tpacket-\u003etotal_packets = 2;\n+\tpacket-\u003etotal_bytes = 64;\n+\tfx.nvdev-\u003esend_section_map = \u0026send_slots;\n+\tstats = \u0026fx.nvdev-\u003echan_table[1].tx_stats;\n+\tu64_stats_init(\u0026stats-\u003esyncp);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[0].queue_sends, 7);\n+\tatomic_set(\u0026fx.nvdev-\u003echan_table[1].queue_sends, 3);\n+\tfx.once_addr = (u64)(unsigned long)skb;\n+\tpkt.desc.offset8 = sizeof(pkt.desc) / 8;\n+\tpkt.desc.len8 = DIV_ROUND_UP(sizeof(pkt), 8);\n+\tpkt.desc.trans_id = 0x79;\n+\tpkt.message.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE;\n+\tpkt.message.msg.v1_msg.send_rndis_pkt_complete.status = status;\n+\n+\t/* Budget zero consumes the real skb synchronously, outside NAPI. */\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\tKUNIT_EXPECT_EQ(test, send_slots, 0UL);\n+\tKUNIT_EXPECT_EQ(test, fx.skb_frees, 1U);\n+\tKUNIT_EXPECT_EQ(test, stats-\u003epackets, 2ULL);\n+\tKUNIT_EXPECT_EQ(test, stats-\u003ebytes, 64ULL);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 0), 7);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 1), 2);\n+\n+\t/* The consumed transaction cannot free or account the skb twice. */\n+\tnetvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, \u0026pkt.desc, 0);\n+\tKUNIT_EXPECT_EQ(test, send_slots, 0UL);\n+\tKUNIT_EXPECT_EQ(test, fx.skb_frees, 1U);\n+\tKUNIT_EXPECT_EQ(test, stats-\u003epackets, 2ULL);\n+\tKUNIT_EXPECT_EQ(test, stats-\u003ebytes, 64ULL);\n+\tKUNIT_EXPECT_EQ(test, netvsc_send_sends(\u0026fx, 1), 2);\n+out:\n+\tnetvsc_completion_fixture_exit(\u0026fx);\n+}\n+\n+static void netvsc_tx_complete_skb_success_test(struct kunit *test)\n+{\n+\tnetvsc_tx_complete_skb(test, NVSP_STAT_SUCCESS);\n+}\n+\n+static void netvsc_tx_complete_skb_error_test(struct kunit *test)\n+{\n+\tnetvsc_tx_complete_skb(test, NVSP_STAT_FAIL);\n+}\n+\n+static struct kunit_case netvsc_completion_test_cases[] = {\n+\tKUNIT_CASE(netvsc_completion_null_address_acct_test),\n+\tKUNIT_CASE(netvsc_completion_rqst_error_sentinel_test),\n+\tKUNIT_CASE(netvsc_completion_no_rqstor_sentinel_test),\n+\tKUNIT_CASE(netvsc_completion_switch_data_path_test),\n+\tKUNIT_CASE(netvsc_completion_unknown_msg_type_test),\n+\tKUNIT_CASE(netvsc_completion_duplicate_completion_test),\n+\tKUNIT_CASE(netvsc_completion_single_decrement_test),\n+\tKUNIT_CASE(netvsc_send_acct_drain_wake_test),\n+\tKUNIT_CASE(netvsc_tx_complete_null_skb_acct_test),\n+\tKUNIT_CASE(netvsc_tx_complete_skb_success_test),\n+\tKUNIT_CASE(netvsc_tx_complete_skb_error_test),\n+\t{}\n+};\n+\n+static struct kunit_suite netvsc_completion_test_suite = {\n+\t.name = \"hyperv-netvsc-completion\",\n+\t.test_cases = netvsc_completion_test_cases,\n+};\n+\n+kunit_test_suite(netvsc_completion_test_suite);\ndiff --git a/drivers/net/hyperv/rndis_filter.c b/drivers/net/hyperv/rndis_filter.c\nindex 9b6c44979b4ea..1ce40baa2d239 100644\n--- a/drivers/net/hyperv/rndis_filter.c\n+++ b/drivers/net/hyperv/rndis_filter.c\n@@ -16,6 +16,7 @@\n #include \u003clinux/if_ether.h\u003e\n #include \u003clinux/netdevice.h\u003e\n #include \u003clinux/if_vlan.h\u003e\n+#include \u003clinux/mm.h\u003e\n #include \u003clinux/nls.h\u003e\n #include \u003clinux/vmalloc.h\u003e\n #include \u003clinux/rtnetlink.h\u003e\n@@ -27,31 +28,6 @@\n \n static void rndis_set_multicast(struct work_struct *w);\n \n-#define RNDIS_EXT_LEN HV_HYP_PAGE_SIZE\n-struct rndis_request {\n-\tstruct list_head list_ent;\n-\tstruct completion  wait_event;\n-\n-\tstruct rndis_message response_msg;\n-\t/*\n-\t * The buffer for extended info after the RNDIS response message. It's\n-\t * referenced based on the data offset in the RNDIS message. Its size\n-\t * is enough for current needs, and should be sufficient for the near\n-\t * future.\n-\t */\n-\tu8 response_ext[RNDIS_EXT_LEN];\n-\n-\t/* Simplify allocation by having a netvsc packet inline */\n-\tstruct hv_netvsc_packet\tpkt;\n-\n-\tstruct rndis_message request_msg;\n-\t/*\n-\t * The buffer for the extended info after the RNDIS request message.\n-\t * It is referenced and sized in a similar way as response_ext.\n-\t */\n-\tu8 request_ext[RNDIS_EXT_LEN];\n-};\n-\n static const u8 netvsc_hash_key[NETVSC_HASH_KEYLEN] = {\n \t0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2,\n \t0x41, 0x67, 0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0,\n@@ -78,16 +54,27 @@ static struct rndis_device *get_rndis_device(void)\n \treturn device;\n }\n \n-static struct rndis_request *get_rndis_request(struct rndis_device *dev,\n-\t\t\t\t\t     u32 msg_type,\n-\t\t\t\t\t     u32 msg_len)\n+struct rndis_request *get_rndis_request(struct rndis_device *dev,\n+\t\t\t\t\tu32 msg_type,\n+\t\t\t\t\tu32 msg_len)\n {\n \tstruct rndis_request *request;\n \tstruct rndis_message *rndis_msg;\n \tstruct rndis_set_request *set;\n \tunsigned long flags;\n \n-\trequest = kzalloc_obj(struct rndis_request);\n+\t/*\n+\t * struct rndis_request embeds two RNDIS_EXT_LEN (4 KiB) protocol\n+\t * tails and is larger than KMALLOC_MAX_CACHE_SIZE, so\n+\t * kzalloc_obj() needs an order-2 compound page. That high-order\n+\t * allocation can fail under buddy fragmentation. kvzalloc_obj()\n+\t * keeps the zeroing semantics while allowing vmalloc backing when\n+\t * a suitable kmalloc allocation is unavailable. The request payload\n+\t * is sent as GPADL-direct page buffers, so rndis_filter_send_request()\n+\t * must describe each backing page instead of assuming virt_to_phys()\n+\t * yields one contiguous physical range.\n+\t */\n+\trequest = kvzalloc_obj(struct rndis_request);\n \tif (!request)\n \t\treturn NULL;\n \n@@ -115,8 +102,8 @@ static struct rndis_request *get_rndis_request(struct rndis_device *dev,\n \treturn request;\n }\n \n-static void put_rndis_request(struct rndis_device *dev,\n-\t\t\t    struct rndis_request *req)\n+void put_rndis_request(struct rndis_device *dev,\n+\t\t       struct rndis_request *req)\n {\n \tunsigned long flags;\n \n@@ -124,7 +111,8 @@ static void put_rndis_request(struct rndis_device *dev,\n \tlist_del(\u0026req-\u003elist_ent);\n \tspin_unlock_irqrestore(\u0026dev-\u003erequest_lock, flags);\n \n-\tkfree(req);\n+\t/* Paired with the kvzalloc_obj() in get_rndis_request(). */\n+\tkvfree(req);\n }\n \n static void dump_rndis_message(struct net_device *netdev,\n@@ -221,27 +209,78 @@ static void dump_rndis_message(struct net_device *netdev,\n \t}\n }\n \n+int rndis_build_page_buffers(const void *data, u32 len,\n+\t\t\t     struct hv_page_buffer *page_bufs,\n+\t\t\t     u32 *page_buf_cnt)\n+{\n+\tconst u8 *addr = data;\n+\tu32 count = 0;\n+\n+\tif (!data || !len || !page_bufs || !page_buf_cnt)\n+\t\treturn -EINVAL;\n+\n+\t*page_buf_cnt = 0;\n+\n+\twhile (len) {\n+\t\tstruct page *page;\n+\t\tphys_addr_t phys;\n+\t\tu32 offset, chunk;\n+\t\tunsigned long page_offset = offset_in_page(addr);\n+\n+\t\tif (count == MAX_PAGE_BUFFER_COUNT)\n+\t\t\treturn -E2BIG;\n+\n+\t\tif (is_vmalloc_addr(addr))\n+\t\t\tpage = vmalloc_to_page(addr);\n+\t\telse if (virt_addr_valid(addr))\n+\t\t\tpage = virt_to_page(addr);\n+\t\telse\n+\t\t\treturn -EFAULT;\n+\n+\t\tif (!page)\n+\t\t\treturn -EFAULT;\n+\n+\t\tphys = page_to_phys(page) + page_offset;\n+\t\toffset = offset_in_hvpage(phys);\n+\t\tchunk = min_t(u32, len, PAGE_SIZE - page_offset);\n+\t\tchunk = min_t(u32, chunk, HV_HYP_PAGE_SIZE - offset);\n+\n+\t\tpage_bufs[count].pfn = phys \u003e\u003e HV_HYP_PAGE_SHIFT;\n+\t\tpage_bufs[count].offset = offset;\n+\t\tpage_bufs[count].len = chunk;\n+\n+\t\taddr += chunk;\n+\t\tlen -= chunk;\n+\t\tcount++;\n+\t}\n+\n+\t*page_buf_cnt = count;\n+\treturn 0;\n+}\n+\n static int rndis_filter_send_request(struct rndis_device *dev,\n \t\t\t\t  struct rndis_request *req)\n {\n \tstruct hv_netvsc_packet *packet;\n-\tstruct hv_page_buffer pb;\n+\tstruct hv_page_buffer page_bufs[MAX_PAGE_BUFFER_COUNT];\n+\tu32 page_buf_cnt;\n \tint ret;\n \n \t/* Setup the packet to send it */\n \tpacket = \u0026req-\u003epkt;\n \n \tpacket-\u003etotal_data_buflen = req-\u003erequest_msg.msg_len;\n-\tpacket-\u003epage_buf_cnt = 1;\n-\n-\tpb.pfn = virt_to_phys(\u0026req-\u003erequest_msg) \u003e\u003e HV_HYP_PAGE_SHIFT;\n-\tpb.len = req-\u003erequest_msg.msg_len;\n-\tpb.offset = offset_in_hvpage(\u0026req-\u003erequest_msg);\n+\tret = rndis_build_page_buffers(\u0026req-\u003erequest_msg,\n+\t\t\t\t       req-\u003erequest_msg.msg_len,\n+\t\t\t\t       page_bufs, \u0026page_buf_cnt);\n+\tif (ret)\n+\t\treturn ret;\n+\tpacket-\u003epage_buf_cnt = page_buf_cnt;\n \n \ttrace_rndis_send(dev-\u003endev, 0, \u0026req-\u003erequest_msg);\n \n \trcu_read_lock_bh();\n-\tret = netvsc_send(dev-\u003endev, packet, NULL, \u0026pb, NULL, false);\n+\tret = netvsc_send(dev-\u003endev, packet, NULL, page_bufs, NULL, false);\n \trcu_read_unlock_bh();\n \n \treturn ret;\ndiff --git a/drivers/net/hyperv/rndis_request_test.c b/drivers/net/hyperv/rndis_request_test.c\nnew file mode 100644\nindex 0000000000000..6affa916e74e3\n--- /dev/null\n+++ b/drivers/net/hyperv/rndis_request_test.c\n@@ -0,0 +1,216 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * KUnit tests for RNDIS request descriptor allocation.\n+ *\n+ * Built into the hv_netvsc object rather than a separate module so the\n+ * cases can reach the internal helpers declared in hyperv_net.h\n+ * without exporting them.\n+ */\n+#include \u003ckunit/test.h\u003e\n+#include \u003clinux/hyperv.h\u003e\n+#include \u003clinux/mm.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/stddef.h\u003e\n+#include \u003clinux/vmalloc.h\u003e\n+\n+#include \"hyperv_net.h\"\n+\n+static int rndis_test_device_init(struct rndis_device *dev)\n+{\n+\tmemset(dev, 0, sizeof(*dev));\n+\tatomic_set(\u0026dev-\u003enew_req_id, 0);\n+\tspin_lock_init(\u0026dev-\u003erequest_lock);\n+\tINIT_LIST_HEAD(\u0026dev-\u003ereq_list);\n+\treturn 0;\n+}\n+\n+/*\n+ * The premise of the kvzalloc_obj() conversion: the descriptor embeds\n+ * two RNDIS_EXT_LEN protocol tails and sits past\n+ * KMALLOC_MAX_CACHE_SIZE, so kzalloc_obj() reached kmalloc_large() and\n+ * took an order-2 compound page on the subchannel open path. If the\n+ * struct ever drops back inside the cache, the conversion stops being\n+ * about high-order allocation and this assertion is the reminder.\n+ */\n+static void rndis_request_size_premise_test(struct kunit *test)\n+{\n+\tKUNIT_EXPECT_GT(test, sizeof(struct rndis_request),\n+\t\t\t(size_t)KMALLOC_MAX_CACHE_SIZE);\n+\t/*\n+\t * The copy bound in rndis_filter_receive_resp() is\n+\t * sizeof(struct rndis_message) + RNDIS_EXT_LEN. That is exactly\n+\t * the response_msg + response_ext tail of the object. A reorder\n+\t * or a resize of either member makes the bound lie.\n+\t */\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\toffsetofend(struct rndis_request, response_ext),\n+\t\t\toffsetof(struct rndis_request, response_msg) +\n+\t\t\t\tsizeof(struct rndis_message) + RNDIS_EXT_LEN);\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\toffsetofend(struct rndis_request, request_ext),\n+\t\t\toffsetof(struct rndis_request, request_msg) +\n+\t\t\t\tsizeof(struct rndis_message) + RNDIS_EXT_LEN);\n+}\n+\n+/*\n+ * kvzalloc_obj() keeps the zeroing kzalloc_obj() provided. The two\n+ * protocol tails are the fields a response is copied into; a stale\n+ * tail is a stale response.\n+ */\n+static void rndis_request_alloc_zeroed_test(struct kunit *test)\n+{\n+\tstruct rndis_device dev;\n+\tstruct rndis_request *req;\n+\n+\tKUNIT_ASSERT_EQ(test, rndis_test_device_init(\u0026dev), 0);\n+\treq = get_rndis_request(\u0026dev, RNDIS_MSG_INIT, 0x20);\n+\tKUNIT_ASSERT_NOT_NULL(test, req);\n+\n+\tKUNIT_EXPECT_EQ(test, req-\u003eresponse_ext[0], 0);\n+\tKUNIT_EXPECT_EQ(test, req-\u003eresponse_ext[RNDIS_EXT_LEN - 1], 0);\n+\tKUNIT_EXPECT_EQ(test, req-\u003erequest_ext[0], 0);\n+\tKUNIT_EXPECT_EQ(test, req-\u003erequest_ext[RNDIS_EXT_LEN - 1], 0);\n+\tKUNIT_EXPECT_EQ(test, req-\u003eresponse_msg.msg_len, 0U);\n+\n+\tput_rndis_request(\u0026dev, req);\n+}\n+\n+/* Request ids come from a per-device counter and the list tracks the live set. */\n+static void rndis_request_id_lifecycle_test(struct kunit *test)\n+{\n+\tstruct rndis_device dev;\n+\tstruct rndis_request *req0, *req1;\n+\tstruct rndis_request *cursor;\n+\tunsigned int n = 0;\n+\n+\tKUNIT_ASSERT_EQ(test, rndis_test_device_init(\u0026dev), 0);\n+\n+\treq0 = get_rndis_request(\u0026dev, RNDIS_MSG_INIT, 0x20);\n+\tKUNIT_ASSERT_NOT_NULL(test, req0);\n+\treq1 = get_rndis_request(\u0026dev, RNDIS_MSG_QUERY, 0x20);\n+\tKUNIT_ASSERT_NOT_NULL(test, req1);\n+\n+\t/*\n+\t * get_rndis_request() stamps the id through the set_req template,\n+\t * which shares the union slot with every other request body. Read\n+\t * it back through the same member the producer used.\n+\t */\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\treq0-\u003erequest_msg.msg.set_req.req_id, 1U);\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\treq1-\u003erequest_msg.msg.set_req.req_id, 2U);\n+\n+\tlist_for_each_entry(cursor, \u0026dev.req_list, list_ent)\n+\t\tn++;\n+\tKUNIT_EXPECT_EQ(test, n, 2U);\n+\n+\t/*\n+\t * put_rndis_request() is the cleanup path every error and\n+\t * timeout branch takes. It unlinks before it frees.\n+\t */\n+\tput_rndis_request(\u0026dev, req0);\n+\tn = 0;\n+\tlist_for_each_entry(cursor, \u0026dev.req_list, list_ent)\n+\t\tn++;\n+\tKUNIT_EXPECT_EQ(test, n, 1U);\n+\tKUNIT_EXPECT_TRUE(test,\n+\t\t\t  list_first_entry(\u0026dev.req_list, struct rndis_request,\n+\t\t\t\t\t   list_ent) == req1);\n+\n+\tput_rndis_request(\u0026dev, req1);\n+\tKUNIT_EXPECT_TRUE(test, list_empty(\u0026dev.req_list));\n+}\n+\n+/*\n+ * A request left on the list after a completed exchange is a leak of\n+ * the descriptor and of its slot in the outstanding set. Repeated\n+ * get/put cycles must return to the empty list every time.\n+ */\n+static void rndis_request_put_cleanup_test(struct kunit *test)\n+{\n+\tstruct rndis_device dev;\n+\tstruct rndis_request *req;\n+\tint i;\n+\n+\tKUNIT_ASSERT_EQ(test, rndis_test_device_init(\u0026dev), 0);\n+\n+\tfor (i = 0; i \u003c 4; i++) {\n+\t\treq = get_rndis_request(\u0026dev, RNDIS_MSG_INIT, 0x20);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, req);\n+\t\tKUNIT_EXPECT_FALSE(test, list_empty(\u0026dev.req_list));\n+\t\tput_rndis_request(\u0026dev, req);\n+\t\tKUNIT_EXPECT_TRUE(test, list_empty(\u0026dev.req_list));\n+\t}\n+}\n+\n+/*\n+ * kvzalloc_obj() may return a vmalloc address under fragmentation. RNDIS\n+ * requests are GPA-direct packets, so each backing page must be represented\n+ * explicitly instead of deriving a single PFN with virt_to_phys().\n+ */\n+static void rndis_request_vmalloc_page_buffers_test(struct kunit *test)\n+{\n+\tstruct hv_page_buffer page_bufs[MAX_PAGE_BUFFER_COUNT];\n+\tconst u32 data_len = 16;\n+\tu8 *allocation = vzalloc(2 * PAGE_SIZE);\n+\tconst u8 *cursor;\n+\tphys_addr_t phys;\n+\tu32 count = 0, remaining = data_len, i;\n+\tint ret;\n+\n+\tif (!allocation) {\n+\t\tKUNIT_FAIL(test, \"could not allocate vmalloc test buffer\");\n+\t\treturn;\n+\t}\n+\n+\tcursor = allocation + PAGE_SIZE - 8;\n+\tret = rndis_build_page_buffers(cursor, data_len, page_bufs, \u0026count);\n+\tKUNIT_EXPECT_EQ(test, ret, 0);\n+\tif (ret)\n+\t\tgoto out;\n+\n+\tKUNIT_EXPECT_EQ(test, count, 2U);\n+\tfor (i = 0; i \u003c count; i++) {\n+\t\tstruct page *page = vmalloc_to_page(cursor);\n+\t\tunsigned long page_offset = offset_in_page(cursor);\n+\t\tu32 offset, chunk;\n+\n+\t\tif (!page) {\n+\t\t\tKUNIT_FAIL(test, \"vmalloc test buffer has no backing page\");\n+\t\t\tgoto out;\n+\t\t}\n+\n+\t\tphys = page_to_phys(page) + page_offset;\n+\t\toffset = offset_in_hvpage(phys);\n+\t\tchunk = min_t(u32, remaining, PAGE_SIZE - page_offset);\n+\t\tchunk = min_t(u32, chunk, HV_HYP_PAGE_SIZE - offset);\n+\n+\t\tKUNIT_EXPECT_EQ(test, page_bufs[i].pfn,\n+\t\t\t\t(u64)(phys \u003e\u003e HV_HYP_PAGE_SHIFT));\n+\t\tKUNIT_EXPECT_EQ(test, page_bufs[i].offset, offset);\n+\t\tKUNIT_EXPECT_EQ(test, page_bufs[i].len, chunk);\n+\n+\t\tcursor += chunk;\n+\t\tremaining -= chunk;\n+\t}\n+\tKUNIT_EXPECT_EQ(test, remaining, 0U);\n+\n+out:\n+\tvfree(allocation);\n+}\n+\n+static struct kunit_case rndis_request_test_cases[] = {\n+\tKUNIT_CASE(rndis_request_size_premise_test),\n+\tKUNIT_CASE(rndis_request_alloc_zeroed_test),\n+\tKUNIT_CASE(rndis_request_id_lifecycle_test),\n+\tKUNIT_CASE(rndis_request_put_cleanup_test),\n+\tKUNIT_CASE(rndis_request_vmalloc_page_buffers_test),\n+\t{}\n+};\n+\n+static struct kunit_suite rndis_request_test_suite = {\n+\t.name = \"hyperv-rndis-request\",\n+\t.test_cases = rndis_request_test_cases,\n+};\n+\n+kunit_test_suite(rndis_request_test_suite);\ndiff --git a/drivers/uio/Kconfig b/drivers/uio/Kconfig\nindex 9242e77385c64..0a01906bd6cdc 100644\n--- a/drivers/uio/Kconfig\n+++ b/drivers/uio/Kconfig\n@@ -148,6 +148,17 @@ config UIO_HV_GENERIC\n \n \t  If you compile this as a module, it will be called uio_hv_generic.\n \n+config UIO_HV_GENERIC_KUNIT_TEST\n+\tbool \"Tests for the UIO Hyper-V generic mmap\" if !KUNIT_ALL_TESTS\n+\tdepends on UIO_HV_GENERIC \u0026\u0026 KUNIT=y\n+\tdefault KUNIT_ALL_TESTS\n+\thelp\n+\t  Enable KUnit tests for the UIO Hyper-V generic mmap paths.\n+\t  The tests are included from uio_hv_generic.c so they can\n+\t  reach the static page-selection helpers. Select this option\n+\t  only if you will boot the kernel for the purpose of running\n+\t  unit tests (e.g. under UML or qemu). If unsure, say N.\n+\n config UIO_DFL\n \ttristate \"Generic driver for DFL (Device Feature List) bus\"\n \tdepends on FPGA_DFL\ndiff --git a/drivers/uio/uio.c b/drivers/uio/uio.c\nindex f8fa205226601..4767ed0661f74 100644\n--- a/drivers/uio/uio.c\n+++ b/drivers/uio/uio.c\n@@ -857,7 +857,27 @@ static int uio_mmap(struct file *filep, struct vm_area_struct *vma)\n \t\tret = idev-\u003einfo-\u003emmap_prepare(idev-\u003einfo, \u0026desc);\n \t\tif (ret)\n \t\t\tgoto out;\n+\n+\t\t/*\n+\t\t * Install the per-VMA state before __compat_vma_mmap() so a\n+\t\t * failure in mmap_action_prepare() still reaches close(). That\n+\t\t * path never runs compat_set_vma_from_desc(), and the legacy\n+\t\t * .mmap error path frees the VMA without calling close() on\n+\t\t * its own. __compat_vma_mmap() installs the same values again\n+\t\t * on its way to the action.\n+\t\t *\n+\t\t * close() must be safe to call without a prior mapped() when\n+\t\t * it tears down state mmap_prepare() installed. Drivers that\n+\t\t * leave vm_ops alone have nothing to tear down here.\n+\t\t */\n+\t\tif (desc.vm_ops) {\n+\t\t\tvma-\u003evm_ops = desc.vm_ops;\n+\t\t\tvma-\u003evm_private_data = desc.private_data;\n+\t\t}\n+\n \t\tret = __compat_vma_mmap(\u0026desc, vma);\n+\t\tif (ret \u0026\u0026 vma-\u003evm_ops \u0026\u0026 vma-\u003evm_ops-\u003eclose)\n+\t\t\tvma-\u003evm_ops-\u003eclose(vma);\n \t\tgoto out;\n \t}\n \ndiff --git a/drivers/uio/uio_hv_generic.c b/drivers/uio/uio_hv_generic.c\nindex 7b4cc456c4534..91cb25d019be9 100644\n--- a/drivers/uio/uio_hv_generic.c\n+++ b/drivers/uio/uio_hv_generic.c\n@@ -25,6 +25,7 @@\n #include \u003clinux/uio_driver.h\u003e\n #include \u003clinux/netdevice.h\u003e\n #include \u003clinux/if_ether.h\u003e\n+#include \u003clinux/mm.h\u003e\n #include \u003clinux/skbuff.h\u003e\n #include \u003clinux/hyperv.h\u003e\n #include \u003clinux/vmalloc.h\u003e\n@@ -55,13 +56,13 @@ struct hv_uio_private_data {\n \tstruct uio_info info;\n \tstruct hv_device *device;\n \tatomic_t refcnt;\n+\tstruct page *int_pages[1];\n+\tstruct page *monitor_pages[1];\n \n-\tvoid\t*recv_buf;\n-\tstruct vmbus_gpadl recv_gpadl;\n+\tstruct vmbus_buffer recv_buffer;\n \tchar\trecv_name[32];\t/* \"recv_4294967295\" */\n \n-\tvoid\t*send_buf;\n-\tstruct vmbus_gpadl send_gpadl;\n+\tstruct vmbus_buffer send_buffer;\n \tchar\tsend_name[32];\n };\n \n@@ -123,49 +124,310 @@ static void hv_uio_channel_cb(void *context)\n \tuio_event_notify(\u0026pdata-\u003einfo);\n }\n \n+/* Function used for mmap of the ring buffer sysfs interface. */\n+static bool hv_uio_mmap_range_valid(unsigned long map_pages,\n+\t\t\t\t    pgoff_t offset,\n+\t\t\t\t    unsigned long pages)\n+{\n+\treturn pages \u0026\u0026 offset \u003c map_pages \u0026\u0026 pages \u003c= map_pages - offset;\n+}\n+\n+struct hv_uio_mmap_region {\n+\tstruct page **pages;\n+\tunsigned long page_count;\n+\tstruct vmbus_buffer *buffer;\n+\tbool decrypted;\n+};\n+\n+static int hv_uio_mmap_get_region(struct hv_uio_private_data *pdata,\n+\t\t\t\t  unsigned int map_index,\n+\t\t\t\t  struct hv_uio_mmap_region *region)\n+{\n+\tstruct hv_device *dev = pdata-\u003edevice;\n+\tstruct vmbus_channel *channel = dev-\u003echannel;\n+\n+\tif (map_index \u003e= MAX_UIO_MAPS || !pdata-\u003einfo.mem[map_index].size)\n+\t\treturn -EINVAL;\n+\n+\t/*\n+\t * Buffer-backed regions are not described here. Their page array\n+\t * and protection state are only meaningful as the locked snapshot\n+\t * from vmbus_buffer_pin_pages(): reading the descriptor outside\n+\t * that lock can describe a buffer a concurrent release has already\n+\t * cleared. Only the owning buffer is selected at this stage.\n+\t */\n+\tregion-\u003ebuffer = NULL;\n+\tregion-\u003epages = NULL;\n+\tregion-\u003epage_count = 0;\n+\tregion-\u003edecrypted = false;\n+\n+\tswitch (map_index) {\n+\tcase TXRX_RING_MAP:\n+\t\tif (channel-\u003estate != CHANNEL_OPENED_STATE)\n+\t\t\treturn -ENODEV;\n+\t\tregion-\u003ebuffer = \u0026channel-\u003eringbuffer;\n+\t\treturn 0;\n+\tcase INT_PAGE_MAP:\n+\t\tregion-\u003epages = pdata-\u003eint_pages;\n+\t\tregion-\u003epage_count = ARRAY_SIZE(pdata-\u003eint_pages);\n+\t\tregion-\u003edecrypted = false;\n+\t\tbreak;\n+\tcase MON_PAGE_MAP:\n+\t\tregion-\u003epages = pdata-\u003emonitor_pages;\n+\t\tregion-\u003epage_count = ARRAY_SIZE(pdata-\u003emonitor_pages);\n+\t\tregion-\u003edecrypted = true;\n+\t\tbreak;\n+\tcase RECV_BUF_MAP:\n+\t\tregion-\u003ebuffer = \u0026pdata-\u003erecv_buffer;\n+\t\treturn 0;\n+\tcase SEND_BUF_MAP:\n+\t\tregion-\u003ebuffer = \u0026pdata-\u003esend_buffer;\n+\t\treturn 0;\n+\tdefault:\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tif (!region-\u003epages || !region-\u003epage_count)\n+\t\treturn -EINVAL;\n+\n+\treturn 0;\n+}\n+\n+static int hv_uio_mmap_prepare_pages(struct vm_area_desc *desc,\n+\t\t\t\t     struct page **pages,\n+\t\t\t\t     unsigned long page_count,\n+\t\t\t\t     pgoff_t offset,\n+\t\t\t\t     bool decrypted)\n+{\n+\tunsigned long nr_pages = vma_desc_pages(desc);\n+\n+\tif (!vma_desc_test(desc, VMA_SHARED_BIT))\n+\t\treturn -EINVAL;\n+\n+\tif (!pages || !hv_uio_mmap_range_valid(page_count, offset, nr_pages))\n+\t\treturn -EINVAL;\n+\n+\tvma_desc_set_flags(desc, VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT);\n+\tif (decrypted)\n+\t\tdesc-\u003epage_prot = pgprot_decrypted(desc-\u003epage_prot);\n+\n+\tmmap_action_map_kernel_pages(desc, desc-\u003estart, pages + offset,\n+\t\t\t\t     nr_pages);\n+\treturn 0;\n+}\n+\n /*\n- * Callback from vmbus_event when channel is rescinded.\n- * It is meant for rescind of primary channels only.\n+ * mmap_action_map_kernel_pages() only stores the page-array pointer. The\n+ * mapping takes its own folio references inside insert_pages(), which runs\n+ * after the prepare callback has returned. Dropping the pin therefore has\n+ * to wait for the VMA to be established (mapped) or for the attempt to be\n+ * abandoned. Release is one-shot: the establish and abandon paths can both\n+ * be reached for the same attempt.\n+ *\n+ * Two surfaces, two ownership contracts. /dev/uioN is a character device,\n+ * so kernfs is not in the path and vm_ops-\u003eclose is a legal abandon path.\n+ * The sysfs \"ring\" bin attribute is kernfs: fs/kernfs/file.c rejects any\n+ * VMA whose vm_ops carry .close, because kernfs has to wrap the operations\n+ * and cannot wrap close. That surface installs no vm_ops at all and its\n+ * synchronous legacy .mmap wrapper owns the pin for the whole window.\n  */\n-static void hv_uio_rescind(struct vmbus_channel *channel)\n+#define HV_UIO_PIN_MAGIC 0x48565049UL /* \"HVPI\" */\n+\n+struct hv_uio_pin {\n+\tunsigned long magic;\n+\tstruct vmbus_buffer_pin snap;\n+};\n+\n+static void hv_uio_pin_release(void *data)\n {\n-\tstruct hv_device *hv_dev = channel-\u003edevice_obj;\n-\tstruct hv_uio_private_data *pdata = hv_get_drvdata(hv_dev);\n+\tstruct hv_uio_pin *pin = data;\n \n+\tif (!pin)\n+\t\treturn;\n \t/*\n-\t * Turn off the interrupt file handle\n-\t * Next read for event will return -EIO\n+\t * close() can be reached with a private_data that this driver did\n+\t * not install. A foreign pointer must not be freed or unpinned.\n \t */\n-\tpdata-\u003einfo.irq = 0;\n+\tif (pin-\u003emagic != HV_UIO_PIN_MAGIC)\n+\t\treturn;\n+\tpin-\u003emagic = 0;\n+\tvmbus_buffer_unpin_pages(\u0026pin-\u003esnap);\n+\tkfree(pin);\n+}\n \n-\t/* Wake up reader */\n-\tuio_event_notify(\u0026pdata-\u003einfo);\n+static int hv_uio_pin_vma_mapped(unsigned long start, unsigned long end,\n+\t\t\t\t pgoff_t pgoff, const struct file *file,\n+\t\t\t\t void **vm_private_data)\n+{\n+\t/*\n+\t * insert_pages() has taken a folio reference for every page the\n+\t * VMA now maps, so the reclaim worker can no longer free them\n+\t * under the mapping. The bridge pin is done.\n+\t */\n+\thv_uio_pin_release(*vm_private_data);\n+\t*vm_private_data = NULL;\n+\treturn 0;\n+}\n \n+static void hv_uio_pin_vma_close(struct vm_area_struct *vma)\n+{\n \t/*\n-\t * With rescind callback registered, rescind path will not unregister the device\n-\t * from vmbus when the primary channel is rescinded.\n-\t * Without it, rescind handling is incomplete and next onoffer msg does not come.\n-\t * Unregister the device from vmbus here.\n+\t * Reached with the pin still held when the VMA is torn down before\n+\t * mapped() ran (an insert_pages() failure, or a merge that never\n+\t * calls mapped), and with nothing left to do when it already ran.\n \t */\n-\tvmbus_device_unregister(channel-\u003edevice_obj);\n+\thv_uio_pin_release(vma-\u003evm_private_data);\n+\tvma-\u003evm_private_data = NULL;\n }\n \n-/* Function used for mmap of ring buffer sysfs interface.\n- * The ring buffer is allocated as contiguous memory by vmbus_open\n+/*\n+ * Character-device surface only. The sysfs ring must never adopt this set:\n+ * see the kernfs contract above.\n+ */\n+static const struct vm_operations_struct hv_uio_pin_vm_ops = {\n+\t.mapped = hv_uio_pin_vma_mapped,\n+\t.close = hv_uio_pin_vma_close,\n+};\n+\n+/*\n+ * Install @snap as the VMA's per-mapping state under @ops. Consumes @snap:\n+ * returns 0 with the pin owned by @desc and @snap cleared, or -ENOMEM with\n+ * the references dropped here. The caller must not drop the references on\n+ * the success path: mapped() and close() own them from here.\n  */\n+static int hv_uio_pin_install(struct vm_area_desc *desc,\n+\t\t\t      const struct vm_operations_struct *ops,\n+\t\t\t      struct vmbus_buffer_pin *snap)\n+{\n+\tstruct hv_uio_pin *pin;\n+\n+\tpin = kzalloc_obj(*pin);\n+\tif (!pin) {\n+\t\tvmbus_buffer_unpin_pages(snap);\n+\t\treturn -ENOMEM;\n+\t}\n+\tpin-\u003emagic = HV_UIO_PIN_MAGIC;\n+\tpin-\u003esnap = *snap;\n+\tsnap-\u003epages = NULL;\n+\tsnap-\u003epage_count = 0;\n+\n+\tdesc-\u003evm_ops = ops;\n+\tdesc-\u003eprivate_data = pin;\n+\treturn 0;\n+}\n+\n+static int hv_uio_mmap_prepare(struct uio_info *info,\n+\t\t\t       struct vm_area_desc *desc)\n+{\n+\tstruct hv_uio_private_data *pdata = info-\u003epriv;\n+\tstruct hv_uio_mmap_region region;\n+\tstruct vmbus_buffer_pin pin = {};\n+\tstruct page **pages;\n+\tunsigned long page_count;\n+\tbool decrypted;\n+\tint ret;\n+\n+\t/* UIO encodes the map index in pgoff; mmap offsets start at the map. */\n+\tif (desc-\u003epgoff \u003e= MAX_UIO_MAPS)\n+\t\treturn -EINVAL;\n+\n+\tret = hv_uio_mmap_get_region(pdata, desc-\u003epgoff, \u0026region);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\t/*\n+\t * Buffer-backed maps race with the reclaim worker: the page\n+\t * array and the pages themselves can be freed between the\n+\t * selection above and the mapping below. Hold references until\n+\t * the VMA holds its own. The pin is also the only safe source of\n+\t * the protection state: it is taken in the same critical section\n+\t * that reads the page array.\n+\t */\n+\tif (region.buffer) {\n+\t\tret = vmbus_buffer_pin_pages(region.buffer, \u0026pin);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tpages = pin.pages;\n+\t\tpage_count = pin.page_count;\n+\t\tdecrypted = pin.decrypted;\n+\t} else {\n+\t\tpages = region.pages;\n+\t\tpage_count = region.page_count;\n+\t\tdecrypted = region.decrypted;\n+\t}\n+\n+\tret = hv_uio_mmap_prepare_pages(desc, pages, page_count, 0, decrypted);\n+\tif (ret) {\n+\t\tif (region.buffer)\n+\t\t\tvmbus_buffer_unpin_pages(\u0026pin);\n+\t\treturn ret;\n+\t}\n+\n+\tif (!region.buffer)\n+\t\treturn 0;\n+\n+\treturn hv_uio_pin_install(desc, \u0026hv_uio_pin_vm_ops, \u0026pin);\n+}\n+\n static int\n-hv_uio_ring_mmap_prepare(struct vmbus_channel *channel, struct vm_area_desc *desc)\n+hv_uio_ring_mmap_prepare(struct vmbus_channel *channel,\n+\t\t\t struct vm_area_desc *desc)\n {\n-\tvoid *ring_buffer = page_address(channel-\u003eringbuffer_page);\n+\tstruct vmbus_buffer *buffer = \u0026channel-\u003eringbuffer;\n+\tstruct vmbus_buffer_pin *pin;\n+\tpgoff_t offset = desc-\u003epgoff;\n+\tint ret;\n \n \tif (channel-\u003estate != CHANNEL_OPENED_STATE)\n \t\treturn -ENODEV;\n \n-\tmmap_action_simple_ioremap(desc, virt_to_phys(ring_buffer),\n-\t\t\tchannel-\u003eringbuffer_pagecount \u003c\u003c PAGE_SHIFT);\n+\tpin = kzalloc_obj(*pin);\n+\tif (!pin)\n+\t\treturn -ENOMEM;\n+\n+\tret = vmbus_buffer_pin_pages(buffer, pin);\n+\tif (ret) {\n+\t\tkfree(pin);\n+\t\treturn ret;\n+\t}\n+\n+\tret = hv_uio_mmap_prepare_pages(desc, pin-\u003epages, pin-\u003epage_count,\n+\t\t\t\t\toffset, pin-\u003edecrypted);\n+\tif (ret) {\n+\t\tvmbus_buffer_unpin_pages(pin);\n+\t\tkfree(pin);\n+\t\treturn ret;\n+\t}\n+\n+\t/*\n+\t * Install no vm_ops. kernfs_fop_mmap() returns -EINVAL for a VMA\n+\t * whose vm_ops carry .close, and a successful mapping still has to\n+\t * survive that check, so this surface cannot carry an abandon path\n+\t * in vm_ops at all. The caller is hv_mmap_ring_buffer_wrapper(),\n+\t * a synchronous legacy .mmap: it holds @pin across\n+\t * __compat_vma_mmap() and frees it when that returns, exactly once,\n+\t * on every outcome. desc-\u003eprivate_data is a plain\n+\t * struct vmbus_buffer_pin for that wrapper to release.\n+\t */\n+\tdesc-\u003evm_ops = NULL;\n+\tdesc-\u003eprivate_data = pin;\n \treturn 0;\n }\n \n+/* Caller has withdrawn UIO callbacks before removing its backing memory. */\n+static int hv_uio_disconnect_if_open(struct vmbus_channel *channel,\n+\t\t\t\t     int (*disconnect)(struct vmbus_channel *))\n+{\n+\tif (channel-\u003estate != CHANNEL_OPENED_STATE)\n+\t\treturn 0;\n+\n+\treturn disconnect(channel);\n+}\n+\n+#if defined(CONFIG_UIO_HV_GENERIC_KUNIT_TEST)\n+#include \"uio_hv_generic_mmap_test.c\"\n+#endif\n+\n /* Callback from VMBUS subsystem when new channel created. */\n static void\n hv_uio_new_channel(struct vmbus_channel *new_sc)\n@@ -195,17 +457,13 @@ hv_uio_new_channel(struct vmbus_channel *new_sc)\n static void\n hv_uio_cleanup(struct hv_device *dev, struct hv_uio_private_data *pdata)\n {\n-\tif (pdata-\u003esend_gpadl.gpadl_handle) {\n-\t\tvmbus_teardown_gpadl(dev-\u003echannel, \u0026pdata-\u003esend_gpadl);\n-\t\tif (!pdata-\u003esend_gpadl.decrypted)\n-\t\t\tvfree(pdata-\u003esend_buf);\n-\t}\n+\tif (pdata-\u003esend_buffer.gpadl.gpadl_handle)\n+\t\tvmbus_teardown_gpadl_owned(dev-\u003echannel, \u0026pdata-\u003esend_buffer);\n+\tvmbus_release_buffer(\u0026pdata-\u003esend_buffer);\n \n-\tif (pdata-\u003erecv_gpadl.gpadl_handle) {\n-\t\tvmbus_teardown_gpadl(dev-\u003echannel, \u0026pdata-\u003erecv_gpadl);\n-\t\tif (!pdata-\u003erecv_gpadl.decrypted)\n-\t\t\tvfree(pdata-\u003erecv_buf);\n-\t}\n+\tif (pdata-\u003erecv_buffer.gpadl.gpadl_handle)\n+\t\tvmbus_teardown_gpadl_owned(dev-\u003echannel, \u0026pdata-\u003erecv_buffer);\n+\tvmbus_release_buffer(\u0026pdata-\u003erecv_buffer);\n }\n \n /* VMBus primary channel is opened on first use */\n@@ -220,7 +478,6 @@ hv_uio_open(struct uio_info *info, struct inode *inode)\n \tif (atomic_inc_return(\u0026pdata-\u003erefcnt) != 1)\n \t\treturn 0;\n \n-\tvmbus_set_chn_rescind_callback(dev-\u003echannel, hv_uio_rescind);\n \tvmbus_set_sc_create_callback(dev-\u003echannel, hv_uio_new_channel);\n \n \tret = vmbus_connect_ring(dev-\u003echannel,\n@@ -276,6 +533,7 @@ hv_uio_probe(struct hv_device *dev,\n \tpdata-\u003einfo.name = \"uio_hv_generic\";\n \tpdata-\u003einfo.version = DRIVER_VERSION;\n \tpdata-\u003einfo.irqcontrol = hv_uio_irqcontrol;\n+\tpdata-\u003einfo.mmap_prepare = hv_uio_mmap_prepare;\n \tpdata-\u003einfo.open = hv_uio_open;\n \tpdata-\u003einfo.release = hv_uio_release;\n \tpdata-\u003einfo.irq = UIO_IRQ_CUSTOM;\n@@ -283,66 +541,60 @@ hv_uio_probe(struct hv_device *dev,\n \n \t/* mem resources */\n \tpdata-\u003einfo.mem[TXRX_RING_MAP].name = \"txrx_rings\";\n-\tring_buffer = page_address(channel-\u003eringbuffer_page);\n-\tpdata-\u003einfo.mem[TXRX_RING_MAP].addr\n-\t\t= (uintptr_t)virt_to_phys(ring_buffer);\n+\tring_buffer = channel-\u003eringbuffer.addr;\n+\tpdata-\u003einfo.mem[TXRX_RING_MAP].addr = (uintptr_t)ring_buffer;\n \tpdata-\u003einfo.mem[TXRX_RING_MAP].size\n \t\t= channel-\u003eringbuffer_pagecount \u003c\u003c PAGE_SHIFT;\n-\tpdata-\u003einfo.mem[TXRX_RING_MAP].memtype = UIO_MEM_IOVA;\n+\tpdata-\u003einfo.mem[TXRX_RING_MAP].memtype = UIO_MEM_VIRTUAL;\n \n \tpdata-\u003einfo.mem[INT_PAGE_MAP].name = \"int_page\";\n \tpdata-\u003einfo.mem[INT_PAGE_MAP].addr\n \t\t= (uintptr_t)vmbus_connection.int_page;\n \tpdata-\u003einfo.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;\n \tpdata-\u003einfo.mem[INT_PAGE_MAP].memtype = UIO_MEM_LOGICAL;\n+\tpdata-\u003eint_pages[0] = virt_to_page(vmbus_connection.int_page);\n \n \tpdata-\u003einfo.mem[MON_PAGE_MAP].name = \"monitor_page\";\n \tpdata-\u003einfo.mem[MON_PAGE_MAP].addr\n \t\t= (uintptr_t)vmbus_connection.monitor_pages[1];\n \tpdata-\u003einfo.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;\n \tpdata-\u003einfo.mem[MON_PAGE_MAP].memtype = UIO_MEM_LOGICAL;\n+\tpdata-\u003emonitor_pages[0] =\n+\t\tvirt_to_page(vmbus_connection.monitor_pages[1]);\n \n \tif (channel-\u003edevice_id == HV_NIC) {\n-\t\tpdata-\u003erecv_buf = vzalloc(RECV_BUFFER_SIZE);\n-\t\tif (!pdata-\u003erecv_buf) {\n-\t\t\tret = -ENOMEM;\n+\t\tret = vmbus_alloc_buffer_owned(channel, RECV_BUFFER_SIZE, false,\n+\t\t\t\t\t       \u0026pdata-\u003erecv_buffer);\n+\t\tif (ret)\n \t\t\tgoto fail_free_ring;\n-\t\t}\n \n-\t\tret = vmbus_establish_gpadl(channel, pdata-\u003erecv_buf,\n-\t\t\t\t\t    RECV_BUFFER_SIZE, \u0026pdata-\u003erecv_gpadl);\n-\t\tif (ret) {\n-\t\t\tif (!pdata-\u003erecv_gpadl.decrypted)\n-\t\t\t\tvfree(pdata-\u003erecv_buf);\n+\t\tret = vmbus_establish_gpadl_owned(channel, \u0026pdata-\u003erecv_buffer);\n+\t\tif (ret)\n \t\t\tgoto fail_close;\n-\t\t}\n \n \t\t/* put Global Physical Address Label in name */\n \t\tsnprintf(pdata-\u003erecv_name, sizeof(pdata-\u003erecv_name),\n-\t\t\t \"recv:%u\", pdata-\u003erecv_gpadl.gpadl_handle);\n+\t\t\t \"recv:%u\", pdata-\u003erecv_buffer.gpadl.gpadl_handle);\n \t\tpdata-\u003einfo.mem[RECV_BUF_MAP].name = pdata-\u003erecv_name;\n-\t\tpdata-\u003einfo.mem[RECV_BUF_MAP].addr = (uintptr_t)pdata-\u003erecv_buf;\n+\t\tpdata-\u003einfo.mem[RECV_BUF_MAP].addr =\n+\t\t\t(uintptr_t)pdata-\u003erecv_buffer.addr;\n \t\tpdata-\u003einfo.mem[RECV_BUF_MAP].size = RECV_BUFFER_SIZE;\n \t\tpdata-\u003einfo.mem[RECV_BUF_MAP].memtype = UIO_MEM_VIRTUAL;\n \n-\t\tpdata-\u003esend_buf = vzalloc(SEND_BUFFER_SIZE);\n-\t\tif (!pdata-\u003esend_buf) {\n-\t\t\tret = -ENOMEM;\n+\t\tret = vmbus_alloc_buffer_owned(channel, SEND_BUFFER_SIZE, false,\n+\t\t\t\t\t       \u0026pdata-\u003esend_buffer);\n+\t\tif (ret)\n \t\t\tgoto fail_close;\n-\t\t}\n \n-\t\tret = vmbus_establish_gpadl(channel, pdata-\u003esend_buf,\n-\t\t\t\t\t    SEND_BUFFER_SIZE, \u0026pdata-\u003esend_gpadl);\n-\t\tif (ret) {\n-\t\t\tif (!pdata-\u003esend_gpadl.decrypted)\n-\t\t\t\tvfree(pdata-\u003esend_buf);\n+\t\tret = vmbus_establish_gpadl_owned(channel, \u0026pdata-\u003esend_buffer);\n+\t\tif (ret)\n \t\t\tgoto fail_close;\n-\t\t}\n \n \t\tsnprintf(pdata-\u003esend_name, sizeof(pdata-\u003esend_name),\n-\t\t\t \"send:%u\", pdata-\u003esend_gpadl.gpadl_handle);\n+\t\t\t \"send:%u\", pdata-\u003esend_buffer.gpadl.gpadl_handle);\n \t\tpdata-\u003einfo.mem[SEND_BUF_MAP].name = pdata-\u003esend_name;\n-\t\tpdata-\u003einfo.mem[SEND_BUF_MAP].addr = (uintptr_t)pdata-\u003esend_buf;\n+\t\tpdata-\u003einfo.mem[SEND_BUF_MAP].addr =\n+\t\t\t(uintptr_t)pdata-\u003esend_buffer.addr;\n \t\tpdata-\u003einfo.mem[SEND_BUF_MAP].size = SEND_BUFFER_SIZE;\n \t\tpdata-\u003einfo.mem[SEND_BUF_MAP].memtype = UIO_MEM_VIRTUAL;\n \t}\n@@ -385,12 +637,20 @@ static void\n hv_uio_remove(struct hv_device *dev)\n {\n \tstruct hv_uio_private_data *pdata = hv_get_drvdata(dev);\n+\tint ret;\n \n \tif (!pdata)\n \t\treturn;\n \n \thv_remove_ring_sysfs(dev-\u003echannel);\n+\t/* Keep event notification alive until channel callbacks are stopped. */\n+\tget_device(\u0026pdata-\u003einfo.uio_dev-\u003edev);\n \tuio_unregister_device(\u0026pdata-\u003einfo);\n+\t/* unregister prevents the eventual fd close from calling .release. */\n+\tret = hv_uio_disconnect_if_open(dev-\u003echannel, vmbus_disconnect_ring);\n+\tif (ret)\n+\t\tdev_err(\u0026dev-\u003edevice, \"channel disconnect failed: %d\\n\", ret);\n+\tput_device(\u0026pdata-\u003einfo.uio_dev-\u003edev);\n \thv_uio_cleanup(dev, pdata);\n \n \tvmbus_free_ring(dev-\u003echannel);\ndiff --git a/drivers/uio/uio_hv_generic_mmap_test.c b/drivers/uio/uio_hv_generic_mmap_test.c\nnew file mode 100644\nindex 0000000000000..615df78b266e7\n--- /dev/null\n+++ b/drivers/uio/uio_hv_generic_mmap_test.c\n@@ -0,0 +1,875 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * KUnit tests for the UIO Hyper-V generic mmap paths.\n+ *\n+ * This file is included from uio_hv_generic.c so the cases can reach the\n+ * static helpers that select, validate and pin the mapped pages.\n+ *\n+ * Two ownership contracts are under test:\n+ *   - the /dev/uioN character-device path installs hv_uio_pin_vm_ops\n+ *     (.mapped + .close) and a struct hv_uio_pin;\n+ *   - the sysfs \"ring\" bin attribute cannot, because kernfs_fop_mmap()\n+ *     rejects a vm_operations_struct that carries .close. That path\n+ *     installs no vm_ops and hands a bare struct vmbus_buffer_pin to its\n+ *     synchronous .mmap wrapper, which is the single release site.\n+ */\n+#include \u003ckunit/test.h\u003e\n+\n+/*\n+ * Release exactly what hv_mmap_ring_buffer_wrapper() releases after\n+ * __compat_vma_mmap() returns: the bare pin's references, then the pin.\n+ */\n+static void sysfs_pin_release(struct vmbus_buffer_pin *pin)\n+{\n+\tvmbus_buffer_unpin_pages(pin);\n+\tkfree(pin);\n+}\n+\n+static void hv_uio_ring_mmap_range_test(struct kunit *test)\n+{\n+\tKUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 0, 8));\n+\tKUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 4, 4));\n+\tKUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 8, 1));\n+\tKUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 7, 2));\n+\tKUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 0, 0));\n+\tKUNIT_EXPECT_FALSE(test,\n+\t\t\t   hv_uio_mmap_range_valid(8, U64_MAX, 1));\n+}\n+\n+static void hv_uio_ring_mmap_prepare_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t\t.ringbuffer = {\n+\t\t\t.page_cnt = 8,\n+\t\t},\n+\t};\n+\tstruct page *pages[8] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vmbus_buffer_pin *pin;\n+\tstruct vm_area_desc desc = {\n+\t\t.start = PAGE_SIZE,\n+\t\t.end = 5 * PAGE_SIZE,\n+\t\t.pgoff = 2,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tunsigned int i;\n+\tint ret;\n+\n+\t/* Mapping pins real pages; the array cannot hold NULL entries. */\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.chunks = chunks;\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages, \u0026pages[2]);\n+\tKUNIT_EXPECT_EQ(test, desc.action.map_kernel.nr_pages, 4UL);\n+\tKUNIT_EXPECT_TRUE(test, vma_desc_test(\u0026desc, VMA_DONTEXPAND_BIT));\n+\tKUNIT_EXPECT_TRUE(test, vma_desc_test(\u0026desc, VMA_DONTDUMP_BIT));\n+\tKUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),\n+\t\t\tpgprot_val(pgprot_decrypted(PAGE_SHARED)));\n+\n+\t/*\n+\t * The sysfs surface installs no vm_ops at all: see the kernfs\n+\t * contract in the comment at the top of this file. The wrapper\n+\t * holds the pin and is the only thing that releases it.\n+\t */\n+\tKUNIT_EXPECT_NULL(test, desc.vm_ops);\n+\tpin = desc.private_data;\n+\tKUNIT_ASSERT_NOT_NULL(test, pin);\n+\tKUNIT_EXPECT_TRUE(test, pin-\u003edecrypted);\n+\tKUNIT_EXPECT_EQ(test, pin-\u003epage_count, ARRAY_SIZE(pages));\n+\tsysfs_pin_release(pin);\n+\n+\tdesc.vma_flags = EMPTY_VMA_FLAGS;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\n+\tdesc.start = PAGE_SIZE;\n+\tdesc.end = 3 * PAGE_SIZE;\n+\tdesc.pgoff = 7;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\n+\n+\tchannel.state = CHANNEL_OPEN_STATE;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -ENODEV);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+static void hv_uio_mmap_region_select_test(struct kunit *test)\n+{\n+\tstruct hv_uio_private_data pdata = {};\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t};\n+\tstruct hv_device dev = {\n+\t\t.channel = \u0026channel,\n+\t};\n+\tstruct hv_uio_mmap_region region;\n+\tstruct page *ring_pages[4] = {};\n+\tstruct page *recv_pages[3] = {};\n+\tstruct page *send_pages[2] = {};\n+\tstruct page *chunks[1] = {};\n+\tint ret;\n+\n+\tpdata.device = \u0026dev;\n+\tpdata.info.mem[TXRX_RING_MAP].size =\n+\t\tARRAY_SIZE(ring_pages) * PAGE_SIZE;\n+\tpdata.info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;\n+\tpdata.info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;\n+\tpdata.info.mem[RECV_BUF_MAP].size =\n+\t\tARRAY_SIZE(recv_pages) * PAGE_SIZE;\n+\tpdata.info.mem[SEND_BUF_MAP].size =\n+\t\tARRAY_SIZE(send_pages) * PAGE_SIZE;\n+\tchannel.ringbuffer.pages = ring_pages;\n+\tchannel.ringbuffer.page_cnt = ARRAY_SIZE(ring_pages);\n+\tchannel.ringbuffer.chunks = chunks;\n+\tpdata.int_pages[0] = ring_pages[0];\n+\tpdata.monitor_pages[0] = ring_pages[1];\n+\tpdata.recv_buffer.pages = recv_pages;\n+\tpdata.recv_buffer.page_cnt = ARRAY_SIZE(recv_pages);\n+\tpdata.recv_buffer.chunks = chunks;\n+\tpdata.send_buffer.pages = send_pages;\n+\tpdata.send_buffer.page_cnt = ARRAY_SIZE(send_pages);\n+\n+\t/*\n+\t * Buffer-backed maps are described only by their owning buffer.\n+\t * The page array and the protection state are deliberately absent\n+\t * here: reading them outside vmbus_buffer_owners_lock can describe\n+\t * a buffer a concurrent release has already cleared. The locked\n+\t * pin snapshot is the only safe source.\n+\t */\n+\tret = hv_uio_mmap_get_region(\u0026pdata, TXRX_RING_MAP, \u0026region);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_PTR_EQ(test, region.buffer, \u0026channel.ringbuffer);\n+\tKUNIT_EXPECT_NULL(test, region.pages);\n+\tKUNIT_EXPECT_EQ(test, region.page_count, 0UL);\n+\tKUNIT_EXPECT_FALSE(test, region.decrypted);\n+\n+\tret = hv_uio_mmap_get_region(\u0026pdata, INT_PAGE_MAP, \u0026region);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_NULL(test, region.buffer);\n+\tKUNIT_EXPECT_PTR_EQ(test, region.pages, \u0026pdata.int_pages[0]);\n+\tKUNIT_EXPECT_FALSE(test, region.decrypted);\n+\n+\tret = hv_uio_mmap_get_region(\u0026pdata, MON_PAGE_MAP, \u0026region);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_NULL(test, region.buffer);\n+\tKUNIT_EXPECT_PTR_EQ(test, region.pages, \u0026pdata.monitor_pages[0]);\n+\tKUNIT_EXPECT_TRUE(test, region.decrypted);\n+\n+\tret = hv_uio_mmap_get_region(\u0026pdata, RECV_BUF_MAP, \u0026region);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_PTR_EQ(test, region.buffer, \u0026pdata.recv_buffer);\n+\tKUNIT_EXPECT_NULL(test, region.pages);\n+\tKUNIT_EXPECT_EQ(test, region.page_count, 0UL);\n+\tKUNIT_EXPECT_FALSE(test, region.decrypted);\n+\n+\tret = hv_uio_mmap_get_region(\u0026pdata, SEND_BUF_MAP, \u0026region);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_PTR_EQ(test, region.buffer, \u0026pdata.send_buffer);\n+\tKUNIT_EXPECT_NULL(test, region.pages);\n+\tKUNIT_EXPECT_EQ(test, region.page_count, 0UL);\n+\tKUNIT_EXPECT_FALSE(test, region.decrypted);\n+\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\thv_uio_mmap_get_region(\u0026pdata, MAX_UIO_MAPS, \u0026region),\n+\t\t\t-EINVAL);\n+\tchannel.state = CHANNEL_OPEN_STATE;\n+\tKUNIT_EXPECT_EQ(test,\n+\t\t\thv_uio_mmap_get_region(\u0026pdata, TXRX_RING_MAP, \u0026region),\n+\t\t\t-ENODEV);\n+}\n+\n+static void hv_uio_mmap_prepare_test(struct kunit *test)\n+{\n+\tstruct hv_uio_private_data *pdata;\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t};\n+\tstruct hv_device dev = {\n+\t\t.channel = \u0026channel,\n+\t};\n+\tstruct page *pages[4] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vm_area_desc desc = {\n+\t\t.start = PAGE_SIZE,\n+\t\t.end = 3 * PAGE_SIZE,\n+\t\t.pgoff = RECV_BUF_MAP,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tunsigned int i;\n+\tint ret;\n+\n+\t/* Mapping pins real pages; the array cannot hold NULL entries. */\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\n+\tpdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, pdata);\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tpdata-\u003edevice = \u0026dev;\n+\tpdata-\u003einfo.priv = pdata;\n+\tpdata-\u003einfo.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;\n+\tpdata-\u003erecv_buffer.pages = pages;\n+\tpdata-\u003erecv_buffer.page_cnt = ARRAY_SIZE(pages);\n+\tpdata-\u003erecv_buffer.chunks = chunks;\n+\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages, \u0026pages[0]);\n+\tKUNIT_EXPECT_EQ(test, desc.action.map_kernel.nr_pages, 2UL);\n+\t/*\n+\t * The protection state comes from the locked pin snapshot, not\n+\t * from a second read of the buffer descriptor. chunks is set, so\n+\t * the snapshot says decrypted.\n+\t */\n+\tKUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),\n+\t\t\tpgprot_val(pgprot_decrypted(PAGE_SHARED)));\n+\tKUNIT_EXPECT_TRUE(test, vma_desc_test(\u0026desc, VMA_DONTEXPAND_BIT));\n+\tKUNIT_EXPECT_TRUE(test, vma_desc_test(\u0026desc, VMA_DONTDUMP_BIT));\n+\t/*\n+\t * Character-device maps can carry an abandon path: kernfs is not\n+\t * in this path, so .close is legal here and illegal on \"ring\".\n+\t */\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, \u0026hv_uio_pin_vm_ops);\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.vm_ops-\u003emapped);\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.vm_ops-\u003eclose);\n+\t/* Buffer-backed maps leave the pin held for mapped()/close(). */\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.private_data);\n+\thv_uio_pin_release(desc.private_data);\n+\tdesc.private_data = NULL;\n+\n+\tdesc.vma_flags = EMPTY_VMA_FLAGS;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc), -EINVAL);\n+\n+\tdesc.pgoff = INT_PAGE_MAP;\n+\tpdata-\u003einfo.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;\n+\tpdata-\u003eint_pages[0] = pages[0];\n+\tdesc.end = 2 * PAGE_SIZE;\n+\tdesc.page_prot = PAGE_SHARED;\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages,\n+\t\t\t    \u0026pdata-\u003eint_pages[0]);\n+\tKUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),\n+\t\t\tpgprot_val(PAGE_SHARED));\n+\t/* int_pages is not a vmbus_buffer, so nothing is pinned. */\n+\tKUNIT_EXPECT_NULL(test, desc.private_data);\n+\n+\tdesc.pgoff = MON_PAGE_MAP;\n+\tpdata-\u003einfo.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;\n+\tpdata-\u003emonitor_pages[0] = pages[1];\n+\tdesc.page_prot = PAGE_SHARED;\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages,\n+\t\t\t    \u0026pdata-\u003emonitor_pages[0]);\n+\tKUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),\n+\t\t\tpgprot_val(pgprot_decrypted(PAGE_SHARED)));\n+\tKUNIT_EXPECT_NULL(test, desc.private_data);\n+\n+\tdesc.pgoff = SEND_BUF_MAP;\n+\tpdata-\u003einfo.mem[SEND_BUF_MAP].size = PAGE_SIZE;\n+\tpdata-\u003esend_buffer.pages = pages;\n+\tpdata-\u003esend_buffer.page_cnt = ARRAY_SIZE(pages);\n+\tdesc.page_prot = PAGE_SHARED;\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\t/* send_buffer has no chunks, so the snapshot says encrypted. */\n+\tKUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),\n+\t\t\tpgprot_val(PAGE_SHARED));\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.private_data);\n+\thv_uio_pin_release(desc.private_data);\n+\tdesc.private_data = NULL;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/*\n+ * The reclaim race this driver closes is a lifetime question: the pin has\n+ * to span the gap between mmap_prepare() returning and insert_pages()\n+ * taking its own folio references. Dropping it inside the prepare hook\n+ * leaves the pages freeable before the mapping exists.\n+ *\n+ * This is the character-device contract: mapped() and close() share the\n+ * release, and release is one-shot.\n+ */\n+static void hv_uio_pin_lifetime_test(struct kunit *test)\n+{\n+\tstruct hv_uio_private_data *pdata;\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t};\n+\tstruct hv_device dev = {\n+\t\t.channel = \u0026channel,\n+\t};\n+\tstruct page *pages[4] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = 4 * PAGE_SIZE,\n+\t\t.pgoff = RECV_BUF_MAP,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tstruct vm_area_struct *vma;\n+\tunsigned int i;\n+\tint ret;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\n+\tpdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, pdata);\n+\tpdata-\u003edevice = \u0026dev;\n+\tpdata-\u003einfo.priv = pdata;\n+\tpdata-\u003einfo.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;\n+\tpdata-\u003erecv_buffer.pages = pages;\n+\tpdata-\u003erecv_buffer.page_cnt = ARRAY_SIZE(pages);\n+\tpdata-\u003erecv_buffer.chunks = chunks;\n+\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\n+\t/*\n+\t * Prepare must hold a reference on every page: the mapping is not\n+\t * installed until insert_pages() runs after the hook returns.\n+\t */\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);\n+\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, \u0026hv_uio_pin_vm_ops);\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.private_data);\n+\n+\t/* mapped(): the mapping holds its own refs, so the pin is released. */\n+\tret = desc.vm_ops-\u003emapped(desc.start, desc.end, 0, NULL,\n+\t\t\t\t  \u0026desc.private_data);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_NULL(test, desc.private_data);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\t/* close() after mapped() must not unpin again. */\n+\tvma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, vma);\n+\tvma-\u003evm_ops = desc.vm_ops;\n+\tvma-\u003evm_private_data = desc.private_data;\n+\tdesc.vm_ops-\u003eclose(vma);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/*\n+ * The abandonment path: when the mapping is torn down before mapped() ran\n+ * (insert_pages() failure, or a merge that never calls mapped()), close()\n+ * must still drop the pin. A foreign private_data must be left alone.\n+ */\n+static void hv_uio_pin_close_before_mapped_test(struct kunit *test)\n+{\n+\tstruct hv_uio_private_data *pdata;\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t};\n+\tstruct hv_device dev = {\n+\t\t.channel = \u0026channel,\n+\t};\n+\tstruct page *pages[2] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = 2 * PAGE_SIZE,\n+\t\t.pgoff = RECV_BUF_MAP,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tstruct vm_area_struct *vma;\n+\tunsigned int i;\n+\tint ret;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\n+\tpdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, pdata);\n+\tpdata-\u003edevice = \u0026dev;\n+\tpdata-\u003einfo.priv = pdata;\n+\tpdata-\u003einfo.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;\n+\tpdata-\u003erecv_buffer.pages = pages;\n+\tpdata-\u003erecv_buffer.page_cnt = ARRAY_SIZE(pages);\n+\tpdata-\u003erecv_buffer.chunks = chunks;\n+\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.private_data);\n+\n+\tvma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, vma);\n+\tvma-\u003evm_ops = desc.vm_ops;\n+\tvma-\u003evm_private_data = desc.private_data;\n+\tdesc.vm_ops-\u003eclose(vma);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\t/* A second close is a no-op, not a double unpin. */\n+\tdesc.vm_ops-\u003eclose(vma);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\t/* A pointer this driver did not install must not be freed. */\n+\tvma-\u003evm_private_data = \u0026pages[0];\n+\tdesc.vm_ops-\u003eclose(vma);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/*\n+ * The kernfs contract, named. fs/kernfs/file.c returns -EINVAL for a VMA\n+ * whose vm_ops carry .close, and it performs that check after the .mmap\n+ * hook has already succeeded. A successful sysfs mapping therefore cannot\n+ * carry an abandon path in vm_ops at all.\n+ */\n+static void sysfs_ring_mmap_ops_have_no_close(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t\t.ringbuffer = {\n+\t\t\t.page_cnt = 1,\n+\t\t},\n+\t};\n+\tstruct page *pages[1] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vmbus_buffer_pin *pin;\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = PAGE_SIZE,\n+\t\t.pgoff = 0,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tint ret;\n+\n+\tpages[0] = alloc_page(GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, pages[0]);\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.chunks = chunks;\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\n+\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\n+\t/* The exact predicate kernfs_fop_mmap() applies must be false. */\n+\tKUNIT_EXPECT_NULL(test, desc.vm_ops);\n+\tKUNIT_EXPECT_FALSE(test, desc.vm_ops \u0026\u0026 desc.vm_ops-\u003eclose);\n+\n+\tpin = desc.private_data;\n+\tKUNIT_ASSERT_NOT_NULL(test, pin);\n+\tsysfs_pin_release(pin);\n+\n+\t__free_page(pages[0]);\n+}\n+\n+/*\n+ * The character-device counterpart: a buffer-backed map prepares and\n+ * installs the ops that carry the abandon path, then mapped() releases.\n+ */\n+static void uio_buffer_mmap_success(struct kunit *test)\n+{\n+\tstruct hv_uio_private_data *pdata;\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t};\n+\tstruct hv_device dev = {\n+\t\t.channel = \u0026channel,\n+\t};\n+\tstruct page *pages[2] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = 2 * PAGE_SIZE,\n+\t\t.pgoff = RECV_BUF_MAP,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tunsigned int i;\n+\tint ret;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\n+\tpdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, pdata);\n+\tpdata-\u003edevice = \u0026dev;\n+\tpdata-\u003einfo.priv = pdata;\n+\tpdata-\u003einfo.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;\n+\tpdata-\u003erecv_buffer.pages = pages;\n+\tpdata-\u003erecv_buffer.page_cnt = ARRAY_SIZE(pages);\n+\tpdata-\u003erecv_buffer.chunks = chunks;\n+\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);\n+\tKUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, \u0026hv_uio_pin_vm_ops);\n+\tKUNIT_ASSERT_NOT_NULL(test, desc.private_data);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);\n+\n+\tret = desc.vm_ops-\u003emapped(desc.start, desc.end, 0, NULL,\n+\t\t\t\t  \u0026desc.private_data);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_NULL(test, desc.private_data);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/*\n+ * A prepare that refuses must not leave references behind. Each failure\n+ * mode is checked against the page reference count, which is the only\n+ * externally visible record of a leaked pin.\n+ */\n+static void sysfs_mmap_prepare_failure_releases_pin(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t\t.ringbuffer = {\n+\t\t\t.page_cnt = 2,\n+\t\t},\n+\t};\n+\tstruct page *pages[2] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = 2 * PAGE_SIZE,\n+\t\t.pgoff = 0,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tunsigned int i;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.chunks = chunks;\n+\n+\t/* Not shared: refused before anything is pinned. */\n+\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\t/* pgoff past the end of the pin: refused before anything is pinned. */\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\tdesc.pgoff = 2;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\t/* Channel not open: refused before anything is pinned. */\n+\tdesc.pgoff = 0;\n+\tchannel.state = CHANNEL_OPEN_STATE;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -ENODEV);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/*\n+ * Prepare succeeded and the pin is installed, but the mapping never\n+ * becomes established (insert_pages() fails part-way, or the attempt is\n+ * otherwise abandoned). The wrapper is the only owner on this surface and\n+ * releases with one unpin plus one free, whether or not any VMA ever held\n+ * the pages. This proves the object it is handed is fully releasable that\n+ * way, and that releasing twice is not possible to observe.\n+ */\n+static void sysfs_mmap_partial_insert_failure_releases_pin(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t\t.ringbuffer = {\n+\t\t\t.page_cnt = 3,\n+\t\t},\n+\t};\n+\tstruct page *pages[3] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vmbus_buffer_pin *pin;\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = 3 * PAGE_SIZE,\n+\t\t.pgoff = 0,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tunsigned int i;\n+\tint ret;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.chunks = chunks;\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\n+\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tpin = desc.private_data;\n+\tKUNIT_ASSERT_NOT_NULL(test, pin);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);\n+\n+\t/* The wrapper's abandon path: one unpin, one free. */\n+\tsysfs_pin_release(pin);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/*\n+ * The window the pin exists to close. Between the snapshot and the point\n+ * where the mapping holds its own references, a concurrent\n+ * vmbus_release_buffer() can drop the buffer's reference to each page.\n+ * The pin must keep the pages alive for the whole window, and must be the\n+ * thing that drops the last reference.\n+ */\n+static void sysfs_mmap_release_during_insert_keeps_pages_alive(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t\t.ringbuffer = {\n+\t\t\t.page_cnt = 2,\n+\t\t},\n+\t};\n+\tstruct page *pages[2] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vmbus_buffer_pin *pin;\n+\tstruct vm_area_desc desc = {\n+\t\t.start = 0,\n+\t\t.end = 2 * PAGE_SIZE,\n+\t\t.pgoff = 0,\n+\t\t.page_prot = PAGE_SHARED,\n+\t};\n+\tunsigned int i;\n+\tint ret;\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++) {\n+\t\tpages[i] = alloc_page(GFP_KERNEL);\n+\t\tKUNIT_ASSERT_NOT_NULL(test, pages[i]);\n+\t}\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.chunks = chunks;\n+\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n+\n+\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tpin = desc.private_data;\n+\tKUNIT_ASSERT_NOT_NULL(test, pin);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);\n+\n+\t/*\n+\t * Concurrent release: the buffer drops its own reference to each\n+\t * page. The pages must still be alive, held only by the pin, so a\n+\t * mapping that is mid-insert cannot walk freed memory.\n+\t */\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\t__free_page(pages[i]);\n+\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n+\t\tKUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);\n+\tKUNIT_EXPECT_PTR_EQ(test, pin-\u003epages, \u0026pages[0]);\n+\tKUNIT_EXPECT_EQ(test, pin-\u003epage_count, ARRAY_SIZE(pages));\n+\n+\t/* The pin is what drops the last reference. */\n+\tsysfs_pin_release(pin);\n+}\n+\n+/*\n+ * KCA-23: the protection state has to travel with the pin. The snapshot is\n+ * taken in the same critical section as the page array, so a later\n+ * vmbus_release_buffer() clearing the descriptor cannot change what this\n+ * mapping is told about the pages it holds.\n+ */\n+static void ring_mmap_release_preserves_protection_snapshot(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = {\n+\t\t.state = CHANNEL_OPENED_STATE,\n+\t\t.ringbuffer = {\n+\t\t\t.page_cnt = 1,\n+\t\t},\n+\t};\n+\tstruct page *pages[1] = {};\n+\tstruct page *chunks[1] = {};\n+\tstruct vmbus_buffer_pin pin = {};\n+\tint ret;\n+\n+\tpages[0] = alloc_page(GFP_KERNEL);\n+\tKUNIT_ASSERT_NOT_NULL(test, pages[0]);\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.chunks = chunks;\n+\n+\tret = vmbus_buffer_pin_pages(\u0026channel.ringbuffer, \u0026pin);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_TRUE(test, pin.decrypted);\n+\tKUNIT_EXPECT_EQ(test, pin.page_count, 1UL);\n+\n+\t/*\n+\t * A concurrent release clears the descriptor. The pin must still\n+\t * describe the pages it holds, not the cleared descriptor.\n+\t */\n+\tchannel.ringbuffer.chunks = NULL;\n+\tchannel.ringbuffer.pages = NULL;\n+\tchannel.ringbuffer.page_cnt = 0;\n+\tKUNIT_EXPECT_TRUE(test, pin.decrypted);\n+\tKUNIT_EXPECT_PTR_EQ(test, pin.pages, \u0026pages[0]);\n+\tKUNIT_EXPECT_EQ(test, pin.page_count, 1UL);\n+\n+\tvmbus_buffer_unpin_pages(\u0026pin);\n+\tKUNIT_EXPECT_NULL(test, pin.pages);\n+\tKUNIT_EXPECT_EQ(test, pin.page_count, 0UL);\n+\n+\t/* A buffer that never took the shared-page path is not decrypted. */\n+\tchannel.ringbuffer.pages = pages;\n+\tchannel.ringbuffer.page_cnt = 1;\n+\tchannel.ringbuffer.chunks = NULL;\n+\tret = vmbus_buffer_pin_pages(\u0026channel.ringbuffer, \u0026pin);\n+\tKUNIT_ASSERT_EQ(test, ret, 0);\n+\tKUNIT_EXPECT_FALSE(test, pin.decrypted);\n+\tvmbus_buffer_unpin_pages(\u0026pin);\n+\n+\t__free_page(pages[0]);\n+}\n+\n+static unsigned int hv_uio_disconnect_calls;\n+static int hv_uio_disconnect_result;\n+\n+static int hv_uio_test_disconnect(struct vmbus_channel *channel)\n+{\n+\thv_uio_disconnect_calls++;\n+\tchannel-\u003estate = CHANNEL_OPEN_STATE;\n+\treturn hv_uio_disconnect_result;\n+}\n+\n+static void hv_uio_remove_disconnects_open_channel_test(struct kunit *test)\n+{\n+\tstruct vmbus_channel channel = { .state = CHANNEL_OPEN_STATE };\n+\n+\thv_uio_disconnect_calls = 0;\n+\thv_uio_disconnect_result = 0;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(\u0026channel,\n+\t\t\t\t\t\t\thv_uio_test_disconnect), 0);\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 0U);\n+\tchannel.state = CHANNEL_OPENED_STATE;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(\u0026channel,\n+\t\t\t\t\t\t\thv_uio_test_disconnect), 0);\n+\tKUNIT_EXPECT_EQ(test, channel.state, CHANNEL_OPEN_STATE);\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 1U);\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(\u0026channel,\n+\t\t\t\t\t\t\thv_uio_test_disconnect), 0);\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 1U);\n+\n+\tchannel.state = CHANNEL_OPENED_STATE;\n+\thv_uio_disconnect_result = -EIO;\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(\u0026channel,\n+\t\t\t\t\t\t\thv_uio_test_disconnect), -EIO);\n+\tKUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 2U);\n+}\n+\n+static int hv_uio_test_reader_wake(struct wait_queue_entry *wait,\n+\t\t\t\t   unsigned int mode, int flags, void *key)\n+{\n+\tunsigned int *wakes = wait-\u003eprivate;\n+\n+\t(*wakes)++;\n+\treturn 1;\n+}\n+\n+static void hv_uio_unregister_wakes_reader_test(struct kunit *test)\n+{\n+\tstruct uio_info info = {\n+\t\t.name = \"hv-uio-withdrawal-test\",\n+\t\t.version = \"1\",\n+\t\t.irq = UIO_IRQ_CUSTOM,\n+\t};\n+\tstruct uio_device *idev;\n+\tstruct device *parent;\n+\twait_queue_entry_t wait;\n+\tunsigned int wakes = 0;\n+\tint ret;\n+\n+\tparent = root_device_register(\"hv-uio-withdrawal-test\");\n+\tKUNIT_ASSERT_FALSE(test, IS_ERR(parent));\n+\tret = uio_register_device(parent, \u0026info);\n+\tif (ret) {\n+\t\troot_device_unregister(parent);\n+\t\tKUNIT_FAIL(test, \"UIO registration failed: %d\", ret);\n+\t\treturn;\n+\t}\n+\tidev = info.uio_dev;\n+\tget_device(\u0026idev-\u003edev);\n+\tinit_waitqueue_func_entry(\u0026wait, hv_uio_test_reader_wake);\n+\twait.private = \u0026wakes;\n+\tadd_wait_queue(\u0026idev-\u003ewait, \u0026wait);\n+\n+\tuio_unregister_device(\u0026info);\n+\tKUNIT_EXPECT_PTR_EQ(test, idev-\u003einfo, NULL);\n+\tKUNIT_EXPECT_EQ(test, wakes, 1U);\n+\tremove_wait_queue(\u0026idev-\u003ewait, \u0026wait);\n+\tput_device(\u0026idev-\u003edev);\n+\troot_device_unregister(parent);\n+}\n+\n+static struct kunit_case hv_uio_ring_mmap_test_cases[] = {\n+\tKUNIT_CASE(hv_uio_unregister_wakes_reader_test),\n+\tKUNIT_CASE(hv_uio_remove_disconnects_open_channel_test),\n+\tKUNIT_CASE(hv_uio_ring_mmap_range_test),\n+\tKUNIT_CASE(hv_uio_ring_mmap_prepare_test),\n+\tKUNIT_CASE(hv_uio_mmap_region_select_test),\n+\tKUNIT_CASE(hv_uio_mmap_prepare_test),\n+\tKUNIT_CASE(hv_uio_pin_lifetime_test),\n+\tKUNIT_CASE(hv_uio_pin_close_before_mapped_test),\n+\tKUNIT_CASE(sysfs_ring_mmap_ops_have_no_close),\n+\tKUNIT_CASE(uio_buffer_mmap_success),\n+\tKUNIT_CASE(sysfs_mmap_prepare_failure_releases_pin),\n+\tKUNIT_CASE(sysfs_mmap_partial_insert_failure_releases_pin),\n+\tKUNIT_CASE(sysfs_mmap_release_during_insert_keeps_pages_alive),\n+\tKUNIT_CASE(ring_mmap_release_preserves_protection_snapshot),\n+\t{}\n+};\n+\n+static struct kunit_suite hv_uio_ring_mmap_test_suite = {\n+\t.name = \"hyperv-uio-mmap\",\n+\t.test_cases = hv_uio_ring_mmap_test_cases,\n+};\n+\n+kunit_test_suite(hv_uio_ring_mmap_test_suite);\ndiff --git a/include/linux/hyperv.h b/include/linux/hyperv.h\nindex 9e109d91aa143..f0e8f1af8e757 100644\n--- a/include/linux/hyperv.h\n+++ b/include/linux/hyperv.h\n@@ -70,8 +70,7 @@\n  */\n enum hv_gpadl_type {\n \tHV_GPADL_BUFFER,\n-\tHV_GPADL_RING,\n-\tHV_GPADL_BUFFER_DECRYPTED\n+\tHV_GPADL_RING\n };\n \n /* Single-page buffer */\n@@ -782,6 +781,21 @@ struct vmbus_gpadl {\n \tu32 size;\n \tvoid *buffer;\n \tbool decrypted;\n+\tbool leak;\n+};\n+\n+struct vmbus_buffer_retained;\n+\n+struct vmbus_buffer {\n+\tvoid *addr;\n+\tstruct page **chunks;\n+\tstruct page **pages;\n+\tu32 chunk_cnt;\n+\tu32 page_cnt;\n+\tu32 size;\n+\tstruct vmbus_gpadl gpadl;\n+\tbool leak;\n+\tstruct vmbus_buffer_retained *owner;\n };\n \n struct vmbus_channel {\n@@ -800,13 +814,13 @@ struct vmbus_channel {\n \tu8 monitor_bit;\n \n \tbool rescind; /* got rescind msg */\n+\tbool rescind_from_host; /* host revocation, not local channel removal */\n \tbool rescind_ref; /* got rescind msg, got channel reference */\n+\tu64 lifetime_id;\n \tstruct completion rescind_event;\n \n-\tstruct vmbus_gpadl ringbuffer_gpadlhandle;\n-\n \t/* Allocated memory for ring buffer */\n-\tstruct page *ringbuffer_page;\n+\tstruct vmbus_buffer ringbuffer;\n \tu32 ringbuffer_pagecount;\n \tu32 ringbuffer_send_offset;\n \tstruct hv_ring_buffer_info outbound;\t/* send to parent */\n@@ -1110,7 +1124,8 @@ static inline void set_channel_pending_send_size(struct vmbus_channel *c,\n \tc-\u003eoutbound.ring_buffer-\u003epending_send_sz = size;\n }\n \n-void vmbus_onmessage(struct vmbus_channel_message_header *hdr);\n+void vmbus_onmessage(struct vmbus_channel_message_header *hdr,\n+\t\t     bool host_generated);\n \n int vmbus_request_offers(void);\n \n@@ -1201,9 +1216,9 @@ extern int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,\n \t\t\t\t     u64 requestid);\n \n extern int vmbus_establish_gpadl(struct vmbus_channel *channel,\n-\t\t\t\t      void *kbuffer,\n-\t\t\t\t      u32 size,\n-\t\t\t\t      struct vmbus_gpadl *gpadl);\n+\t\t\t\t void *kbuffer,\n+\t\t\t\t u32 size,\n+\t\t\t\t struct vmbus_gpadl *gpadl);\n \n extern int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,\n \t\t\t\t\t\t  void *kbuffer,\n@@ -1211,7 +1226,7 @@ extern int vmbus_establish_gpadl_caller_decrypted(struct vmbus_channel *channel,\n \t\t\t\t\t\t  struct vmbus_gpadl *gpadl);\n \n extern int vmbus_teardown_gpadl(struct vmbus_channel *channel,\n-\t\t\t\t     struct vmbus_gpadl *gpadl);\n+\t\t\t\tstruct vmbus_gpadl *gpadl);\n \n extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,\n \t\t\t\tu32 size,\n@@ -1220,6 +1235,43 @@ extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,\n \n extern void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt);\n \n+int vmbus_establish_gpadl_owned(struct vmbus_channel *channel,\n+\t\t\t\tstruct vmbus_buffer *buffer);\n+\n+int vmbus_teardown_gpadl_owned(struct vmbus_channel *channel,\n+\t\t\t       struct vmbus_buffer *buffer);\n+\n+int vmbus_alloc_buffer_owned(struct vmbus_channel *channel,\n+\t\t\t     u32 size,\n+\t\t\t     bool confidential,\n+\t\t\t     struct vmbus_buffer *buffer);\n+\n+void vmbus_release_buffer(struct vmbus_buffer *buffer);\n+\n+/**\n+ * struct vmbus_buffer_pin - locked snapshot of a buffer's mappable pages\n+ * @pages: page array owned by the buffer\n+ * @page_count: number of pages in @pages\n+ * @decrypted: backing pages are in the decrypted (host-shared) state\n+ *\n+ * vmbus_buffer_pin_pages() fills every field under\n+ * vmbus_buffer_owners_lock. A mapper reads only this snapshot and must\n+ * not re-read the buffer descriptor afterwards: vmbus_release_buffer()\n+ * clears the descriptor under that same lock while the pin still holds\n+ * the pages alive, so a later descriptor read describes the cleared\n+ * descriptor rather than the pages this mapper holds.\n+ */\n+struct vmbus_buffer_pin {\n+\tstruct page **pages;\n+\tunsigned long page_count;\n+\tbool decrypted;\n+};\n+\n+int vmbus_buffer_pin_pages(struct vmbus_buffer *buffer,\n+\t\t\t   struct vmbus_buffer_pin *pin);\n+\n+void vmbus_buffer_unpin_pages(struct vmbus_buffer_pin *pin);\n+\n void vmbus_reset_channel_cb(struct vmbus_channel *channel);\n \n extern int vmbus_recvpacket(struct vmbus_channel *channel,\n"
}

2/1 2026/10/07 21:53 agent patch-evaluator
6m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "UIO",
    "TARGET_CORE",
    "TCM_USER2",
    "HYPERV",
    "HYPERV_VMBUS",
    "HYPERV_NET",
    "UIO_HV_GENERIC"
  ],
  "FocusSymbols": [
    "uio_mmap",
    "hv_uio_mmap_prepare",
    "hv_uio_ring_mmap_prepare",
    "vmbus_alloc_buffer_owned",
    "vmbus_release_buffer",
    "vmbus_buffer_pin_pages",
    "vmbus_buffer_unpin_pages",
    "vmbus_buffer_reclaim_work",
    "vmbus_gpadl_teardown_request",
    "vmbus_teardown_gpadl_owned",
    "vmbus_establish_gpadl_owned",
    "hv_mmap_ring_buffer_wrapper",
    "netvsc_send_completion",
    "netvsc_send_tx_complete",
    "netvsc_send_acct",
    "rndis_build_page_buffers",
    "get_rndis_request"
  ],
  "Reasoning": "The patch modifies core UIO subsystem mmap logic in drivers/uio/uio.c (uio_mmap), changing VMA state installation and invoking vma-\u003evm_ops-\u003eclose() on mmap failure for drivers providing mmap_prepare (which directly affects reachable virtual subsystems like TCMU / target_core_user). It also significantly refactors buffer allocation, page pinning, asynchronous deferred page reclaim, and GPADL lifecycle management across Hyper-V VMBus and netvsc. These logic alterations and error-path cleanups warrant fuzzing.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit b46a7f3a76fb605ed8bbd8f5217b7a13200e774b
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Oct 7 21:53:22 2026 +0000

    syz-cluster: applied patch under review

diff --git a/drivers/hv/Kconfig b/drivers/hv/Kconfig
index aa11bcefddf2c..d44dd60fbc237 100644
--- a/drivers/hv/Kconfig
+++ b/drivers/hv/Kconfig
@@ -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)
diff --git a/drivers/hv/Makefile b/drivers/hv/Makefile
index 888a748cc7cb9..80d33e9c0e572 100644
--- a/drivers/hv/Makefile
+++ b/drivers/hv/Makefile
@@ -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
diff --git a/drivers/hv/channel.c b/drivers/hv/channel.c
index 7e4cc6f55237a..c7f3f5c6c0d28 100644
--- a/drivers/hv/channel.c
+++ b/drivers/hv/channel.c
@@ -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>
@@ -21,11 +23,378 @@
 #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
+ * therefore not static; nothing outside hv_vmbus links against them.
+ */
+int vmbus_buffer_round_size(u32 size, u32 *rounded_size)
+{
+	if (!size)
+		return -EINVAL;
+
+	if (size > U32_MAX - (u32)PAGE_SIZE + 1)
+		return -EOVERFLOW;
+
+	*rounded_size = round_up(size, (u32)PAGE_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)
+{
+	return min_t(unsigned int, max_order, ilog2(remaining));
+}
+
+bool vmbus_buffer_lower_order(unsigned int *order)
+{
+	if (!*order)
+		return false;
+
+	(*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 &&
+	       !buffer->gpadl.gpadl_handle;
+}
+
+/* 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
  *
@@ -42,7 +411,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 +471,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 +521,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,25 +537,21 @@ 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;
+	int ret;
 
-	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)
-		return -ENOMEM;
+	ret = vmbus_alloc_buffer_owned(newchannel, size,
+				       newchannel->co_ring_buffer, buffer);
+	if (ret)
+		return ret;
 
-	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;
 
 	return 0;
@@ -440,20 +801,106 @@ 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)
+{
+	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;
+}
+
+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,
-				   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_gpadl_body *gpadl_body;
 	struct vmbus_channel_msginfo *msginfo = NULL;
-	struct vmbus_channel_msginfo *submsginfo;
-	struct list_head *curr;
+	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;
 
+	gpadl->leak = false;
+
 	next_gpadl_handle =
 		(atomic_inc_return(&vmbus_connection.next_gpadl_handle) - 1);
 
@@ -463,9 +910,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.
@@ -479,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;
 		}
@@ -504,45 +954,22 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 		goto cleanup;
 	}
 
-	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 (posted && owner)
+		vmbus_buffer_update_host_ownership(owner, true);
+	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) {
-		pr_err("Failed to establish GPADL: err = 0x%x\n",
-		       msginfo->response.gpadl_created.creation_status);
-
-		ret = -EDQUOT;
-		goto cleanup;
-	}
-
-	if (channel->rescind) {
-		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;
 	}
 
@@ -550,7 +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);
@@ -559,34 +987,44 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 
 	vmbus_free_channel_msginfo(msginfo);
 
-	if (ret) {
-		/*
-		 * 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;
-		}
-	}
+	if (ret && posted)
+		gpadl->leak = true;
+	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, 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);
 
@@ -600,13 +1038,23 @@ EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
  * @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,
-					   struct vmbus_gpadl *gpadl)
+					  void *kbuffer, u32 size,
+					  struct vmbus_gpadl *gpadl)
 {
-	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER_DECRYPTED,
-				       kbuffer, size, 0U, 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);
 
@@ -632,7 +1080,8 @@ void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt)
 		return;
 	}
 
-	vunmap(addr);
+	if (addr)
+		vunmap(addr);
 
 	for (i = 0; i < chunk_cnt; i++) {
 		unsigned long vaddr =
@@ -648,14 +1097,162 @@ 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)
+{
+	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");
+
+	memset(buffer, 0, sizeof(*buffer));
+	vmbus_buffer_schedule_reclaim_locked(owner);
+	mutex_unlock(&vmbus_buffer_owners_lock);
+}
+EXPORT_SYMBOL_GPL(vmbus_release_buffer);
+
 /**
- * vmbus_alloc_buffer - allocate a host-visible, virtually-contiguous 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)
+{
+	(void)context;
+	return alloc_pages_node(nid, gfp, order);
+}
+
+/**
+ * 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)
- * @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
+ * @confidential: keep the buffer private to the guest
+ * @buffer: output descriptor that owns the allocation and its backing pages
  *
  * Buffers not requiring decryption are allocated with vzalloc().
  *
@@ -665,66 +1262,88 @@ EXPORT_SYMBOL_GPL(vmbus_free_buffer);
  * 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.
  */
-void *vmbus_alloc_buffer(struct vmbus_channel *channel,
-			 u32 size,
-			 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)
 {
-	unsigned long nr_pages = PFN_UP(size);
-	unsigned long remaining = nr_pages;
+	u32 rounded_size;
+	unsigned long nr_pages;
+	unsigned long remaining;
 	unsigned long page_idx = 0;
-	struct page **chunks = NULL;
-	struct page **pages = NULL;
-	int order = MAX_PAGE_ORDER;
-	u32 chunk_cnt = 0;
-	void *addr;
+	struct vmbus_buffer_retained *owner;
+	unsigned int order = MAX_PAGE_ORDER;
+	bool hv_isolation;
+	bool guest_mem_encrypted;
 	u32 i;
 	int ret;
 
-	*chunks_out = NULL;
-	*chunk_cnt_out = 0;
+	memset(buffer, 0, sizeof(*buffer));
 
-	if (!nr_pages)
-		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 (!hv_is_isolation_supported() || channel->co_external_memory)
-		return vzalloc(nr_pages << PAGE_SHIFT);
+	if (!vmbus_needs_shared_pages(hv_isolation, guest_mem_encrypted,
+				      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) {
 		struct page *page;
 		gfp_t gfp;
+		int nid;
 
-		order = min(order, ilog2(remaining));
+		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 (!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;
+
+		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);
@@ -733,32 +1352,57 @@ 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, nr_pages << PAGE_SHIFT);
-
-	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;
+}
+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)
+{
+	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);
 
@@ -767,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;
 
@@ -792,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;
 
@@ -801,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;
 	}
 
@@ -820,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,
@@ -832,7 +1497,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 +1525,22 @@ 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),
-				      (send_pages + recv_pages) << PAGE_SHIFT,
+	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING, buffer,
 				      newchannel->ringbuffer_send_offset << PAGE_SHIFT,
-				      &newchannel->ringbuffer_gpadlhandle);
+				      true);
 	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 +1562,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 +1620,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 error_free_info:
 	kfree(open_info);
 error_free_gpadl:
-	vmbus_teardown_gpadl(newchannel, &newchannel->ringbuffer_gpadlhandle);
+	vmbus_teardown_gpadl_owned(newchannel, buffer);
 error_clean_ring:
 	hv_ringbuffer_cleanup(&newchannel->outbound);
 	hv_ringbuffer_cleanup(&newchannel->inbound);
@@ -1002,71 +1666,164 @@ 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);
-	if (!info)
-		return -ENOMEM;
+	info = alloc_info();
+	if (!info) {
+		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 = channel->offermsg.child_relid;
-	msg->gpadl = gpadl->gpadl_handle;
+	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);
 
-	if (channel->rescind)
-		goto post_msg_err;
+	spin_lock_irqsave(&connection->channelmsg_lock, flags);
+	list_add_tail(&info->msglistentry, &connection->chn_msg_list);
+	spin_unlock_irqrestore(&connection->channelmsg_lock, flags);
 
-	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),
-			     true);
+	if (channel->offermsg.child_relid != relid ||
+	    (READ_ONCE(channel->rescind) &&
+	     !READ_ONCE(channel->rescind_from_host)))
+		goto cleanup;
 
-	trace_vmbus_teardown_gpadl(msg, ret);
+	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 (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);
+retain:
+	if (ret) {
+		gpadl->leak = true;
+		if (owner)
+			vmbus_buffer_update_host_ownership(owner, true);
+	}
 
-	gpadl->decrypted = ret;
+	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) {
+			pr_warn("Failed to re-encrypt GPADL buffer: %d\n",
+				encrypt_ret);
+			ret = encrypt_ret;
+		}
+		gpadl->decrypted = !!encrypt_ret;
+	}
 
 	return ret;
 }
@@ -1142,8 +1899,8 @@ 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_owned(channel, &channel->ringbuffer);
 		if (ret) {
 			pr_err("Close failed: teardown gpadl return %d\n", ret);
 			/*
diff --git a/drivers/hv/channel_mgmt.c b/drivers/hv/channel_mgmt.c
index a044fd3b3c4e7..be0f70a3541cd 100644
--- a/drivers/hv/channel_mgmt.c
+++ b/drivers/hv/channel_mgmt.c
@@ -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[] = {
@@ -170,14 +172,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 +960,10 @@ 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);
+
 	/*
 	 * Setup state for signalling the host.
 	 */
@@ -1159,7 +1168,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 +1248,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
@@ -1477,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;
 
@@ -1514,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);
 }
 
 /*
@@ -1555,12 +1568,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 +1615,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 +1624,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);
 }
 
diff --git a/drivers/hv/hv_trace.h b/drivers/hv/hv_trace.h
index c02a1719e92f2..a3eeb817b00ea 100644
--- a/drivers/hv/hv_trace.h
+++ b/drivers/hv/hv_trace.h
@@ -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),
diff --git a/drivers/hv/hyperv_vmbus.h b/drivers/hv/hyperv_vmbus.h
index 33923621a5a3f..9819a6b686cec 100644
--- a/drivers/hv/hyperv_vmbus.h
+++ b/drivers/hv/hyperv_vmbus.h
@@ -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);
 
@@ -354,6 +354,7 @@ struct vmbus_channel_message_table_entry {
 extern const struct vmbus_channel_message_table_entry
 	channel_message_table[CHANNELMSG_COUNT];
 
+void vmbus_buffer_reclaimer_shutdown(void);
 
 /* General vmbus interface */
 
@@ -551,4 +552,111 @@ int hv_create_ring_sysfs(struct vmbus_channel *channel,
 							    struct vm_area_desc *desc));
 int hv_remove_ring_sysfs(struct vmbus_channel *channel);
 
+/*
+ * Retained buffer owner. One per channel-keyed allocation; freed only
+ * after GPADL, page-state and mapping-reference gates all clear.
+ */
+struct vmbus_buffer_retained {
+	struct list_head list;
+	struct delayed_work reclaim_work;
+	u64 channel_id;
+	u64 owner_id;
+	void *addr;
+	struct page **chunks;
+	struct page **pages;
+	u32 chunk_cnt;
+	u32 page_cnt;
+	u32 size;
+	bool released;
+	bool host_may_own;
+	bool needs_encrypt;
+	bool raw_decrypted;
+	bool encryption_unknown;
+	bool permanent_leak;
+	bool work_active;
+	bool reclaiming;
+};
+
+/*
+ * 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.
+ */
+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);
+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);
+
+/*
+ * Owner lifetime and reclaim-gate helpers, shared with
+ * vmbus_buffer_test.c for the same reason as the sizing helpers.
+ * Defined in channel.c, unexported.
+ */
+bool vmbus_buffer_owner_can_reclaim(const struct vmbus_buffer_retained *owner);
+bool vmbus_buffer_owner_should_schedule(const struct vmbus_buffer_retained *owner,
+					bool stopping, bool queue_live);
+bool vmbus_buffer_pages_busy(struct vmbus_buffer_retained *owner);
+void vmbus_buffer_owner_drain(struct vmbus_buffer_retained *owner,
+			      struct workqueue_struct *wq);
+struct vmbus_buffer_retained *
+vmbus_buffer_owner_alloc(struct vmbus_channel *channel);
+
+/*
+ * 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);
+typedef struct vmbus_channel_msginfo *(*vmbus_gpadl_info_alloc_fn)(void);
+typedef int (*vmbus_gpadl_teardown_post_fn)(struct vmbus_connection *connection,
+					 struct vmbus_channel_msginfo *info);
+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);
+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 */
diff --git a/drivers/hv/ring_buffer.c b/drivers/hv/ring_buffer.c
index 592a9601faaaf..16b1c29107890 100644
--- a/drivers/hv/ring_buffer.c
+++ b/drivers/hv/ring_buffer.c
@@ -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,
diff --git a/drivers/hv/vmbus_buffer_test.c b/drivers/hv/vmbus_buffer_test.c
new file mode 100644
index 0000000000000..d0102dabef737
--- /dev/null
+++ b/drivers/hv/vmbus_buffer_test.c
@@ -0,0 +1,976 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for Hyper-V VMBus buffer allocation and GPADL lifetime.
+ *
+ * Built into the hv_vmbus object rather than a separate module so the
+ * cases can reach the internal helpers declared in hyperv_vmbus.h
+ * without exporting them.
+ */
+#include <kunit/test.h>
+#include <linux/completion.h>
+#include <linux/hyperv.h>
+#include <linux/mm.h>
+#include <linux/sizes.h>
+#include <linux/slab.h>
+#include <linux/vmalloc.h>
+
+#include "hyperv_vmbus.h"
+
+static void vmbus_buffer_size_rounding_test(struct kunit *test)
+{
+	u32 rounded_size;
+
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(1, &rounded_size), 0);
+	KUNIT_EXPECT_EQ(test, rounded_size, (u32)PAGE_SIZE);
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(PAGE_SIZE, &rounded_size), 0);
+	KUNIT_EXPECT_EQ(test, rounded_size, (u32)PAGE_SIZE);
+}
+
+static void vmbus_buffer_size_overflow_test(struct kunit *test)
+{
+	u32 rounded_size = 0;
+	int ret;
+
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(0, &rounded_size), -EINVAL);
+	ret = vmbus_buffer_round_size(U32_MAX, &rounded_size);
+	KUNIT_EXPECT_EQ(test, ret, -EOVERFLOW);
+	ret = vmbus_buffer_round_size(U32_MAX - PAGE_SIZE + 1, &rounded_size);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, rounded_size,
+			(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_buffer_owner_reclaim_gate_test(struct kunit *test)
+{
+	struct vmbus_buffer_retained owner = {
+		.released = false,
+	};
+
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+	owner.released = true;
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.host_may_own = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.host_may_own = false;	/* GPADL teardown acknowledgment */
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.permanent_leak = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.permanent_leak = false;
+	owner.encryption_unknown = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+}
+
+static void vmbus_buffer_reclaim_schedule_gate_test(struct kunit *test)
+{
+	struct vmbus_buffer_retained owner = {
+		.released = true,
+	};
+
+	KUNIT_EXPECT_TRUE(test,
+			  vmbus_buffer_owner_should_schedule(&owner, false, true));
+	owner.work_active = true;
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, false, true));
+	owner.work_active = false;
+	owner.reclaiming = true;
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, false, true));
+	owner.reclaiming = false;
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, true, true));
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, false, false));
+}
+
+struct vmbus_reclaim_test_work {
+	struct vmbus_buffer_retained owner;
+	struct workqueue_struct *wq;
+	struct completion entered;
+	struct completion proceed;
+	atomic_t calls;
+	bool claim_owner;
+};
+
+static void vmbus_reclaim_test_callback(struct work_struct *work)
+{
+	struct vmbus_buffer_retained *owner =
+		container_of(to_delayed_work(work),
+			     struct vmbus_buffer_retained, reclaim_work);
+	struct vmbus_reclaim_test_work *ctx =
+		container_of(owner, struct vmbus_reclaim_test_work, owner);
+
+	atomic_inc(&ctx->calls);
+	if (ctx->claim_owner)
+		owner->reclaiming = true;
+	complete(&ctx->entered);
+	wait_for_completion(&ctx->proceed);
+}
+
+static void vmbus_reclaim_test_cleanup(void *data)
+{
+	struct vmbus_reclaim_test_work *ctx = data;
+
+	complete_all(&ctx->proceed);
+	cancel_delayed_work_sync(&ctx->owner.reclaim_work);
+	destroy_workqueue(ctx->wq);
+}
+
+static struct vmbus_reclaim_test_work *
+vmbus_reclaim_test_init(struct kunit *test)
+{
+	struct vmbus_reclaim_test_work *ctx;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return NULL;
+	init_completion(&ctx->entered);
+	init_completion(&ctx->proceed);
+	atomic_set(&ctx->calls, 0);
+	ctx->owner.released = true;
+	ctx->owner.work_active = true;
+	INIT_DELAYED_WORK(&ctx->owner.reclaim_work,
+			  vmbus_reclaim_test_callback);
+	ctx->wq = alloc_workqueue("vmbus-reclaim-test",
+				  WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
+	if (!ctx->wq)
+		return NULL;
+	if (kunit_add_action_or_reset(test, vmbus_reclaim_test_cleanup, ctx))
+		return NULL;
+	return ctx;
+}
+
+static void vmbus_reclaim_running_test(struct kunit *test, bool claim_owner)
+{
+	struct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->claim_owner = claim_owner;
+	KUNIT_ASSERT_TRUE(test,
+			  queue_delayed_work(ctx->wq, &ctx->owner.reclaim_work, 0));
+	KUNIT_ASSERT_NE(test,
+			wait_for_completion_timeout(&ctx->entered,
+						    msecs_to_jiffies(1000)), 0UL);
+
+	/*
+	 * The native workqueue cleared pending before entering the callback.
+	 * Test both windows around the callback taking ownership. Keep the
+	 * fixture alive so an incorrect second queue fails without a UAF.
+	 */
+	vmbus_buffer_owner_drain(&ctx->owner, ctx->wq);
+	KUNIT_EXPECT_FALSE(test, delayed_work_pending(&ctx->owner.reclaim_work));
+	KUNIT_EXPECT_TRUE(test, ctx->owner.work_active);
+	complete_all(&ctx->proceed);
+	flush_workqueue(ctx->wq);
+	KUNIT_EXPECT_EQ(test, atomic_read(&ctx->calls), 1);
+}
+
+static void vmbus_reclaim_shutdown_before_claim_test(struct kunit *test)
+{
+	vmbus_reclaim_running_test(test, false);
+}
+
+static void vmbus_reclaim_shutdown_during_reclaim_test(struct kunit *test)
+{
+	vmbus_reclaim_running_test(test, true);
+}
+
+static void vmbus_reclaim_shutdown_pending_test(struct kunit *test)
+{
+	struct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	KUNIT_ASSERT_TRUE(test,
+			  queue_delayed_work(ctx->wq, &ctx->owner.reclaim_work,
+					     msecs_to_jiffies(60000)));
+	complete_all(&ctx->proceed);
+	vmbus_buffer_owner_drain(&ctx->owner, ctx->wq);
+	flush_workqueue(ctx->wq);
+	KUNIT_EXPECT_EQ(test, atomic_read(&ctx->calls), 1);
+}
+
+static void vmbus_reclaim_shutdown_unsafe_pending_test(struct kunit *test)
+{
+	struct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->owner.host_may_own = true;
+	KUNIT_ASSERT_TRUE(test,
+			  queue_delayed_work(ctx->wq, &ctx->owner.reclaim_work,
+					     msecs_to_jiffies(60000)));
+	vmbus_buffer_owner_drain(&ctx->owner, ctx->wq);
+	KUNIT_EXPECT_FALSE(test, delayed_work_pending(&ctx->owner.reclaim_work));
+	KUNIT_EXPECT_FALSE(test, ctx->owner.work_active);
+	flush_workqueue(ctx->wq);
+	KUNIT_EXPECT_EQ(test, atomic_read(&ctx->calls), 0);
+}
+
+static struct vmbus_channel_msginfo *vmbus_test_alloc_teardown_fail(void)
+{
+	return NULL;
+}
+
+static void vmbus_buffer_rescind_retains_gpadl_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rescind = true };
+	struct vmbus_buffer_retained owner = {
+		.released = true,
+		.host_may_own = true,
+	};
+	struct vmbus_buffer buffer = { .owner = &owner };
+	unsigned int origin, pending;
+	u32 handle;
+	int ret;
+
+	/* Exercise the request core without touching the live connection. */
+	for (origin = 0; origin < 2; origin++) {
+		channel.rescind_from_host = origin;
+		for (pending = 0; pending < 2; pending++) {
+			buffer.gpadl.gpadl_handle = pending ? 0 : 17;
+			buffer.gpadl.leak = pending;
+			handle = buffer.gpadl.gpadl_handle;
+			ret = vmbus_gpadl_teardown_request(&channel, &buffer,
+							   vmbus_test_alloc_teardown_fail,
+							   NULL, NULL, 1);
+			KUNIT_EXPECT_EQ(test, ret, !origin ? -ENODEV :
+					  pending ? -EINPROGRESS : -ENOMEM);
+			KUNIT_EXPECT_EQ(test, buffer.gpadl.gpadl_handle, handle);
+			KUNIT_EXPECT_TRUE(test, buffer.gpadl.leak);
+			KUNIT_EXPECT_TRUE(test, owner.host_may_own);
+			KUNIT_EXPECT_FALSE(test, owner.work_active);
+			KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+			KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+		}
+	}
+}
+
+enum vmbus_test_teardown_reply {
+	VMBUS_TEST_REPLY_ACK,
+	VMBUS_TEST_REPLY_NONE,
+	VMBUS_TEST_REPLY_WRONG_HANDLE,
+	VMBUS_TEST_REPLY_WRONG_TYPE,
+	VMBUS_TEST_REPLY_POST_FAILURE,
+};
+
+struct vmbus_teardown_test_context {
+	struct vmbus_connection connection;
+	struct vmbus_channel channel;
+	struct vmbus_buffer buffer;
+	struct vmbus_buffer_retained owner;
+	struct kunit *test;
+	enum vmbus_test_teardown_reply reply;
+	unsigned int post_calls;
+};
+
+static struct vmbus_channel_msginfo *vmbus_test_alloc_teardown(void)
+{
+	return kzalloc(sizeof(struct vmbus_channel_msginfo) +
+		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
+}
+
+static int vmbus_test_post_teardown(struct vmbus_connection *connection,
+				    struct vmbus_channel_msginfo *info)
+{
+	struct vmbus_teardown_test_context *ctx =
+		container_of(connection, struct vmbus_teardown_test_context,
+			     connection);
+	struct vmbus_channel_gpadl_teardown *msg = (void *)info->msg;
+	struct vmbus_channel_gpadl_torndown response = {
+		.header.msgtype = CHANNELMSG_GPADL_TORNDOWN,
+		.gpadl = msg->gpadl,
+	};
+
+	ctx->post_calls++;
+	KUNIT_EXPECT_EQ(ctx->test, msg->header.msgtype, CHANNELMSG_GPADL_TEARDOWN);
+	KUNIT_EXPECT_EQ(ctx->test, msg->child_relid, 71U);
+	KUNIT_EXPECT_EQ(ctx->test, msg->gpadl, 51U);
+	KUNIT_EXPECT_PTR_EQ(ctx->test, info->waiting_channel, NULL);
+	if (ctx->reply == VMBUS_TEST_REPLY_POST_FAILURE)
+		return -EIO;
+	if (ctx->reply == VMBUS_TEST_REPLY_NONE)
+		return 0;
+	if (ctx->reply == VMBUS_TEST_REPLY_WRONG_HANDLE)
+		response.gpadl++;
+	if (ctx->reply == VMBUS_TEST_REPLY_WRONG_TYPE)
+		response.header.msgtype = CHANNELMSG_GPADL_CREATED;
+	vmbus_complete_gpadl_teardown(connection, &response);
+	return 0;
+}
+
+static struct vmbus_teardown_test_context *
+vmbus_test_teardown_context(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return NULL;
+	ctx->test = test;
+	ctx->buffer.gpadl.gpadl_handle = 51;
+	ctx->buffer.owner = &ctx->owner;
+	ctx->owner.host_may_own = true;
+	ctx->channel.rescind = true;
+	ctx->channel.rescind_from_host = true;
+	ctx->channel.offermsg.child_relid = 71;
+	INIT_LIST_HEAD(&ctx->connection.chn_msg_list);
+	spin_lock_init(&ctx->connection.channelmsg_lock);
+	return ctx;
+}
+
+static int vmbus_test_teardown_request(struct vmbus_teardown_test_context *ctx)
+{
+	return vmbus_gpadl_teardown_request(&ctx->channel, &ctx->buffer,
+					  vmbus_test_alloc_teardown,
+					  &ctx->connection,
+					  vmbus_test_post_teardown, 1);
+}
+
+static void vmbus_host_rescind_teardown_ack_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), 0);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 1U);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 0U);
+	KUNIT_EXPECT_FALSE(test, ctx->buffer.gpadl.leak);
+	KUNIT_EXPECT_FALSE(test, ctx->owner.host_may_own);
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_should_free(&ctx->buffer));
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->connection.chn_msg_list));
+}
+
+static void vmbus_test_teardown_failure(struct kunit *test,
+					enum vmbus_test_teardown_reply reply,
+					int expected)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->reply = reply;
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), expected);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 1U);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&ctx->buffer));
+	KUNIT_EXPECT_TRUE(test, ctx->owner.host_may_own);
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->connection.chn_msg_list));
+}
+
+static void vmbus_host_rescind_teardown_timeout_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_NONE, -ETIMEDOUT);
+}
+
+static void vmbus_host_rescind_teardown_wrong_handle_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_WRONG_HANDLE,
+				    -ETIMEDOUT);
+}
+
+static void vmbus_host_rescind_teardown_wrong_type_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_WRONG_TYPE, -ENODEV);
+}
+
+static void vmbus_host_rescind_teardown_post_failure_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_POST_FAILURE, -EIO);
+}
+
+static void vmbus_local_rescind_skips_teardown_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->channel.rescind_from_host = false;
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), -ENODEV);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 0U);
+	KUNIT_EXPECT_TRUE(test, ctx->buffer.gpadl.leak);
+	KUNIT_EXPECT_TRUE(test, ctx->owner.host_may_own);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+}
+
+static void vmbus_invalid_relid_skips_teardown_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->channel.offermsg.child_relid = INVALID_RELID;
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), -ENODEV);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 0U);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+}
+
+static void vmbus_host_rescind_teardown_late_ack_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+	struct vmbus_channel_gpadl_torndown response = {
+		.header.msgtype = CHANNELMSG_GPADL_TORNDOWN,
+		.gpadl = 51,
+	};
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->reply = VMBUS_TEST_REPLY_NONE;
+	KUNIT_ASSERT_EQ(test, vmbus_test_teardown_request(ctx), -ETIMEDOUT);
+	/* Run the production response matcher after its waiter has been freed. */
+	vmbus_complete_gpadl_teardown(&ctx->connection, &response);
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->connection.chn_msg_list));
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&ctx->buffer));
+	KUNIT_EXPECT_TRUE(test, ctx->owner.host_may_own);
+}
+
+static void vmbus_buffer_mapping_reference_test(struct kunit *test)
+{
+	struct vmbus_buffer_retained owner = {};
+	struct page *page;
+	struct page *pages[1];
+
+	page = alloc_page(GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, page);
+	pages[0] = page;
+	owner.pages = pages;
+	owner.page_cnt = ARRAY_SIZE(pages);
+
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_pages_busy(&owner));
+	get_page(page); /* vm_insert_pages() holds one reference per mapping */
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_pages_busy(&owner));
+	put_page(page);
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_pages_busy(&owner));
+	__free_page(page);
+}
+
+static void vmbus_buffer_repeated_owner_release_test(struct kunit *test)
+{
+	struct vmbus_channel channel = {};
+	struct vmbus_buffer buffer = {};
+	struct vmbus_buffer empty = {};
+
+	buffer.addr = vzalloc(PAGE_SIZE);
+	KUNIT_ASSERT_NOT_NULL(test, buffer.addr);
+	buffer.owner = vmbus_buffer_owner_alloc(&channel);
+	if (!buffer.owner) {
+		vfree(buffer.addr);
+		KUNIT_FAIL(test, "failed to allocate a VMBus buffer owner");
+		return;
+	}
+	buffer.size = PAGE_SIZE;
+	empty.owner = vmbus_buffer_owner_alloc(&channel);
+	if (!empty.owner) {
+		vmbus_release_buffer(&buffer);
+		KUNIT_FAIL(test, "failed to allocate a second VMBus buffer owner");
+		return;
+	}
+	KUNIT_EXPECT_TRUE(test, empty.owner->owner_id != buffer.owner->owner_id);
+	vmbus_release_buffer(&empty);
+	KUNIT_EXPECT_PTR_EQ(test, empty.owner, NULL);
+
+	vmbus_release_buffer(&buffer);
+	KUNIT_EXPECT_PTR_EQ(test, buffer.addr, NULL);
+	KUNIT_EXPECT_PTR_EQ(test, buffer.owner, NULL);
+	vmbus_release_buffer(&buffer);
+}
+
+static void vmbus_ring_fallback_order_zero_test(struct kunit *test)
+{
+	unsigned int order;
+
+	order = vmbus_buffer_order(1UL << MAX_PAGE_ORDER, MAX_PAGE_ORDER);
+	KUNIT_EXPECT_EQ(test, order, (unsigned int)MAX_PAGE_ORDER);
+	while (order)
+		KUNIT_ASSERT_TRUE(test, vmbus_buffer_lower_order(&order));
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_lower_order(&order));
+	KUNIT_EXPECT_EQ(test, order, 0U);
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_order(3, MAX_PAGE_ORDER), 1U);
+}
+
+static void vmbus_buffer_failed_teardown_leaks_test(struct kunit *test)
+{
+	struct vmbus_buffer buffer = {
+		.addr = (void *)1,
+		.gpadl.gpadl_handle = 1,
+	};
+
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+	buffer.gpadl.gpadl_handle = 0;
+	buffer.gpadl.leak = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+	buffer.gpadl.leak = false;
+	buffer.leak = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+	buffer.leak = false;
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_should_free(&buffer));
+}
+
+static void vmbus_buffer_partial_allocation_cleanup_test(struct kunit *test)
+{
+	struct page **chunks;
+	struct vmbus_buffer buffer = {};
+
+	chunks = kmalloc_obj(*chunks, GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, chunks);
+	vmbus_free_buffer(NULL, chunks, 0);
+
+	buffer.addr = vzalloc(PAGE_SIZE);
+	KUNIT_ASSERT_NOT_NULL(test, buffer.addr);
+	vmbus_release_buffer(&buffer);
+	KUNIT_EXPECT_PTR_EQ(test, buffer.addr, NULL);
+	vmbus_release_buffer(&buffer);
+}
+
+struct vmbus_gpadl_post_test_context {
+	struct kunit *test;
+	unsigned int call_count;
+	unsigned int fail_call;
+	u32 first_msgtype;
+	u32 expected_gpadl;
+};
+
+static int vmbus_gpadl_test_post(void *context, void *buffer,
+				 size_t buflen, bool can_sleep)
+{
+	struct vmbus_gpadl_post_test_context *test_context = context;
+	struct vmbus_channel_message_header *header = buffer;
+
+	KUNIT_EXPECT_TRUE(test_context->test, can_sleep);
+	KUNIT_EXPECT_GT(test_context->test, buflen,
+			(size_t)sizeof(*header));
+	test_context->call_count++;
+	KUNIT_EXPECT_EQ(test_context->test, header->msgtype,
+			test_context->call_count == 1 ?
+			test_context->first_msgtype : CHANNELMSG_GPADL_BODY);
+	switch (header->msgtype) {
+	case CHANNELMSG_GPADL_HEADER: {
+		struct vmbus_channel_gpadl_header *gpadl_header = buffer;
+
+		KUNIT_EXPECT_EQ(test_context->test, gpadl_header->gpadl,
+				test_context->expected_gpadl);
+		break;
+	}
+	case CHANNELMSG_GPADL_BODY: {
+		struct vmbus_channel_gpadl_body *gpadl_body = buffer;
+
+		KUNIT_EXPECT_EQ(test_context->test, gpadl_body->gpadl,
+				test_context->expected_gpadl);
+		break;
+	}
+	case CHANNELMSG_GPADL_TEARDOWN: {
+		struct vmbus_channel_gpadl_teardown *teardown = buffer;
+
+		KUNIT_EXPECT_EQ(test_context->test, teardown->gpadl,
+				test_context->expected_gpadl);
+		KUNIT_EXPECT_EQ(test_context->test, teardown->child_relid,
+				7U);
+		break;
+	}
+	default:
+		KUNIT_FAIL(test_context->test,
+			   "unexpected GPADL message type: %d",
+			   header->msgtype);
+	}
+	if (test_context->call_count == test_context->fail_call)
+		return -EIO;
+
+	return 0;
+}
+
+static struct vmbus_channel_msginfo *
+vmbus_gpadl_test_msginfo(struct kunit *test, unsigned int body_count)
+{
+	struct vmbus_channel_msginfo *msginfo;
+	struct vmbus_channel_msginfo *body_info;
+	unsigned int i;
+
+	msginfo = kunit_kzalloc(test, sizeof(*msginfo) +
+			       sizeof(struct vmbus_channel_gpadl_header),
+			       GFP_KERNEL);
+	if (!msginfo)
+		return NULL;
+
+	msginfo->msgsize = sizeof(*msginfo) +
+			   sizeof(struct vmbus_channel_gpadl_header);
+	INIT_LIST_HEAD(&msginfo->submsglist);
+
+	for (i = 0; i < body_count; i++) {
+		body_info = kunit_kzalloc(test,
+					  sizeof(*body_info) +
+					  sizeof(struct vmbus_channel_gpadl_body),
+					  GFP_KERNEL);
+		if (!body_info)
+			return NULL;
+
+		body_info->msgsize = sizeof(*body_info) +
+				     sizeof(struct vmbus_channel_gpadl_body);
+		INIT_LIST_HEAD(&body_info->msglistentry);
+		list_add_tail(&body_info->msglistentry, &msginfo->submsglist);
+	}
+
+	return msginfo;
+}
+
+static void vmbus_gpadl_post_failure_test(struct kunit *test)
+{
+	unsigned int fail_call;
+
+	for (fail_call = 1; fail_call <= 3; fail_call++) {
+		struct vmbus_gpadl_post_test_context context = {
+			.test = test,
+			.fail_call = fail_call,
+			.first_msgtype = CHANNELMSG_GPADL_HEADER,
+			.expected_gpadl = 17,
+		};
+		struct vmbus_channel_msginfo *msginfo;
+		bool posted = false;
+		int ret;
+
+		msginfo = vmbus_gpadl_test_msginfo(test, 2);
+		KUNIT_ASSERT_NOT_NULL(test, msginfo);
+
+		ret = vmbus_post_gpadl_messages(msginfo, 17, &posted,
+						vmbus_gpadl_test_post, &context);
+		KUNIT_EXPECT_EQ(test, ret, -EIO);
+		KUNIT_EXPECT_EQ(test, context.call_count, fail_call);
+		KUNIT_EXPECT_TRUE(test, posted);
+	}
+}
+
+static void vmbus_gpadl_post_success_test(struct kunit *test)
+{
+	struct vmbus_gpadl_post_test_context context = {
+		.test = test,
+		.first_msgtype = CHANNELMSG_GPADL_HEADER,
+		.expected_gpadl = 17,
+	};
+	struct vmbus_channel_msginfo *msginfo;
+	bool posted = false;
+	int ret;
+
+	msginfo = vmbus_gpadl_test_msginfo(test, 2);
+	KUNIT_ASSERT_NOT_NULL(test, msginfo);
+
+	ret = vmbus_post_gpadl_messages(msginfo, 17, &posted,
+					vmbus_gpadl_test_post, &context);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, context.call_count, 3U);
+	KUNIT_EXPECT_TRUE(test, posted);
+}
+
+static void vmbus_gpadl_response_state_test(struct kunit *test)
+{
+	bool posted = true;
+
+	KUNIT_EXPECT_EQ(test, vmbus_gpadl_response_status(0, false, &posted), 0);
+	KUNIT_EXPECT_FALSE(test, posted);
+
+	posted = true;
+	KUNIT_EXPECT_EQ(test,
+			vmbus_gpadl_response_status(1, false, &posted), -EDQUOT);
+	KUNIT_EXPECT_FALSE(test, posted);
+
+	posted = true;
+	KUNIT_EXPECT_EQ(test,
+			vmbus_gpadl_response_status(0, true, &posted), -ENODEV);
+	KUNIT_EXPECT_TRUE(test, posted);
+}
+
+static void vmbus_gpadl_teardown_post_failure_test(struct kunit *test)
+{
+	struct vmbus_gpadl_post_test_context context = {
+		.test = test,
+		.fail_call = 1,
+		.first_msgtype = CHANNELMSG_GPADL_TEARDOWN,
+		.expected_gpadl = 17,
+	};
+	struct vmbus_channel_gpadl_teardown msg = {};
+	int ret;
+
+	ret = vmbus_post_gpadl_teardown(7, &msg, 17,
+					vmbus_gpadl_test_post, &context);
+	KUNIT_EXPECT_EQ(test, ret, -EIO);
+	KUNIT_EXPECT_EQ(test, context.call_count, 1U);
+}
+
+struct vmbus_buffer_page_alloc_test_context {
+	struct kunit *test;
+	unsigned int attempts;
+	unsigned int expected_order;
+	bool fail_order_zero;
+};
+
+static struct page *vmbus_buffer_test_alloc_page(void *context, int nid,
+						 gfp_t gfp,
+						 unsigned int order)
+{
+	struct vmbus_buffer_page_alloc_test_context *test_context = context;
+
+	(void)nid;
+	KUNIT_EXPECT_EQ(test_context->test, order,
+			test_context->expected_order);
+	test_context->attempts++;
+	if (test_context->expected_order)
+		test_context->expected_order--;
+
+	if (order)
+		return NULL;
+	if (test_context->fail_order_zero)
+		return NULL;
+
+	return alloc_pages(gfp, 0);
+}
+
+static void vmbus_buffer_order_zero_allocation_test(struct kunit *test)
+{
+	struct vmbus_buffer_page_alloc_test_context context = {
+		.test = test,
+		.expected_order = MAX_PAGE_ORDER,
+	};
+	struct page *page;
+	unsigned int order = MAX_PAGE_ORDER;
+
+	page = vmbus_alloc_pages_with_fallback(0, GFP_KERNEL, &order,
+					       vmbus_buffer_test_alloc_page, &context);
+	KUNIT_ASSERT_NOT_NULL(test, page);
+	KUNIT_EXPECT_EQ(test, order, 0U);
+	KUNIT_EXPECT_EQ(test, context.expected_order, 0U);
+	KUNIT_EXPECT_EQ(test, context.attempts, (unsigned int)MAX_PAGE_ORDER + 1);
+	__free_pages(page, 0);
+
+	context.attempts = 0;
+	context.expected_order = MAX_PAGE_ORDER;
+	context.fail_order_zero = true;
+	order = MAX_PAGE_ORDER;
+	page = vmbus_alloc_pages_with_fallback(0, GFP_KERNEL, &order,
+					       vmbus_buffer_test_alloc_page, &context);
+	KUNIT_EXPECT_PTR_EQ(test, page, NULL);
+	KUNIT_EXPECT_EQ(test, order, 0U);
+	KUNIT_EXPECT_EQ(test, context.expected_order, 0U);
+	KUNIT_EXPECT_EQ(test, context.attempts, (unsigned int)MAX_PAGE_ORDER + 1);
+}
+
+/*
+ * Requestor metadata must use vmalloc backing because both the array and its
+ * bitmap can require multiple pages. The requestor is guest-private
+ * bookkeeping: the host never sees the slot values, so this mapping has no
+ * Confidential Computing implication and needs no set_memory_decrypted().
+ * Cover a typical 8 KiB array, a requestor whose bitmap exceeds one page,
+ * and a size beyond KMALLOC_MAX_SIZE without memory pressure.
+ */
+static void vmbus_requestor_alloc_free_test(struct kunit *test)
+{
+	struct vmbus_requestor rqstor = {};
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(&rqstor, 4), 0);
+	KUNIT_EXPECT_EQ(test, rqstor.size, 4U);
+	KUNIT_EXPECT_EQ(test, rqstor.next_request_id, 0U);
+	KUNIT_EXPECT_NOT_NULL(test, rqstor.req_arr);
+	KUNIT_EXPECT_NOT_NULL(test, rqstor.req_bitmap);
+
+	/* The free list links 0->1->2->3 and terminates in U64_MAX. */
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[0], 1U);
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[1], 2U);
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[2], 3U);
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[3], U64_MAX);
+
+	vmbus_free_requestor(&rqstor);
+}
+
+static void vmbus_requestor_vmalloc_backing_test(struct kunit *test)
+{
+	/*
+	 * Cover the small array, a requestor whose bitmap exceeds one page,
+	 * and a size beyond KMALLOC_MAX_SIZE. All requestor metadata must use
+	 * vmalloc backing regardless of size or allocator pressure.
+	 */
+	u32 small_size = 1024;
+	u32 bitmap_size = (PAGE_SIZE / sizeof(unsigned long)) * BITS_PER_LONG + 1;
+	u32 size = (KMALLOC_MAX_SIZE / sizeof(u64)) + 1;
+	struct vmbus_requestor rqstor = {};
+	u64 *req_arr;
+
+	KUNIT_EXPECT_PTR_EQ(test, request_arr_init(0), NULL);
+
+	req_arr = request_arr_init(small_size);
+	KUNIT_ASSERT_NOT_NULL(test, req_arr);
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(req_arr));
+	KUNIT_EXPECT_EQ(test, req_arr[0], 1U);
+	KUNIT_EXPECT_EQ(test, req_arr[small_size - 1], U64_MAX);
+	vfree(req_arr);
+
+	req_arr = request_arr_init(size);
+	KUNIT_ASSERT_NOT_NULL(test, req_arr);
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(req_arr));
+	KUNIT_EXPECT_EQ(test, req_arr[0], 1U);
+	KUNIT_EXPECT_EQ(test, req_arr[size - 1], U64_MAX);
+	vfree(req_arr);
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(&rqstor, bitmap_size), 0);
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(rqstor.req_arr));
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(rqstor.req_bitmap));
+	vmbus_free_requestor(&rqstor);
+}
+
+static void vmbus_requestor_id_lifecycle_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rqstor_size = 4 };
+	struct vmbus_requestor *rqstor = &channel.requestor;
+	u64 id0, id1, id2, id3, addr;
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 4), 0);
+
+	/* IDs are 1-based; 0 is reserved for unsolicited host messages. */
+	id0 = vmbus_next_request_id(&channel, 0x1000);
+	KUNIT_EXPECT_EQ(test, id0, 1U);
+	id1 = vmbus_next_request_id(&channel, 0x2000);
+	KUNIT_EXPECT_EQ(test, id1, 2U);
+
+	/* Consumption returns the registered address and frees the slot. */
+	addr = vmbus_request_addr_match(&channel, id0, VMBUS_RQST_ADDR_ANY);
+	KUNIT_EXPECT_EQ(test, addr, 0x1000U);
+	addr = vmbus_request_addr_match(&channel, id1, 0x2000);
+	KUNIT_EXPECT_EQ(test, addr, 0x2000U);
+
+	/*
+	 * Consumed slots are reusable. The free list is LIFO -- each
+	 * consume pushes its slot onto the head -- so the slot freed last
+	 * is the one handed out first. Freeing id0 then id1 leaves slot 1
+	 * at the head, and the next ID is therefore id1 again, not id0.
+	 */
+	id2 = vmbus_next_request_id(&channel, 0x3000);
+	KUNIT_EXPECT_EQ(test, id2, id1);
+	id3 = vmbus_next_request_id(&channel, 0x4000);
+	KUNIT_EXPECT_EQ(test, id3, id0);
+
+	vmbus_free_requestor(rqstor);
+}
+
+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),
+			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);
+
+	/* A wrong expected address does not consume the slot. */
+	addr = vmbus_request_addr_match(&channel, id, 0x9999);
+	KUNIT_EXPECT_EQ(test, addr, 0xABCDU);
+
+	/* The slot is still live and a matching lookup consumes it once. */
+	addr = vmbus_request_addr_match(&channel, id, 0xABCD);
+	KUNIT_EXPECT_EQ(test, addr, 0xABCDU);
+
+	/* Replay: the slot is gone. */
+	addr = vmbus_request_addr_match(&channel, id, VMBUS_RQST_ADDR_ANY);
+	KUNIT_EXPECT_EQ(test, addr, VMBUS_RQST_ERROR);
+
+	vmbus_free_requestor(rqstor);
+}
+
+static void vmbus_requestor_exhaustion_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rqstor_size = 2 };
+	struct vmbus_requestor *rqstor = &channel.requestor;
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 2), 0);
+
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x1), 1U);
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x2), 2U);
+
+	/* Both slots taken: the free list is empty and the API says so. */
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x3),
+			VMBUS_RQST_ERROR);
+
+	/* An uninitialized requestor is not a full one. */
+	channel.rqstor_size = 0;
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x4),
+			VMBUS_NO_RQSTOR);
+
+	vmbus_free_requestor(rqstor);
+}
+
+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_owner_reclaim_gate_test),
+	KUNIT_CASE(vmbus_buffer_reclaim_schedule_gate_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_before_claim_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_during_reclaim_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_pending_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_unsafe_pending_test),
+	KUNIT_CASE(vmbus_buffer_rescind_retains_gpadl_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_ack_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_timeout_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_wrong_handle_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_wrong_type_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_post_failure_test),
+	KUNIT_CASE(vmbus_local_rescind_skips_teardown_test),
+	KUNIT_CASE(vmbus_invalid_relid_skips_teardown_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_late_ack_test),
+	KUNIT_CASE(vmbus_buffer_mapping_reference_test),
+	KUNIT_CASE(vmbus_buffer_partial_allocation_cleanup_test),
+	KUNIT_CASE(vmbus_buffer_repeated_owner_release_test),
+	KUNIT_CASE(vmbus_buffer_order_zero_allocation_test),
+	KUNIT_CASE(vmbus_gpadl_post_failure_test),
+	KUNIT_CASE(vmbus_gpadl_post_success_test),
+	KUNIT_CASE(vmbus_gpadl_response_state_test),
+	KUNIT_CASE(vmbus_gpadl_teardown_post_failure_test),
+	KUNIT_CASE(vmbus_requestor_alloc_free_test),
+	KUNIT_CASE(vmbus_requestor_vmalloc_backing_test),
+	KUNIT_CASE(vmbus_requestor_id_lifecycle_test),
+	KUNIT_CASE(vmbus_requestor_invalid_ids_test),
+	KUNIT_CASE(vmbus_requestor_exhaustion_test),
+	{}
+};
+
+static struct kunit_suite vmbus_buffer_test_suite = {
+	.name = "hyperv-vmbus-buffer",
+	.test_cases = vmbus_buffer_test_cases,
+};
+
+kunit_test_suite(vmbus_buffer_test_suite);
diff --git a/drivers/hv/vmbus_drv.c b/drivers/hv/vmbus_drv.c
index 5ebdbe24b5a1e..198b43d240510 100644
--- a/drivers/hv/vmbus_drv.c
+++ b/drivers/hv/vmbus_drv.c
@@ -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);
 }
@@ -1926,6 +1929,7 @@ static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,
 {
 	struct vmbus_channel *channel = container_of(kobj, struct vmbus_channel, kobj);
 	struct vm_area_desc desc;
+	struct vmbus_buffer_pin *pin;
 	int err;
 
 	/*
@@ -1937,9 +1941,55 @@ static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,
 	if (err)
 		return err;
 
-	return __compat_vma_mmap(&desc, vma);
+	/*
+	 * This is a kernfs bin attribute. kernfs_fop_mmap() rejects a VMA
+	 * whose vm_ops carry .close, because kernfs has to replace the set
+	 * with its own and cannot wrap close. So the prepare callback has
+	 * to pick one of two ownership contracts, and this wrapper honors
+	 * whichever it installed. Each contract has exactly one release
+	 * site, reached on every outcome.
+	 *
+	 * With vm_ops, the callback handed the per-VMA state to an abandon
+	 * path in vm_ops->close and typically to vm_ops->mapped. Install
+	 * both 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. Note
+	 * that such a set is rejected by kernfs after this returns, so a
+	 * prepare callback that wants a successful mapping must not choose
+	 * this contract.
+	 *
+	 * Without vm_ops, desc.private_data is a plain struct
+	 * vmbus_buffer_pin and this wrapper is its only owner. Release it
+	 * when __compat_vma_mmap() returns: on success insert_pages() has
+	 * already taken a folio reference for every page the VMA maps, and
+	 * on failure the attempt is over. Clear vma->vm_private_data first
+	 * so the freed pin is never reachable from the VMA that outlives
+	 * this call.
+	 */
+	if (desc.vm_ops) {
+		vma->vm_ops = desc.vm_ops;
+		vma->vm_private_data = desc.private_data;
+
+		err = __compat_vma_mmap(&desc, vma);
+		if (err && vma->vm_ops && vma->vm_ops->close)
+			vma->vm_ops->close(vma);
+		return err;
+	}
+
+	pin = desc.private_data;
+	err = __compat_vma_mmap(&desc, vma);
+	vma->vm_private_data = NULL;
+	vmbus_buffer_unpin_pages(pin);
+	kfree(pin);
+	return err;
 }
 
+#if IS_ENABLED(CONFIG_HYPERV_VMBUS_KUNIT_TEST)
+#include "vmbus_mmap_test.c"
+#endif
+
 static struct bin_attribute chan_attr_ring_buffer = {
 	.attr = {
 		.name = "ring",
@@ -3072,6 +3122,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();
diff --git a/drivers/hv/vmbus_mmap_test.c b/drivers/hv/vmbus_mmap_test.c
new file mode 100644
index 0000000000000..50b961f2b782d
--- /dev/null
+++ b/drivers/hv/vmbus_mmap_test.c
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Included beside the production sysfs wrapper; no VMBus device is touched. */
+#include <kunit/test.h>
+#include <linux/mman.h>
+#include <linux/uaccess.h>
+
+struct vmbus_mmap_test_context {
+	struct vmbus_channel channel;
+	struct page *pages[3];
+	struct page *blocker;
+};
+
+static void vmbus_mmap_test_put_page(void *page)
+{
+	__free_page(page);
+}
+
+static struct page *vmbus_mmap_test_page(struct kunit *test, u8 value)
+{
+	struct page *page = alloc_page(GFP_KERNEL);
+
+	if (!page)
+		return NULL;
+	if (kunit_add_action_or_reset(test, vmbus_mmap_test_put_page, page))
+		return NULL;
+	memset(page_address(page), value, PAGE_SIZE);
+	return page;
+}
+
+static int vmbus_mmap_test_prepare(struct vmbus_channel *channel,
+				   struct vm_area_desc *desc)
+{
+	struct vmbus_buffer_pin *pin;
+	int ret;
+
+	pin = kzalloc_obj(*pin);
+	if (!pin)
+		return -ENOMEM;
+	ret = vmbus_buffer_pin_pages(&channel->ringbuffer, pin);
+	if (ret) {
+		kfree(pin);
+		return ret;
+	}
+	mmap_action_map_kernel_pages(desc, desc->start, pin->pages,
+				     pin->page_count);
+	desc->vm_ops = NULL;
+	desc->private_data = pin;
+	return 0;
+}
+
+static struct vmbus_mmap_test_context *
+vmbus_mmap_test_context(struct kunit *test)
+{
+	struct vmbus_mmap_test_context *ctx;
+	unsigned int i;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return NULL;
+	for (i = 0; i < ARRAY_SIZE(ctx->pages); i++) {
+		ctx->pages[i] = vmbus_mmap_test_page(test, 0x61 + i);
+		if (!ctx->pages[i])
+			return NULL;
+	}
+	ctx->blocker = vmbus_mmap_test_page(test, 0xcc);
+	if (!ctx->blocker)
+		return NULL;
+	ctx->channel.mmap_prepare_ring_buffer = vmbus_mmap_test_prepare;
+	ctx->channel.ringbuffer.pages = ctx->pages;
+	ctx->channel.ringbuffer.page_cnt = ARRAY_SIZE(ctx->pages);
+	return ctx;
+}
+
+static void vmbus_mmap_test_action(struct kunit *test, bool partial)
+{
+	struct vmbus_mmap_test_context *ctx = vmbus_mmap_test_context(test);
+	struct vm_area_struct *vma;
+	unsigned long start;
+	unsigned int i;
+	u8 value = 0;
+	int ret;
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	start = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE,
+			      MAP_SHARED | MAP_ANONYMOUS, 0);
+	KUNIT_ASSERT_NE(test, start, 0UL);
+	KUNIT_ASSERT_LT(test, start, (unsigned long)TASK_SIZE);
+
+	mmap_write_lock(current->mm);
+	vma = find_vma(current->mm, start);
+	if (!vma) {
+		mmap_write_unlock(current->mm);
+		KUNIT_FAIL(test, "managed VMA missing");
+		return;
+	}
+	if (partial) {
+		ret = vm_insert_page(vma, start + PAGE_SIZE, ctx->blocker);
+		if (ret) {
+			mmap_write_unlock(current->mm);
+			KUNIT_FAIL(test, "owned blocking PTE could not be installed");
+			return;
+		}
+	}
+	ret = hv_mmap_ring_buffer_wrapper(vma->vm_file, &ctx->channel.kobj,
+					  NULL, vma);
+	KUNIT_EXPECT_EQ(test, ret, partial ? -EBUSY : 0);
+	KUNIT_EXPECT_NULL(test, vma->vm_private_data);
+	KUNIT_EXPECT_NULL(test, vma->vm_ops);
+	for (i = 0; i < ARRAY_SIZE(ctx->pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(ctx->pages[i]),
+				partial && i ? 1 : 2);
+	KUNIT_EXPECT_EQ(test, page_ref_count(ctx->blocker), partial ? 2 : 1);
+	mmap_write_unlock(current->mm);
+
+	/* The first insertion really happened, including on the partial error. */
+	KUNIT_EXPECT_EQ(test, copy_from_user(&value, (void __user *)start, 1), 0UL);
+	KUNIT_EXPECT_EQ(test, value, (u8)0x61);
+	KUNIT_ASSERT_EQ(test, vm_munmap(start, 3 * PAGE_SIZE), 0);
+	for (i = 0; i < ARRAY_SIZE(ctx->pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(ctx->pages[i]), 1);
+	KUNIT_EXPECT_EQ(test, page_ref_count(ctx->blocker), 1);
+}
+
+static void vmbus_sysfs_mmap_success_test(struct kunit *test)
+{
+	vmbus_mmap_test_action(test, false);
+}
+
+static void vmbus_sysfs_mmap_partial_insert_test(struct kunit *test)
+{
+	vmbus_mmap_test_action(test, true);
+}
+
+static struct kunit_case vmbus_mmap_test_cases[] = {
+	KUNIT_CASE(vmbus_sysfs_mmap_success_test),
+	KUNIT_CASE(vmbus_sysfs_mmap_partial_insert_test),
+	{}
+};
+
+static struct kunit_suite vmbus_mmap_test_suite = {
+	.name = "hyperv-vmbus-mmap",
+	.test_cases = vmbus_mmap_test_cases,
+};
+
+kunit_test_suite(vmbus_mmap_test_suite);
diff --git a/drivers/net/hyperv/Kconfig b/drivers/net/hyperv/Kconfig
index 982964c1a9fb9..226728fd77d71 100644
--- a/drivers/net/hyperv/Kconfig
+++ b/drivers/net/hyperv/Kconfig
@@ -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.
diff --git a/drivers/net/hyperv/Makefile b/drivers/net/hyperv/Makefile
index 0db7ccaec4a4c..b2d22855fd8a0 100644
--- a/drivers/net/hyperv/Makefile
+++ b/drivers/net/hyperv/Makefile
@@ -2,3 +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
diff --git a/drivers/net/hyperv/hyperv_net.h b/drivers/net/hyperv/hyperv_net.h
index 4841367fdab2f..be3a63a168cfa 100644
--- a/drivers/net/hyperv/hyperv_net.h
+++ b/drivers/net/hyperv/hyperv_net.h
@@ -210,14 +210,40 @@ struct rndis_device {
 	u8 rss_key[NETVSC_HASH_KEYLEN];
 };
 
+#define RNDIS_EXT_LEN HV_HYP_PAGE_SIZE
 
-/* Interface */
+/* Full definitions are below, after the RNDIS message format. */
+struct rndis_request;
 struct rndis_message;
+
+/* Interface */
 struct ndis_offload_params;
 struct netvsc_device;
 struct netvsc_channel;
 struct net_device_context;
 
+struct rndis_request *get_rndis_request(struct rndis_device *dev,
+					u32 msg_type, u32 msg_len);
+void put_rndis_request(struct rndis_device *dev, struct rndis_request *req);
+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);
@@ -1158,21 +1184,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;
@@ -1785,6 +1805,36 @@ struct rndis_message {
 	union rndis_message_container msg;
 };
 
+/*
+ * RNDIS request descriptor. Declared here so the KUnit cases can reach
+ * the layout the response-copy bound in rndis_filter_receive_resp()
+ * relies on. The two RNDIS_EXT_LEN tails are what make the object
+ * larger than KMALLOC_MAX_CACHE_SIZE.
+ */
+struct rndis_request {
+	struct list_head list_ent;
+	struct completion  wait_event;
+
+	struct rndis_message response_msg;
+	/*
+	 * The buffer for extended info after the RNDIS response message. It's
+	 * referenced based on the data offset in the RNDIS message. Its size
+	 * is enough for current needs, and should be sufficient for the near
+	 * future.
+	 */
+	u8 response_ext[RNDIS_EXT_LEN];
+
+	/* Simplify allocation by having a netvsc packet inline */
+	struct hv_netvsc_packet	pkt;
+
+	struct rndis_message request_msg;
+	/*
+	 * The buffer for the extended info after the RNDIS request message.
+	 * It is referenced and sized in a similar way as response_ext.
+	 */
+	u8 request_ext[RNDIS_EXT_LEN];
+};
+
 
 /* Handy macros */
 
diff --git a/drivers/net/hyperv/netvsc.c b/drivers/net/hyperv/netvsc.c
index 5cd084e5696cd..8ea7c993baac0 100644
--- a/drivers/net/hyperv/netvsc.c
+++ b/drivers/net/hyperv/netvsc.c
@@ -134,10 +134,8 @@ static void __free_netvsc_device(struct netvsc_device *nvdev)
 
 	kfree(nvdev->extension);
 
-	vmbus_free_buffer(nvdev->recv_buf, nvdev->recv_buf_chunks,
-			  nvdev->recv_buf_chunk_cnt);
-	vmbus_free_buffer(nvdev->send_buf, nvdev->send_buf_chunks,
-			  nvdev->send_buf_chunk_cnt);
+	vmbus_release_buffer(&nvdev->recv_buffer);
+	vmbus_release_buffer(&nvdev->send_buffer);
 	bitmap_free(nvdev->send_section_map);
 
 	for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
@@ -146,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)
@@ -173,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;
 
@@ -308,9 +306,9 @@ static void netvsc_teardown_recv_gpadl(struct hv_device *device,
 {
 	int ret;
 
-	if (net_device->recv_buf_gpadl_handle.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(device->channel,
-					   &net_device->recv_buf_gpadl_handle);
+	if (net_device->recv_buffer.gpadl.gpadl_handle) {
+		ret = vmbus_teardown_gpadl_owned(device->channel,
+						 &net_device->recv_buffer);
 
 		/* If we failed here, we might as well return and have a leak
 		 * rather than continue and a bugchk
@@ -329,9 +327,9 @@ static void netvsc_teardown_send_gpadl(struct hv_device *device,
 {
 	int ret;
 
-	if (net_device->send_buf_gpadl_handle.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(device->channel,
-					   &net_device->send_buf_gpadl_handle);
+	if (net_device->send_buffer.gpadl.gpadl_handle) {
+		ret = vmbus_teardown_gpadl_owned(device->channel,
+						 &net_device->send_buffer);
 
 		/* If we failed here, we might as well return and have a leak
 		 * rather than continue and a bugchk
@@ -377,15 +375,13 @@ static int netvsc_init_buf(struct hv_device *device,
 		buf_size = min_t(unsigned int, buf_size,
 				 NETVSC_RECEIVE_BUFFER_SIZE_LEGACY);
 
-	net_device->recv_buf =
-		vmbus_alloc_buffer(device->channel, buf_size,
-				   &net_device->recv_buf_chunks,
-				   &net_device->recv_buf_chunk_cnt);
-	if (!net_device->recv_buf) {
+	ret = vmbus_alloc_buffer_owned(device->channel, buf_size,
+				       device->channel->co_external_memory,
+				       &net_device->recv_buffer);
+	if (ret) {
 		netdev_err(ndev,
 			   "unable to allocate receive buffer of size %u\n",
 			   buf_size);
-		ret = -ENOMEM;
 		goto cleanup;
 	}
 
@@ -396,10 +392,8 @@ static int netvsc_init_buf(struct hv_device *device,
 	 * channel.  Note: This call uses the vmbus connection rather
 	 * than the channel to establish the gpadl handle.
 	 */
-	ret = vmbus_establish_gpadl_caller_decrypted(device->channel,
-						     net_device->recv_buf,
-						     buf_size,
-						     &net_device->recv_buf_gpadl_handle);
+	ret = vmbus_establish_gpadl_owned(device->channel,
+					  &net_device->recv_buffer);
 	if (ret != 0) {
 		netdev_err(ndev,
 			"unable to establish receive buffer's gpadl\n");
@@ -411,7 +405,7 @@ static int netvsc_init_buf(struct hv_device *device,
 	memset(init_packet, 0, sizeof(struct nvsp_message));
 	init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_RECV_BUF;
 	init_packet->msg.v1_msg.send_recv_buf.
-		gpadl_handle = net_device->recv_buf_gpadl_handle.gpadl_handle;
+		gpadl_handle = net_device->recv_buffer.gpadl.gpadl_handle;
 	init_packet->msg.v1_msg.
 		send_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
 
@@ -487,14 +481,12 @@ static int netvsc_init_buf(struct hv_device *device,
 	buf_size = device_info->send_sections * device_info->send_section_size;
 	buf_size = round_up(buf_size, PAGE_SIZE);
 
-	net_device->send_buf =
-		vmbus_alloc_buffer(device->channel, buf_size,
-				   &net_device->send_buf_chunks,
-				   &net_device->send_buf_chunk_cnt);
-	if (!net_device->send_buf) {
+	ret = vmbus_alloc_buffer_owned(device->channel, buf_size,
+				       device->channel->co_external_memory,
+				       &net_device->send_buffer);
+	if (ret) {
 		netdev_err(ndev, "unable to allocate send buffer of size %u\n",
 			   buf_size);
-		ret = -ENOMEM;
 		goto cleanup;
 	}
 	net_device->send_buf_size = buf_size;
@@ -503,10 +495,8 @@ static int netvsc_init_buf(struct hv_device *device,
 	 * channel.  Note: This call uses the vmbus connection rather
 	 * than the channel to establish the gpadl handle.
 	 */
-	ret = vmbus_establish_gpadl_caller_decrypted(device->channel,
-						     net_device->send_buf,
-						     buf_size,
-						     &net_device->send_buf_gpadl_handle);
+	ret = vmbus_establish_gpadl_owned(device->channel,
+					  &net_device->send_buffer);
 	if (ret != 0) {
 		netdev_err(ndev,
 			   "unable to establish send buffer's gpadl\n");
@@ -518,7 +508,7 @@ static int netvsc_init_buf(struct hv_device *device,
 	memset(init_packet, 0, sizeof(struct nvsp_message));
 	init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_SEND_BUF;
 	init_packet->msg.v1_msg.send_send_buf.gpadl_handle =
-		net_device->send_buf_gpadl_handle.gpadl_handle;
+		net_device->send_buffer.gpadl.gpadl_handle;
 	init_packet->msg.v1_msg.send_send_buf.id = NETVSC_SEND_BUFFER_ID;
 
 	trace_nvsp_send(ndev, init_packet);
@@ -774,20 +764,45 @@ static inline void netvsc_free_send_slot(struct netvsc_device *net_device,
 	sync_change_bit(index, net_device->send_section_map);
 }
 
-static 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_acct(struct net_device *ndev,
+		      struct netvsc_device *net_device,
+		      struct vmbus_channel *channel,
+		      u16 q_idx)
+{
+	struct net_device_context *ndev_ctx = netdev_priv(ndev);
+	int queue_sends;
+
+	queue_sends =
+		atomic_dec_return(&net_device->chan_table[q_idx].queue_sends);
+
+	if (unlikely(net_device->destroy)) {
+		if (queue_sends == 0)
+			wake_up(&net_device->wait_drain);
+	} else {
+		struct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);
+
+		if (netif_tx_queue_stopped(txq) && !net_device->tx_disable &&
+		    (hv_get_avail_to_write_percent(&channel->outbound) >
+		     RING_AVAIL_PERCENT_HIWATER || queue_sends < 1)) {
+			netif_tx_wake_queue(txq);
+			ndev_ctx->eth_stats.wake_queue++;
+		}
+	}
+}
+
+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)
 {
 	struct net_device_context *ndev_ctx = netdev_priv(ndev);
 	struct sk_buff *skb;
 	u16 q_idx = 0;
-	int queue_sends;
 	u64 cmd_rqst;
 
 	cmd_rqst = channel->request_addr_callback(channel, desc->trans_id);
-	if (cmd_rqst == VMBUS_RQST_ERROR) {
+	if (cmd_rqst == VMBUS_RQST_ERROR || cmd_rqst == VMBUS_NO_RQSTOR) {
 		netdev_err(ndev, "Invalid transaction ID %llx\n", desc->trans_id);
 		return;
 	}
@@ -816,29 +831,14 @@ static void netvsc_send_tx_complete(struct net_device *ndev,
 		napi_consume_skb(skb, budget);
 	}
 
-	queue_sends =
-		atomic_dec_return(&net_device->chan_table[q_idx].queue_sends);
-
-	if (unlikely(net_device->destroy)) {
-		if (queue_sends == 0)
-			wake_up(&net_device->wait_drain);
-	} else {
-		struct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);
-
-		if (netif_tx_queue_stopped(txq) && !net_device->tx_disable &&
-		    (hv_get_avail_to_write_percent(&channel->outbound) >
-		     RING_AVAIL_PERCENT_HIWATER || queue_sends < 1)) {
-			netif_tx_wake_queue(txq);
-			ndev_ctx->eth_stats.wake_queue++;
-		}
-	}
+	netvsc_send_acct(ndev, net_device, channel, q_idx);
 }
 
-static 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)
+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)
 {
 	const struct nvsp_message *nvsp_packet;
 	u32 msglen = hv_pkt_datalen(desc);
@@ -850,11 +850,24 @@ static void netvsc_send_completion(struct net_device *ndev,
 	if (!msglen) {
 		cmd_rqst = incoming_channel->request_addr_callback(incoming_channel,
 								   desc->trans_id);
-		if (cmd_rqst == VMBUS_RQST_ERROR) {
+		if (cmd_rqst == VMBUS_RQST_ERROR || cmd_rqst == VMBUS_NO_RQSTOR) {
 			netdev_err(ndev, "Invalid transaction ID %llx\n", desc->trans_id);
 			return;
 		}
 
+		/*
+		 * netvsc_send_pkt() registers (ulong)skb as the request
+		 * address. Control RNDIS sends carry no skb, so the
+		 * registered address is NULL and there is no nvsp_message
+		 * to inspect. The request id is consumed above, so this
+		 * completion owns the send accounting -- the same thing
+		 * netvsc_send_tx_complete() does when it sees a NULL skb.
+		 */
+		if (!cmd_rqst) {
+			netvsc_send_acct(ndev, net_device, incoming_channel, 0);
+			return;
+		}
+
 		pkt_rqst = (struct nvsp_message *)(uintptr_t)cmd_rqst;
 		switch (pkt_rqst->hdr.msg_type) {
 		case NVSP_MSG4_TYPE_SWITCH_DATA_PATH:
@@ -968,7 +981,7 @@ static void netvsc_copy_to_send_buf(struct netvsc_device *net_device,
 				    struct hv_page_buffer *pb,
 				    bool xmit_more)
 {
-	char *start = net_device->send_buf;
+	char *start = net_device->send_buffer.addr;
 	char *dest = start + (section_index * net_device->send_section_size)
 		     + pend_size;
 	int i;
@@ -1475,7 +1488,7 @@ static int netvsc_receive(struct net_device *ndev,
 	const struct nvsp_message *nvsp = hv_pkt_data(desc);
 	u32 msglen = hv_pkt_datalen(desc);
 	u16 q_idx = channel->offermsg.offer.sub_channel_index;
-	char *recv_buf = net_device->recv_buf;
+	char *recv_buf = net_device->recv_buffer.addr;
 	u32 status = NVSP_STAT_SUCCESS;
 	int i;
 	int count = 0;
diff --git a/drivers/net/hyperv/netvsc_completion_test.c b/drivers/net/hyperv/netvsc_completion_test.c
new file mode 100644
index 0000000000000..2614b1ece2327
--- /dev/null
+++ b/drivers/net/hyperv/netvsc_completion_test.c
@@ -0,0 +1,439 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for empty and skb-backed netvsc completion handling.
+ *
+ * Built into the hv_netvsc object rather than a separate module so the
+ * cases can reach the internal helpers declared in hyperv_net.h
+ * without exporting them.
+ */
+#include <kunit/test.h>
+#include <linux/etherdevice.h>
+#include <linux/hyperv.h>
+#include <linux/netdevice.h>
+#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/wait.h>
+
+#include "hyperv_net.h"
+
+/*
+ * Scripted requestor. request_addr_callback() only receives the channel
+ * and the transaction id, so the fixture is hung off a file-scope
+ * pointer. KUnit runs suite cases serially; one active fixture is
+ * enough and keeps the callback signature untouched.
+ */
+struct netvsc_completion_fixture {
+	struct net_device *ndev;
+	struct netvsc_device *nvdev;
+	struct vmbus_channel *channel;
+	/* Address returned on first use, then VMBUS_NO_RQSTOR: the id is
+	 * consumed exactly once, as vmbus_request_addr_match() does.
+	 */
+	u64 once_addr;
+	unsigned int calls;
+	u64 seen_ids[8];
+	unsigned int skb_frees;
+};
+
+static struct netvsc_completion_fixture *active_fx;
+
+static u64 test_request_addr(struct vmbus_channel *channel, u64 rqst_id)
+{
+	struct netvsc_completion_fixture *fx = active_fx;
+
+	if (fx->calls < ARRAY_SIZE(fx->seen_ids))
+		fx->seen_ids[fx->calls] = rqst_id;
+	fx->calls++;
+
+	if (fx->calls == 1)
+		return fx->once_addr;
+	return VMBUS_NO_RQSTOR;
+}
+
+/*
+ * A completion carrying no payload: hv_pkt_datalen() == 0. The
+ * empty-completion path looks the request up by trans_id and reads its
+ * message type, so the request itself is a separate object the fixture
+ * hands back through request_addr_callback().
+ */
+struct netvsc_empty_desc {
+	struct vmpacket_descriptor desc;
+} __packed;
+
+static void make_empty_desc(struct netvsc_empty_desc *pkt, u64 trans_id)
+{
+	memset(pkt, 0, sizeof(*pkt));
+	pkt->desc.offset8 = sizeof(pkt->desc) / 8;
+	pkt->desc.len8 = pkt->desc.offset8;
+	pkt->desc.trans_id = trans_id;
+}
+
+/*
+ * The production path never dereferences a net_device queue while
+ * tx_disable is set: netif_tx_queue_stopped() && !tx_disable
+ * short-circuits before hv_get_avail_to_write_percent() reads the
+ * ring. Set it here so a test needs no live outbound ring.
+ */
+static int netvsc_completion_fixture_init(struct netvsc_completion_fixture *fx)
+{
+	fx->ndev = alloc_netdev_mqs(sizeof(struct net_device_context),
+				    "hvcompl%d", NET_NAME_UNKNOWN,
+				    ether_setup, 2, 2);
+	if (!fx->ndev)
+		return -ENOMEM;
+
+	fx->nvdev = kzalloc_obj(*fx->nvdev, GFP_KERNEL);
+	if (!fx->nvdev) {
+		free_netdev(fx->ndev);
+		return -ENOMEM;
+	}
+
+	fx->channel = kzalloc_obj(*fx->channel, GFP_KERNEL);
+	if (!fx->channel) {
+		kfree(fx->nvdev);
+		free_netdev(fx->ndev);
+		return -ENOMEM;
+	}
+
+	init_waitqueue_head(&fx->nvdev->wait_drain);
+	init_completion(&fx->nvdev->channel_init_wait);
+	fx->nvdev->tx_disable = true;
+	fx->channel->request_addr_callback = test_request_addr;
+	fx->once_addr = 0;
+	fx->calls = 0;
+	memset(fx->seen_ids, 0, sizeof(fx->seen_ids));
+	active_fx = fx;
+	return 0;
+}
+
+static void netvsc_completion_fixture_exit(struct netvsc_completion_fixture *fx)
+{
+	active_fx = NULL;
+	kfree(fx->channel);
+	kfree(fx->nvdev);
+	free_netdev(fx->ndev);
+}
+
+static int netvsc_send_sends(struct netvsc_completion_fixture *fx, u16 q_idx)
+{
+	return atomic_read(&fx->nvdev->chan_table[q_idx].queue_sends);
+}
+
+/* Empty completion, request address NULL: owns the send accounting. */
+static void netvsc_completion_null_address_acct_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x11);
+	/* once_addr = 0 is the control-path NULL skb case. */
+	fx.once_addr = 0;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+	KUNIT_EXPECT_EQ(test, fx.calls, 1U);
+	KUNIT_EXPECT_EQ(test, fx.seen_ids[0], 0x11U);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* VMBUS_RQST_ERROR is rejected: no accounting, no completion. */
+static void netvsc_completion_rqst_error_sentinel_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x22);
+	fx.once_addr = VMBUS_RQST_ERROR;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* VMBUS_NO_RQSTOR is rejected the same way. */
+static void netvsc_completion_no_rqstor_sentinel_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x33);
+	fx.once_addr = VMBUS_NO_RQSTOR;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/*
+ * A real request address whose message type is SWITCH_DATA_PATH
+ * completes the channel-init wait. It is not send accounting: the
+ * control request was not a send.
+ */
+static void netvsc_completion_switch_data_path_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+	struct nvsp_message req = {};
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x44);
+	req.hdr.msg_type = NVSP_MSG4_TYPE_SWITCH_DATA_PATH;
+	fx.once_addr = (u64)(unsigned long)&req;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_TRUE(test, completion_done(&fx.nvdev->channel_init_wait));
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* An unexpected message type takes neither the complete nor the acct path. */
+static void netvsc_completion_unknown_msg_type_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+	struct nvsp_message req = {};
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x55);
+	req.hdr.msg_type = 0xdead;
+	fx.once_addr = (u64)(unsigned long)&req;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/*
+ * A repeated completion for an already-consumed transaction id must not
+ * account twice. The requestor returns VMBUS_NO_RQSTOR on the second
+ * use and the empty-completion path rejects it.
+ */
+static void netvsc_completion_duplicate_completion_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x66);
+	fx.once_addr = 0;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+	KUNIT_EXPECT_EQ(test, fx.calls, 1U);
+
+	/* Second completion for the same id: already consumed. */
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+	KUNIT_EXPECT_EQ(test, fx.calls, 2U);
+	KUNIT_EXPECT_EQ(test, fx.seen_ids[0], 0x66U);
+	KUNIT_EXPECT_EQ(test, fx.seen_ids[1], 0x66U);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* N completions decrement the queue exactly N times. */
+static void netvsc_completion_single_decrement_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+	int i;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 5);
+
+	for (i = 0; i < 5; i++) {
+		make_empty_desc(&pkt, 0x100 + i);
+		fx.once_addr = 0;
+		fx.calls = 0;
+		netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel,
+				       &pkt.desc, 0);
+		KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 4 - i);
+		KUNIT_EXPECT_EQ(test, fx.calls, 1U);
+	}
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 0);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+static int netvsc_test_wake(struct wait_queue_entry *wq_entry,
+			    unsigned int mode, int flags, void *key)
+{
+	unsigned int *woken = wq_entry->private;
+
+	(*woken)++;
+	return 0;
+}
+
+/* destroy + a decrement that reaches zero wakes the drain wait. */
+static void netvsc_send_acct_drain_wake_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct wait_queue_entry entry;
+	unsigned int woken = 0;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	fx.nvdev->destroy = true;
+
+	memset(&entry, 0, sizeof(entry));
+	entry.func = netvsc_test_wake;
+	entry.private = &woken;
+	add_wait_queue(&fx.nvdev->wait_drain, &entry);
+
+	/* Non-zero remainder: the drain wait is not woken. */
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 2);
+	netvsc_send_acct(fx.ndev, fx.nvdev, fx.channel, 0);
+	KUNIT_EXPECT_EQ(test, woken, 0U);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 1);
+
+	/* Exactly zero: the drain wait is woken once. */
+	netvsc_send_acct(fx.ndev, fx.nvdev, fx.channel, 0);
+	KUNIT_EXPECT_EQ(test, woken, 1U);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 0);
+
+	remove_wait_queue(&fx.nvdev->wait_drain, &entry);
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/*
+ * netvsc_send_tx_complete() applies the same sentinel rejection and
+ * still accounts a NULL skb.
+ */
+static void netvsc_tx_complete_null_skb_acct_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x77);
+	fx.once_addr = 0;
+
+	netvsc_send_tx_complete(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+
+	/* The sentinel is rejected before any accounting. */
+	make_empty_desc(&pkt, 0x78);
+	fx.once_addr = VMBUS_RQST_ERROR;
+	fx.calls = 0;
+	netvsc_send_tx_complete(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+static void netvsc_test_skb_destructor(struct sk_buff *skb)
+{
+	active_fx->skb_frees++;
+}
+
+static void netvsc_tx_complete_skb(struct kunit *test, u32 status)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct {
+		struct vmpacket_descriptor desc;
+		struct nvsp_message message;
+	} pkt = {};
+	unsigned long send_slots = BIT(3);
+	struct hv_netvsc_packet *packet;
+	struct netvsc_stats_tx *stats;
+	struct sk_buff *skb;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	skb = alloc_skb(64, GFP_KERNEL);
+	if (!skb) {
+		KUNIT_FAIL(test, "skb allocation failed");
+		goto out;
+	}
+	skb->destructor = netvsc_test_skb_destructor;
+	packet = (struct hv_netvsc_packet *)skb->cb;
+	memset(packet, 0, sizeof(*packet));
+	packet->send_buf_index = 3;
+	packet->q_idx = 1;
+	packet->total_packets = 2;
+	packet->total_bytes = 64;
+	fx.nvdev->send_section_map = &send_slots;
+	stats = &fx.nvdev->chan_table[1].tx_stats;
+	u64_stats_init(&stats->syncp);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 7);
+	atomic_set(&fx.nvdev->chan_table[1].queue_sends, 3);
+	fx.once_addr = (u64)(unsigned long)skb;
+	pkt.desc.offset8 = sizeof(pkt.desc) / 8;
+	pkt.desc.len8 = DIV_ROUND_UP(sizeof(pkt), 8);
+	pkt.desc.trans_id = 0x79;
+	pkt.message.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE;
+	pkt.message.msg.v1_msg.send_rndis_pkt_complete.status = status;
+
+	/* Budget zero consumes the real skb synchronously, outside NAPI. */
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, send_slots, 0UL);
+	KUNIT_EXPECT_EQ(test, fx.skb_frees, 1U);
+	KUNIT_EXPECT_EQ(test, stats->packets, 2ULL);
+	KUNIT_EXPECT_EQ(test, stats->bytes, 64ULL);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 7);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 1), 2);
+
+	/* The consumed transaction cannot free or account the skb twice. */
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, send_slots, 0UL);
+	KUNIT_EXPECT_EQ(test, fx.skb_frees, 1U);
+	KUNIT_EXPECT_EQ(test, stats->packets, 2ULL);
+	KUNIT_EXPECT_EQ(test, stats->bytes, 64ULL);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 1), 2);
+out:
+	netvsc_completion_fixture_exit(&fx);
+}
+
+static void netvsc_tx_complete_skb_success_test(struct kunit *test)
+{
+	netvsc_tx_complete_skb(test, NVSP_STAT_SUCCESS);
+}
+
+static void netvsc_tx_complete_skb_error_test(struct kunit *test)
+{
+	netvsc_tx_complete_skb(test, NVSP_STAT_FAIL);
+}
+
+static struct kunit_case netvsc_completion_test_cases[] = {
+	KUNIT_CASE(netvsc_completion_null_address_acct_test),
+	KUNIT_CASE(netvsc_completion_rqst_error_sentinel_test),
+	KUNIT_CASE(netvsc_completion_no_rqstor_sentinel_test),
+	KUNIT_CASE(netvsc_completion_switch_data_path_test),
+	KUNIT_CASE(netvsc_completion_unknown_msg_type_test),
+	KUNIT_CASE(netvsc_completion_duplicate_completion_test),
+	KUNIT_CASE(netvsc_completion_single_decrement_test),
+	KUNIT_CASE(netvsc_send_acct_drain_wake_test),
+	KUNIT_CASE(netvsc_tx_complete_null_skb_acct_test),
+	KUNIT_CASE(netvsc_tx_complete_skb_success_test),
+	KUNIT_CASE(netvsc_tx_complete_skb_error_test),
+	{}
+};
+
+static struct kunit_suite netvsc_completion_test_suite = {
+	.name = "hyperv-netvsc-completion",
+	.test_cases = netvsc_completion_test_cases,
+};
+
+kunit_test_suite(netvsc_completion_test_suite);
diff --git a/drivers/net/hyperv/rndis_filter.c b/drivers/net/hyperv/rndis_filter.c
index 9b6c44979b4ea..1ce40baa2d239 100644
--- a/drivers/net/hyperv/rndis_filter.c
+++ b/drivers/net/hyperv/rndis_filter.c
@@ -16,6 +16,7 @@
 #include <linux/if_ether.h>
 #include <linux/netdevice.h>
 #include <linux/if_vlan.h>
+#include <linux/mm.h>
 #include <linux/nls.h>
 #include <linux/vmalloc.h>
 #include <linux/rtnetlink.h>
@@ -27,31 +28,6 @@
 
 static void rndis_set_multicast(struct work_struct *w);
 
-#define RNDIS_EXT_LEN HV_HYP_PAGE_SIZE
-struct rndis_request {
-	struct list_head list_ent;
-	struct completion  wait_event;
-
-	struct rndis_message response_msg;
-	/*
-	 * The buffer for extended info after the RNDIS response message. It's
-	 * referenced based on the data offset in the RNDIS message. Its size
-	 * is enough for current needs, and should be sufficient for the near
-	 * future.
-	 */
-	u8 response_ext[RNDIS_EXT_LEN];
-
-	/* Simplify allocation by having a netvsc packet inline */
-	struct hv_netvsc_packet	pkt;
-
-	struct rndis_message request_msg;
-	/*
-	 * The buffer for the extended info after the RNDIS request message.
-	 * It is referenced and sized in a similar way as response_ext.
-	 */
-	u8 request_ext[RNDIS_EXT_LEN];
-};
-
 static const u8 netvsc_hash_key[NETVSC_HASH_KEYLEN] = {
 	0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2,
 	0x41, 0x67, 0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0,
@@ -78,16 +54,27 @@ static struct rndis_device *get_rndis_device(void)
 	return device;
 }
 
-static struct rndis_request *get_rndis_request(struct rndis_device *dev,
-					     u32 msg_type,
-					     u32 msg_len)
+struct rndis_request *get_rndis_request(struct rndis_device *dev,
+					u32 msg_type,
+					u32 msg_len)
 {
 	struct rndis_request *request;
 	struct rndis_message *rndis_msg;
 	struct rndis_set_request *set;
 	unsigned long flags;
 
-	request = kzalloc_obj(struct rndis_request);
+	/*
+	 * struct rndis_request embeds two RNDIS_EXT_LEN (4 KiB) protocol
+	 * tails and is larger than KMALLOC_MAX_CACHE_SIZE, so
+	 * kzalloc_obj() needs an order-2 compound page. That high-order
+	 * allocation can fail under buddy fragmentation. kvzalloc_obj()
+	 * keeps the zeroing semantics while allowing vmalloc backing when
+	 * a suitable kmalloc allocation is unavailable. The request payload
+	 * is sent as GPADL-direct page buffers, so rndis_filter_send_request()
+	 * must describe each backing page instead of assuming virt_to_phys()
+	 * yields one contiguous physical range.
+	 */
+	request = kvzalloc_obj(struct rndis_request);
 	if (!request)
 		return NULL;
 
@@ -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;
 
@@ -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);
 }
 
 static void dump_rndis_message(struct net_device *netdev,
@@ -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)
+{
+	const u8 *addr = data;
+	u32 count = 0;
+
+	if (!data || !len || !page_bufs || !page_buf_cnt)
+		return -EINVAL;
+
+	*page_buf_cnt = 0;
+
+	while (len) {
+		struct page *page;
+		phys_addr_t phys;
+		u32 offset, chunk;
+		unsigned long page_offset = offset_in_page(addr);
+
+		if (count == MAX_PAGE_BUFFER_COUNT)
+			return -E2BIG;
+
+		if (is_vmalloc_addr(addr))
+			page = vmalloc_to_page(addr);
+		else if (virt_addr_valid(addr))
+			page = virt_to_page(addr);
+		else
+			return -EFAULT;
+
+		if (!page)
+			return -EFAULT;
+
+		phys = page_to_phys(page) + page_offset;
+		offset = offset_in_hvpage(phys);
+		chunk = min_t(u32, len, PAGE_SIZE - page_offset);
+		chunk = min_t(u32, chunk, HV_HYP_PAGE_SIZE - offset);
+
+		page_bufs[count].pfn = phys >> HV_HYP_PAGE_SHIFT;
+		page_bufs[count].offset = offset;
+		page_bufs[count].len = chunk;
+
+		addr += chunk;
+		len -= chunk;
+		count++;
+	}
+
+	*page_buf_cnt = count;
+	return 0;
+}
+
 static int rndis_filter_send_request(struct rndis_device *dev,
 				  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);
+	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();
 
 	return ret;
diff --git a/drivers/net/hyperv/rndis_request_test.c b/drivers/net/hyperv/rndis_request_test.c
new file mode 100644
index 0000000000000..6affa916e74e3
--- /dev/null
+++ b/drivers/net/hyperv/rndis_request_test.c
@@ -0,0 +1,216 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for RNDIS request descriptor allocation.
+ *
+ * Built into the hv_netvsc object rather than a separate module so the
+ * cases can reach the internal helpers declared in hyperv_net.h
+ * without exporting them.
+ */
+#include <kunit/test.h>
+#include <linux/hyperv.h>
+#include <linux/mm.h>
+#include <linux/slab.h>
+#include <linux/stddef.h>
+#include <linux/vmalloc.h>
+
+#include "hyperv_net.h"
+
+static int rndis_test_device_init(struct rndis_device *dev)
+{
+	memset(dev, 0, sizeof(*dev));
+	atomic_set(&dev->new_req_id, 0);
+	spin_lock_init(&dev->request_lock);
+	INIT_LIST_HEAD(&dev->req_list);
+	return 0;
+}
+
+/*
+ * The premise of the kvzalloc_obj() conversion: the descriptor embeds
+ * two RNDIS_EXT_LEN protocol tails and sits past
+ * KMALLOC_MAX_CACHE_SIZE, so kzalloc_obj() reached kmalloc_large() and
+ * took an order-2 compound page on the subchannel open path. If the
+ * struct ever drops back inside the cache, the conversion stops being
+ * about high-order allocation and this assertion is the reminder.
+ */
+static void rndis_request_size_premise_test(struct kunit *test)
+{
+	KUNIT_EXPECT_GT(test, sizeof(struct rndis_request),
+			(size_t)KMALLOC_MAX_CACHE_SIZE);
+	/*
+	 * The copy bound in rndis_filter_receive_resp() is
+	 * sizeof(struct rndis_message) + RNDIS_EXT_LEN. That is exactly
+	 * the response_msg + response_ext tail of the object. A reorder
+	 * or a resize of either member makes the bound lie.
+	 */
+	KUNIT_EXPECT_EQ(test,
+			offsetofend(struct rndis_request, response_ext),
+			offsetof(struct rndis_request, response_msg) +
+				sizeof(struct rndis_message) + RNDIS_EXT_LEN);
+	KUNIT_EXPECT_EQ(test,
+			offsetofend(struct rndis_request, request_ext),
+			offsetof(struct rndis_request, request_msg) +
+				sizeof(struct rndis_message) + RNDIS_EXT_LEN);
+}
+
+/*
+ * kvzalloc_obj() keeps the zeroing kzalloc_obj() provided. The two
+ * protocol tails are the fields a response is copied into; a stale
+ * tail is a stale response.
+ */
+static void rndis_request_alloc_zeroed_test(struct kunit *test)
+{
+	struct rndis_device dev;
+	struct rndis_request *req;
+
+	KUNIT_ASSERT_EQ(test, rndis_test_device_init(&dev), 0);
+	req = get_rndis_request(&dev, RNDIS_MSG_INIT, 0x20);
+	KUNIT_ASSERT_NOT_NULL(test, req);
+
+	KUNIT_EXPECT_EQ(test, req->response_ext[0], 0);
+	KUNIT_EXPECT_EQ(test, req->response_ext[RNDIS_EXT_LEN - 1], 0);
+	KUNIT_EXPECT_EQ(test, req->request_ext[0], 0);
+	KUNIT_EXPECT_EQ(test, req->request_ext[RNDIS_EXT_LEN - 1], 0);
+	KUNIT_EXPECT_EQ(test, req->response_msg.msg_len, 0U);
+
+	put_rndis_request(&dev, req);
+}
+
+/* Request ids come from a per-device counter and the list tracks the live set. */
+static void rndis_request_id_lifecycle_test(struct kunit *test)
+{
+	struct rndis_device dev;
+	struct rndis_request *req0, *req1;
+	struct rndis_request *cursor;
+	unsigned int n = 0;
+
+	KUNIT_ASSERT_EQ(test, rndis_test_device_init(&dev), 0);
+
+	req0 = get_rndis_request(&dev, RNDIS_MSG_INIT, 0x20);
+	KUNIT_ASSERT_NOT_NULL(test, req0);
+	req1 = get_rndis_request(&dev, RNDIS_MSG_QUERY, 0x20);
+	KUNIT_ASSERT_NOT_NULL(test, req1);
+
+	/*
+	 * get_rndis_request() stamps the id through the set_req template,
+	 * which shares the union slot with every other request body. Read
+	 * it back through the same member the producer used.
+	 */
+	KUNIT_EXPECT_EQ(test,
+			req0->request_msg.msg.set_req.req_id, 1U);
+	KUNIT_EXPECT_EQ(test,
+			req1->request_msg.msg.set_req.req_id, 2U);
+
+	list_for_each_entry(cursor, &dev.req_list, list_ent)
+		n++;
+	KUNIT_EXPECT_EQ(test, n, 2U);
+
+	/*
+	 * put_rndis_request() is the cleanup path every error and
+	 * timeout branch takes. It unlinks before it frees.
+	 */
+	put_rndis_request(&dev, req0);
+	n = 0;
+	list_for_each_entry(cursor, &dev.req_list, list_ent)
+		n++;
+	KUNIT_EXPECT_EQ(test, n, 1U);
+	KUNIT_EXPECT_TRUE(test,
+			  list_first_entry(&dev.req_list, struct rndis_request,
+					   list_ent) == req1);
+
+	put_rndis_request(&dev, req1);
+	KUNIT_EXPECT_TRUE(test, list_empty(&dev.req_list));
+}
+
+/*
+ * A request left on the list after a completed exchange is a leak of
+ * the descriptor and of its slot in the outstanding set. Repeated
+ * get/put cycles must return to the empty list every time.
+ */
+static void rndis_request_put_cleanup_test(struct kunit *test)
+{
+	struct rndis_device dev;
+	struct rndis_request *req;
+	int i;
+
+	KUNIT_ASSERT_EQ(test, rndis_test_device_init(&dev), 0);
+
+	for (i = 0; i < 4; i++) {
+		req = get_rndis_request(&dev, RNDIS_MSG_INIT, 0x20);
+		KUNIT_ASSERT_NOT_NULL(test, req);
+		KUNIT_EXPECT_FALSE(test, list_empty(&dev.req_list));
+		put_rndis_request(&dev, req);
+		KUNIT_EXPECT_TRUE(test, list_empty(&dev.req_list));
+	}
+}
+
+/*
+ * kvzalloc_obj() may return a vmalloc address under fragmentation. RNDIS
+ * requests are GPA-direct packets, so each backing page must be represented
+ * explicitly instead of deriving a single PFN with virt_to_phys().
+ */
+static void rndis_request_vmalloc_page_buffers_test(struct kunit *test)
+{
+	struct hv_page_buffer page_bufs[MAX_PAGE_BUFFER_COUNT];
+	const u32 data_len = 16;
+	u8 *allocation = vzalloc(2 * PAGE_SIZE);
+	const u8 *cursor;
+	phys_addr_t phys;
+	u32 count = 0, remaining = data_len, i;
+	int ret;
+
+	if (!allocation) {
+		KUNIT_FAIL(test, "could not allocate vmalloc test buffer");
+		return;
+	}
+
+	cursor = allocation + PAGE_SIZE - 8;
+	ret = rndis_build_page_buffers(cursor, data_len, page_bufs, &count);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto out;
+
+	KUNIT_EXPECT_EQ(test, count, 2U);
+	for (i = 0; i < count; i++) {
+		struct page *page = vmalloc_to_page(cursor);
+		unsigned long page_offset = offset_in_page(cursor);
+		u32 offset, chunk;
+
+		if (!page) {
+			KUNIT_FAIL(test, "vmalloc test buffer has no backing page");
+			goto out;
+		}
+
+		phys = page_to_phys(page) + page_offset;
+		offset = offset_in_hvpage(phys);
+		chunk = min_t(u32, remaining, PAGE_SIZE - page_offset);
+		chunk = min_t(u32, chunk, HV_HYP_PAGE_SIZE - offset);
+
+		KUNIT_EXPECT_EQ(test, page_bufs[i].pfn,
+				(u64)(phys >> HV_HYP_PAGE_SHIFT));
+		KUNIT_EXPECT_EQ(test, page_bufs[i].offset, offset);
+		KUNIT_EXPECT_EQ(test, page_bufs[i].len, chunk);
+
+		cursor += chunk;
+		remaining -= chunk;
+	}
+	KUNIT_EXPECT_EQ(test, remaining, 0U);
+
+out:
+	vfree(allocation);
+}
+
+static struct kunit_case rndis_request_test_cases[] = {
+	KUNIT_CASE(rndis_request_size_premise_test),
+	KUNIT_CASE(rndis_request_alloc_zeroed_test),
+	KUNIT_CASE(rndis_request_id_lifecycle_test),
+	KUNIT_CASE(rndis_request_put_cleanup_test),
+	KUNIT_CASE(rndis_request_vmalloc_page_buffers_test),
+	{}
+};
+
+static struct kunit_suite rndis_request_test_suite = {
+	.name = "hyperv-rndis-request",
+	.test_cases = rndis_request_test_cases,
+};
+
+kunit_test_suite(rndis_request_test_suite);
diff --git a/drivers/uio/Kconfig b/drivers/uio/Kconfig
index 9242e77385c64..0a01906bd6cdc 100644
--- a/drivers/uio/Kconfig
+++ b/drivers/uio/Kconfig
@@ -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
diff --git a/drivers/uio/uio.c b/drivers/uio/uio.c
index f8fa205226601..4767ed0661f74 100644
--- a/drivers/uio/uio.c
+++ b/drivers/uio/uio.c
@@ -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;
 	}
 
diff --git a/drivers/uio/uio_hv_generic.c b/drivers/uio/uio_hv_generic.c
index 7b4cc456c4534..91cb25d019be9 100644
--- a/drivers/uio/uio_hv_generic.c
+++ b/drivers/uio/uio_hv_generic.c
@@ -25,6 +25,7 @@
 #include <linux/uio_driver.h>
 #include <linux/netdevice.h>
 #include <linux/if_ether.h>
+#include <linux/mm.h>
 #include <linux/skbuff.h>
 #include <linux/hyperv.h>
 #include <linux/vmalloc.h>
@@ -55,13 +56,13 @@ struct hv_uio_private_data {
 	struct uio_info info;
 	struct hv_device *device;
 	atomic_t refcnt;
+	struct page *int_pages[1];
+	struct page *monitor_pages[1];
 
-	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];
 };
 
@@ -123,49 +124,310 @@ static void hv_uio_channel_cb(void *context)
 	uio_event_notify(&pdata->info);
 }
 
+/* Function used for mmap of the ring buffer sysfs interface. */
+static bool hv_uio_mmap_range_valid(unsigned long map_pages,
+				    pgoff_t offset,
+				    unsigned long pages)
+{
+	return pages && offset < map_pages && pages <= map_pages - offset;
+}
+
+struct hv_uio_mmap_region {
+	struct page **pages;
+	unsigned long page_count;
+	struct vmbus_buffer *buffer;
+	bool decrypted;
+};
+
+static int hv_uio_mmap_get_region(struct hv_uio_private_data *pdata,
+				  unsigned int map_index,
+				  struct hv_uio_mmap_region *region)
+{
+	struct hv_device *dev = pdata->device;
+	struct vmbus_channel *channel = dev->channel;
+
+	if (map_index >= MAX_UIO_MAPS || !pdata->info.mem[map_index].size)
+		return -EINVAL;
+
+	/*
+	 * Buffer-backed regions are not described here. Their page array
+	 * and protection state are only meaningful as the locked snapshot
+	 * from vmbus_buffer_pin_pages(): reading the descriptor outside
+	 * that lock can describe a buffer a concurrent release has already
+	 * cleared. Only the owning buffer is selected at this stage.
+	 */
+	region->buffer = NULL;
+	region->pages = NULL;
+	region->page_count = 0;
+	region->decrypted = false;
+
+	switch (map_index) {
+	case TXRX_RING_MAP:
+		if (channel->state != CHANNEL_OPENED_STATE)
+			return -ENODEV;
+		region->buffer = &channel->ringbuffer;
+		return 0;
+	case INT_PAGE_MAP:
+		region->pages = pdata->int_pages;
+		region->page_count = ARRAY_SIZE(pdata->int_pages);
+		region->decrypted = false;
+		break;
+	case MON_PAGE_MAP:
+		region->pages = pdata->monitor_pages;
+		region->page_count = ARRAY_SIZE(pdata->monitor_pages);
+		region->decrypted = true;
+		break;
+	case RECV_BUF_MAP:
+		region->buffer = &pdata->recv_buffer;
+		return 0;
+	case SEND_BUF_MAP:
+		region->buffer = &pdata->send_buffer;
+		return 0;
+	default:
+		return -EINVAL;
+	}
+
+	if (!region->pages || !region->page_count)
+		return -EINVAL;
+
+	return 0;
+}
+
+static int hv_uio_mmap_prepare_pages(struct vm_area_desc *desc,
+				     struct page **pages,
+				     unsigned long page_count,
+				     pgoff_t offset,
+				     bool decrypted)
+{
+	unsigned long nr_pages = vma_desc_pages(desc);
+
+	if (!vma_desc_test(desc, VMA_SHARED_BIT))
+		return -EINVAL;
+
+	if (!pages || !hv_uio_mmap_range_valid(page_count, offset, nr_pages))
+		return -EINVAL;
+
+	vma_desc_set_flags(desc, VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT);
+	if (decrypted)
+		desc->page_prot = pgprot_decrypted(desc->page_prot);
+
+	mmap_action_map_kernel_pages(desc, desc->start, pages + offset,
+				     nr_pages);
+	return 0;
+}
+
 /*
- * Callback from vmbus_event when channel is rescinded.
- * It is meant for rescind of primary channels only.
+ * mmap_action_map_kernel_pages() only stores the page-array pointer. The
+ * mapping takes its own folio references inside insert_pages(), which runs
+ * after the prepare callback has returned. Dropping the pin therefore has
+ * to wait for the VMA to be established (mapped) or for the attempt to be
+ * abandoned. Release is one-shot: the establish and abandon paths can both
+ * be reached for the same attempt.
+ *
+ * Two surfaces, two ownership contracts. /dev/uioN is a character device,
+ * so kernfs is not in the path and vm_ops->close is a legal abandon path.
+ * The sysfs "ring" bin attribute is kernfs: fs/kernfs/file.c rejects any
+ * VMA whose vm_ops carry .close, because kernfs has to wrap the operations
+ * and cannot wrap close. That surface installs no vm_ops at all and its
+ * synchronous legacy .mmap wrapper owns the pin for the whole window.
  */
-static void hv_uio_rescind(struct vmbus_channel *channel)
+#define HV_UIO_PIN_MAGIC 0x48565049UL /* "HVPI" */
+
+struct hv_uio_pin {
+	unsigned long magic;
+	struct vmbus_buffer_pin snap;
+};
+
+static void hv_uio_pin_release(void *data)
 {
-	struct hv_device *hv_dev = channel->device_obj;
-	struct hv_uio_private_data *pdata = hv_get_drvdata(hv_dev);
+	struct hv_uio_pin *pin = data;
 
+	if (!pin)
+		return;
 	/*
-	 * Turn off the interrupt file handle
-	 * Next read for event will return -EIO
+	 * close() can be reached with a private_data that this driver did
+	 * not install. A foreign pointer must not be freed or unpinned.
 	 */
-	pdata->info.irq = 0;
+	if (pin->magic != HV_UIO_PIN_MAGIC)
+		return;
+	pin->magic = 0;
+	vmbus_buffer_unpin_pages(&pin->snap);
+	kfree(pin);
+}
 
-	/* Wake up reader */
-	uio_event_notify(&pdata->info);
+static int hv_uio_pin_vma_mapped(unsigned long start, unsigned long end,
+				 pgoff_t pgoff, const struct file *file,
+				 void **vm_private_data)
+{
+	/*
+	 * insert_pages() has taken a folio reference for every page the
+	 * VMA now maps, so the reclaim worker can no longer free them
+	 * under the mapping. The bridge pin is done.
+	 */
+	hv_uio_pin_release(*vm_private_data);
+	*vm_private_data = NULL;
+	return 0;
+}
 
+static void hv_uio_pin_vma_close(struct vm_area_struct *vma)
+{
 	/*
-	 * With rescind callback registered, rescind path will not unregister the device
-	 * from vmbus when the primary channel is rescinded.
-	 * Without it, rescind handling is incomplete and next onoffer msg does not come.
-	 * Unregister the device from vmbus here.
+	 * Reached with the pin still held when the VMA is torn down before
+	 * mapped() ran (an insert_pages() failure, or a merge that never
+	 * calls mapped), and with nothing left to do when it already ran.
 	 */
-	vmbus_device_unregister(channel->device_obj);
+	hv_uio_pin_release(vma->vm_private_data);
+	vma->vm_private_data = NULL;
 }
 
-/* Function used for mmap of ring buffer sysfs interface.
- * The ring buffer is allocated as contiguous memory by vmbus_open
+/*
+ * Character-device surface only. The sysfs ring must never adopt this set:
+ * see the kernfs contract above.
+ */
+static const struct vm_operations_struct hv_uio_pin_vm_ops = {
+	.mapped = hv_uio_pin_vma_mapped,
+	.close = hv_uio_pin_vma_close,
+};
+
+/*
+ * Install @snap as the VMA's per-mapping state under @ops. Consumes @snap:
+ * returns 0 with the pin owned by @desc and @snap cleared, or -ENOMEM with
+ * the references dropped here. The caller must not drop the references on
+ * the success path: mapped() and close() own them from here.
  */
+static int hv_uio_pin_install(struct vm_area_desc *desc,
+			      const struct vm_operations_struct *ops,
+			      struct vmbus_buffer_pin *snap)
+{
+	struct hv_uio_pin *pin;
+
+	pin = kzalloc_obj(*pin);
+	if (!pin) {
+		vmbus_buffer_unpin_pages(snap);
+		return -ENOMEM;
+	}
+	pin->magic = HV_UIO_PIN_MAGIC;
+	pin->snap = *snap;
+	snap->pages = NULL;
+	snap->page_count = 0;
+
+	desc->vm_ops = ops;
+	desc->private_data = pin;
+	return 0;
+}
+
+static int hv_uio_mmap_prepare(struct uio_info *info,
+			       struct vm_area_desc *desc)
+{
+	struct hv_uio_private_data *pdata = info->priv;
+	struct hv_uio_mmap_region region;
+	struct vmbus_buffer_pin pin = {};
+	struct page **pages;
+	unsigned long page_count;
+	bool decrypted;
+	int ret;
+
+	/* UIO encodes the map index in pgoff; mmap offsets start at the map. */
+	if (desc->pgoff >= MAX_UIO_MAPS)
+		return -EINVAL;
+
+	ret = hv_uio_mmap_get_region(pdata, desc->pgoff, &region);
+	if (ret)
+		return ret;
+
+	/*
+	 * Buffer-backed maps race with the reclaim worker: the page
+	 * array and the pages themselves can be freed between the
+	 * selection above and the mapping below. Hold references until
+	 * the VMA holds its own. The pin is also the only safe source of
+	 * the protection state: it is taken in the same critical section
+	 * that reads the page array.
+	 */
+	if (region.buffer) {
+		ret = vmbus_buffer_pin_pages(region.buffer, &pin);
+		if (ret)
+			return ret;
+		pages = pin.pages;
+		page_count = pin.page_count;
+		decrypted = pin.decrypted;
+	} else {
+		pages = region.pages;
+		page_count = region.page_count;
+		decrypted = region.decrypted;
+	}
+
+	ret = hv_uio_mmap_prepare_pages(desc, pages, page_count, 0, decrypted);
+	if (ret) {
+		if (region.buffer)
+			vmbus_buffer_unpin_pages(&pin);
+		return ret;
+	}
+
+	if (!region.buffer)
+		return 0;
+
+	return hv_uio_pin_install(desc, &hv_uio_pin_vm_ops, &pin);
+}
+
 static int
-hv_uio_ring_mmap_prepare(struct vmbus_channel *channel, struct vm_area_desc *desc)
+hv_uio_ring_mmap_prepare(struct vmbus_channel *channel,
+			 struct vm_area_desc *desc)
 {
-	void *ring_buffer = page_address(channel->ringbuffer_page);
+	struct vmbus_buffer *buffer = &channel->ringbuffer;
+	struct vmbus_buffer_pin *pin;
+	pgoff_t offset = desc->pgoff;
+	int ret;
 
 	if (channel->state != CHANNEL_OPENED_STATE)
 		return -ENODEV;
 
-	mmap_action_simple_ioremap(desc, virt_to_phys(ring_buffer),
-			channel->ringbuffer_pagecount << PAGE_SHIFT);
+	pin = kzalloc_obj(*pin);
+	if (!pin)
+		return -ENOMEM;
+
+	ret = vmbus_buffer_pin_pages(buffer, pin);
+	if (ret) {
+		kfree(pin);
+		return ret;
+	}
+
+	ret = hv_uio_mmap_prepare_pages(desc, pin->pages, pin->page_count,
+					offset, pin->decrypted);
+	if (ret) {
+		vmbus_buffer_unpin_pages(pin);
+		kfree(pin);
+		return ret;
+	}
+
+	/*
+	 * Install no vm_ops. kernfs_fop_mmap() returns -EINVAL for a VMA
+	 * whose vm_ops carry .close, and a successful mapping still has to
+	 * survive that check, so this surface cannot carry an abandon path
+	 * in vm_ops at all. The caller is hv_mmap_ring_buffer_wrapper(),
+	 * a synchronous legacy .mmap: it holds @pin across
+	 * __compat_vma_mmap() and frees it when that returns, exactly once,
+	 * on every outcome. desc->private_data is a plain
+	 * struct vmbus_buffer_pin for that wrapper to release.
+	 */
+	desc->vm_ops = NULL;
+	desc->private_data = pin;
 	return 0;
 }
 
+/* Caller has withdrawn UIO callbacks before removing its backing memory. */
+static int hv_uio_disconnect_if_open(struct vmbus_channel *channel,
+				     int (*disconnect)(struct vmbus_channel *))
+{
+	if (channel->state != CHANNEL_OPENED_STATE)
+		return 0;
+
+	return disconnect(channel);
+}
+
+#if defined(CONFIG_UIO_HV_GENERIC_KUNIT_TEST)
+#include "uio_hv_generic_mmap_test.c"
+#endif
+
 /* Callback from VMBUS subsystem when new channel created. */
 static void
 hv_uio_new_channel(struct vmbus_channel *new_sc)
@@ -195,17 +457,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) {
-		vmbus_teardown_gpadl(dev->channel, &pdata->send_gpadl);
-		if (!pdata->send_gpadl.decrypted)
-			vfree(pdata->send_buf);
-	}
+	if (pdata->send_buffer.gpadl.gpadl_handle)
+		vmbus_teardown_gpadl_owned(dev->channel, &pdata->send_buffer);
+	vmbus_release_buffer(&pdata->send_buffer);
 
-	if (pdata->recv_gpadl.gpadl_handle) {
-		vmbus_teardown_gpadl(dev->channel, &pdata->recv_gpadl);
-		if (!pdata->recv_gpadl.decrypted)
-			vfree(pdata->recv_buf);
-	}
+	if (pdata->recv_buffer.gpadl.gpadl_handle)
+		vmbus_teardown_gpadl_owned(dev->channel, &pdata->recv_buffer);
+	vmbus_release_buffer(&pdata->recv_buffer);
 }
 
 /* VMBus primary channel is opened on first use */
@@ -220,7 +478,6 @@ hv_uio_open(struct uio_info *info, struct inode *inode)
 	if (atomic_inc_return(&pdata->refcnt) != 1)
 		return 0;
 
-	vmbus_set_chn_rescind_callback(dev->channel, hv_uio_rescind);
 	vmbus_set_sc_create_callback(dev->channel, hv_uio_new_channel);
 
 	ret = vmbus_connect_ring(dev->channel,
@@ -276,6 +533,7 @@ hv_uio_probe(struct hv_device *dev,
 	pdata->info.name = "uio_hv_generic";
 	pdata->info.version = DRIVER_VERSION;
 	pdata->info.irqcontrol = hv_uio_irqcontrol;
+	pdata->info.mmap_prepare = hv_uio_mmap_prepare;
 	pdata->info.open = hv_uio_open;
 	pdata->info.release = hv_uio_release;
 	pdata->info.irq = UIO_IRQ_CUSTOM;
@@ -283,66 +541,60 @@ 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
 		= (uintptr_t)vmbus_connection.int_page;
 	pdata->info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
 	pdata->info.mem[INT_PAGE_MAP].memtype = UIO_MEM_LOGICAL;
+	pdata->int_pages[0] = virt_to_page(vmbus_connection.int_page);
 
 	pdata->info.mem[MON_PAGE_MAP].name = "monitor_page";
 	pdata->info.mem[MON_PAGE_MAP].addr
 		= (uintptr_t)vmbus_connection.monitor_pages[1];
 	pdata->info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
 	pdata->info.mem[MON_PAGE_MAP].memtype = UIO_MEM_LOGICAL;
+	pdata->monitor_pages[0] =
+		virt_to_page(vmbus_connection.monitor_pages[1]);
 
 	if (channel->device_id == HV_NIC) {
-		pdata->recv_buf = vzalloc(RECV_BUFFER_SIZE);
-		if (!pdata->recv_buf) {
-			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_buf,
-					    RECV_BUFFER_SIZE, &pdata->recv_gpadl);
-		if (ret) {
-			if (!pdata->recv_gpadl.decrypted)
-				vfree(pdata->recv_buf);
+		ret = vmbus_establish_gpadl_owned(channel, &pdata->recv_buffer);
+		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) {
-			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_buf,
-					    SEND_BUFFER_SIZE, &pdata->send_gpadl);
-		if (ret) {
-			if (!pdata->send_gpadl.decrypted)
-				vfree(pdata->send_buf);
+		ret = vmbus_establish_gpadl_owned(channel, &pdata->send_buffer);
+		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;
 	}
@@ -385,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);
+	/* 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);
+	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);
diff --git a/drivers/uio/uio_hv_generic_mmap_test.c b/drivers/uio/uio_hv_generic_mmap_test.c
new file mode 100644
index 0000000000000..615df78b266e7
--- /dev/null
+++ b/drivers/uio/uio_hv_generic_mmap_test.c
@@ -0,0 +1,875 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * KUnit tests for the UIO Hyper-V generic mmap paths.
+ *
+ * This file is included from uio_hv_generic.c so the cases can reach the
+ * static helpers that select, validate and pin the mapped pages.
+ *
+ * Two ownership contracts are under test:
+ *   - the /dev/uioN character-device path installs hv_uio_pin_vm_ops
+ *     (.mapped + .close) and a struct hv_uio_pin;
+ *   - the sysfs "ring" bin attribute cannot, because kernfs_fop_mmap()
+ *     rejects a vm_operations_struct that carries .close. That path
+ *     installs no vm_ops and hands a bare struct vmbus_buffer_pin to its
+ *     synchronous .mmap wrapper, which is the single release site.
+ */
+#include <kunit/test.h>
+
+/*
+ * Release exactly what hv_mmap_ring_buffer_wrapper() releases after
+ * __compat_vma_mmap() returns: the bare pin's references, then the pin.
+ */
+static void sysfs_pin_release(struct vmbus_buffer_pin *pin)
+{
+	vmbus_buffer_unpin_pages(pin);
+	kfree(pin);
+}
+
+static void hv_uio_ring_mmap_range_test(struct kunit *test)
+{
+	KUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 0, 8));
+	KUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 4, 4));
+	KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 8, 1));
+	KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 7, 2));
+	KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 0, 0));
+	KUNIT_EXPECT_FALSE(test,
+			   hv_uio_mmap_range_valid(8, U64_MAX, 1));
+}
+
+static void hv_uio_ring_mmap_prepare_test(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 8,
+		},
+	};
+	struct page *pages[8] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = PAGE_SIZE,
+		.end = 5 * PAGE_SIZE,
+		.pgoff = 2,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	/* Mapping pins real pages; the array cannot hold NULL entries. */
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages, &pages[2]);
+	KUNIT_EXPECT_EQ(test, desc.action.map_kernel.nr_pages, 4UL);
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTEXPAND_BIT));
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTDUMP_BIT));
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(pgprot_decrypted(PAGE_SHARED)));
+
+	/*
+	 * The sysfs surface installs no vm_ops at all: see the kernfs
+	 * contract in the comment at the top of this file. The wrapper
+	 * holds the pin and is the only thing that releases it.
+	 */
+	KUNIT_EXPECT_NULL(test, desc.vm_ops);
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	KUNIT_EXPECT_TRUE(test, pin->decrypted);
+	KUNIT_EXPECT_EQ(test, pin->page_count, ARRAY_SIZE(pages));
+	sysfs_pin_release(pin);
+
+	desc.vma_flags = EMPTY_VMA_FLAGS;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	desc.start = PAGE_SIZE;
+	desc.end = 3 * PAGE_SIZE;
+	desc.pgoff = 7;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+
+	channel.state = CHANNEL_OPEN_STATE;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -ENODEV);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+static void hv_uio_mmap_region_select_test(struct kunit *test)
+{
+	struct hv_uio_private_data pdata = {};
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct hv_uio_mmap_region region;
+	struct page *ring_pages[4] = {};
+	struct page *recv_pages[3] = {};
+	struct page *send_pages[2] = {};
+	struct page *chunks[1] = {};
+	int ret;
+
+	pdata.device = &dev;
+	pdata.info.mem[TXRX_RING_MAP].size =
+		ARRAY_SIZE(ring_pages) * PAGE_SIZE;
+	pdata.info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata.info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata.info.mem[RECV_BUF_MAP].size =
+		ARRAY_SIZE(recv_pages) * PAGE_SIZE;
+	pdata.info.mem[SEND_BUF_MAP].size =
+		ARRAY_SIZE(send_pages) * PAGE_SIZE;
+	channel.ringbuffer.pages = ring_pages;
+	channel.ringbuffer.page_cnt = ARRAY_SIZE(ring_pages);
+	channel.ringbuffer.chunks = chunks;
+	pdata.int_pages[0] = ring_pages[0];
+	pdata.monitor_pages[0] = ring_pages[1];
+	pdata.recv_buffer.pages = recv_pages;
+	pdata.recv_buffer.page_cnt = ARRAY_SIZE(recv_pages);
+	pdata.recv_buffer.chunks = chunks;
+	pdata.send_buffer.pages = send_pages;
+	pdata.send_buffer.page_cnt = ARRAY_SIZE(send_pages);
+
+	/*
+	 * Buffer-backed maps are described only by their owning buffer.
+	 * The page array and the protection state are deliberately absent
+	 * here: reading them outside vmbus_buffer_owners_lock can describe
+	 * a buffer a concurrent release has already cleared. The locked
+	 * pin snapshot is the only safe source.
+	 */
+	ret = hv_uio_mmap_get_region(&pdata, TXRX_RING_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, region.buffer, &channel.ringbuffer);
+	KUNIT_EXPECT_NULL(test, region.pages);
+	KUNIT_EXPECT_EQ(test, region.page_count, 0UL);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, INT_PAGE_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, region.buffer);
+	KUNIT_EXPECT_PTR_EQ(test, region.pages, &pdata.int_pages[0]);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, MON_PAGE_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, region.buffer);
+	KUNIT_EXPECT_PTR_EQ(test, region.pages, &pdata.monitor_pages[0]);
+	KUNIT_EXPECT_TRUE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, RECV_BUF_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, region.buffer, &pdata.recv_buffer);
+	KUNIT_EXPECT_NULL(test, region.pages);
+	KUNIT_EXPECT_EQ(test, region.page_count, 0UL);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, SEND_BUF_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, region.buffer, &pdata.send_buffer);
+	KUNIT_EXPECT_NULL(test, region.pages);
+	KUNIT_EXPECT_EQ(test, region.page_count, 0UL);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	KUNIT_EXPECT_EQ(test,
+			hv_uio_mmap_get_region(&pdata, MAX_UIO_MAPS, &region),
+			-EINVAL);
+	channel.state = CHANNEL_OPEN_STATE;
+	KUNIT_EXPECT_EQ(test,
+			hv_uio_mmap_get_region(&pdata, TXRX_RING_MAP, &region),
+			-ENODEV);
+}
+
+static void hv_uio_mmap_prepare_test(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[4] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = PAGE_SIZE,
+		.end = 3 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	/* Mapping pins real pages; the array cannot hold NULL entries. */
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages, &pages[0]);
+	KUNIT_EXPECT_EQ(test, desc.action.map_kernel.nr_pages, 2UL);
+	/*
+	 * The protection state comes from the locked pin snapshot, not
+	 * from a second read of the buffer descriptor. chunks is set, so
+	 * the snapshot says decrypted.
+	 */
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(pgprot_decrypted(PAGE_SHARED)));
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTEXPAND_BIT));
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTDUMP_BIT));
+	/*
+	 * Character-device maps can carry an abandon path: kernfs is not
+	 * in this path, so .close is legal here and illegal on "ring".
+	 */
+	KUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, &hv_uio_pin_vm_ops);
+	KUNIT_ASSERT_NOT_NULL(test, desc.vm_ops->mapped);
+	KUNIT_ASSERT_NOT_NULL(test, desc.vm_ops->close);
+	/* Buffer-backed maps leave the pin held for mapped()/close(). */
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+	hv_uio_pin_release(desc.private_data);
+	desc.private_data = NULL;
+
+	desc.vma_flags = EMPTY_VMA_FLAGS;
+	KUNIT_EXPECT_EQ(test, hv_uio_mmap_prepare(&pdata->info, &desc), -EINVAL);
+
+	desc.pgoff = INT_PAGE_MAP;
+	pdata->info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata->int_pages[0] = pages[0];
+	desc.end = 2 * PAGE_SIZE;
+	desc.page_prot = PAGE_SHARED;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages,
+			    &pdata->int_pages[0]);
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(PAGE_SHARED));
+	/* int_pages is not a vmbus_buffer, so nothing is pinned. */
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+
+	desc.pgoff = MON_PAGE_MAP;
+	pdata->info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata->monitor_pages[0] = pages[1];
+	desc.page_prot = PAGE_SHARED;
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages,
+			    &pdata->monitor_pages[0]);
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(pgprot_decrypted(PAGE_SHARED)));
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+
+	desc.pgoff = SEND_BUF_MAP;
+	pdata->info.mem[SEND_BUF_MAP].size = PAGE_SIZE;
+	pdata->send_buffer.pages = pages;
+	pdata->send_buffer.page_cnt = ARRAY_SIZE(pages);
+	desc.page_prot = PAGE_SHARED;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	/* send_buffer has no chunks, so the snapshot says encrypted. */
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(PAGE_SHARED));
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+	hv_uio_pin_release(desc.private_data);
+	desc.private_data = NULL;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The reclaim race this driver closes is a lifetime question: the pin has
+ * to span the gap between mmap_prepare() returning and insert_pages()
+ * taking its own folio references. Dropping it inside the prepare hook
+ * leaves the pages freeable before the mapping exists.
+ *
+ * This is the character-device contract: mapped() and close() share the
+ * release, and release is one-shot.
+ */
+static void hv_uio_pin_lifetime_test(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[4] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 4 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	struct vm_area_struct *vma;
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	/*
+	 * Prepare must hold a reference on every page: the mapping is not
+	 * installed until insert_pages() runs after the hook returns.
+	 */
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	KUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, &hv_uio_pin_vm_ops);
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+
+	/* mapped(): the mapping holds its own refs, so the pin is released. */
+	ret = desc.vm_ops->mapped(desc.start, desc.end, 0, NULL,
+				  &desc.private_data);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* close() after mapped() must not unpin again. */
+	vma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, vma);
+	vma->vm_ops = desc.vm_ops;
+	vma->vm_private_data = desc.private_data;
+	desc.vm_ops->close(vma);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The abandonment path: when the mapping is torn down before mapped() ran
+ * (insert_pages() failure, or a merge that never calls mapped()), close()
+ * must still drop the pin. A foreign private_data must be left alone.
+ */
+static void hv_uio_pin_close_before_mapped_test(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	struct vm_area_struct *vma;
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+
+	vma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, vma);
+	vma->vm_ops = desc.vm_ops;
+	vma->vm_private_data = desc.private_data;
+	desc.vm_ops->close(vma);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* A second close is a no-op, not a double unpin. */
+	desc.vm_ops->close(vma);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* A pointer this driver did not install must not be freed. */
+	vma->vm_private_data = &pages[0];
+	desc.vm_ops->close(vma);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The kernfs contract, named. fs/kernfs/file.c returns -EINVAL for a VMA
+ * whose vm_ops carry .close, and it performs that check after the .mmap
+ * hook has already succeeded. A successful sysfs mapping therefore cannot
+ * carry an abandon path in vm_ops at all.
+ */
+static void sysfs_ring_mmap_ops_have_no_close(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 1,
+		},
+	};
+	struct page *pages[1] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	int ret;
+
+	pages[0] = alloc_page(GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pages[0]);
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	/* The exact predicate kernfs_fop_mmap() applies must be false. */
+	KUNIT_EXPECT_NULL(test, desc.vm_ops);
+	KUNIT_EXPECT_FALSE(test, desc.vm_ops && desc.vm_ops->close);
+
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	sysfs_pin_release(pin);
+
+	__free_page(pages[0]);
+}
+
+/*
+ * The character-device counterpart: a buffer-backed map prepares and
+ * installs the ops that carry the abandon path, then mapped() releases.
+ */
+static void uio_buffer_mmap_success(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);
+	KUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, &hv_uio_pin_vm_ops);
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	ret = desc.vm_ops->mapped(desc.start, desc.end, 0, NULL,
+				  &desc.private_data);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * A prepare that refuses must not leave references behind. Each failure
+ * mode is checked against the page reference count, which is the only
+ * externally visible record of a leaked pin.
+ */
+static void sysfs_mmap_prepare_failure_releases_pin(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 2,
+		},
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+
+	/* Not shared: refused before anything is pinned. */
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* pgoff past the end of the pin: refused before anything is pinned. */
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	desc.pgoff = 2;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* Channel not open: refused before anything is pinned. */
+	desc.pgoff = 0;
+	channel.state = CHANNEL_OPEN_STATE;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -ENODEV);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * Prepare succeeded and the pin is installed, but the mapping never
+ * becomes established (insert_pages() fails part-way, or the attempt is
+ * otherwise abandoned). The wrapper is the only owner on this surface and
+ * releases with one unpin plus one free, whether or not any VMA ever held
+ * the pages. This proves the object it is handed is fully releasable that
+ * way, and that releasing twice is not possible to observe.
+ */
+static void sysfs_mmap_partial_insert_failure_releases_pin(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 3,
+		},
+	};
+	struct page *pages[3] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 3 * PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	/* The wrapper's abandon path: one unpin, one free. */
+	sysfs_pin_release(pin);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The window the pin exists to close. Between the snapshot and the point
+ * where the mapping holds its own references, a concurrent
+ * vmbus_release_buffer() can drop the buffer's reference to each page.
+ * The pin must keep the pages alive for the whole window, and must be the
+ * thing that drops the last reference.
+ */
+static void sysfs_mmap_release_during_insert_keeps_pages_alive(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 2,
+		},
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	/*
+	 * Concurrent release: the buffer drops its own reference to each
+	 * page. The pages must still be alive, held only by the pin, so a
+	 * mapping that is mid-insert cannot walk freed memory.
+	 */
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+	KUNIT_EXPECT_PTR_EQ(test, pin->pages, &pages[0]);
+	KUNIT_EXPECT_EQ(test, pin->page_count, ARRAY_SIZE(pages));
+
+	/* The pin is what drops the last reference. */
+	sysfs_pin_release(pin);
+}
+
+/*
+ * KCA-23: the protection state has to travel with the pin. The snapshot is
+ * taken in the same critical section as the page array, so a later
+ * vmbus_release_buffer() clearing the descriptor cannot change what this
+ * mapping is told about the pages it holds.
+ */
+static void ring_mmap_release_preserves_protection_snapshot(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 1,
+		},
+	};
+	struct page *pages[1] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin pin = {};
+	int ret;
+
+	pages[0] = alloc_page(GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pages[0]);
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+
+	ret = vmbus_buffer_pin_pages(&channel.ringbuffer, &pin);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_TRUE(test, pin.decrypted);
+	KUNIT_EXPECT_EQ(test, pin.page_count, 1UL);
+
+	/*
+	 * A concurrent release clears the descriptor. The pin must still
+	 * describe the pages it holds, not the cleared descriptor.
+	 */
+	channel.ringbuffer.chunks = NULL;
+	channel.ringbuffer.pages = NULL;
+	channel.ringbuffer.page_cnt = 0;
+	KUNIT_EXPECT_TRUE(test, pin.decrypted);
+	KUNIT_EXPECT_PTR_EQ(test, pin.pages, &pages[0]);
+	KUNIT_EXPECT_EQ(test, pin.page_count, 1UL);
+
+	vmbus_buffer_unpin_pages(&pin);
+	KUNIT_EXPECT_NULL(test, pin.pages);
+	KUNIT_EXPECT_EQ(test, pin.page_count, 0UL);
+
+	/* A buffer that never took the shared-page path is not decrypted. */
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.page_cnt = 1;
+	channel.ringbuffer.chunks = NULL;
+	ret = vmbus_buffer_pin_pages(&channel.ringbuffer, &pin);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_FALSE(test, pin.decrypted);
+	vmbus_buffer_unpin_pages(&pin);
+
+	__free_page(pages[0]);
+}
+
+static unsigned int hv_uio_disconnect_calls;
+static int hv_uio_disconnect_result;
+
+static int hv_uio_test_disconnect(struct vmbus_channel *channel)
+{
+	hv_uio_disconnect_calls++;
+	channel->state = CHANNEL_OPEN_STATE;
+	return hv_uio_disconnect_result;
+}
+
+static void hv_uio_remove_disconnects_open_channel_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .state = CHANNEL_OPEN_STATE };
+
+	hv_uio_disconnect_calls = 0;
+	hv_uio_disconnect_result = 0;
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), 0);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 0U);
+	channel.state = CHANNEL_OPENED_STATE;
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), 0);
+	KUNIT_EXPECT_EQ(test, channel.state, CHANNEL_OPEN_STATE);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 1U);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), 0);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 1U);
+
+	channel.state = CHANNEL_OPENED_STATE;
+	hv_uio_disconnect_result = -EIO;
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), -EIO);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 2U);
+}
+
+static int hv_uio_test_reader_wake(struct wait_queue_entry *wait,
+				   unsigned int mode, int flags, void *key)
+{
+	unsigned int *wakes = wait->private;
+
+	(*wakes)++;
+	return 1;
+}
+
+static void hv_uio_unregister_wakes_reader_test(struct kunit *test)
+{
+	struct uio_info info = {
+		.name = "hv-uio-withdrawal-test",
+		.version = "1",
+		.irq = UIO_IRQ_CUSTOM,
+	};
+	struct uio_device *idev;
+	struct device *parent;
+	wait_queue_entry_t wait;
+	unsigned int wakes = 0;
+	int ret;
+
+	parent = root_device_register("hv-uio-withdrawal-test");
+	KUNIT_ASSERT_FALSE(test, IS_ERR(parent));
+	ret = uio_register_device(parent, &info);
+	if (ret) {
+		root_device_unregister(parent);
+		KUNIT_FAIL(test, "UIO registration failed: %d", ret);
+		return;
+	}
+	idev = info.uio_dev;
+	get_device(&idev->dev);
+	init_waitqueue_func_entry(&wait, hv_uio_test_reader_wake);
+	wait.private = &wakes;
+	add_wait_queue(&idev->wait, &wait);
+
+	uio_unregister_device(&info);
+	KUNIT_EXPECT_PTR_EQ(test, idev->info, NULL);
+	KUNIT_EXPECT_EQ(test, wakes, 1U);
+	remove_wait_queue(&idev->wait, &wait);
+	put_device(&idev->dev);
+	root_device_unregister(parent);
+}
+
+static struct kunit_case hv_uio_ring_mmap_test_cases[] = {
+	KUNIT_CASE(hv_uio_unregister_wakes_reader_test),
+	KUNIT_CASE(hv_uio_remove_disconnects_open_channel_test),
+	KUNIT_CASE(hv_uio_ring_mmap_range_test),
+	KUNIT_CASE(hv_uio_ring_mmap_prepare_test),
+	KUNIT_CASE(hv_uio_mmap_region_select_test),
+	KUNIT_CASE(hv_uio_mmap_prepare_test),
+	KUNIT_CASE(hv_uio_pin_lifetime_test),
+	KUNIT_CASE(hv_uio_pin_close_before_mapped_test),
+	KUNIT_CASE(sysfs_ring_mmap_ops_have_no_close),
+	KUNIT_CASE(uio_buffer_mmap_success),
+	KUNIT_CASE(sysfs_mmap_prepare_failure_releases_pin),
+	KUNIT_CASE(sysfs_mmap_partial_insert_failure_releases_pin),
+	KUNIT_CASE(sysfs_mmap_release_during_insert_keeps_pages_alive),
+	KUNIT_CASE(ring_mmap_release_preserves_protection_snapshot),
+	{}
+};
+
+static struct kunit_suite hv_uio_ring_mmap_test_suite = {
+	.name = "hyperv-uio-mmap",
+	.test_cases = hv_uio_ring_mmap_test_cases,
+};
+
+kunit_test_suite(hv_uio_ring_mmap_test_suite);
diff --git a/include/linux/hyperv.h b/include/linux/hyperv.h
index 9e109d91aa143..f0e8f1af8e757 100644
--- a/include/linux/hyperv.h
+++ b/include/linux/hyperv.h
@@ -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,21 @@ struct vmbus_gpadl {
 	u32 size;
 	void *buffer;
 	bool decrypted;
+	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 {
@@ -800,13 +814,13 @@ 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 */
+	u64 lifetime_id;
 	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 */
@@ -1110,7 +1124,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);
 
@@ -1201,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,
@@ -1211,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,
@@ -1220,6 +1235,43 @@ extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 
 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);
+
+/**
+ * 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,

3/2 2026/10/07 21:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 81263
							output: 18
							thoughts: 1361
						

Thoughts:
**Analyzing the Patch Series for Fuzzing Potential**

Okay, so the task is to determine if this patch series applied to the Linux kernel is worth fuzzing, focusing on whether the modified code is reachable in standard virtualized environments. Given the target architecture is amd64, reachability is absolutely paramount. I need to make sure this code *can* actually execute within the typical GCE or QEMU setups, specifically those utilizing software-emulated devices like USB gadgets, netdev, or tun/tap. Any code that's structurally unreachable is a no-go, regardless of complexity or assertions.

First, I need to understand the constraints. Section 2 dictates that non-kernel and non-executable changes, or code dependent on structurally unreachable hardware, are off-limits. Hyper-V devices and drivers are my immediate point of focus. Now, let's see, can Hyper-V run in standard environments like GCE or QEMU? GCE uses KVM, and QEMU can use KVM or TCG. Does either of them emulate the Hyper-V VMBus? I need to quickly determine if a standard syzkaller setup or general Linux kernel reachability covers Hyper-V and VMBus. This is a crucial first step. If not reachable, it's not worth further consideration.

Now, let's look at the specific files. I see the patch touches a bunch of stuff: `drivers/hv/Kconfig`, `drivers/hv/Makefile`, various `*.c` files in `drivers/hv`, and even some KUnit tests. Then there's `drivers/net/hyperv` – more Hyper-V code – and even more KUnit tests related to network interfaces. The `drivers/uio` directory is also modified. Okay, right away, the presence of `drivers/uio/uio.c` is significant.

Wait a moment, I need to inspect the changes to `drivers/uio/uio.c`. The diff introduces some logic within the `uio_mmap` function. It looks like it's dealing with installing per-VMA state before `__compat_vma_mmap` call and handling potential errors.

The key question is, is `drivers/uio/uio.c` reachable? Can UIO devices be created and accessed within the standard QEMU/GCE environments used for fuzzing? Do these environments support UIO devices? I need to check. To understand that, I need to figure out what drivers actually utilize the `mmap_prepare` function that's being used here. A quick grep of the source tree is in order. This will provide some important insight into how, and whether, the changes in `uio_mmap` can ever be triggered during a fuzzing campaign. This is going to be key to making the final decision.



4/2 2026/10/07 21:53 tool grepper
0m Args:
{
  "Expression": "mmap_prepare"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 1330 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (87 files in total):\nDocumentation/driver-api/uio-howto.rst:2\nDocumentation/driver-api/vme.rst:1\nDocumentation/filesystems/index.rst:1\nDocumentation/filesystems/mmap_prepare.rst:9\nDocumentation/filesystems/porting.rst:1\nDocumentation/filesystems/vfs.rst:3\nblock/fops.c:4\ndrivers/char/hpet.c:3\ndrivers/char/mem.c:2\ndrivers/dax/device.c:2\ndrivers/hv/hyperv_vmbus.h:1\ndrivers/hv/vmbus_drv.c:8\ndrivers/hv/vmbus_mmap_test.c:1\ndrivers/hwtracing/stm/core.c:2\ndrivers/misc/open-dice.c:2\ndrivers/mtd/mtdchar.c:2\ndrivers/staging/vme_user/vme.c:3\ndrivers/staging/vme_user/vme.h:1\ndrivers/staging/vme_user/vme_user.c:5\ndrivers/target/target_core_user.c:2\ndrivers/uio/uio.c:3\ndrivers/uio/uio_hv_generic.c:8\ndrivers/uio/uio_hv_generic_mmap_test.c:25\nfs/9p/vfs_file.c:5\nfs/adfs/file.c:1\nfs/affs/file.c:1\nfs/afs/file.c:4\nfs/aio.c:2\nfs/bfs/file.c:1\nfs/btrfs/file.c:2\nfs/ceph/addr.c:1\nfs/ceph/file.c:1\nfs/ceph/super.h:1\nfs/debugfs/file.c:1\nfs/erofs/data.c:4\nfs/exfat/file.c:2\nfs/ext2/file.c:1\nfs/ext4/file.c:2\nfs/f2fs/file.c:2\nfs/fat/file.c:1\nfs/hfs/inode.c:1\nfs/hfsplus/inode.c:1\nfs/hostfs/hostfs_kern.c:1\nfs/hpfs/file.c:1\nfs/jffs2/file.c:1\nfs/jfs/file.c:1\nfs/minix/file.c:1\nfs/nfs/file.c:5\nfs/nfs/internal.h:1\nfs/nfs/nfs4file.c:1\n... and 37 more files\n\nDocumentation/driver-api/uio-howto.rst=220=the members are required, others are optional.\n--\nDocumentation/driver-api/uio-howto.rst-248-\nDocumentation/driver-api/uio-howto.rst:249:-  ``int (*mmap_prepare)(struct uio_info *info, struct vm_area_desc *desc)``:\nDocumentation/driver-api/uio-howto.rst-250-   Optional. If you need a special :c:func:`mmap()`\nDocumentation/driver-api/uio-howto.rst-251-   function, you can set it here. If this pointer is not NULL, your\nDocumentation/driver-api/uio-howto.rst:252:   ``mmap_prepare`` will be called instead of the built-in one.\nDocumentation/driver-api/uio-howto.rst-253-\n--\nDocumentation/driver-api/vme.rst=109=do a read-modify-write transaction. Parts of a VME window can also be mapped\nDocumentation/driver-api/vme.rst:110:into user space memory using :c:func:`vme_master_mmap_prepare`.\nDocumentation/driver-api/vme.rst-111-\n--\nDocumentation/filesystems/index.rst=16=algorithms work.\n--\nDocumentation/filesystems/index.rst-31-   locks\nDocumentation/filesystems/index.rst:32:   mmap_prepare\nDocumentation/filesystems/index.rst-33-   multigrain-ts\n--\nDocumentation/filesystems/mmap_prepare.rst-3-===========================\nDocumentation/filesystems/mmap_prepare.rst:4:mmap_prepare callback HOWTO\nDocumentation/filesystems/mmap_prepare.rst-5-===========================\n--\nDocumentation/filesystems/mmap_prepare.rst=12=mappings resulting in unnecessary memory fragmentation.\nDocumentation/filesystems/mmap_prepare.rst-13-\nDocumentation/filesystems/mmap_prepare.rst:14:It has been replaced with the ``file-\u003ef_op-\u003emmap_prepare()`` callback which\nDocumentation/filesystems/mmap_prepare.rst-15-solves these problems.\n--\nDocumentation/filesystems/mmap_prepare.rst=32=count needs to be manipulated, this should be done using the ``vm_ops-\u003emapped``\nDocumentation/filesystems/mmap_prepare.rst:33:hook, which itself should be set by the \u003emmap_prepare hook.\nDocumentation/filesystems/mmap_prepare.rst-34-\n--\nDocumentation/filesystems/mmap_prepare.rst=43=How To Use\n--\nDocumentation/filesystems/mmap_prepare.rst-45-\nDocumentation/filesystems/mmap_prepare.rst:46:In your driver's struct file_operations struct, specify an ``mmap_prepare``\nDocumentation/filesystems/mmap_prepare.rst-47-callback rather than an ``mmap`` one, e.g. for ext4:\n--\nDocumentation/filesystems/mmap_prepare.rst-52-        ...\nDocumentation/filesystems/mmap_prepare.rst:53:        .mmap_prepare    = ext4_file_mmap_prepare,\nDocumentation/filesystems/mmap_prepare.rst-54-    };\nDocumentation/filesystems/mmap_prepare.rst-55-\nDocumentation/filesystems/mmap_prepare.rst:56:This has a signature of ``int (*mmap_prepare)(struct vm_area_desc *)``.\nDocumentation/filesystems/mmap_prepare.rst-57-\n--\nDocumentation/filesystems/mmap_prepare.rst=84=mapping, and you can update the mutable and writable fields, for instance:\n--\nDocumentation/filesystems/mmap_prepare.rst-87-\nDocumentation/filesystems/mmap_prepare.rst:88:    static int ext4_file_mmap_prepare(struct vm_area_desc *desc)\nDocumentation/filesystems/mmap_prepare.rst-89-    {\n--\nDocumentation/filesystems/mmap_prepare.rst=111=VMA Flags\n--\nDocumentation/filesystems/mmap_prepare.rst-113-\nDocumentation/filesystems/mmap_prepare.rst:114:Along with ``mmap_prepare``, VMA flags have undergone an overhaul. Where before\nDocumentation/filesystems/mmap_prepare.rst-115-you would invoke one of vm_flags_init(), vm_flags_reset(), vm_flags_set(),\n--\nDocumentation/filesystems/mmap_prepare.rst=120=etc. - i.e. using a ``-VM_xxx``- macro has changed too.\nDocumentation/filesystems/mmap_prepare.rst-121-\nDocumentation/filesystems/mmap_prepare.rst:122:When implementing mmap_prepare(), reference flags by their bit number, defined\nDocumentation/filesystems/mmap_prepare.rst-123-as a ``VMA_xxx_BIT`` macro, e.g. ``VMA_READ_BIT``, ``VMA_WRITE_BIT`` etc.,\n--\nDocumentation/filesystems/porting.rst=1278=The file operations mmap() callback is deprecated in favour of\nDocumentation/filesystems/porting.rst:1279:mmap_prepare(). This passes a pointer to a vm_area_desc to the callback\nDocumentation/filesystems/porting.rst-1280-rather than a VMA, as the VMA at this stage is not yet valid.\n--\nDocumentation/filesystems/vfs.rst=996=This describes how the VFS can manipulate an open file.  As of kernel\n--\nDocumentation/filesystems/vfs.rst-1043-\t\t\t\t\tunsigned int poll_flags);\nDocumentation/filesystems/vfs.rst:1044:\t\tint (*mmap_prepare)(struct vm_area_desc *);\nDocumentation/filesystems/vfs.rst-1045-\t};\n--\nDocumentation/filesystems/vfs.rst=1048=otherwise noted.\n--\nDocumentation/filesystems/vfs.rst-1084-\tcalled by the mmap(2) system call. Deprecated in favour of\nDocumentation/filesystems/vfs.rst:1085:\t``mmap_prepare``.\nDocumentation/filesystems/vfs.rst-1086-\n--\nDocumentation/filesystems/vfs.rst-1164-\nDocumentation/filesystems/vfs.rst:1165:``mmap_prepare``\nDocumentation/filesystems/vfs.rst-1166-\tCalled by the mmap(2) system call. Allows a VFS to set up a\n--\nblock/fops.c=845=static long blkdev_fallocate(struct file *file, int mode, loff_t start,\n--\nblock/fops.c-918-\nblock/fops.c:919:static int blkdev_mmap_prepare(struct vm_area_desc *desc)\nblock/fops.c-920-{\n--\nblock/fops.c-923-\tif (bdev_read_only(I_BDEV(bdev_file_inode(file))))\nblock/fops.c:924:\t\treturn generic_file_readonly_mmap_prepare(desc);\nblock/fops.c-925-\nblock/fops.c:926:\treturn generic_file_mmap_prepare(desc);\nblock/fops.c-927-}\n--\nblock/fops.c=929=const struct file_operations def_blk_fops = {\n--\nblock/fops.c-935-\t.iopoll\t\t= iocb_bio_iopoll,\nblock/fops.c:936:\t.mmap_prepare\t= blkdev_mmap_prepare,\nblock/fops.c-937-\t.fsync\t\t= blkdev_fsync,\n--\ndrivers/char/hpet.c=356=__setup(\"hpet_mmap=\", hpet_mmap_enable);\ndrivers/char/hpet.c-357-\ndrivers/char/hpet.c:358:static int hpet_mmap_prepare(struct vm_area_desc *desc)\ndrivers/char/hpet.c-359-{\n--\ndrivers/char/hpet.c-377-#else\ndrivers/char/hpet.c:378:static int hpet_mmap_prepare(struct vm_area_desc *desc)\ndrivers/char/hpet.c-379-{\n--\ndrivers/char/hpet.c=705=static const struct file_operations hpet_fops = {\n--\ndrivers/char/hpet.c-715-\t.fasync = hpet_fasync,\ndrivers/char/hpet.c:716:\t.mmap_prepare = hpet_mmap_prepare,\ndrivers/char/hpet.c-717-};\n--\ndrivers/char/mem.c=634=static const struct file_operations __maybe_unused mem_fops = {\n--\ndrivers/char/mem.c-637-\t.write\t\t= write_mem,\ndrivers/char/mem.c:638:\t.mmap_prepare\t= mmap_mem_prepare,\ndrivers/char/mem.c-639-\t.open\t\t= open_mem,\n--\ndrivers/char/mem.c=666=static const struct file_operations zero_fops = {\n--\ndrivers/char/mem.c-673-\t.splice_write\t= splice_write_zero,\ndrivers/char/mem.c:674:\t.mmap_prepare\t= mmap_zero_prepare,\ndrivers/char/mem.c-675-\t.get_unmapped_area = get_unmapped_area_zero,\n--\ndrivers/dax/device.c=266=static const struct vm_operations_struct dax_vm_ops = {\n--\ndrivers/dax/device.c-272-\ndrivers/dax/device.c:273:static int dax_mmap_prepare(struct vm_area_desc *desc)\ndrivers/dax/device.c-274-{\n--\ndrivers/dax/device.c=360=static const struct file_operations dax_fops = {\n--\ndrivers/dax/device.c-365-\t.get_unmapped_area = dax_get_unmapped_area,\ndrivers/dax/device.c:366:\t.mmap_prepare = dax_mmap_prepare,\ndrivers/dax/device.c-367-\t.fop_flags = FOP_MMAP_SYNC,\n--\ndrivers/hv/hyperv_vmbus.h=550=int hv_create_ring_sysfs(struct vmbus_channel *channel,\ndrivers/hv/hyperv_vmbus.h:551:\t\t\t int (*hv_mmap_prepare_ring_buffer)(struct vmbus_channel *channel,\ndrivers/hv/hyperv_vmbus.h-552-\t\t\t\t\t\t\t    struct vm_area_desc *desc));\n--\ndrivers/hv/vmbus_drv.c=1926=static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,\n--\ndrivers/hv/vmbus_drv.c-1936-\t * hv_(create|remove)_ring_sysfs implementation ensures that\ndrivers/hv/vmbus_drv.c:1937:\t * mmap_prepare_ring_buffer is not NULL.\ndrivers/hv/vmbus_drv.c-1938-\t */\ndrivers/hv/vmbus_drv.c-1939-\tcompat_set_desc_from_vma(\u0026desc, filp, vma);\ndrivers/hv/vmbus_drv.c:1940:\terr = channel-\u003emmap_prepare_ring_buffer(channel, \u0026desc);\ndrivers/hv/vmbus_drv.c-1941-\tif (err)\n--\ndrivers/hv/vmbus_drv.c=2074=static const struct kobj_type vmbus_chan_ktype = {\n--\ndrivers/hv/vmbus_drv.c-2081- * @channel: Pointer to vmbus_channel structure\ndrivers/hv/vmbus_drv.c:2082: * @hv_mmap_prepare_ring_buffer: function pointer for initializing the function to be called on mmap\ndrivers/hv/vmbus_drv.c-2083- *                       channel's \"ring\" sysfs node, which is for the ring buffer of that channel.\ndrivers/hv/vmbus_drv.c-2084- *                       Function pointer is of below type:\ndrivers/hv/vmbus_drv.c:2085: *                       int (*hv_mmap_prepare_ring_buffer)(struct vmbus_channel *channel,\ndrivers/hv/vmbus_drv.c-2086- *                                                          struct vm_area_desc *desc))\ndrivers/hv/vmbus_drv.c-2087- *                       This has a pointer to the channel and a pointer to vm_area_desc,\ndrivers/hv/vmbus_drv.c:2088: *                       used for mmap_prepare, as arguments.\ndrivers/hv/vmbus_drv.c-2089- *\n--\ndrivers/hv/vmbus_drv.c=2104=int hv_create_ring_sysfs(struct vmbus_channel *channel,\ndrivers/hv/vmbus_drv.c:2105:\t\t\t int (*hv_mmap_prepare_ring_buffer)(struct vmbus_channel *channel,\ndrivers/hv/vmbus_drv.c-2106-\t\t\t\t\t\t\t    struct vm_area_desc *desc))\n--\ndrivers/hv/vmbus_drv.c-2109-\ndrivers/hv/vmbus_drv.c:2110:\tchannel-\u003emmap_prepare_ring_buffer = hv_mmap_prepare_ring_buffer;\ndrivers/hv/vmbus_drv.c-2111-\tchannel-\u003ering_sysfs_visible = true;\n--\ndrivers/hv/vmbus_drv.c=2125=int hv_remove_ring_sysfs(struct vmbus_channel *channel)\n--\ndrivers/hv/vmbus_drv.c-2131-\tret = sysfs_update_group(kobj, \u0026vmbus_chan_group);\ndrivers/hv/vmbus_drv.c:2132:\tchannel-\u003emmap_prepare_ring_buffer = NULL;\ndrivers/hv/vmbus_drv.c-2133-\treturn ret;\n--\ndrivers/hv/vmbus_mmap_test.c=52=vmbus_mmap_test_context(struct kunit *test)\n--\ndrivers/hv/vmbus_mmap_test.c-67-\t\treturn NULL;\ndrivers/hv/vmbus_mmap_test.c:68:\tctx-\u003echannel.mmap_prepare_ring_buffer = vmbus_mmap_test_prepare;\ndrivers/hv/vmbus_mmap_test.c-69-\tctx-\u003echannel.ringbuffer.pages = ctx-\u003epages;\n--\ndrivers/hwtracing/stm/core.c=696=static const struct vm_operations_struct stm_mmap_vmops = {\n--\ndrivers/hwtracing/stm/core.c-701-\ndrivers/hwtracing/stm/core.c:702:static int stm_char_mmap_prepare(struct vm_area_desc *desc)\ndrivers/hwtracing/stm/core.c-703-{\n--\ndrivers/hwtracing/stm/core.c=846=static const struct file_operations stm_fops = {\n--\ndrivers/hwtracing/stm/core.c-849-\t.write\t\t= stm_char_write,\ndrivers/hwtracing/stm/core.c:850:\t.mmap_prepare\t= stm_char_mmap_prepare,\ndrivers/hwtracing/stm/core.c-851-\t.unlocked_ioctl\t= stm_char_ioctl,\n--\ndrivers/misc/open-dice.c=79=static ssize_t open_dice_write(struct file *filp, const char __user *ptr,\n--\ndrivers/misc/open-dice.c-91- */\ndrivers/misc/open-dice.c:92:static int open_dice_mmap_prepare(struct vm_area_desc *desc)\n\n"
}

5/2 2026/10/07 21:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 88029
							output: 29
							thoughts: 38
						

Thoughts:
Okay, here's my take on those thoughts, framed as an expert's internal monologue:

**Investigating UIO's `mmap_prepare` Usage**

Alright, I need to get a handle on which UIO drivers are utilizing the `info->mmap_prepare` function pointer. This is a common pattern, but I need to quickly refresh my understanding of *how* these specific drivers are leveraging it. The goal is to get a picture of the overall architecture of how memory mapping is being managed within the User-space I/O framework. I can't just rely on memory; a quick grep through the `drivers/uio` directory is the most direct way to pinpoint those instances. Let's get to it. Time to run a quick search and see what we find.



6/2 2026/10/07 21:53 tool grepper
0m Args:
{
  "Expression": "mmap_prepare",
  "PathPrefixes": [
    "drivers/uio"
  ]
}

Results:
{
  "Output": "drivers/uio/uio.c=820=static int uio_mmap(struct file *filep, struct vm_area_struct *vma)\n--\ndrivers/uio/uio.c-852-\ndrivers/uio/uio.c:853:\tif (idev-\u003einfo-\u003emmap_prepare) {\ndrivers/uio/uio.c-854-\t\tstruct vm_area_desc desc;\n--\ndrivers/uio/uio.c-856-\t\tcompat_set_desc_from_vma(\u0026desc, filep, vma);\ndrivers/uio/uio.c:857:\t\tret = idev-\u003einfo-\u003emmap_prepare(idev-\u003einfo, \u0026desc);\ndrivers/uio/uio.c-858-\t\tif (ret)\n--\ndrivers/uio/uio.c-869-\t\t * close() must be safe to call without a prior mapped() when\ndrivers/uio/uio.c:870:\t\t * it tears down state mmap_prepare() installed. Drivers that\ndrivers/uio/uio.c-871-\t\t * leave vm_ops alone have nothing to tear down here.\n--\ndrivers/uio/uio_hv_generic.c=142=static int hv_uio_mmap_get_region(struct hv_uio_private_data *pdata,\n--\ndrivers/uio/uio_hv_generic.c-195-\ndrivers/uio/uio_hv_generic.c:196:static int hv_uio_mmap_prepare_pages(struct vm_area_desc *desc,\ndrivers/uio/uio_hv_generic.c-197-\t\t\t\t     struct page **pages,\n--\ndrivers/uio/uio_hv_generic.c=298=static int hv_uio_pin_install(struct vm_area_desc *desc,\n--\ndrivers/uio/uio_hv_generic.c-318-\ndrivers/uio/uio_hv_generic.c:319:static int hv_uio_mmap_prepare(struct uio_info *info,\ndrivers/uio/uio_hv_generic.c-320-\t\t\t       struct vm_area_desc *desc)\n--\ndrivers/uio/uio_hv_generic.c-358-\ndrivers/uio/uio_hv_generic.c:359:\tret = hv_uio_mmap_prepare_pages(desc, pages, page_count, 0, decrypted);\ndrivers/uio/uio_hv_generic.c-360-\tif (ret) {\n--\ndrivers/uio/uio_hv_generic.c=372=static int\ndrivers/uio/uio_hv_generic.c:373:hv_uio_ring_mmap_prepare(struct vmbus_channel *channel,\ndrivers/uio/uio_hv_generic.c-374-\t\t\t struct vm_area_desc *desc)\n--\ndrivers/uio/uio_hv_generic.c-393-\ndrivers/uio/uio_hv_generic.c:394:\tret = hv_uio_mmap_prepare_pages(desc, pin-\u003epages, pin-\u003epage_count,\ndrivers/uio/uio_hv_generic.c-395-\t\t\t\t\toffset, pin-\u003edecrypted);\n--\ndrivers/uio/uio_hv_generic.c=433=hv_uio_new_channel(struct vmbus_channel *new_sc)\n--\ndrivers/uio/uio_hv_generic.c-448-\tset_channel_read_mode(new_sc, HV_CALL_ISR);\ndrivers/uio/uio_hv_generic.c:449:\tret = hv_create_ring_sysfs(new_sc, hv_uio_ring_mmap_prepare);\ndrivers/uio/uio_hv_generic.c-450-\tif (ret) {\n--\ndrivers/uio/uio_hv_generic.c=507=hv_uio_probe(struct hv_device *dev,\n--\ndrivers/uio/uio_hv_generic.c-535-\tpdata-\u003einfo.irqcontrol = hv_uio_irqcontrol;\ndrivers/uio/uio_hv_generic.c:536:\tpdata-\u003einfo.mmap_prepare = hv_uio_mmap_prepare;\ndrivers/uio/uio_hv_generic.c-537-\tpdata-\u003einfo.open = hv_uio_open;\n--\ndrivers/uio/uio_hv_generic.c-621-\t */\ndrivers/uio/uio_hv_generic.c:622:\thv_create_ring_sysfs(channel, hv_uio_ring_mmap_prepare);\ndrivers/uio/uio_hv_generic.c-623-\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=28=static void hv_uio_ring_mmap_range_test(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-38-\ndrivers/uio/uio_hv_generic_mmap_test.c:39:static void hv_uio_ring_mmap_prepare_test(struct kunit *test)\ndrivers/uio/uio_hv_generic_mmap_test.c-40-{\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-67-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\ndrivers/uio/uio_hv_generic_mmap_test.c:68:\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-69-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-90-\tdesc.vma_flags = EMPTY_VMA_FLAGS;\ndrivers/uio/uio_hv_generic_mmap_test.c:91:\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\ndrivers/uio/uio_hv_generic_mmap_test.c-92-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-96-\tdesc.pgoff = 7;\ndrivers/uio/uio_hv_generic_mmap_test.c:97:\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\ndrivers/uio/uio_hv_generic_mmap_test.c-98-\ndrivers/uio/uio_hv_generic_mmap_test.c-99-\tchannel.state = CHANNEL_OPEN_STATE;\ndrivers/uio/uio_hv_generic_mmap_test.c:100:\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -ENODEV);\ndrivers/uio/uio_hv_generic_mmap_test.c-101-\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=106=static void hv_uio_mmap_region_select_test(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-190-\ndrivers/uio/uio_hv_generic_mmap_test.c:191:static void hv_uio_mmap_prepare_test(struct kunit *test)\ndrivers/uio/uio_hv_generic_mmap_test.c-192-{\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-226-\ndrivers/uio/uio_hv_generic_mmap_test.c:227:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-228-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-253-\tdesc.vma_flags = EMPTY_VMA_FLAGS;\ndrivers/uio/uio_hv_generic_mmap_test.c:254:\tKUNIT_EXPECT_EQ(test, hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc), -EINVAL);\ndrivers/uio/uio_hv_generic_mmap_test.c-255-\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-261-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\ndrivers/uio/uio_hv_generic_mmap_test.c:262:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-263-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-274-\tdesc.page_prot = PAGE_SHARED;\ndrivers/uio/uio_hv_generic_mmap_test.c:275:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-276-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-288-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\ndrivers/uio/uio_hv_generic_mmap_test.c:289:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-290-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-303- * The reclaim race this driver closes is a lifetime question: the pin has\ndrivers/uio/uio_hv_generic_mmap_test.c:304: * to span the gap between mmap_prepare() returning and insert_pages()\ndrivers/uio/uio_hv_generic_mmap_test.c-305- * taking its own folio references. Dropping it inside the prepare hook\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=311=static void hv_uio_pin_lifetime_test(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-346-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\ndrivers/uio/uio_hv_generic_mmap_test.c:347:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-348-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=386=static void hv_uio_pin_close_before_mapped_test(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-421-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\ndrivers/uio/uio_hv_generic_mmap_test.c:422:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-423-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=456=static void sysfs_ring_mmap_ops_have_no_close(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-480-\ndrivers/uio/uio_hv_generic_mmap_test.c:481:\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-482-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=499=static void uio_buffer_mmap_success(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-533-\tvma_desc_set_flags(\u0026desc, VMA_SHARED_BIT);\ndrivers/uio/uio_hv_generic_mmap_test.c:534:\tret = hv_uio_mmap_prepare(\u0026pdata-\u003einfo, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-535-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-558- */\ndrivers/uio/uio_hv_generic_mmap_test.c:559:static void sysfs_mmap_prepare_failure_releases_pin(struct kunit *test)\ndrivers/uio/uio_hv_generic_mmap_test.c-560-{\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-584-\t/* Not shared: refused before anything is pinned. */\ndrivers/uio/uio_hv_generic_mmap_test.c:585:\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\ndrivers/uio/uio_hv_generic_mmap_test.c-586-\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-591-\tdesc.pgoff = 2;\ndrivers/uio/uio_hv_generic_mmap_test.c:592:\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -EINVAL);\ndrivers/uio/uio_hv_generic_mmap_test.c-593-\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-598-\tchannel.state = CHANNEL_OPEN_STATE;\ndrivers/uio/uio_hv_generic_mmap_test.c:599:\tKUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc), -ENODEV);\ndrivers/uio/uio_hv_generic_mmap_test.c-600-\tfor (i = 0; i \u003c ARRAY_SIZE(pages); i++)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=615=static void sysfs_mmap_partial_insert_failure_releases_pin(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-642-\ndrivers/uio/uio_hv_generic_mmap_test.c:643:\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-644-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=666=static void sysfs_mmap_release_during_insert_keeps_pages_alive(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-693-\ndrivers/uio/uio_hv_generic_mmap_test.c:694:\tret = hv_uio_ring_mmap_prepare(\u0026channel, \u0026desc);\ndrivers/uio/uio_hv_generic_mmap_test.c-695-\tKUNIT_ASSERT_EQ(test, ret, 0);\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=852=static struct kunit_case hv_uio_ring_mmap_test_cases[] = {\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-855-\tKUNIT_CASE(hv_uio_ring_mmap_range_test),\ndrivers/uio/uio_hv_generic_mmap_test.c:856:\tKUNIT_CASE(hv_uio_ring_mmap_prepare_test),\ndrivers/uio/uio_hv_generic_mmap_test.c-857-\tKUNIT_CASE(hv_uio_mmap_region_select_test),\ndrivers/uio/uio_hv_generic_mmap_test.c:858:\tKUNIT_CASE(hv_uio_mmap_prepare_test),\ndrivers/uio/uio_hv_generic_mmap_test.c-859-\tKUNIT_CASE(hv_uio_pin_lifetime_test),\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-862-\tKUNIT_CASE(uio_buffer_mmap_success),\ndrivers/uio/uio_hv_generic_mmap_test.c:863:\tKUNIT_CASE(sysfs_mmap_prepare_failure_releases_pin),\ndrivers/uio/uio_hv_generic_mmap_test.c-864-\tKUNIT_CASE(sysfs_mmap_partial_insert_failure_releases_pin),\n"
}

7/2 2026/10/07 21:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 92901
							output: 19
							thoughts: 95
						

Thoughts:
Okay, let's break this down.

**Investigating UIO's mmap_prepare Usage**

Right, so I'm looking at `uio_hv_generic.c` specifically. My immediate thought is, isn't that the *only* UIO driver implementing `mmap_prepare`? Feels odd if it is isolated like that. Let me confirm that suspicion by quickly checking for other instances of `mmap_prepare` within the `drivers/uio` directory. Okay, *just* `uio_hv_generic.c`? That seems unlikely, especially considering the UIO framework's purpose. I need to broaden the scope here. Hmm, what about other drivers *outside* the `drivers/uio` directory that might leverage UIO? Right, I need a global search. I'll grep the entire tree for `\.mmap_prepare` to be absolutely sure. This should give me a complete picture of its usage.



8/2 2026/10/07 21:53 tool grepper
0m Args:
{
  "Expression": "\\.mmap_prepare"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 437 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (61 files in total):\nDocumentation/filesystems/mmap_prepare.rst:1\nblock/fops.c:1\ndrivers/char/hpet.c:1\ndrivers/char/mem.c:2\ndrivers/dax/device.c:1\ndrivers/hv/vmbus_mmap_test.c:1\ndrivers/hwtracing/stm/core.c:1\ndrivers/misc/open-dice.c:1\ndrivers/mtd/mtdchar.c:1\ndrivers/staging/vme_user/vme_user.c:1\ndrivers/uio/uio_hv_generic.c:1\nfs/9p/vfs_file.c:2\nfs/adfs/file.c:1\nfs/affs/file.c:1\nfs/afs/file.c:1\nfs/aio.c:1\nfs/bfs/file.c:1\nfs/btrfs/file.c:1\nfs/ceph/file.c:1\nfs/erofs/data.c:1\nfs/exfat/file.c:1\nfs/ext2/file.c:1\nfs/ext4/file.c:1\nfs/f2fs/file.c:1\nfs/fat/file.c:1\nfs/hfs/inode.c:1\nfs/hfsplus/inode.c:1\nfs/hostfs/hostfs_kern.c:1\nfs/hpfs/file.c:1\nfs/jffs2/file.c:1\nfs/jfs/file.c:1\nfs/minix/file.c:1\nfs/nfs/file.c:1\nfs/nfs/nfs4file.c:1\nfs/nilfs2/file.c:1\nfs/ntfs/file.c:1\nfs/ntfs3/file.c:1\nfs/ocfs2/file.c:2\nfs/omfs/file.c:1\nfs/orangefs/file.c:1\nfs/ramfs/file-mmu.c:1\nfs/ramfs/file-nommu.c:1\nfs/read_write.c:1\nfs/resctrl/pseudo_lock.c:1\nfs/romfs/mmap-nommu.c:1\nfs/smb/client/cifsfs.c:6\nfs/squashfs/file.c:1\nfs/ubifs/file.c:1\nfs/ufs/file.c:1\nfs/vboxsf/file.c:1\n... and 11 more files\n\nDocumentation/filesystems/mmap_prepare.rst=47=callback rather than an ``mmap`` one, e.g. for ext4:\n--\nDocumentation/filesystems/mmap_prepare.rst-52-        ...\nDocumentation/filesystems/mmap_prepare.rst:53:        .mmap_prepare    = ext4_file_mmap_prepare,\nDocumentation/filesystems/mmap_prepare.rst-54-    };\n--\nblock/fops.c=929=const struct file_operations def_blk_fops = {\n--\nblock/fops.c-935-\t.iopoll\t\t= iocb_bio_iopoll,\nblock/fops.c:936:\t.mmap_prepare\t= blkdev_mmap_prepare,\nblock/fops.c-937-\t.fsync\t\t= blkdev_fsync,\n--\ndrivers/char/hpet.c=705=static const struct file_operations hpet_fops = {\n--\ndrivers/char/hpet.c-715-\t.fasync = hpet_fasync,\ndrivers/char/hpet.c:716:\t.mmap_prepare = hpet_mmap_prepare,\ndrivers/char/hpet.c-717-};\n--\ndrivers/char/mem.c=634=static const struct file_operations __maybe_unused mem_fops = {\n--\ndrivers/char/mem.c-637-\t.write\t\t= write_mem,\ndrivers/char/mem.c:638:\t.mmap_prepare\t= mmap_mem_prepare,\ndrivers/char/mem.c-639-\t.open\t\t= open_mem,\n--\ndrivers/char/mem.c=666=static const struct file_operations zero_fops = {\n--\ndrivers/char/mem.c-673-\t.splice_write\t= splice_write_zero,\ndrivers/char/mem.c:674:\t.mmap_prepare\t= mmap_zero_prepare,\ndrivers/char/mem.c-675-\t.get_unmapped_area = get_unmapped_area_zero,\n--\ndrivers/dax/device.c=360=static const struct file_operations dax_fops = {\n--\ndrivers/dax/device.c-365-\t.get_unmapped_area = dax_get_unmapped_area,\ndrivers/dax/device.c:366:\t.mmap_prepare = dax_mmap_prepare,\ndrivers/dax/device.c-367-\t.fop_flags = FOP_MMAP_SYNC,\n--\ndrivers/hv/vmbus_mmap_test.c=52=vmbus_mmap_test_context(struct kunit *test)\n--\ndrivers/hv/vmbus_mmap_test.c-67-\t\treturn NULL;\ndrivers/hv/vmbus_mmap_test.c:68:\tctx-\u003echannel.mmap_prepare_ring_buffer = vmbus_mmap_test_prepare;\ndrivers/hv/vmbus_mmap_test.c-69-\tctx-\u003echannel.ringbuffer.pages = ctx-\u003epages;\n--\ndrivers/hwtracing/stm/core.c=846=static const struct file_operations stm_fops = {\n--\ndrivers/hwtracing/stm/core.c-849-\t.write\t\t= stm_char_write,\ndrivers/hwtracing/stm/core.c:850:\t.mmap_prepare\t= stm_char_mmap_prepare,\ndrivers/hwtracing/stm/core.c-851-\t.unlocked_ioctl\t= stm_char_ioctl,\n--\ndrivers/misc/open-dice.c=113=static const struct file_operations open_dice_fops = {\n--\ndrivers/misc/open-dice.c-116-\t.write = open_dice_write,\ndrivers/misc/open-dice.c:117:\t.mmap_prepare = open_dice_mmap_prepare,\ndrivers/misc/open-dice.c-118-};\n--\ndrivers/mtd/mtdchar.c=1388=static const struct file_operations mtd_fops = {\n--\ndrivers/mtd/mtdchar.c-1398-\t.release\t= mtdchar_close,\ndrivers/mtd/mtdchar.c:1399:\t.mmap_prepare\t= mtdchar_mmap_prepare,\ndrivers/mtd/mtdchar.c-1400-#ifndef CONFIG_MMU\n--\ndrivers/staging/vme_user/vme_user.c=526=static const struct file_operations vme_user_fops = {\n--\ndrivers/staging/vme_user/vme_user.c-531-\t.compat_ioctl = compat_ptr_ioctl,\ndrivers/staging/vme_user/vme_user.c:532:\t.mmap_prepare = vme_user_mmap_prepare,\ndrivers/staging/vme_user/vme_user.c-533-};\n--\ndrivers/uio/uio_hv_generic.c=507=hv_uio_probe(struct hv_device *dev,\n--\ndrivers/uio/uio_hv_generic.c-535-\tpdata-\u003einfo.irqcontrol = hv_uio_irqcontrol;\ndrivers/uio/uio_hv_generic.c:536:\tpdata-\u003einfo.mmap_prepare = hv_uio_mmap_prepare;\ndrivers/uio/uio_hv_generic.c-537-\tpdata-\u003einfo.open = hv_uio_open;\n--\nfs/9p/vfs_file.c=509=const struct file_operations v9fs_file_operations = {\n--\nfs/9p/vfs_file.c-515-\t.lock = v9fs_file_lock,\nfs/9p/vfs_file.c:516:\t.mmap_prepare = generic_file_readonly_mmap_prepare,\nfs/9p/vfs_file.c-517-\t.splice_read = v9fs_file_splice_read,\n--\nfs/9p/vfs_file.c=522=const struct file_operations v9fs_file_operations_dotl = {\n--\nfs/9p/vfs_file.c-529-\t.flock = v9fs_file_flock_dotl,\nfs/9p/vfs_file.c:530:\t.mmap_prepare = v9fs_file_mmap_prepare,\nfs/9p/vfs_file.c-531-\t.splice_read = v9fs_file_splice_read,\n--\nfs/adfs/file.c=25=const struct file_operations adfs_file_operations = {\n--\nfs/adfs/file.c-27-\t.read_iter\t= generic_file_read_iter,\nfs/adfs/file.c:28:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/adfs/file.c-29-\t.fsync\t\t= simple_fsync,\n--\nfs/affs/file.c=1003=const struct file_operations affs_file_operations = {\n--\nfs/affs/file.c-1006-\t.write_iter\t= generic_file_write_iter,\nfs/affs/file.c:1007:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/affs/file.c-1008-\t.open\t\t= affs_file_open,\n--\nfs/afs/file.c=34=const struct file_operations afs_file_operations = {\n--\nfs/afs/file.c-39-\t.write_iter\t= netfs_file_write_iter,\nfs/afs/file.c:40:\t.mmap_prepare\t= afs_file_mmap_prepare,\nfs/afs/file.c-41-\t.splice_read\t= afs_file_splice_read,\n--\nfs/aio.c=455=static const struct file_operations aio_ring_fops = {\nfs/aio.c:456:\t.mmap_prepare = aio_ring_mmap_prepare,\nfs/aio.c-457-};\n--\nfs/bfs/file.c=26=const struct file_operations bfs_file_operations = {\n--\nfs/bfs/file.c-29-\t.write_iter\t= generic_file_write_iter,\nfs/bfs/file.c:30:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/bfs/file.c-31-\t.splice_read\t= filemap_splice_read,\n--\nfs/btrfs/file.c=3819=const struct file_operations btrfs_file_operations = {\n--\nfs/btrfs/file.c-3824-\t.splice_write\t= iter_file_splice_write,\nfs/btrfs/file.c:3825:\t.mmap_prepare\t= btrfs_file_mmap_prepare,\nfs/btrfs/file.c-3826-\t.open\t\t= btrfs_file_open,\n--\nfs/ceph/file.c=3294=const struct file_operations ceph_file_fops = {\n--\nfs/ceph/file.c-3299-\t.write_iter = ceph_write_iter,\nfs/ceph/file.c:3300:\t.mmap_prepare = ceph_mmap_prepare,\nfs/ceph/file.c-3301-\t.fsync = ceph_fsync,\n--\nfs/erofs/data.c=523=const struct file_operations erofs_file_fops = {\n--\nfs/erofs/data.c-529-#endif\nfs/erofs/data.c:530:\t.mmap_prepare\t= erofs_file_mmap_prepare,\nfs/erofs/data.c-531-\t.get_unmapped_area = thp_get_unmapped_area,\n--\nfs/exfat/file.c=1062=const struct file_operations exfat_file_operations = {\n--\nfs/exfat/file.c-1070-#endif\nfs/exfat/file.c:1071:\t.mmap_prepare\t= exfat_file_mmap_prepare,\nfs/exfat/file.c-1072-\t.fsync\t\t= exfat_file_fsync,\n--\nfs/ext2/file.c=190=const struct file_operations ext2_file_operations = {\n--\nfs/ext2/file.c-197-#endif\nfs/ext2/file.c:198:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/ext2/file.c-199-\t.open\t\t= ext2_file_open,\n--\nfs/ext4/file.c=1035=const struct file_operations ext4_file_operations = {\n--\nfs/ext4/file.c-1043-#endif\nfs/ext4/file.c:1044:\t.mmap_prepare\t= ext4_file_mmap_prepare,\nfs/ext4/file.c-1045-\t.open\t\t= ext4_file_open,\n--\nfs/f2fs/file.c=5894=const struct file_operations f2fs_file_operations = {\n--\nfs/f2fs/file.c-5900-\t.release\t= f2fs_release_file,\nfs/f2fs/file.c:5901:\t.mmap_prepare\t= f2fs_file_mmap_prepare,\nfs/f2fs/file.c-5902-\t.flush\t\t= f2fs_file_flush,\n--\nfs/fat/file.c=205=const struct file_operations fat_file_operations = {\n--\nfs/fat/file.c-208-\t.write_iter\t= generic_file_write_iter,\nfs/fat/file.c:209:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/fat/file.c-210-\t.release\t= fat_file_release,\n--\nfs/hfs/inode.c=735=static const struct file_operations hfs_file_operations = {\n--\nfs/hfs/inode.c-738-\t.write_iter\t= generic_file_write_iter,\nfs/hfs/inode.c:739:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hfs/inode.c-740-\t.splice_read\t= filemap_splice_read,\n--\nfs/hfsplus/inode.c=465=static const struct file_operations hfsplus_file_operations = {\n--\nfs/hfsplus/inode.c-468-\t.write_iter\t= generic_file_write_iter,\nfs/hfsplus/inode.c:469:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hfsplus/inode.c-470-\t.splice_read\t= filemap_splice_read,\n--\nfs/hostfs/hostfs_kern.c=379=static const struct file_operations hostfs_file_fops = {\n--\nfs/hostfs/hostfs_kern.c-384-\t.write_iter\t= generic_file_write_iter,\nfs/hostfs/hostfs_kern.c:385:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hostfs/hostfs_kern.c-386-\t.open\t\t= hostfs_open,\n--\nfs/hpfs/file.c=259=const struct file_operations hpfs_file_ops =\n--\nfs/hpfs/file.c-263-\t.write_iter\t= generic_file_write_iter,\nfs/hpfs/file.c:264:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hpfs/file.c-265-\t.release\t= hpfs_file_release,\n--\nfs/jffs2/file.c=53=const struct file_operations jffs2_file_operations =\n--\nfs/jffs2/file.c-59-\t.unlocked_ioctl=jffs2_ioctl,\nfs/jffs2/file.c:60:\t.mmap_prepare =\tgeneric_file_readonly_mmap_prepare,\nfs/jffs2/file.c-61-\t.fsync =\tjffs2_fsync,\n--\nfs/jfs/file.c=145=const struct file_operations jfs_file_operations = {\n--\nfs/jfs/file.c-149-\t.write_iter\t= generic_file_write_iter,\nfs/jfs/file.c:150:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/jfs/file.c-151-\t.splice_read\t= filemap_splice_read,\n--\nfs/minix/file.c=17=const struct file_operations minix_file_operations = {\n--\nfs/minix/file.c-20-\t.write_iter\t= generic_file_write_iter,\nfs/minix/file.c:21:\t.mmap_prepare\t= generic_file_mmap_prepare,\n\n"
}

9/2 2026/10/07 21:53 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 97838
							output: 25
							thoughts: 511
						

Thoughts:
**UIO mmap Examination**

Okay, so I'm looking at `drivers/uio/uio.c` specifically the `uio_mmap` function. My initial thought is about the `mmap_prepare` hook. It seems that this `mmap_prepare` function pointer, if it's set in the `uio_info` structure, allows for some custom pre-mapping setup. This is intriguing.

I'm starting to think about whether this could be a potential attack vector or at least an area for fuzzing. Can UIO devices be routinely mmapped and opened in a standard fuzzing environment? I need to understand the typical context. I need to be thinking about QEMU or Google Compute Engine specifically. What kind of UIO devices will actually exist in those contexts?

My next question is whether `uio_hv_generic` is the only driver that actually *uses* this `mmap_prepare` functionality. I need to know if this is a common thing or something that is pretty uncommon.

I guess the best way to do that is to grep the kernel source for any other occurrences of this. So, time to check all instances of either `\.mmap_prepare\s*=` or `->mmap_prepare`. Let's see what turns up!



10/2 2026/10/07 21:54 tool grepper
0m Args:
{
  "Expression": "(-\u003e|\\.)mmap_prepare\\s*="
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 369 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (55 files in total):\nDocumentation/filesystems/mmap_prepare.rst:1\nblock/fops.c:1\ndrivers/char/hpet.c:1\ndrivers/char/mem.c:2\ndrivers/dax/device.c:1\ndrivers/hwtracing/stm/core.c:1\ndrivers/misc/open-dice.c:1\ndrivers/mtd/mtdchar.c:1\ndrivers/staging/vme_user/vme_user.c:1\ndrivers/target/target_core_user.c:1\ndrivers/uio/uio_hv_generic.c:1\nfs/9p/vfs_file.c:2\nfs/adfs/file.c:1\nfs/affs/file.c:1\nfs/afs/file.c:1\nfs/aio.c:1\nfs/bfs/file.c:1\nfs/btrfs/file.c:1\nfs/ceph/file.c:1\nfs/erofs/data.c:1\nfs/exfat/file.c:1\nfs/ext2/file.c:1\nfs/ext4/file.c:1\nfs/f2fs/file.c:1\nfs/fat/file.c:1\nfs/hfs/inode.c:1\nfs/hfsplus/inode.c:1\nfs/hostfs/hostfs_kern.c:1\nfs/hpfs/file.c:1\nfs/jffs2/file.c:1\nfs/jfs/file.c:1\nfs/minix/file.c:1\nfs/nfs/file.c:1\nfs/nfs/nfs4file.c:1\nfs/nilfs2/file.c:1\nfs/ntfs/file.c:1\nfs/ntfs3/file.c:1\nfs/ocfs2/file.c:2\nfs/omfs/file.c:1\nfs/orangefs/file.c:1\nfs/ramfs/file-mmu.c:1\nfs/ramfs/file-nommu.c:1\nfs/read_write.c:1\nfs/resctrl/pseudo_lock.c:1\nfs/romfs/mmap-nommu.c:1\nfs/smb/client/cifsfs.c:6\nfs/squashfs/file.c:1\nfs/ubifs/file.c:1\nfs/ufs/file.c:1\nfs/vboxsf/file.c:1\n... and 5 more files\n\nDocumentation/filesystems/mmap_prepare.rst=47=callback rather than an ``mmap`` one, e.g. for ext4:\n--\nDocumentation/filesystems/mmap_prepare.rst-52-        ...\nDocumentation/filesystems/mmap_prepare.rst:53:        .mmap_prepare    = ext4_file_mmap_prepare,\nDocumentation/filesystems/mmap_prepare.rst-54-    };\n--\nblock/fops.c=929=const struct file_operations def_blk_fops = {\n--\nblock/fops.c-935-\t.iopoll\t\t= iocb_bio_iopoll,\nblock/fops.c:936:\t.mmap_prepare\t= blkdev_mmap_prepare,\nblock/fops.c-937-\t.fsync\t\t= blkdev_fsync,\n--\ndrivers/char/hpet.c=705=static const struct file_operations hpet_fops = {\n--\ndrivers/char/hpet.c-715-\t.fasync = hpet_fasync,\ndrivers/char/hpet.c:716:\t.mmap_prepare = hpet_mmap_prepare,\ndrivers/char/hpet.c-717-};\n--\ndrivers/char/mem.c=634=static const struct file_operations __maybe_unused mem_fops = {\n--\ndrivers/char/mem.c-637-\t.write\t\t= write_mem,\ndrivers/char/mem.c:638:\t.mmap_prepare\t= mmap_mem_prepare,\ndrivers/char/mem.c-639-\t.open\t\t= open_mem,\n--\ndrivers/char/mem.c=666=static const struct file_operations zero_fops = {\n--\ndrivers/char/mem.c-673-\t.splice_write\t= splice_write_zero,\ndrivers/char/mem.c:674:\t.mmap_prepare\t= mmap_zero_prepare,\ndrivers/char/mem.c-675-\t.get_unmapped_area = get_unmapped_area_zero,\n--\ndrivers/dax/device.c=360=static const struct file_operations dax_fops = {\n--\ndrivers/dax/device.c-365-\t.get_unmapped_area = dax_get_unmapped_area,\ndrivers/dax/device.c:366:\t.mmap_prepare = dax_mmap_prepare,\ndrivers/dax/device.c-367-\t.fop_flags = FOP_MMAP_SYNC,\n--\ndrivers/hwtracing/stm/core.c=846=static const struct file_operations stm_fops = {\n--\ndrivers/hwtracing/stm/core.c-849-\t.write\t\t= stm_char_write,\ndrivers/hwtracing/stm/core.c:850:\t.mmap_prepare\t= stm_char_mmap_prepare,\ndrivers/hwtracing/stm/core.c-851-\t.unlocked_ioctl\t= stm_char_ioctl,\n--\ndrivers/misc/open-dice.c=113=static const struct file_operations open_dice_fops = {\n--\ndrivers/misc/open-dice.c-116-\t.write = open_dice_write,\ndrivers/misc/open-dice.c:117:\t.mmap_prepare = open_dice_mmap_prepare,\ndrivers/misc/open-dice.c-118-};\n--\ndrivers/mtd/mtdchar.c=1388=static const struct file_operations mtd_fops = {\n--\ndrivers/mtd/mtdchar.c-1398-\t.release\t= mtdchar_close,\ndrivers/mtd/mtdchar.c:1399:\t.mmap_prepare\t= mtdchar_mmap_prepare,\ndrivers/mtd/mtdchar.c-1400-#ifndef CONFIG_MMU\n--\ndrivers/staging/vme_user/vme_user.c=526=static const struct file_operations vme_user_fops = {\n--\ndrivers/staging/vme_user/vme_user.c-531-\t.compat_ioctl = compat_ptr_ioctl,\ndrivers/staging/vme_user/vme_user.c:532:\t.mmap_prepare = vme_user_mmap_prepare,\ndrivers/staging/vme_user/vme_user.c-533-};\n--\ndrivers/target/target_core_user.c=2207=static int tcmu_configure_device(struct se_device *dev)\n--\ndrivers/target/target_core_user.c-2265-\ndrivers/target/target_core_user.c:2266:\tinfo-\u003emmap_prepare = tcmu_mmap_prepare;\ndrivers/target/target_core_user.c-2267-\tinfo-\u003eopen = tcmu_open;\n--\ndrivers/uio/uio_hv_generic.c=507=hv_uio_probe(struct hv_device *dev,\n--\ndrivers/uio/uio_hv_generic.c-535-\tpdata-\u003einfo.irqcontrol = hv_uio_irqcontrol;\ndrivers/uio/uio_hv_generic.c:536:\tpdata-\u003einfo.mmap_prepare = hv_uio_mmap_prepare;\ndrivers/uio/uio_hv_generic.c-537-\tpdata-\u003einfo.open = hv_uio_open;\n--\nfs/9p/vfs_file.c=509=const struct file_operations v9fs_file_operations = {\n--\nfs/9p/vfs_file.c-515-\t.lock = v9fs_file_lock,\nfs/9p/vfs_file.c:516:\t.mmap_prepare = generic_file_readonly_mmap_prepare,\nfs/9p/vfs_file.c-517-\t.splice_read = v9fs_file_splice_read,\n--\nfs/9p/vfs_file.c=522=const struct file_operations v9fs_file_operations_dotl = {\n--\nfs/9p/vfs_file.c-529-\t.flock = v9fs_file_flock_dotl,\nfs/9p/vfs_file.c:530:\t.mmap_prepare = v9fs_file_mmap_prepare,\nfs/9p/vfs_file.c-531-\t.splice_read = v9fs_file_splice_read,\n--\nfs/adfs/file.c=25=const struct file_operations adfs_file_operations = {\n--\nfs/adfs/file.c-27-\t.read_iter\t= generic_file_read_iter,\nfs/adfs/file.c:28:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/adfs/file.c-29-\t.fsync\t\t= simple_fsync,\n--\nfs/affs/file.c=1003=const struct file_operations affs_file_operations = {\n--\nfs/affs/file.c-1006-\t.write_iter\t= generic_file_write_iter,\nfs/affs/file.c:1007:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/affs/file.c-1008-\t.open\t\t= affs_file_open,\n--\nfs/afs/file.c=34=const struct file_operations afs_file_operations = {\n--\nfs/afs/file.c-39-\t.write_iter\t= netfs_file_write_iter,\nfs/afs/file.c:40:\t.mmap_prepare\t= afs_file_mmap_prepare,\nfs/afs/file.c-41-\t.splice_read\t= afs_file_splice_read,\n--\nfs/aio.c=455=static const struct file_operations aio_ring_fops = {\nfs/aio.c:456:\t.mmap_prepare = aio_ring_mmap_prepare,\nfs/aio.c-457-};\n--\nfs/bfs/file.c=26=const struct file_operations bfs_file_operations = {\n--\nfs/bfs/file.c-29-\t.write_iter\t= generic_file_write_iter,\nfs/bfs/file.c:30:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/bfs/file.c-31-\t.splice_read\t= filemap_splice_read,\n--\nfs/btrfs/file.c=3819=const struct file_operations btrfs_file_operations = {\n--\nfs/btrfs/file.c-3824-\t.splice_write\t= iter_file_splice_write,\nfs/btrfs/file.c:3825:\t.mmap_prepare\t= btrfs_file_mmap_prepare,\nfs/btrfs/file.c-3826-\t.open\t\t= btrfs_file_open,\n--\nfs/ceph/file.c=3294=const struct file_operations ceph_file_fops = {\n--\nfs/ceph/file.c-3299-\t.write_iter = ceph_write_iter,\nfs/ceph/file.c:3300:\t.mmap_prepare = ceph_mmap_prepare,\nfs/ceph/file.c-3301-\t.fsync = ceph_fsync,\n--\nfs/erofs/data.c=523=const struct file_operations erofs_file_fops = {\n--\nfs/erofs/data.c-529-#endif\nfs/erofs/data.c:530:\t.mmap_prepare\t= erofs_file_mmap_prepare,\nfs/erofs/data.c-531-\t.get_unmapped_area = thp_get_unmapped_area,\n--\nfs/exfat/file.c=1062=const struct file_operations exfat_file_operations = {\n--\nfs/exfat/file.c-1070-#endif\nfs/exfat/file.c:1071:\t.mmap_prepare\t= exfat_file_mmap_prepare,\nfs/exfat/file.c-1072-\t.fsync\t\t= exfat_file_fsync,\n--\nfs/ext2/file.c=190=const struct file_operations ext2_file_operations = {\n--\nfs/ext2/file.c-197-#endif\nfs/ext2/file.c:198:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/ext2/file.c-199-\t.open\t\t= ext2_file_open,\n--\nfs/ext4/file.c=1035=const struct file_operations ext4_file_operations = {\n--\nfs/ext4/file.c-1043-#endif\nfs/ext4/file.c:1044:\t.mmap_prepare\t= ext4_file_mmap_prepare,\nfs/ext4/file.c-1045-\t.open\t\t= ext4_file_open,\n--\nfs/f2fs/file.c=5894=const struct file_operations f2fs_file_operations = {\n--\nfs/f2fs/file.c-5900-\t.release\t= f2fs_release_file,\nfs/f2fs/file.c:5901:\t.mmap_prepare\t= f2fs_file_mmap_prepare,\nfs/f2fs/file.c-5902-\t.flush\t\t= f2fs_file_flush,\n--\nfs/fat/file.c=205=const struct file_operations fat_file_operations = {\n--\nfs/fat/file.c-208-\t.write_iter\t= generic_file_write_iter,\nfs/fat/file.c:209:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/fat/file.c-210-\t.release\t= fat_file_release,\n--\nfs/hfs/inode.c=735=static const struct file_operations hfs_file_operations = {\n--\nfs/hfs/inode.c-738-\t.write_iter\t= generic_file_write_iter,\nfs/hfs/inode.c:739:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hfs/inode.c-740-\t.splice_read\t= filemap_splice_read,\n--\nfs/hfsplus/inode.c=465=static const struct file_operations hfsplus_file_operations = {\n--\nfs/hfsplus/inode.c-468-\t.write_iter\t= generic_file_write_iter,\nfs/hfsplus/inode.c:469:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hfsplus/inode.c-470-\t.splice_read\t= filemap_splice_read,\n--\nfs/hostfs/hostfs_kern.c=379=static const struct file_operations hostfs_file_fops = {\n--\nfs/hostfs/hostfs_kern.c-384-\t.write_iter\t= generic_file_write_iter,\nfs/hostfs/hostfs_kern.c:385:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hostfs/hostfs_kern.c-386-\t.open\t\t= hostfs_open,\n--\nfs/hpfs/file.c=259=const struct file_operations hpfs_file_ops =\n--\nfs/hpfs/file.c-263-\t.write_iter\t= generic_file_write_iter,\nfs/hpfs/file.c:264:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/hpfs/file.c-265-\t.release\t= hpfs_file_release,\n--\nfs/jffs2/file.c=53=const struct file_operations jffs2_file_operations =\n--\nfs/jffs2/file.c-59-\t.unlocked_ioctl=jffs2_ioctl,\nfs/jffs2/file.c:60:\t.mmap_prepare =\tgeneric_file_readonly_mmap_prepare,\nfs/jffs2/file.c-61-\t.fsync =\tjffs2_fsync,\n--\nfs/jfs/file.c=145=const struct file_operations jfs_file_operations = {\n--\nfs/jfs/file.c-149-\t.write_iter\t= generic_file_write_iter,\nfs/jfs/file.c:150:\t.mmap_prepare\t= generic_file_mmap_prepare,\nfs/jfs/file.c-151-\t.splice_read\t= filemap_splice_read,\n--\nfs/minix/file.c=17=const struct file_operations minix_file_operations = {\n--\nfs/minix/file.c-20-\t.write_iter\t= generic_file_write_iter,\nfs/minix/file.c:21:\t.mmap_prepare\t= generic_file_mmap_prepare,\n\n"
}

11/2 2026/10/07 21:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 103243
							output: 31
							thoughts: 55
						

Thoughts:
Here's my take on those thoughts:

**Analyzing `target_core_user.c` for `mmap` Implementation**

Okay, now *that's* interesting! My eyes just landed on something potentially important: the assignment within `drivers/target/target_core_user.c`. Specifically, I see `info->mmap_prepare = tcmu_mmap_prepare;`. My brain immediately starts running through possible implications. *This* looks like a key piece of the puzzle. I need to dive deeper into `drivers/target/target_core_user.c` right away, with a focus on how `tcmu_mmap_prepare` is being used and what the context around that assignment is within the TCMU framework. It looks like we've got a hook for `mmap`, and I need to figure out exactly how the user-space target code interacts with memory mapping. This has the potential to reveal a lot about performance, security implications and how this all fits into the bigger picture.



12/2 2026/10/07 21:54 tool grepper
0m Args:
{
  "Expression": "tcmu_mmap_prepare",
  "PathPrefixes": [
    "drivers/target"
  ]
}

Results:
{
  "Output": "drivers/target/target_core_user.c=1932=static const struct vm_operations_struct tcmu_vm_ops = {\n--\ndrivers/target/target_core_user.c-1938-\ndrivers/target/target_core_user.c:1939:static int tcmu_mmap_prepare(struct uio_info *info, struct vm_area_desc *desc)\ndrivers/target/target_core_user.c-1940-{\n--\ndrivers/target/target_core_user.c=2207=static int tcmu_configure_device(struct se_device *dev)\n--\ndrivers/target/target_core_user.c-2265-\ndrivers/target/target_core_user.c:2266:\tinfo-\u003emmap_prepare = tcmu_mmap_prepare;\ndrivers/target/target_core_user.c-2267-\tinfo-\u003eopen = tcmu_open;\n"
}

13/2 2026/10/07 21:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 103792
							output: 40
							thoughts: 65
						

Thoughts:
Here's my summary, as though I'm thinking through this process:

**Diving into the User-Space Target Code**

Okay, so I'm focusing on the user-space target implementation, specifically `drivers/target/target_core_user.c`. Right, that's where the UIO (User I/O) magic happens. I need to refresh my memory on the interactions here, especially because we're talking about the `tcmu_mmap_prepare` function.

I should really dig into the code around `tcmu_mmap_prepare` within `drivers/target/target_core_user.c`. That's where I need to start. I need to remind myself of the interplay between the UIO framework and the TCMU (Target Core Management Unit) user-space implementation. I need to understand what this `tcmu_mmap_prepare` function is doing in relation to memory mapping within this context, particularly how it affects data transfer and access. This will give me a base to go on.



14/2 2026/10/07 21:55 tool read-file
0m Args:
{
  "File": "drivers/target/target_core_user.c",
  "FirstLine": 1930,
  "LineCount": 40
}

Results:
{
  "Contents": "1930:\t}\n1931:\t\n1932:\tstatic const struct vm_operations_struct tcmu_vm_ops = {\n1933:\t\t.mapped = tcmu_vma_mapped,\n1934:\t\t.open = tcmu_vma_open,\n1935:\t\t.close = tcmu_vma_close,\n1936:\t\t.fault = tcmu_vma_fault,\n1937:\t};\n1938:\t\n1939:\tstatic int tcmu_mmap_prepare(struct uio_info *info, struct vm_area_desc *desc)\n1940:\t{\n1941:\t\tstruct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);\n1942:\t\n1943:\t\tvma_desc_set_flags(desc, VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT);\n1944:\t\tdesc-\u003evm_ops = \u0026tcmu_vm_ops;\n1945:\t\n1946:\t\tdesc-\u003eprivate_data = udev;\n1947:\t\n1948:\t\t/* Ensure the mmap is exactly the right size */\n1949:\t\tif (vma_desc_pages(desc) != udev-\u003emmap_pages)\n1950:\t\t\treturn -EINVAL;\n1951:\t\n1952:\t\treturn 0;\n1953:\t}\n1954:\t\n1955:\tstatic int tcmu_open(struct uio_info *info, struct inode *inode)\n1956:\t{\n1957:\t\tstruct tcmu_dev *udev = container_of(info, struct tcmu_dev, uio_info);\n1958:\t\n1959:\t\t/* O_EXCL not supported for char devs, so fake it? */\n1960:\t\tif (test_and_set_bit(TCMU_DEV_BIT_OPEN, \u0026udev-\u003eflags))\n1961:\t\t\treturn -EBUSY;\n1962:\t\n1963:\t\tudev-\u003einode = inode;\n1964:\t\n1965:\t\tpr_debug(\"open\\n\");\n1966:\t\n1967:\t\treturn 0;\n1968:\t}\n1969:\t\n"
}

15/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 104732
							output: 37
							thoughts: 516
						

Thoughts:
**Analyzing the VMA Lifecycle in UIO and TCMU**

Okay, let's break this down. My initial observation focuses on `tcmu_mmap_prepare`. I see it sets `desc->vm_ops = &tcmu_vm_ops;`, and crucially, `tcmu_vm_ops` includes `.close = tcmu_vma_close`. This immediately flags the potential for a custom close function to manage the Virtual Memory Area (VMA) lifecycle within TCMU.

Now, let's shift focus to `drivers/uio/uio.c` in the provided patch. The core of this patch seems to be about how the UIO framework interacts with the VMA.  Specifically, I need to understand what this patch changed in `uio_mmap` function.

I see that the patch includes a section related to installing per-VMA state before calling `__compat_vma_mmap()`. The comment is key here. It highlights a critical aspect of error handling. The patch aims to ensure that if `mmap_action_prepare()` fails, the `close()` function, if present, is still invoked. This prevents resource leaks and cleanup issues.

The patch includes the following code:
```c
		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;
```
This looks to have been added.  I need to go back and read the prior code, before this patch, to understand why these changes were needed.

The patch emphasizes that the `close()` function needs to be safe to call even if the VMA hasn't been fully mapped by `mmap_prepare()`, and that drivers that leave the `vm_ops` field unmodified won't have anything to do in `close()`.  This suggests a pattern where a `mmap_prepare()` might allocate resources and the `close()` function would free them in case of error. This makes sense. The code's comment indicates this is necessary because the legacy `.mmap` error path, which calls `__compat_vma_mmap`, releases the VMA without calling its `close()` routine.

The whole thing seems like a careful addition to address a subtle error handling issue in the UIO framework's interaction with driver-specific mmap implementations, like those used by TCMU. The patch ensures that even if something goes wrong in the VMA setup, the driver gets a chance to clean up resources, preventing leaks. I need to keep reading, to confirm this assessment.



16/2 2026/10/07 21:55 tool read-file
0m Args:
{
  "File": "drivers/uio/uio.c",
  "FirstLine": 845,
  "LineCount": 45
}

Results:
{
  "Contents": " 845:\t\trequested_pages = vma_pages(vma);\n 846:\t\tactual_pages = ((idev-\u003einfo-\u003emem[mi].addr \u0026 ~PAGE_MASK)\n 847:\t\t\t\t+ idev-\u003einfo-\u003emem[mi].size + PAGE_SIZE -1) \u003e\u003e PAGE_SHIFT;\n 848:\t\tif (requested_pages \u003e actual_pages) {\n 849:\t\t\tret = -EINVAL;\n 850:\t\t\tgoto out;\n 851:\t\t}\n 852:\t\n 853:\t\tif (idev-\u003einfo-\u003emmap_prepare) {\n 854:\t\t\tstruct vm_area_desc desc;\n 855:\t\n 856:\t\t\tcompat_set_desc_from_vma(\u0026desc, filep, vma);\n 857:\t\t\tret = idev-\u003einfo-\u003emmap_prepare(idev-\u003einfo, \u0026desc);\n 858:\t\t\tif (ret)\n 859:\t\t\t\tgoto out;\n 860:\t\n 861:\t\t\t/*\n 862:\t\t\t * Install the per-VMA state before __compat_vma_mmap() so a\n 863:\t\t\t * failure in mmap_action_prepare() still reaches close(). That\n 864:\t\t\t * path never runs compat_set_vma_from_desc(), and the legacy\n 865:\t\t\t * .mmap error path frees the VMA without calling close() on\n 866:\t\t\t * its own. __compat_vma_mmap() installs the same values again\n 867:\t\t\t * on its way to the action.\n 868:\t\t\t *\n 869:\t\t\t * close() must be safe to call without a prior mapped() when\n 870:\t\t\t * it tears down state mmap_prepare() installed. Drivers that\n 871:\t\t\t * leave vm_ops alone have nothing to tear down here.\n 872:\t\t\t */\n 873:\t\t\tif (desc.vm_ops) {\n 874:\t\t\t\tvma-\u003evm_ops = desc.vm_ops;\n 875:\t\t\t\tvma-\u003evm_private_data = desc.private_data;\n 876:\t\t\t}\n 877:\t\n 878:\t\t\tret = __compat_vma_mmap(\u0026desc, vma);\n 879:\t\t\tif (ret \u0026\u0026 vma-\u003evm_ops \u0026\u0026 vma-\u003evm_ops-\u003eclose)\n 880:\t\t\t\tvma-\u003evm_ops-\u003eclose(vma);\n 881:\t\t\tgoto out;\n 882:\t\t}\n 883:\t\n 884:\t\tswitch (idev-\u003einfo-\u003emem[mi].memtype) {\n 885:\t\tcase UIO_MEM_IOVA:\n 886:\t\tcase UIO_MEM_PHYS:\n 887:\t\t\tret = uio_mmap_physical(vma);\n 888:\t\t\tbreak;\n 889:\t\tcase UIO_MEM_LOGICAL:\n"
}

17/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 106657
							output: 40
							thoughts: 28
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Diving into the TCM-U Core**

Alright, time to dig in. We need to understand how things are being handled at the virtual memory area (VMA) level within the target core user space. The place to start, obviously, is `drivers/target/target_core_user.c`. And specifically, the function we need to examine is `tcmu_vma_close`. This is where the cleanup should be. Let's see how they're handling the close operation. What resources are being freed here? Any potential race conditions? Need to see if there are any lingering pointers or references that might lead to memory leaks or corruption. Let's see what the code has to offer!



18/2 2026/10/07 21:55 tool read-file
0m Args:
{
  "File": "drivers/target/target_core_user.c",
  "FirstLine": 1900,
  "LineCount": 35
}

Results:
{
  "Contents": "1900:\t\tvm_fault_t ret = 0;\n1901:\t\n1902:\t\tint mi = tcmu_find_mem_index(vmf-\u003evma);\n1903:\t\tif (mi \u003c 0)\n1904:\t\t\treturn VM_FAULT_SIGBUS;\n1905:\t\n1906:\t\t/*\n1907:\t\t * We need to subtract mi because userspace uses offset = N*PAGE_SIZE\n1908:\t\t * to use mem[N].\n1909:\t\t */\n1910:\t\toffset = (vmf-\u003epgoff - mi) \u003c\u003c PAGE_SHIFT;\n1911:\t\n1912:\t\tif (offset \u003c udev-\u003edata_off) {\n1913:\t\t\t/* For the vmalloc()ed cmd area pages */\n1914:\t\t\taddr = (void *)(unsigned long)info-\u003emem[mi].addr + offset;\n1915:\t\t\tpage = vmalloc_to_page(addr);\n1916:\t\t\tget_page(page);\n1917:\t\t} else {\n1918:\t\t\tuint32_t dpi;\n1919:\t\n1920:\t\t\t/* For the dynamically growing data area pages */\n1921:\t\t\tdpi = (offset - udev-\u003edata_off) / PAGE_SIZE;\n1922:\t\t\tpage = tcmu_try_get_data_page(udev, dpi);\n1923:\t\t\tif (!page)\n1924:\t\t\t\treturn VM_FAULT_SIGBUS;\n1925:\t\t\tret = VM_FAULT_LOCKED;\n1926:\t\t}\n1927:\t\n1928:\t\tvmf-\u003epage = page;\n1929:\t\treturn ret;\n1930:\t}\n1931:\t\n1932:\tstatic const struct vm_operations_struct tcmu_vm_ops = {\n1933:\t\t.mapped = tcmu_vma_mapped,\n1934:\t\t.open = tcmu_vma_open,\n"
}

19/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 107426
							output: 40
							thoughts: 26
						

Thoughts:
Okay, here's my take on those functions, thinking through it as you asked:

**Delving into `tcmu_vma_open` and `tcmu_vma_close`**

Alright, let's get down to brass tacks. I need to understand the lifecycle of a TCMU VMA, so I'm focusing on `tcmu_vma_open` and `tcmu_vma_close`. My initial thought is to figure out what their specific roles are in the overall TCMU architecture. I'm assuming, given the naming, that these functions are responsible for managing the virtual memory areas (VMAs) associated with our targets. Specifically, I'm expecting them to handle the opening and closing of access to the VMA. What state changes do they initiate? Are these just reference count updates, or does something more involved happen on open and close, like resource allocation/deallocation or perhaps permission checks? I'll need to look deeper into the surrounding code to determine the contexts in which they are used. Are they tied to a specific type of target operation, or are they more general? I need to understand how these routines fit into the overall TCMU framework. What layers of abstraction are we dealing with? Where is the real magic of this all taking place, and how do these functions fit into the big picture? Let's figure this out.



20/2 2026/10/07 21:55 tool read-file
0m Args:
{
  "File": "drivers/target/target_core_user.c",
  "FirstLine": 1860,
  "LineCount": 45
}

Results:
{
  "Contents": "1860:\t\treturn NULL;\n1861:\t}\n1862:\t\n1863:\tstatic int tcmu_vma_mapped(unsigned long start, unsigned long end, pgoff_t pgoff,\n1864:\t\t\t\t   const struct file *file, void **vm_private_data)\n1865:\t{\n1866:\t\tstruct tcmu_dev *udev = *vm_private_data;\n1867:\t\n1868:\t\tpr_debug(\"vma_mapped\\n\");\n1869:\t\n1870:\t\tkref_get(\u0026udev-\u003ekref);\n1871:\t\treturn 0;\n1872:\t}\n1873:\t\n1874:\tstatic void tcmu_vma_open(struct vm_area_struct *vma)\n1875:\t{\n1876:\t\tstruct tcmu_dev *udev = vma-\u003evm_private_data;\n1877:\t\n1878:\t\tpr_debug(\"vma_open\\n\");\n1879:\t\n1880:\t\tkref_get(\u0026udev-\u003ekref);\n1881:\t}\n1882:\t\n1883:\tstatic void tcmu_vma_close(struct vm_area_struct *vma)\n1884:\t{\n1885:\t\tstruct tcmu_dev *udev = vma-\u003evm_private_data;\n1886:\t\n1887:\t\tpr_debug(\"vma_close\\n\");\n1888:\t\n1889:\t\t/* release ref from tcmu_vma_open */\n1890:\t\tkref_put(\u0026udev-\u003ekref, tcmu_dev_kref_release);\n1891:\t}\n1892:\t\n1893:\tstatic vm_fault_t tcmu_vma_fault(struct vm_fault *vmf)\n1894:\t{\n1895:\t\tstruct tcmu_dev *udev = vmf-\u003evma-\u003evm_private_data;\n1896:\t\tstruct uio_info *info = \u0026udev-\u003euio_info;\n1897:\t\tstruct page *page;\n1898:\t\tunsigned long offset;\n1899:\t\tvoid *addr;\n1900:\t\tvm_fault_t ret = 0;\n1901:\t\n1902:\t\tint mi = tcmu_find_mem_index(vmf-\u003evma);\n1903:\t\tif (mi \u003c 0)\n1904:\t\t\treturn VM_FAULT_SIGBUS;\n"
}

21/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 108455
							output: 31
							thoughts: 1296
						

Thoughts:
**Analyzing a Potential Kernel Vulnerability and Fuzzing Strategy**

Okay, let's break this down. I'm looking at this `tcmu_vma_close` function and immediately see something that raises an eyebrow. There's a `kref_put` on `udev->kref` here, which is releasing a reference originally taken in `tcmu_vma_open`. But then I notice that `tcmu_vma_mapped` also takes a reference using `kref_get`. My brain immediately starts connecting the dots – what's the lifecycle of these references?

If the `__compat_vma_mmap` call fails, previously, there was no call to `vma->vm_ops->close`, but now the code has been updated to:

```c
		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);
```

Okay, so if `__compat_vma_mmap` *fails*, then `tcmu_vma_mapped` is never called. Therefore, `kref_get` is never incremented! This means the subsequent call to `tcmu_vma_close` *will* call `kref_put` without a corresponding `kref_get`. That's a classic reference count underflow! A potential use-after-free situation, or at the very least, a double-free. The kernel comment about `close()` being safe without a prior `mapped()` is crucial here. TCMU didn't expect a `close()` call without a preceding `mapped()`, and that's the crux of this.

Now, the important question is: is this even exploitable? Can it be fuzzed? Can syzkaller reach `tcmu` and UIO? Fortunately, I know configfs and target_core_user are standard in syzkaller. I need to check the syzkaller configs for "target", "tcmu", or "uio" and see if there are pre-existing configurations or pseudo-syscalls in the tool.

But let's also think outside the box. What about Hyper-V? Can it be fuzzed in QEMU or GCE? Does Hyper-V run in QEMU? I do know QEMU has Hyper-V enlightenments for KVM when running as a Hyper-V guest, which is interesting.

Can Linux run as a Hyper-V guest in QEMU? Yes. QEMU has `-cpu` options like `hv_relaxed`, `hv_spinlocks`, etc. But does QEMU emulate the VMBus? Let me check… Bingo! QEMU has `vmbus` and `hyperv` support! QEMU 4.0+ has `hv-passthrough` and `vmbus` bridge. Wait, does QEMU emulate the VMBus, or is Hyper-V root/VMBus enabled in standard syzkaller?

This is where the syzkaller documentation or standard QEMU VM setup becomes critical. Let me refer to Sections 1, 2, and 3. I recall the primary gate for fuzzing: reachability. The changes must be reachable in standard virtualized environments. I need to check if UIO fits this bill. `drivers/uio/uio.c` is the core UIO subsystem, providing `/dev/uioX` character devices, and it looks like UIO drivers expose `/dev/uioX`. Is UIO compiled in standard kernels? This depends on the Kconfig, but I'm optimistic. This looks reachable and exploitable.



22/2 2026/10/07 21:55 tool grepper
0m Args:
{
  "Expression": "config UIO",
  "PathPrefixes": [
    "drivers/uio/Kconfig"
  ]
}

Results:
{
  "Output": "drivers/uio/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/uio/Kconfig:2:menuconfig UIO\ndrivers/uio/Kconfig-3-\ttristate \"Userspace I/O drivers\"\n--\ndrivers/uio/Kconfig=14=if UIO\ndrivers/uio/Kconfig-15-\ndrivers/uio/Kconfig:16:config UIO_CIF\ndrivers/uio/Kconfig-17-\ttristate \"generic Hilscher CIF Card driver\"\n--\ndrivers/uio/Kconfig-27-\ndrivers/uio/Kconfig:28:config UIO_PDRV_GENIRQ\ndrivers/uio/Kconfig-29-\ttristate \"Userspace I/O platform driver with generic IRQ handling\"\n--\ndrivers/uio/Kconfig-40-\ndrivers/uio/Kconfig:41:config UIO_DMEM_GENIRQ\ndrivers/uio/Kconfig-42-\ttristate \"Userspace platform driver with generic irq and dynamic memory\"\n--\ndrivers/uio/Kconfig-57-\ndrivers/uio/Kconfig:58:config UIO_AEC\ndrivers/uio/Kconfig-59-\ttristate \"AEC video timestamp device\"\n--\ndrivers/uio/Kconfig-74-\ndrivers/uio/Kconfig:75:config UIO_SERCOS3\ndrivers/uio/Kconfig-76-\ttristate \"Automata Sercos III PCI card driver\"\n--\ndrivers/uio/Kconfig-87-\ndrivers/uio/Kconfig:88:config UIO_PCI_GENERIC\ndrivers/uio/Kconfig-89-\ttristate \"Generic driver for PCI 2.3 and PCI Express cards\"\n--\ndrivers/uio/Kconfig-96-\ndrivers/uio/Kconfig:97:config UIO_NETX\ndrivers/uio/Kconfig-98-\ttristate \"Hilscher NetX Card driver\"\n--\ndrivers/uio/Kconfig-107-\ndrivers/uio/Kconfig:108:config UIO_FSL_ELBC_GPCM\ndrivers/uio/Kconfig-109-\ttristate \"eLBC/GPCM driver\"\n--\ndrivers/uio/Kconfig-116-\ndrivers/uio/Kconfig:117:config UIO_FSL_ELBC_GPCM_NETX5152\ndrivers/uio/Kconfig-118-\tbool \"eLBC/GPCM netX 51/52 support\"\n--\ndrivers/uio/Kconfig-127-\ndrivers/uio/Kconfig:128:config UIO_MF624\ndrivers/uio/Kconfig-129-\ttristate \"Humusoft MF624 DAQ PCI card driver\"\n--\ndrivers/uio/Kconfig-140-\ndrivers/uio/Kconfig:141:config UIO_HV_GENERIC\ndrivers/uio/Kconfig-142-\ttristate \"Generic driver for Hyper-V VMBus\"\n--\ndrivers/uio/Kconfig-150-\ndrivers/uio/Kconfig:151:config UIO_HV_GENERIC_KUNIT_TEST\ndrivers/uio/Kconfig-152-\tbool \"Tests for the UIO Hyper-V generic mmap\" if !KUNIT_ALL_TESTS\n--\ndrivers/uio/Kconfig-161-\ndrivers/uio/Kconfig:162:config UIO_DFL\ndrivers/uio/Kconfig-163-\ttristate \"Generic driver for DFL (Device Feature List) bus\"\n--\ndrivers/uio/Kconfig-178-\ndrivers/uio/Kconfig:179:config UIO_PCI_GENERIC_SVA\ndrivers/uio/Kconfig-180-\ttristate \"Generic driver for PCI Express that supports sva\"\n"
}

23/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 111632
							output: 18
							thoughts: 65
						

Thoughts:
Okay, let's take a beat here. Before I jump too deep, I need to methodically approach this Hyper-V issue.

**Hyper-V Initialization Investigation**

First, I need to confirm the obvious – can I even ping the Hyper-V host itself? A basic network connectivity check is always a good starting point. Then, let's circle back to the kernel and check if `CONFIG_HYPERV` is even enabled. That's fundamental; if it's not compiled in, the rest is moot. Now, onto the main investigation. I want to understand *how* Hyper-V is initialized, which is crucial for troubleshooting any problem within the system. I'll search the relevant kernel code, looking for initialization routines. I'll focus on terms like `ms_hyperv`, `hyperv_init`, or anything that sounds like a Hyper-V initialization function. I know these systems and usually there is a dedicated driver or subsystem. Hopefully, that will give me a clear entry point to understand the boot process.



24/2 2026/10/07 21:55 tool grepper
0m Args:
{
  "Expression": "hyperv_init"
}

Results:
{
  "Output": "arch/arm64/hyperv/mshyperv.c-19-\narch/arm64/hyperv/mshyperv.c:20:static bool hyperv_initialized;\narch/arm64/hyperv/mshyperv.c-21-\n--\narch/arm64/hyperv/mshyperv.c=63=static bool __init hyperv_detect_via_smccc(void)\n--\narch/arm64/hyperv/mshyperv.c-72-\narch/arm64/hyperv/mshyperv.c:73:static int __init hyperv_init(void)\narch/arm64/hyperv/mshyperv.c-74-{\n--\narch/arm64/hyperv/mshyperv.c-110-\narch/arm64/hyperv/mshyperv.c:111:\tret = cpuhp_setup_state(CPUHP_AP_HYPERV_ONLINE, \"arm64/hyperv_init:online\",\narch/arm64/hyperv/mshyperv.c-112-\t\t\t\thv_common_cpu_init, hv_common_cpu_die);\n--\narch/arm64/hyperv/mshyperv.c-125-\narch/arm64/hyperv/mshyperv.c:126:\thyperv_initialized = true;\narch/arm64/hyperv/mshyperv.c-127-\treturn 0;\n--\narch/arm64/hyperv/mshyperv.c-129-\narch/arm64/hyperv/mshyperv.c:130:early_initcall(hyperv_init);\narch/arm64/hyperv/mshyperv.c-131-\narch/arm64/hyperv/mshyperv.c:132:bool hv_is_hyperv_initialized(void)\narch/arm64/hyperv/mshyperv.c-133-{\narch/arm64/hyperv/mshyperv.c:134:\treturn hyperv_initialized;\narch/arm64/hyperv/mshyperv.c-135-}\narch/arm64/hyperv/mshyperv.c:136:EXPORT_SYMBOL_GPL(hv_is_hyperv_initialized);\n--\narch/x86/hyperv/hv_init.c=85=EXPORT_SYMBOL_GPL(hv_vp_assist_page);\narch/x86/hyperv/hv_init.c-86-\narch/x86/hyperv/hv_init.c:87:static int hyperv_init_ghcb(void)\narch/x86/hyperv/hv_init.c-88-{\n--\narch/x86/hyperv/hv_init.c=118=static int hv_cpu_init(unsigned int cpu)\n--\narch/x86/hyperv/hv_init.c-175-\narch/x86/hyperv/hv_init.c:176:\treturn hyperv_init_ghcb();\narch/x86/hyperv/hv_init.c-177-}\n--\narch/x86/hyperv/hv_init.c=424=static void __init hv_stimer_setup_percpu_clockev(void)\n--\narch/x86/hyperv/hv_init.c-451- */\narch/x86/hyperv/hv_init.c:452:void __init hyperv_init(void)\narch/x86/hyperv/hv_init.c-453-{\n--\narch/x86/hyperv/hv_init.c-489-\narch/x86/hyperv/hv_init.c:490:\tcpuhp = cpuhp_setup_state(CPUHP_AP_HYPERV_ONLINE, \"x86/hyperv_init:online\",\narch/x86/hyperv/hv_init.c-491-\t\t\t\t  hv_cpu_init, hv_cpu_die);\n--\narch/x86/hyperv/hv_init.c-572-\t/*\narch/x86/hyperv/hv_init.c:573:\t * hyperv_init() is called before LAPIC is initialized: see\narch/x86/hyperv/hv_init.c-574-\t * apic_intr_mode_init() -\u003e x86_platform.apic_post_init() and\n--\narch/x86/hyperv/hv_init.c=688=EXPORT_SYMBOL_GPL(hyperv_report_panic);\narch/x86/hyperv/hv_init.c-689-\narch/x86/hyperv/hv_init.c:690:bool hv_is_hyperv_initialized(void)\narch/x86/hyperv/hv_init.c-691-{\n--\narch/x86/hyperv/hv_init.c-712-}\narch/x86/hyperv/hv_init.c:713:EXPORT_SYMBOL_GPL(hv_is_hyperv_initialized);\narch/x86/hyperv/hv_init.c-714-\n--\narch/x86/include/asm/mshyperv.h=160=static inline struct hv_vp_assist_page *hv_get_vp_assist_page(unsigned int cpu)\n--\narch/x86/include/asm/mshyperv.h-167-\narch/x86/include/asm/mshyperv.h:168:void __init hyperv_init(void);\narch/x86/include/asm/mshyperv.h-169-void hyperv_setup_mmu_ops(void);\n--\narch/x86/include/asm/mshyperv.h=248=static inline void hv_root_crash_init(void) {}\n--\narch/x86/include/asm/mshyperv.h-251-#else /* CONFIG_HYPERV */\narch/x86/include/asm/mshyperv.h:252:static inline void hyperv_init(void) {}\narch/x86/include/asm/mshyperv.h-253-static inline void hyperv_setup_mmu_ops(void) {}\n--\narch/x86/kernel/cpu/mshyperv.c=499=static void hv_reserve_irq_vectors(void)\n--\narch/x86/kernel/cpu/mshyperv.c-532-\narch/x86/kernel/cpu/mshyperv.c:533:static void __init ms_hyperv_init_platform(void)\narch/x86/kernel/cpu/mshyperv.c-534-{\n--\narch/x86/kernel/cpu/mshyperv.c-721-\t */\narch/x86/kernel/cpu/mshyperv.c:722:\tx86_platform.apic_post_init = hyperv_init;\narch/x86/kernel/cpu/mshyperv.c-723-\thyperv_setup_mmu_ops();\n--\narch/x86/kernel/cpu/mshyperv.c=812=const __initconst struct hypervisor_x86 x86_hyper_ms_hyperv = {\n--\narch/x86/kernel/cpu/mshyperv.c-817-\t.init.msi_ext_dest_id\t= ms_hyperv_msi_ext_dest_id,\narch/x86/kernel/cpu/mshyperv.c:818:\t.init.init_platform\t= ms_hyperv_init_platform,\narch/x86/kernel/cpu/mshyperv.c-819-\t.init.guest_late_init\t= ms_hyperv_late_init,\n--\ndrivers/hv/hv_common.c=38=EXPORT_SYMBOL_GPL(hv_curr_partition_type);\n--\ndrivers/hv/hv_common.c-43- * built only when CONFIG_HYPERV is defined.  But on x86,\ndrivers/hv/hv_common.c:44: * ms_hyperv_init_platform() is built even when CONFIG_HYPERV is not\ndrivers/hv/hv_common.c-45- * defined, and it uses these three variables.  So mark them as __weak\ndrivers/hv/hv_common.c-46- * here, allowing for an overriding definition in the module containing\ndrivers/hv/hv_common.c:47: * ms_hyperv_init_platform().\ndrivers/hv/hv_common.c-48- */\n--\ndrivers/hv/hyperv_vmbus.h=126=struct hv_per_cpu_context {\n--\ndrivers/hv/hyperv_vmbus.h-154-\t * VM, so post_msg_page (which is decrypted in hv_synic_alloc()) is\ndrivers/hv/hyperv_vmbus.h:155:\t * introduced for this purpose. See hyperv_init() for more comments.\ndrivers/hv/hyperv_vmbus.h-156-\t */\n--\ndrivers/hv/vmbus_drv.c=3021=static int __init hv_acpi_init(void)\n--\ndrivers/hv/vmbus_drv.c-3024-\ndrivers/hv/vmbus_drv.c:3025:\tif (!hv_is_hyperv_initialized())\ndrivers/hv/vmbus_drv.c-3026-\t\treturn -ENODEV;\n--\ndrivers/pci/controller/pci-hyperv.c=4169=static int __init init_hv_pci_drv(void)\n--\ndrivers/pci/controller/pci-hyperv.c-4172-\ndrivers/pci/controller/pci-hyperv.c:4173:\tif (!hv_is_hyperv_initialized())\ndrivers/pci/controller/pci-hyperv.c-4174-\t\treturn -ENODEV;\n--\ninclude/asm-generic/mshyperv.h=304=void hyperv_report_panic(struct pt_regs *regs, long err, bool in_die);\ninclude/asm-generic/mshyperv.h:305:bool hv_is_hyperv_initialized(void);\ninclude/asm-generic/mshyperv.h-306-bool hv_is_hibernation_supported(void);\n--\ninclude/asm-generic/mshyperv.h=320=static inline void hv_identify_partition_type(void) {}\ninclude/asm-generic/mshyperv.h:321:static inline bool hv_is_hyperv_initialized(void) { return false; }\ninclude/asm-generic/mshyperv.h-322-static inline bool hv_is_hibernation_supported(void) { return false; }\n"
}

25/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 114708
							output: 40
							thoughts: 50
						

Thoughts:
Here's my analysis of the provided snippet, framed as my own thought process:

**Diving into the Hyper-V ACPI Initialization**

Alright, let's get down to it. I'm taking a look at the Hyper-V ACPI initialization routine. Specifically, I need to understand what's happening within `hv_acpi_init()`. Time to jump into `drivers/hv/vmbus_drv.c`.

Now, according to my mental map, the significant stuff should be around line 3020 of `drivers/hv/vmbus_drv.c`. I need to get my bearings and see what the code is doing in that vicinity. Let's see what critical pieces are being set up, initialized, or configured there. What's the context? What are the dependencies? I'm expecting to find the standard ACPI initialization sequence, which will probably involve probing for relevant ACPI tables, registering devices, and potentially handling specific Hyper-V related ACPI methods or objects. I need to understand how the ACPI interactions play a role in the overall VMBus driver initialization flow. My expertise suggests that the design will be in conformance with the ACPI specification. Let's dig in and see.



26/2 2026/10/07 21:55 tool read-file
0m Args:
{
  "File": "drivers/hv/vmbus_drv.c",
  "FirstLine": 3020,
  "LineCount": 40
}

Results:
{
  "Contents": "3020:\t\n3021:\tstatic int __init hv_acpi_init(void)\n3022:\t{\n3023:\t\tint ret;\n3024:\t\n3025:\t\tif (!hv_is_hyperv_initialized())\n3026:\t\t\treturn -ENODEV;\n3027:\t\n3028:\t\tif (hv_root_partition() \u0026\u0026 !hv_nested)\n3029:\t\t\t/*\n3030:\t\t\t * A non-nested root partition does not need VMBus client\n3031:\t\t\t * functionality. However, the mshv_root module may have\n3032:\t\t\t * a dependency on the VMBus module as described in\n3033:\t\t\t * commit 840b740a35bf. Return success so the module\n3034:\t\t\t * loads even though no VMBus initialization is done.\n3035:\t\t\t */\n3036:\t\t\treturn 0;\n3037:\t\n3038:\t\t/*\n3039:\t\t * Get ACPI resources first.\n3040:\t\t */\n3041:\t\tret = platform_driver_register(\u0026vmbus_platform_driver);\n3042:\t\tif (ret)\n3043:\t\t\treturn ret;\n3044:\t\n3045:\t\tif (!vmbus_root_device) {\n3046:\t\t\tret = -ENODEV;\n3047:\t\t\tgoto cleanup;\n3048:\t\t}\n3049:\t\n3050:\t\t/*\n3051:\t\t * If we're on an architecture with a hardcoded hypervisor\n3052:\t\t * vector (i.e. x86/x64), override the VMbus interrupt found\n3053:\t\t * in the ACPI tables. Ensure vmbus_irq is not set since the\n3054:\t\t * normal Linux IRQ mechanism is not used in this case.\n3055:\t\t */\n3056:\t#ifdef HYPERVISOR_CALLBACK_VECTOR\n3057:\t\tvmbus_interrupt = HYPERVISOR_CALLBACK_VECTOR;\n3058:\t\tvmbus_irq = -1;\n3059:\t#endif\n"
}

27/2 2026/10/07 21:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 115640
							output: 42
							thoughts: 84
						

Thoughts:
Here's my analysis of the provided snippet, framed as my own thought process:

**Diving into Hyper-V Initialization on x86**

Okay, so I need to understand how the system determines if Hyper-V is initialized on an x86 architecture. The starting point seems to be the `hv_is_hyperv_initialized()` function. My instinct is to trace that function's implementation.

Therefore, I'll go directly to the source code. Specifically, I'll examine `arch/x86/hyperv/hv_init.c` to see how the boolean `hv_is_hyperv_initialized(void)` function makes that determination. I'll focus on the area around line 690, as that's usually where important details are located. I'll read through it to understand the logic flow and the conditions that lead to `hv_is_hyperv_initialized()` returning true or false. From there, I should be able to deduce the core checks and the underlying mechanisms involved.



28/2 2026/10/07 21:56 tool read-file
0m Args:
{
  "File": "arch/x86/hyperv/hv_init.c",
  "FirstLine": 690,
  "LineCount": 25
}

Results:
{
  "Contents": " 690:\tbool hv_is_hyperv_initialized(void)\n 691:\t{\n 692:\t\tunion hv_x64_msr_hypercall_contents hypercall_msr;\n 693:\t\n 694:\t\t/*\n 695:\t\t * Ensure that we're really on Hyper-V, and not a KVM or Xen\n 696:\t\t * emulation of Hyper-V\n 697:\t\t */\n 698:\t\tif (x86_hyper_type != X86_HYPER_MS_HYPERV)\n 699:\t\t\treturn false;\n 700:\t\n 701:\t\t/* A TDX VM with no paravisor uses TDX GHCI call rather than hv_hypercall_pg */\n 702:\t\tif (hv_isolation_type_tdx() \u0026\u0026 !ms_hyperv.paravisor_present)\n 703:\t\t\treturn true;\n 704:\t\t/*\n 705:\t\t * Verify that earlier initialization succeeded by checking\n 706:\t\t * that the hypercall page is setup\n 707:\t\t */\n 708:\t\thypercall_msr.as_uint64 = 0;\n 709:\t\trdmsrq(HV_X64_MSR_HYPERCALL, hypercall_msr.as_uint64);\n 710:\t\n 711:\t\treturn hypercall_msr.enable;\n 712:\t}\n 713:\tEXPORT_SYMBOL_GPL(hv_is_hyperv_initialized);\n 714:\t\n"
}

29/2 2026/10/07 21:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 116399
							output: 38
							thoughts: 90
						

Thoughts:
Okay, here's my breakdown of what's going through my mind as I analyze this code snippet, keeping in mind my expertise in the field:

**Debugging a Potential Hyper-V Specific Issue**

Alright, line 698 immediately jumps out at me: `if (x86_hyper_type != X86_HYPER_MS_HYPERV) return false;`. This looks like a hypervisor-specific check, likely preventing something from running if it *isn't* a Microsoft Hyper-V environment. The `return false;` suggests that if the condition is true (meaning it's *not* Hyper-V), we're hitting a code path that's intended only for that specific hypervisor.

My immediate question then becomes: How and where is `x86_hyper_type` being set to `X86_HYPER_MS_HYPERV`? I need to understand the control flow and the initialization of that variable to fully grasp what's happening here. This strongly suggests the code relies on detecting the hypervisor environment.

Therefore, my next step is clear. I'm going to navigate to `arch/x86/kernel/cpu/mshyperv.c`. That file's name practically shouts "Hyper-V detection and initialization." I'll need to examine that file to track down the assignment of `x86_hyper_type` and see how the detection mechanism works. Understanding that detection process is critical to understanding the logic behind this conditional, and whether it's behaving as expected in this context. I'm looking for the code that probes the CPU features and/or uses other methods to identify the Hyper-V environment. This will help me determine if the conditional check is valid and if there is a bug or problem.



30/2 2026/10/07 21:56 tool grepper
0m Args:
{
  "Expression": "X86_HYPER_MS_HYPERV",
  "PathPrefixes": [
    "arch/x86"
  ]
}

Results:
{
  "Output": "arch/x86/hyperv/hv_init.c=452=void __init hyperv_init(void)\n--\narch/x86/hyperv/hv_init.c-457-\narch/x86/hyperv/hv_init.c:458:\tif (x86_hyper_type != X86_HYPER_MS_HYPERV)\narch/x86/hyperv/hv_init.c-459-\t\treturn;\n--\narch/x86/hyperv/hv_init.c=690=bool hv_is_hyperv_initialized(void)\n--\narch/x86/hyperv/hv_init.c-697-\t */\narch/x86/hyperv/hv_init.c:698:\tif (x86_hyper_type != X86_HYPER_MS_HYPERV)\narch/x86/hyperv/hv_init.c-699-\t\treturn false;\n--\narch/x86/hyperv/ivm.c=916=bool hv_is_isolation_supported(void)\n--\narch/x86/hyperv/ivm.c-920-\narch/x86/hyperv/ivm.c:921:\tif (!hypervisor_is_type(X86_HYPER_MS_HYPERV))\narch/x86/hyperv/ivm.c-922-\t\treturn false;\n--\narch/x86/include/asm/hypervisor.h=24=enum x86_hypervisor_type {\n--\narch/x86/include/asm/hypervisor.h-26-\tX86_HYPER_VMWARE,\narch/x86/include/asm/hypervisor.h:27:\tX86_HYPER_MS_HYPERV,\narch/x86/include/asm/hypervisor.h-28-\tX86_HYPER_XEN_PV,\n--\narch/x86/kernel/cpu/mshyperv.c=812=const __initconst struct hypervisor_x86 x86_hyper_ms_hyperv = {\n--\narch/x86/kernel/cpu/mshyperv.c-814-\t.detect\t\t\t= ms_hyperv_platform,\narch/x86/kernel/cpu/mshyperv.c:815:\t.type\t\t\t= X86_HYPER_MS_HYPERV,\narch/x86/kernel/cpu/mshyperv.c-816-\t.init.x2apic_available\t= ms_hyperv_x2apic_available,\n--\narch/x86/kvm/x86.c=6999=int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)\n--\narch/x86/kvm/x86.c-7116-\narch/x86/kvm/x86.c:7117:\tif (hypervisor_is_type(X86_HYPER_MS_HYPERV))\narch/x86/kvm/x86.c-7118-\t\tset_hv_tscchange_cb(kvm_hyperv_tsc_notifier);\n--\narch/x86/kvm/x86.c=7158=void kvm_x86_vendor_exit(void)\n--\narch/x86/kvm/x86.c-7162-#ifdef CONFIG_X86_64\narch/x86/kvm/x86.c:7163:\tif (hypervisor_is_type(X86_HYPER_MS_HYPERV))\narch/x86/kvm/x86.c-7164-\t\tclear_hv_tscchange_cb();\n"
}

31/2 2026/10/07 21:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 117882
							output: 44
							thoughts: 33
						

Thoughts:
Okay, here's my interpretation of that code snippet, delivered as if it's my own thought process:

**Diving into Hyper-V Platform Detection**

Alright, let's take a look at `ms_hyperv_platform` within `arch/x86/kernel/cpu/mshyperv.c`. Right, so we're talking about probing for the Hyper-V platform here, specifically on x86 architectures. This file likely houses the low-level functions used to identify if the current system is running as a guest under Microsoft's Hyper-V hypervisor. The goal is to detect and potentially adapt the kernel's behavior to optimize it for a virtualized environment. That's the core of what we're aiming for here. Let's see what's what.



32/2 2026/10/07 21:56 tool read-file
0m Args:
{
  "File": "arch/x86/kernel/cpu/mshyperv.c",
  "FirstLine": 500,
  "LineCount": 40
}

Results:
{
  "Contents": " 500:\t{\n 501:\t\t#define HYPERV_DBG_FASTFAIL_VECTOR\t0x29\n 502:\t\t#define HYPERV_DBG_ASSERT_VECTOR\t0x2C\n 503:\t\t#define HYPERV_DBG_SERVICE_VECTOR\t0x2D\n 504:\t\n 505:\t\t/*\n 506:\t\t * The hypervisor delivers these three to the NT HAL and refuses to\n 507:\t\t * map a device interrupt to any of them.\n 508:\t\t *\n 509:\t\t * The hypervisor will provide a hint in the future when these\n 510:\t\t * vectors become available to use.\n 511:\t\t */\n 512:\t\t#define HAL_NT_APC_VECTOR\t\t0x1F\n 513:\t\t#define HAL_NT_DPC_VECTOR\t\t0x2F\n 514:\t\t#define HAL_NT_CLOCK_IPI_VECTOR\t\t0xD2\n 515:\t\n 516:\t\tif (cpu_feature_enabled(X86_FEATURE_FRED))\n 517:\t\t\treturn;\n 518:\t\n 519:\t\tif (test_and_set_bit(HYPERV_DBG_ASSERT_VECTOR, system_vectors) ||\n 520:\t\t    test_and_set_bit(HYPERV_DBG_SERVICE_VECTOR, system_vectors) ||\n 521:\t\t    test_and_set_bit(HYPERV_DBG_FASTFAIL_VECTOR, system_vectors) ||\n 522:\t\t    test_and_set_bit(HAL_NT_APC_VECTOR, system_vectors) ||\n 523:\t\t    test_and_set_bit(HAL_NT_DPC_VECTOR, system_vectors) ||\n 524:\t\t    test_and_set_bit(HAL_NT_CLOCK_IPI_VECTOR, system_vectors))\n 525:\t\t\tBUG();\n 526:\t\n 527:\t\tpr_info(\"Hyper-V: reserve vectors: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\\n\",\n 528:\t\t\tHYPERV_DBG_ASSERT_VECTOR, HYPERV_DBG_SERVICE_VECTOR,\n 529:\t\t\tHYPERV_DBG_FASTFAIL_VECTOR, HAL_NT_APC_VECTOR,\n 530:\t\t\tHAL_NT_DPC_VECTOR, HAL_NT_CLOCK_IPI_VECTOR);\n 531:\t}\n 532:\t\n 533:\tstatic void __init ms_hyperv_init_platform(void)\n 534:\t{\n 535:\t\tint hv_max_functions_eax, eax;\n 536:\t\n 537:\t#ifdef CONFIG_PARAVIRT\n 538:\t\tpv_info.name = \"Hyper-V\";\n 539:\t#endif\n"
}

33/2 2026/10/07 21:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 118881
							output: 44
							thoughts: 15
						

Thoughts:
Okay, let's dive into this `ms_hyperv_platform` detect function, shall we? Here's how I'm approaching it:

**Dissecting the `ms_hyperv_platform` Detection**

Alright, my first thought is to understand the purpose of this function within the broader context. What's its role? Is it a preliminary check, a deeper dive into system configuration, or something in between? I need to understand its scope. Given the name, I'm guessing it's designed to figure out if we're running in a Hyper-V environment. This is pretty fundamental stuff, actually. I'm going to look for the key indicators—the breadcrumbs, if you will—that would signal the presence of Hyper-V. My intuition tells me to focus on:

*   **Virtualization Artifacts:** Are there specific registry keys, device drivers, or hardware IDs that are characteristic of a Hyper-V guest or host? This is the most logical starting point. I'll need to sift through system information and correlate that with my existing knowledge of Hyper-V.
*   **Hypervisor Interface Detection:** Could this function leverage any known Hyper-V APIs or system calls to determine its presence? Any detectable services or processes? This is the more formal approach, so I'll be looking for that kind of interaction.
*   **Environment Variables & Configuration:** Maybe there are tell-tale environment variables or system configurations that only manifest in a Hyper-V environment. I'll check common ones.
*   **Cross-platform compatibility:** It must be cross-platform, so I must consider this function for linux, windows, or any other platforms.

I'm mentally preparing to methodically check these possibilities, noting that the combination of these checks is usually the key to a robust detection system. I'll then be able to assess the reliability of the function and how well it handles different Hyper-V configurations and versions.



34/2 2026/10/07 21:56 tool read-file
0m Args:
{
  "File": "arch/x86/kernel/cpu/mshyperv.c",
  "FirstLine": 460,
  "LineCount": 40
}

Results:
{
  "Contents": " 460:\t * When a fully enlightened TDX VM runs on Hyper-V, the firmware sets the\n 461:\t * HW_REDUCED flag: refer to acpi_tb_create_local_fadt(). Consequently ttyS0\n 462:\t * interrupts can't work because request_irq() -\u003e ... -\u003e irq_to_desc() returns\n 463:\t * NULL for ttyS0. This happens because mp_config_acpi_legacy_irqs() sees a\n 464:\t * nr_legacy_irqs() of 0, so it doesn't initialize the array 'mp_irqs[]', and\n 465:\t * later setup_IO_APIC_irqs() -\u003e find_irq_entry() fails to find the legacy irqs\n 466:\t * from the array and hence doesn't create the necessary irq description info.\n 467:\t *\n 468:\t * Clone arch/x86/kernel/acpi/boot.c: acpi_generic_reduced_hw_init() here,\n 469:\t * except don't change 'legacy_pic', which keeps its default value\n 470:\t * 'default_legacy_pic'. This way, mp_config_acpi_legacy_irqs() sees a non-zero\n 471:\t * nr_legacy_irqs() and eventually serial console interrupts works properly.\n 472:\t */\n 473:\tstatic void __init reduced_hw_init(void)\n 474:\t{\n 475:\t\tx86_init.timers.timer_init\t= x86_init_noop;\n 476:\t\tx86_init.irqs.pre_vector_init\t= x86_init_noop;\n 477:\t}\n 478:\t\n 479:\tint hv_get_hypervisor_version(union hv_hypervisor_version_info *info)\n 480:\t{\n 481:\t\tunsigned int hv_max_functions;\n 482:\t\n 483:\t\thv_max_functions = cpuid_eax(HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS);\n 484:\t\tif (hv_max_functions \u003c HYPERV_CPUID_VERSION) {\n 485:\t\t\tpr_err(\"%s: Could not detect Hyper-V version\\n\", __func__);\n 486:\t\t\treturn -ENODEV;\n 487:\t\t}\n 488:\t\n 489:\t\tcpuid(HYPERV_CPUID_VERSION, \u0026info-\u003eeax, \u0026info-\u003eebx, \u0026info-\u003eecx, \u0026info-\u003eedx);\n 490:\t\n 491:\t\treturn 0;\n 492:\t}\n 493:\tEXPORT_SYMBOL_GPL(hv_get_hypervisor_version);\n 494:\t\n 495:\t/*\n 496:\t * Reserved vectors hard coded in the hypervisor. If used outside, the hypervisor\n 497:\t * will either crash or hang or attempt to break into debugger.\n 498:\t */\n 499:\tstatic void hv_reserve_irq_vectors(void)\n"
}

35/2 2026/10/07 21:56 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 120163
							output: 44
							thoughts: 15
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Locating the Hyper-V Platform**

Okay, so I need to figure out where `ms_hyperv_platform` resides within the system. That's the key starting point. I can't really proceed with whatever I'm troubleshooting, analyzing, or developing without knowing its location. It's almost like needing to know the root of a tree before you can diagnose a disease affecting its leaves. My mind needs to pinpoint that specific module or component. This is basic, almost a reflex, when working with Hyper-V. Where's the entry point? Where's the core? Let me start there.



36/2 2026/10/07 21:57 tool read-file
0m Args:
{
  "File": "arch/x86/kernel/cpu/mshyperv.c",
  "FirstLine": 400,
  "LineCount": 40
}

Results:
{
  "Contents": " 400:\t\tunsigned long freq;\n 401:\t\n 402:\t\trdmsrq(HV_X64_MSR_TSC_FREQUENCY, freq);\n 403:\t\n 404:\t\treturn freq / 1000;\n 405:\t}\n 406:\t\n 407:\t#if defined(CONFIG_SMP) \u0026\u0026 IS_ENABLED(CONFIG_HYPERV)\n 408:\tstatic void __init hv_smp_prepare_boot_cpu(void)\n 409:\t{\n 410:\t\tnative_smp_prepare_boot_cpu();\n 411:\t#if defined(CONFIG_X86_64) \u0026\u0026 defined(CONFIG_PARAVIRT_SPINLOCKS)\n 412:\t\thv_init_spinlocks();\n 413:\t#endif\n 414:\t}\n 415:\t\n 416:\tstatic void __init hv_smp_prepare_cpus(unsigned int max_cpus)\n 417:\t{\n 418:\t#ifdef CONFIG_X86_64\n 419:\t\tint i;\n 420:\t\tint ret;\n 421:\t#endif\n 422:\t\n 423:\t\tnative_smp_prepare_cpus(max_cpus);\n 424:\t\n 425:\t\t/*\n 426:\t\t *  Override wakeup_secondary_cpu_64 callback for SEV-SNP\n 427:\t\t *  enlightened guest.\n 428:\t\t */\n 429:\t\tif (!ms_hyperv.paravisor_present \u0026\u0026 hv_isolation_type_snp()) {\n 430:\t\t\tapic-\u003ewakeup_secondary_cpu_64 = hv_snp_boot_ap;\n 431:\t\t\treturn;\n 432:\t\t}\n 433:\t\n 434:\t#ifdef CONFIG_X86_64\n 435:\t\t/* If AP LPs exist, we are in a kexec'd kernel and VPs already exist */\n 436:\t\tif (num_present_cpus() == 1 || hv_lp_exists(1))\n 437:\t\t\treturn;\n 438:\t\n 439:\t\tfor_each_present_cpu(i) {\n"
}

37/2 2026/10/07 21:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 120973
							output: 43
							thoughts: 12
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:

**Navigating the Hyper-V Landscape**

Alright, so the task at hand is clear: I need to locate and understand the significance of `ms_hyperv_platform`. It’s a bit of a breadcrumb trail I'm following, so let's start with the basics. My initial instinct is to dig directly into the Hyper-V architecture itself. I need to figure out precisely where this component resides within the broader picture. Is it a core driver, a management interface, or perhaps something more deeply embedded in the virtualization stack? The name strongly suggests a platform-level element, but specifics are crucial. My prior experience tells me that these platform components often act as the foundational layer, and understanding their function is key to the overall operation and performance of Hyper-V. Time to dive into the documentation, source code (if accessible), and system internals to pinpoint its exact role and dependencies. Knowledge is power.



38/2 2026/10/07 21:57 tool grepper
0m Args:
{
  "Expression": "ms_hyperv_platform",
  "PathPrefixes": [
    "arch/x86/kernel/cpu/mshyperv.c"
  ]
}

Results:
{
  "Output": "arch/x86/kernel/cpu/mshyperv.c=337=EXPORT_STATIC_CALL_TRAMP_GPL(hv_hypercall);\n--\narch/x86/kernel/cpu/mshyperv.c-345-\narch/x86/kernel/cpu/mshyperv.c:346:static uint32_t  __init ms_hyperv_platform(void)\narch/x86/kernel/cpu/mshyperv.c-347-{\n--\narch/x86/kernel/cpu/mshyperv.c=812=const __initconst struct hypervisor_x86 x86_hyper_ms_hyperv = {\narch/x86/kernel/cpu/mshyperv.c-813-\t.name\t\t\t= \"Microsoft Hyper-V\",\narch/x86/kernel/cpu/mshyperv.c:814:\t.detect\t\t\t= ms_hyperv_platform,\narch/x86/kernel/cpu/mshyperv.c-815-\t.type\t\t\t= X86_HYPER_MS_HYPERV,\n"
}

39/2 2026/10/07 21:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 121533
							output: 44
							thoughts: 12
						

Thoughts:
Okay, here's my interpretation of what's going on, framed as a first-person expert perspective:

**Diving into `ms_hyperv_platform`**

Alright, let's get into this `ms_hyperv_platform` thing. My initial instinct is to dig right in. I want to see what's under the hood. What assumptions are baked into this? What are the key abstractions being used? Are there any potential gotchas that immediately jump out at me given my experience with similar virtualization environments? I'm looking for the core principles of its design. Is it a monolithic architecture or something more modular? Are there opportunities for performance optimization or, conversely, areas that might be bottlenecks? I need to understand its relationship to the underlying hardware and the host operating system. I'm focusing on its interactions, so that I understand how it all fits together. Finally, is there any chance that it will be useful for my research?



40/2 2026/10/07 21:57 tool read-file
0m Args:
{
  "File": "arch/x86/kernel/cpu/mshyperv.c",
  "FirstLine": 345,
  "LineCount": 45
}

Results:
{
  "Contents": " 345:\t\n 346:\tstatic uint32_t  __init ms_hyperv_platform(void)\n 347:\t{\n 348:\t\tu32 eax;\n 349:\t\tu32 hyp_signature[3];\n 350:\t\n 351:\t\tif (!boot_cpu_has(X86_FEATURE_HYPERVISOR))\n 352:\t\t\treturn 0;\n 353:\t\n 354:\t\tcpuid(HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS,\n 355:\t\t      \u0026eax, \u0026hyp_signature[0], \u0026hyp_signature[1], \u0026hyp_signature[2]);\n 356:\t\n 357:\t\tif (eax \u003c HYPERV_CPUID_MIN || eax \u003e HYPERV_CPUID_MAX ||\n 358:\t\t    memcmp(\"Microsoft Hv\", hyp_signature, 12))\n 359:\t\t\treturn 0;\n 360:\t\n 361:\t\t/* HYPERCALL and VP_INDEX MSRs are mandatory for all features. */\n 362:\t\teax = cpuid_eax(HYPERV_CPUID_FEATURES);\n 363:\t\tif (!(eax \u0026 HV_MSR_HYPERCALL_AVAILABLE)) {\n 364:\t\t\tpr_warn(\"x86/hyperv: HYPERCALL MSR not available.\\n\");\n 365:\t\t\treturn 0;\n 366:\t\t}\n 367:\t\tif (!(eax \u0026 HV_MSR_VP_INDEX_AVAILABLE)) {\n 368:\t\t\tpr_warn(\"x86/hyperv: VP_INDEX MSR not available.\\n\");\n 369:\t\t\treturn 0;\n 370:\t\t}\n 371:\t\n 372:\t\treturn HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;\n 373:\t}\n 374:\t\n 375:\t#ifdef CONFIG_X86_LOCAL_APIC\n 376:\t/*\n 377:\t * Prior to WS2016 Debug-VM sends NMIs to all CPUs which makes\n 378:\t * it difficult to process CHANNELMSG_UNLOAD in case of crash. Handle\n 379:\t * unknown NMI on the first CPU which gets it.\n 380:\t */\n 381:\tstatic int hv_nmi_unknown(unsigned int val, struct pt_regs *regs)\n 382:\t{\n 383:\t\tstatic atomic_t nmi_cpu = ATOMIC_INIT(-1);\n 384:\t\tunsigned int old_cpu, this_cpu;\n 385:\t\n 386:\t\tif (!unknown_nmi_panic)\n 387:\t\t\treturn NMI_DONE;\n 388:\t\n 389:\t\told_cpu = -1;\n"
}

41/2 2026/10/07 21:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 122531
							output: 20
							thoughts: 1249
						

Thoughts:
**Analyzing a Potential Syzkaller Fuzzing Vector**

Okay, let's break this down. My initial thought was about Hyper-V enlightenments in QEMU/KVM. Can QEMU emulate the VMBus? I know there's a `vmbus-bridge` option in QEMU, specified with  `qemu-system-x86_64 -device vmbus-bridge ...`. But does standard syzkaller, by default, utilize `vmbus-bridge`? No, it doesn't. Standard syzkaller typically uses standard virtio devices such as `-net nic,model=e1000 -net user ... -drive file=... if=virtio`.

But wait a minute! Time to dig into the patch and see what's really being touched.  Let's list all the files changed in the patch to get the full picture.

1.  `drivers/hv/Kconfig`
2.  `drivers/hv/Makefile`
3.  `drivers/hv/channel.c`
4.  `drivers/hv/channel_mgmt.c`
5.  `drivers/hv/hv_trace.h`
6.  `drivers/hv/hyperv_vmbus.h`
7.  `drivers/hv/ring_buffer.c`
8.  `drivers/hv/vmbus_buffer_test.c` (KUnit test)
9.  `drivers/hv/vmbus_drv.c`
10. `drivers/hv/vmbus_mmap_test.c` (KUnit test)
11. `drivers/net/hyperv/Kconfig`
12. `drivers/net/hyperv/Makefile`
13. `drivers/net/hyperv/hyperv_net.h`
14. `drivers/net/hyperv/netvsc.c`
15. `drivers/net/hyperv/netvsc_completion_test.c` (KUnit test)
16. `drivers/net/hyperv/rndis_filter.c`
17. `drivers/net/hyperv/rndis_request_test.c` (KUnit test)
18. `drivers/uio/Kconfig`
19. `drivers/uio/uio.c`
20. `drivers/uio/uio_hv_generic.c`
21. `drivers/uio/uio_hv_generic_mmap_test.c` (KUnit test)
22. `include/linux/hyperv.h`

Aha! `drivers/uio/uio.c` is in the list, and that jumps out. Now, is `uio.c` Hyper-V specific? No, `drivers/uio/uio.c` is actually the Userspace I/O driver core framework!

Is this code path reachable? Let's check out the changes to `drivers/uio/uio.c`:

```c
diff --git a/drivers/uio/uio.c b/drivers/uio/uio.c
index f8fa205226601..4767ed0661f74 100644
--- a/drivers/uio/uio.c
+++ b/drivers/uio/uio.c
@@ -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


42/2 2026/10/07 21:57 tool grepper
0m Args:
{
  "Expression": "uio_register_device"
}

Results:
{
  "Output": "drivers/net/ethernet/broadcom/cnic.c=1090=static int cnic_init_uio(struct cnic_dev *dev)\n--\ndrivers/net/ethernet/broadcom/cnic.c-1153-\ndrivers/net/ethernet/broadcom/cnic.c:1154:\t\t\tret = uio_register_device(\u0026udev-\u003epdev-\u003edev, uinfo);\ndrivers/net/ethernet/broadcom/cnic.c-1155-\t\t}\n--\ndrivers/scsi/qedi/qedi_main.c=307=static int qedi_init_uio(struct qedi_ctx *qedi)\n--\ndrivers/scsi/qedi/qedi_main.c-340-\ndrivers/scsi/qedi/qedi_main.c:341:\t\t\tret = uio_register_device(\u0026udev-\u003epdev-\u003edev, uinfo);\ndrivers/scsi/qedi/qedi_main.c-342-\t\t\tif (ret) {\n--\ndrivers/target/target_core_user.c=2207=static int tcmu_configure_device(struct se_device *dev)\n--\ndrivers/target/target_core_user.c-2269-\ndrivers/target/target_core_user.c:2270:\tret = uio_register_device(tcmu_root_device, info);\ndrivers/target/target_core_user.c-2271-\tif (ret)\n--\ndrivers/uio/uio.c=990=static void uio_device_release(struct device *dev)\n--\ndrivers/uio/uio.c-997-/**\ndrivers/uio/uio.c:998: * __uio_register_device - register a new userspace IO device\ndrivers/uio/uio.c-999- * @owner:\tmodule that creates the new device\n--\ndrivers/uio/uio.c-1004- */\ndrivers/uio/uio.c:1005:int __uio_register_device(struct module *owner,\ndrivers/uio/uio.c-1006-\t\t\t  struct device *parent,\n--\ndrivers/uio/uio.c-1090-}\ndrivers/uio/uio.c:1091:EXPORT_SYMBOL_GPL(__uio_register_device);\ndrivers/uio/uio.c-1092-\ndrivers/uio/uio.c=1093=static void devm_uio_unregister_device(struct device *dev, void *res)\n--\ndrivers/uio/uio.c-1098-/**\ndrivers/uio/uio.c:1099: * __devm_uio_register_device - Resource managed uio_register_device()\ndrivers/uio/uio.c-1100- * @owner:\tmodule that creates the new device\n--\ndrivers/uio/uio.c-1105- */\ndrivers/uio/uio.c:1106:int __devm_uio_register_device(struct module *owner,\ndrivers/uio/uio.c-1107-\t\t\t       struct device *parent,\n--\ndrivers/uio/uio.c-1118-\t*ptr = info;\ndrivers/uio/uio.c:1119:\tret = __uio_register_device(owner, parent, info);\ndrivers/uio/uio.c-1120-\tif (ret) {\n--\ndrivers/uio/uio.c-1128-}\ndrivers/uio/uio.c:1129:EXPORT_SYMBOL_GPL(__devm_uio_register_device);\ndrivers/uio/uio.c-1130-\n--\ndrivers/uio/uio_aec.c=69=static int probe(struct pci_dev *pdev, const struct pci_device_id *id)\n--\ndrivers/uio/uio_aec.c-99-\tprint_board_data(pdev, info);\ndrivers/uio/uio_aec.c:100:\tret = uio_register_device(\u0026pdev-\u003edev, info);\ndrivers/uio/uio_aec.c-101-\tif (ret)\n--\ndrivers/uio/uio_cif.c=41=static int hilscher_pci_probe(struct pci_dev *dev,\n--\ndrivers/uio/uio_cif.c-82-\ndrivers/uio/uio_cif.c:83:\tif (uio_register_device(\u0026dev-\u003edev, info))\ndrivers/uio/uio_cif.c-84-\t\tgoto out_unmap;\n--\ndrivers/uio/uio_dfl.c=14=static int uio_dfl_probe(struct dfl_device *ddev)\n--\ndrivers/uio/uio_dfl.c-39-\ndrivers/uio/uio_dfl.c:40:\tret = devm_uio_register_device(dev, uioinfo);\ndrivers/uio/uio_dfl.c-41-\tif (ret)\n--\ndrivers/uio/uio_dmem_genirq.c=152=static int uio_dmem_genirq_probe(struct platform_device *pdev)\n--\ndrivers/uio/uio_dmem_genirq.c-296-\ndrivers/uio/uio_dmem_genirq.c:297:\treturn devm_uio_register_device(\u0026pdev-\u003edev, priv-\u003euioinfo);\ndrivers/uio/uio_dmem_genirq.c-298-}\n--\ndrivers/uio/uio_fsl_elbc_gpcm.c=298=static int uio_fsl_elbc_gpcm_probe(struct platform_device *pdev)\n--\ndrivers/uio/uio_fsl_elbc_gpcm.c-404-\t/* register UIO device */\ndrivers/uio/uio_fsl_elbc_gpcm.c:405:\tif (uio_register_device(priv-\u003edev, info) != 0) {\ndrivers/uio/uio_fsl_elbc_gpcm.c-406-\t\tdev_err(priv-\u003edev, \"UIO registration failed\\n\");\n--\ndrivers/uio/uio_hv_generic.c=507=hv_uio_probe(struct hv_device *dev,\n--\ndrivers/uio/uio_hv_generic.c-604-\ndrivers/uio/uio_hv_generic.c:605:\tret = uio_register_device(\u0026dev-\u003edevice, \u0026pdata-\u003einfo);\ndrivers/uio/uio_hv_generic.c-606-\tif (ret) {\n--\ndrivers/uio/uio_hv_generic_mmap_test.c=817=static void hv_uio_unregister_wakes_reader_test(struct kunit *test)\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-831-\tKUNIT_ASSERT_FALSE(test, IS_ERR(parent));\ndrivers/uio/uio_hv_generic_mmap_test.c:832:\tret = uio_register_device(parent, \u0026info);\ndrivers/uio/uio_hv_generic_mmap_test.c-833-\tif (ret) {\n--\ndrivers/uio/uio_mf624.c=135=static int mf624_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)\n--\ndrivers/uio/uio_mf624.c-171-\ndrivers/uio/uio_mf624.c:172:\tif (uio_register_device(\u0026dev-\u003edev, info))\ndrivers/uio/uio_mf624.c-173-\t\tgoto out_unmap2;\n--\ndrivers/uio/uio_netx.c=50=static int netx_pci_probe(struct pci_dev *dev,\n--\ndrivers/uio/uio_netx.c-99-\ndrivers/uio/uio_netx.c:100:\tif (uio_register_device(\u0026dev-\u003edev, info))\ndrivers/uio/uio_netx.c-101-\t\tgoto out_unmap;\n--\ndrivers/uio/uio_pci_generic.c=71=static int probe(struct pci_dev *pdev,\n--\ndrivers/uio/uio_pci_generic.c-135-\ndrivers/uio/uio_pci_generic.c:136:\treturn devm_uio_register_device(\u0026pdev-\u003edev, \u0026gdev-\u003einfo);\ndrivers/uio/uio_pci_generic.c-137-}\n--\ndrivers/uio/uio_pci_generic_sva.c=62=static int probe(struct pci_dev *pdev, const struct pci_device_id *id)\n--\ndrivers/uio/uio_pci_generic_sva.c-128-\ndrivers/uio/uio_pci_generic_sva.c:129:\tret = devm_uio_register_device(\u0026pdev-\u003edev, \u0026udev-\u003einfo);\ndrivers/uio/uio_pci_generic_sva.c-130-\tif (ret) {\n--\ndrivers/uio/uio_pdrv_genirq.c=109=static int uio_pdrv_genirq_probe(struct platform_device *pdev)\n--\ndrivers/uio/uio_pdrv_genirq.c-243-\ndrivers/uio/uio_pdrv_genirq.c:244:\tret = devm_uio_register_device(\u0026pdev-\u003edev, priv-\u003euioinfo);\ndrivers/uio/uio_pdrv_genirq.c-245-\tif (ret)\n--\ndrivers/uio/uio_sercos3.c=120=static int sercos3_pci_probe(struct pci_dev *dev,\n--\ndrivers/uio/uio_sercos3.c-163-\ndrivers/uio/uio_sercos3.c:164:\tif (uio_register_device(\u0026dev-\u003edev, info))\ndrivers/uio/uio_sercos3.c-165-\t\tgoto out_unmap;\n--\ninclude/linux/uio_driver.h=121=extern int __must_check\ninclude/linux/uio_driver.h:122:\t__uio_register_device(struct module *owner,\ninclude/linux/uio_driver.h-123-\t\t\t      struct device *parent,\n--\ninclude/linux/uio_driver.h-128-/**\ninclude/linux/uio_driver.h:129: * uio_register_device - register a new userspace IO device\ninclude/linux/uio_driver.h-130- * @parent:\tparent device\n--\ninclude/linux/uio_driver.h-134- */\ninclude/linux/uio_driver.h:135:#define uio_register_device(parent, info) \\\ninclude/linux/uio_driver.h:136:\t__uio_register_device(THIS_MODULE, parent, info)\ninclude/linux/uio_driver.h-137-\n--\ninclude/linux/uio_driver.h=141=extern int __must_check\ninclude/linux/uio_driver.h:142:\t__devm_uio_register_device(struct module *owner,\ninclude/linux/uio_driver.h-143-\t\t\t\t   struct device *parent,\n--\ninclude/linux/uio_driver.h-148-/**\ninclude/linux/uio_driver.h:149: * devm_uio_register_device - Resource managed uio_register_device()\ninclude/linux/uio_driver.h-150- * @parent:\tparent device\n--\ninclude/linux/uio_driver.h-154- */\ninclude/linux/uio_driver.h:155:#define devm_uio_register_device(parent, info) \\\ninclude/linux/uio_driver.h:156:\t__devm_uio_register_device(THIS_MODULE, parent, info)\ninclude/linux/uio_driver.h-157-\n"
}

43/2 2026/10/07 21:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 128027
							output: 22
							thoughts: 1880
						

Thoughts:
**Analysis of UIO Driver for Potential Fuzzing**

Okay, so the TCMU (Target Core User) driver dynamically registers UIO devices. I can see it does this through `tcmu_configure_device()` in `drivers/target/target_core_user.c`, specifically using `uio_register_device()`.  I recall TCMU devices can be created via configfs at `/sys/kernel/config/target/core/user_...`, and syzkaller has descriptors for configfs / target.  When TCMU configures a device, `/dev/uioX` is created.  If a user opens and mmaps this device, it executes `uio_mmap`, which in turn calls `tcmu_mmap_prepare`.  That's the setup.

Now, let's pivot to fuzzability. The initial thought was to consider Hyper-V VMBus or other potential paths. I need to make sure I am answering in the terms of the prompt. But first, let's see if there is potential for fuzzing UIO itself. Let's check `drivers/uio/uio.c`.  I need to go through the checklist.

The first rule is: "Non-kernel and non-executable changes". No, the UIO core code isn't just documentation or scripts. "Structurally unreachable hardware?" No, UIO is a driver core framework, not vendor-specific hardware.  Specifically, TCMU is purely software/virtual.  "Unreachable execution paths?"  No, `uio_mmap` *is* the `mmap()` syscall handler for `/dev/uio*` devices, making it reachable.  "Code paths exclusive to architectures other than amd64?" No, amd64 is the target architecture.  Okay, so it seems like `drivers/uio/uio.c` does *not* fall under the negative criteria.

Now, I need to check the positive criteria.  I see that the patch modifies the `uio_mmap` function. This isn't just a refactoring or cleanup. This change modifies core logic. Specifically, `uio_mmap` is modified to include a `__compat_vma_mmap` call with additional checks.  The rules state that I should return WorthFuzzing=true, because I am modifying a reachable driver and executable code.

Now I am going to examine the `uio_mmap` function specifically. I see that there is a call to `__compat_vma_mmap(&desc, vma)` and there are checks on the return value.  Specifically, it's checking what happens if `__compat_vma_mmap` returns an error!  This is promising because this is now a new code path that requires further scrutiny. I now need to examine the definition of `__compat_vma_mmap` to understand the conditions under which it can fail and the implications of those failures.



44/2 2026/10/07 21:58 tool grepper
0m Args:
{
  "Expression": "__compat_vma_mmap"
}

Results:
{
  "Output": "drivers/hv/vmbus_drv.c=1926=static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,\n--\ndrivers/hv/vmbus_drv.c-1953-\t * path in vm_ops-\u003eclose and typically to vm_ops-\u003emapped. Install\ndrivers/hv/vmbus_drv.c:1954:\t * both before __compat_vma_mmap() so a failure in\ndrivers/hv/vmbus_drv.c-1955-\t * mmap_action_prepare() still reaches close(): that path never runs\ndrivers/hv/vmbus_drv.c-1956-\t * compat_set_vma_from_desc(), and the legacy .mmap error path frees\ndrivers/hv/vmbus_drv.c:1957:\t * the VMA without calling close() on its own. __compat_vma_mmap()\ndrivers/hv/vmbus_drv.c-1958-\t * installs the same values again on its way to the action. Note\n--\ndrivers/hv/vmbus_drv.c-1964-\t * vmbus_buffer_pin and this wrapper is its only owner. Release it\ndrivers/hv/vmbus_drv.c:1965:\t * when __compat_vma_mmap() returns: on success insert_pages() has\ndrivers/hv/vmbus_drv.c-1966-\t * already taken a folio reference for every page the VMA maps, and\n--\ndrivers/hv/vmbus_drv.c-1974-\ndrivers/hv/vmbus_drv.c:1975:\t\terr = __compat_vma_mmap(\u0026desc, vma);\ndrivers/hv/vmbus_drv.c-1976-\t\tif (err \u0026\u0026 vma-\u003evm_ops \u0026\u0026 vma-\u003evm_ops-\u003eclose)\n--\ndrivers/hv/vmbus_drv.c-1981-\tpin = desc.private_data;\ndrivers/hv/vmbus_drv.c:1982:\terr = __compat_vma_mmap(\u0026desc, vma);\ndrivers/hv/vmbus_drv.c-1983-\tvma-\u003evm_private_data = NULL;\n--\ndrivers/uio/uio.c=820=static int uio_mmap(struct file *filep, struct vm_area_struct *vma)\n--\ndrivers/uio/uio.c-861-\t\t/*\ndrivers/uio/uio.c:862:\t\t * Install the per-VMA state before __compat_vma_mmap() so a\ndrivers/uio/uio.c-863-\t\t * failure in mmap_action_prepare() still reaches close(). That\n--\ndrivers/uio/uio.c-865-\t\t * .mmap error path frees the VMA without calling close() on\ndrivers/uio/uio.c:866:\t\t * its own. __compat_vma_mmap() installs the same values again\ndrivers/uio/uio.c-867-\t\t * on its way to the action.\n--\ndrivers/uio/uio.c-877-\ndrivers/uio/uio.c:878:\t\tret = __compat_vma_mmap(\u0026desc, vma);\ndrivers/uio/uio.c-879-\t\tif (ret \u0026\u0026 vma-\u003evm_ops \u0026\u0026 vma-\u003evm_ops-\u003eclose)\n--\ndrivers/uio/uio_hv_generic.c=373=hv_uio_ring_mmap_prepare(struct vmbus_channel *channel,\n--\ndrivers/uio/uio_hv_generic.c-407-\t * a synchronous legacy .mmap: it holds @pin across\ndrivers/uio/uio_hv_generic.c:408:\t * __compat_vma_mmap() and frees it when that returns, exactly once,\ndrivers/uio/uio_hv_generic.c-409-\t * on every outcome. desc-\u003eprivate_data is a plain\n--\ndrivers/uio/uio_hv_generic_mmap_test.c-19- * Release exactly what hv_mmap_ring_buffer_wrapper() releases after\ndrivers/uio/uio_hv_generic_mmap_test.c:20: * __compat_vma_mmap() returns: the bare pin's references, then the pin.\ndrivers/uio/uio_hv_generic_mmap_test.c-21- */\n--\ninclude/linux/fs.h=2054=void compat_set_desc_from_vma(struct vm_area_desc *desc, const struct file *file,\ninclude/linux/fs.h-2055-\t\t\t      const struct vm_area_struct *vma);\ninclude/linux/fs.h:2056:int __compat_vma_mmap(struct vm_area_desc *desc, struct vm_area_struct *vma);\ninclude/linux/fs.h-2057-int compat_vma_mmap(struct file *file, struct vm_area_struct *vma);\n--\nmm/util.c=1200=EXPORT_SYMBOL(compat_set_desc_from_vma);\n--\nmm/util.c-1202-/**\nmm/util.c:1203: * __compat_vma_mmap() - Similar to compat_vma_mmap(), only it allows\nmm/util.c-1204- * flexibility as to how the mmap_prepare callback is invoked, which is useful\n--\nmm/util.c-1223- */\nmm/util.c:1224:int __compat_vma_mmap(struct vm_area_desc *desc,\nmm/util.c-1225-\t\t      struct vm_area_struct *vma)\n--\nmm/util.c-1237-}\nmm/util.c:1238:EXPORT_SYMBOL(__compat_vma_mmap);\nmm/util.c-1239-\n--\nmm/util.c=1266=int compat_vma_mmap(struct file *file, struct vm_area_struct *vma)\n--\nmm/util.c-1280-\nmm/util.c:1281:\treturn __compat_vma_mmap(\u0026desc, vma);\nmm/util.c-1282-}\n--\ntools/testing/vma/include/dup.h=1360=static inline int vfs_mmap_prepare(struct file *file, struct vm_area_desc *desc)\n--\ntools/testing/vma/include/dup.h-1364-\ntools/testing/vma/include/dup.h:1365:static inline int __compat_vma_mmap(struct vm_area_desc *desc,\ntools/testing/vma/include/dup.h-1366-\t\tstruct vm_area_struct *vma)\n--\ntools/testing/vma/include/dup.h=1380=static inline int compat_vma_mmap(struct file *file, struct vm_area_struct *vma)\n--\ntools/testing/vma/include/dup.h-1394-\ntools/testing/vma/include/dup.h:1395:\treturn __compat_vma_mmap(\u0026desc, vma);\ntools/testing/vma/include/dup.h-1396-}\n"
}

45/2 2026/10/07 21:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 132440
							output: 34
							thoughts: 23
						

Thoughts:
Okay, let's dive into this! Here's my thought process as I approach the code:

**Diving into `mm/util.c` around `__compat_vma_mmap`**

Right, let's get into this. I need to understand what's going on with compatibility memory mapping. The comment mentions `__compat_vma_mmap` in `mm/util.c`, so that's where I'll begin. I'm already anticipating some of the usual suspects – address space layouts, potential issues arising from different pointer sizes between architectures, and perhaps some considerations around how older programs interact with the kernel's memory management. I suspect this will be interesting, as compatibility layers often deal with subtle, difficult to debug interactions. I expect to be looking for how the kernel handles address translation and permission modifications for memory mapped regions when running in a compatibility context. I will be looking closely at any interactions between different architecture's page size, and the compat mode's memory mapping. Let's start by understanding the flow and then I'll look for potential pitfalls and corner cases.



46/2 2026/10/07 21:58 tool read-file
0m Args:
{
  "File": "mm/util.c",
  "FirstLine": 1200,
  "LineCount": 45
}

Results:
{
  "Contents": "1200:\tEXPORT_SYMBOL(compat_set_desc_from_vma);\n1201:\t\n1202:\t/**\n1203:\t * __compat_vma_mmap() - Similar to compat_vma_mmap(), only it allows\n1204:\t * flexibility as to how the mmap_prepare callback is invoked, which is useful\n1205:\t * for drivers which invoke nested mmap_prepare callbacks in an mmap() hook.\n1206:\t * @desc: A VMA descriptor upon which an mmap_prepare() hook has already been\n1207:\t * executed.\n1208:\t * @vma: The VMA to which @desc should be applied.\n1209:\t *\n1210:\t * The function assumes that you have obtained a VMA descriptor @desc from\n1211:\t * compat_set_desc_from_vma(), and already executed the mmap_prepare() hook upon\n1212:\t * it.\n1213:\t *\n1214:\t * It then performs any specified mmap actions, and invokes the vm_ops-\u003emapped()\n1215:\t * hook if one is present.\n1216:\t *\n1217:\t * See the description of compat_vma_mmap() for more details.\n1218:\t *\n1219:\t * Once the conversion of drivers is complete this function will no longer be\n1220:\t * required and will be removed.\n1221:\t *\n1222:\t * Returns: 0 on success or error.\n1223:\t */\n1224:\tint __compat_vma_mmap(struct vm_area_desc *desc,\n1225:\t\t\t      struct vm_area_struct *vma)\n1226:\t{\n1227:\t\tint err;\n1228:\t\n1229:\t\t/* Perform any preparatory tasks for mmap action. */\n1230:\t\terr = mmap_action_prepare(desc);\n1231:\t\tif (err)\n1232:\t\t\treturn err;\n1233:\t\t/* Update the VMA from the descriptor. */\n1234:\t\tcompat_set_vma_from_desc(vma, desc);\n1235:\t\t/* Complete any specified mmap actions. */\n1236:\t\treturn mmap_action_complete(vma, \u0026desc-\u003eaction, /*is_compat=*/true);\n1237:\t}\n1238:\tEXPORT_SYMBOL(__compat_vma_mmap);\n1239:\t\n1240:\t/**\n1241:\t * compat_vma_mmap() - Apply the file's .mmap_prepare() hook to an\n1242:\t * existing VMA and execute any requested actions.\n1243:\t * @file: The file which possesss an f_op-\u003emmap_prepare() hook.\n1244:\t * @vma: The VMA to apply the .mmap_prepare() hook to.\n"
}

47/2 2026/10/07 21:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 133506
							output: 29
							thoughts: 763
						

Thoughts:
**Analyzing a Potential TCMU Reference Count Underflow**

Okay, let's break this down. I'm looking at the `__compat_vma_mmap` function and its interactions with the Virtual Memory Area (VMA) in the kernel, specifically concerning compatibility with older systems. The key here is the mmap process and how it handles potential failures.

I see that `__compat_vma_mmap` first calls `mmap_action_prepare`, and if that fails, it returns immediately. The critical point is that *if* this preparation fails, `compat_set_vma_from_desc` isn't called. This is crucial because `compat_set_vma_from_desc` is responsible for setting up the VMA's operation structures (`vm_ops`) and private data.

My mind immediately jumps to the implication within `uio_mmap`. Previously, a failure in `__compat_vma_mmap` meant that the VMA wasn't properly initialized. Specifically, the `vm_ops` and `vm_private_data` were *not* set. Now, with the updated code, we have a scenario where the `vm_ops` might be set *before* calling `__compat_vma_mmap`. And then, if the `__compat_vma_mmap` function fails, the system calls `vma->vm_ops->close`.

The alarm bells are getting louder now because I know that in the context of TCMU (`drivers/target/target_core_user.c`), `desc.vm_ops` is set to `&tcmu_vm_ops`. Also, the associated `tcmu_vm_ops.close` is `tcmu_vma_close`. Inside `tcmu_vma_close`, we have the line `kref_put(&udev->kref, tcmu_dev_kref_release);`. And looking at the broader TCMU context I know `kref_get` is called only in `mapped`.

This is where the problem is screaming at me: *If `__compat_vma_mmap` fails (e.g., during `mmap_action_prepare` or `mmap_action_complete`), `vma->vm_ops->close(vma)` is still called*. This happens *without* a corresponding `kref_get`. My expert intuition tells me this is a classic reference count underflow, potentially leading to a Use-After-Free (UAF) situation in TCMU. The `kref_put` would decrement a reference count without it being previously incremented.

This needs further investigation. It will be helpful to establish a full context for `tcmu` and how TCMU is reachable in standard virtualized environments. I'm going to quickly check the `CONFIG_TCM_USER2` and `CONFIG_TARGET_CORE` kernel configuration options. Let's see if this flaw is easily exploitable.



48/2 2026/10/07 21:58 tool grepper
0m Args:
{
  "Expression": "config TCM_USER2",
  "PathPrefixes": [
    "drivers/target"
  ]
}

Results:
{
  "Output": "drivers/target/Kconfig=31=config TCM_PSCSI\n--\ndrivers/target/Kconfig-37-\ndrivers/target/Kconfig:38:config TCM_USER2\ndrivers/target/Kconfig-39-\ttristate \"TCM/USER Subsystem Plugin for Linux\"\n"
}

49/2 2026/10/07 21:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 135021
							output: 33
							thoughts: 15
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Analyzing Dependencies for TCM_USER2**

Alright, let's dive in. My immediate thought is, "What's `TCM_USER2`'s current dependency landscape?" Understanding the dependencies of this particular user model is crucial before proceeding with any action, modification, or even analysis on this user. I need a clear picture of what this component *relies* on. We're talking about things like services, data stores, external APIs, other internal components... the full picture. My initial approach will probably involve some form of introspection – whether that's through documented architecture diagrams, looking at configuration files, inspecting the code itself, or maybe even running some dependency analysis tools. The aim is to build a solid, dependable map of the relationships and understand if there's any implicit or obscure linkages.



50/2 2026/10/07 21:58 tool read-file
0m Args:
{
  "File": "drivers/target/Kconfig",
  "FirstLine": 35,
  "LineCount": 20
}

Results:
{
  "Contents": "  35:\t\tSay Y here to enable the TCM/pSCSI subsystem plugin for non-buffered\n  36:\t\tpassthrough access to Linux/SCSI device\n  37:\t\n  38:\tconfig TCM_USER2\n  39:\t\ttristate \"TCM/USER Subsystem Plugin for Linux\"\n  40:\t\tdepends on UIO \u0026\u0026 NET\n  41:\t\thelp\n  42:\t\tSay Y here to enable the TCM/USER subsystem plugin for a userspace\n  43:\t\tprocess to handle requests. This is version 2 of the ABI; version 1\n  44:\t\tis obsolete.\n  45:\t\n  46:\tsource \"drivers/target/loopback/Kconfig\"\n  47:\tsource \"drivers/target/tcm_fc/Kconfig\"\n  48:\tsource \"drivers/target/iscsi/Kconfig\"\n  49:\tsource \"drivers/target/sbp/Kconfig\"\n  50:\tsource \"drivers/target/tcm_remote/Kconfig\"\n  51:\t\n  52:\tendif\n"
}

51/2 2026/10/07 21:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 135529
							output: 31
							thoughts: 6684
						

Thoughts:
**Analysis of Patch for WorthFuzzing=true**

Okay, after carefully reviewing this patch, my expert assessment is that this patch is **WorthFuzzing=true**.  Here's my reasoning:

First, this patch affects multiple subsystems, most critically `drivers/uio/uio.c`.  `uio.c` is the core of Userspace I/O and is not specific to any particular hardware. The modification to `uio_mmap` introduces a change in the error handling path. Specifically, if `__compat_vma_mmap` fails, it now calls `vma->vm_ops->close(vma)`. This is significant because, for example, the Target Core Module (TCMU), through `tcmu_mmap_prepare`, provides a `vm_ops->close` function (`tcmu_vma_close`) that *decrements* a reference count without a corresponding *increment*. This introduces a clear potential for a use-after-free or a related refcount underflow bug, which is a major red flag for fuzzing. This is a clear semantic change that can be reached and is not a purely decorative change or unreachable path.

Second, the patch's changes related to Hyper-V are likely reachable.  While standard syzkaller configurations might not explicitly enable Hyper-V VMBus emulation (`-device vmbus-bridge`), QEMU *does* support Hyper-V guests and the VMBus, and the code touches Hyper-V network and buffer management via `netvsc.c`, `rndis_filter.c` and `channel.c`. Even if Hyper-V is *not* enabled by default, the changes to the generic UIO code (`uio.c`) *are* reachable. Furthermore, Hyper-V support can be explicitly enabled in QEMU, making those drivers reachable as well, expanding the fuzzing surface.

Third, the patch introduces several new functions related to VMBus buffer management and mmap within Hyper-V, and these new functions could be a source of security issues.  Even if the primary focus becomes UIO, adding these entrypoints to the FocusSymbols will increase the likelihood of discovering crashes.

The key here is that, while this patch also touches Hyper-V code, the most *critical* change, in `uio.c`, is *universally* reachable when UIO is enabled, which is a common kernel configuration. The potential refcount underflow bug introduced is a high-priority target for fuzzing.

My list of **FocusSymbols** should include:

*   `uio_mmap` (drivers/uio/uio.c)
*   `hv_uio_mmap_prepare` (drivers/uio/uio_hv_generic.c)
*   `hv_uio_ring_mmap_prepare` (drivers/uio/uio_hv_generic.c)
*   `hv_uio_probe` (drivers/uio/uio_hv_generic.c)
*   `hv_uio_cleanup` (drivers/uio/uio_hv_generic.c)
*   `vmbus_alloc_buffer_owned` (drivers/hv/channel.c)
*   `vmbus_release_buffer` (drivers/hv/channel.c)
*   `vmbus_buffer_pin_pages` (drivers/hv/channel.c)
*   `vmbus_buffer_unpin_pages` (drivers/hv/channel.c)
*   `vmbus_teardown_gpadl_owned` (drivers/hv/channel.c)
*   `vmbus_establish_gpadl_owned` (drivers/hv/channel.c)
*   `vmbus_buffer_reclaim_work` (drivers/hv/channel.c)
*   `vmbus_gpadl_teardown_request` (drivers/hv/channel.c)
*   `hv_mmap_ring_buffer_wrapper` (drivers/hv/vmbus_drv.c)
*   `netvsc_send_completion` (drivers/net/hyperv/netvsc.c)
*   `netvsc_send_tx_complete` (drivers/net/hyperv/netvsc.c)
*   `netvsc_send_acct` (drivers/net/hyperv/netvsc.c)
*   `netvsc_init_buf` (drivers/net/hyperv/netvsc.c)
*   `rndis_build_page_buffers`


52/2 2026/10/07 21:59 tool grepper
0m Args:
{
  "Expression": "config HYPERV",
  "PathPrefixes": [
    "drivers/hv/Kconfig"
  ]
}

Results:
{
  "Output": "drivers/hv/Kconfig=3=menu \"Microsoft Hyper-V guest support\"\ndrivers/hv/Kconfig-4-\ndrivers/hv/Kconfig:5:config HYPERV\ndrivers/hv/Kconfig-6-\tbool \"Microsoft Hyper-V core hypervisor support\"\n--\ndrivers/hv/Kconfig-16-\ndrivers/hv/Kconfig:17:config HYPERV_VTL_MODE\ndrivers/hv/Kconfig-18-\tbool \"Enable Linux to boot in VTL context\"\n--\ndrivers/hv/Kconfig-42-\ndrivers/hv/Kconfig:43:config HYPERV_TIMER\ndrivers/hv/Kconfig-44-\tdef_bool HYPERV \u0026\u0026 X86\ndrivers/hv/Kconfig-45-\ndrivers/hv/Kconfig:46:config HYPERV_UTILS\ndrivers/hv/Kconfig-47-\ttristate \"Microsoft Hyper-V Utilities driver\"\n--\ndrivers/hv/Kconfig-52-\ndrivers/hv/Kconfig:53:config HYPERV_BALLOON\ndrivers/hv/Kconfig-54-\ttristate \"Microsoft Hyper-V Balloon driver\"\n--\ndrivers/hv/Kconfig-59-\ndrivers/hv/Kconfig:60:config HYPERV_VMBUS\ndrivers/hv/Kconfig-61-\ttristate \"Microsoft Hyper-V VMBus driver\"\n--\ndrivers/hv/Kconfig-67-\ndrivers/hv/Kconfig:68:config HYPERV_VMBUS_KUNIT_TEST\ndrivers/hv/Kconfig-69-\tbool \"Build Hyper-V VMBus buffer KUnit tests\"\n"
}

53/2 2026/10/07 21:59 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 143680
							output: 32
							thoughts: 11
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Dependency Check for HYPERV**

Alright, let's get down to brass tacks. I need to make sure everything's lined up before I even *think* about touching `HYPERV`. First things first: are the core hypervisor components installed and functioning? Specifically, I'm thinking about the Windows features—are the Hyper-V Management Tools, the Hyper-V Platform itself, and Virtual Machine Platform enabled? I can verify this with `Get-WindowsFeature` and a few filtering techniques.

Then, there’s the hardware compatibility. I can't just *assume* the CPU is supporting virtualization extensions (Intel VT-x or AMD-V, naturally). I'd probably need to check the processor flags using something like `Get-WmiObject Win32_Processor | Select-Object -ExpandProperty Name, VirtualizationFirmwareEnabled`. I'll also confirm that the BIOS has virtualization enabled, which is often a forgotten step, even for seasoned professionals. I could use PowerShell to check `Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty Manufacturer, Model, BootupState` to verify BIOS and Boot configuration.

Next, I have to consider the potential for conflicts. Are there any other virtualization technologies running, especially nested virtualization scenarios? VMware, VirtualBox, WSL (if applicable) can all cause issues. I'll need to check for running processes and potentially even examine kernel drivers to ensure there aren't any overlaps that could destabilize `HYPERV`. I can use `Get-Process` to check for conflicting services and processes.

Finally, I'll need to think about the storage and network configurations. Do I have the required drivers, and are they properly installed? Are there any networking conflicts or limitations? Is the storage (physical or virtual) properly configured and capable of supporting the anticipated VM workload? This part often involves checking disk health, network adapter settings, and any specific requirements of the VMs I'm planning to create.

Basically, I need a rock-solid foundation, or I'm asking for trouble. It's all about due diligence and a systematic check. The goal is to minimize potential problems down the line, and that starts with a thorough dependency analysis.



54/2 2026/10/07 21:59 tool read-file
0m Args:
{
  "File": "drivers/hv/Kconfig",
  "FirstLine": 1,
  "LineCount": 30
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0\n   2:\t\n   3:\tmenu \"Microsoft Hyper-V guest support\"\n   4:\t\n   5:\tconfig HYPERV\n   6:\t\tbool \"Microsoft Hyper-V core hypervisor support\"\n   7:\t\tdepends on (X86 \u0026\u0026 X86_LOCAL_APIC \u0026\u0026 HYPERVISOR_GUEST) \\\n   8:\t\t\t|| (ARM64 \u0026\u0026 !CPU_BIG_ENDIAN)\n   9:\t\tselect PARAVIRT\n  10:\t\tselect X86_HV_CALLBACK_VECTOR if X86\n  11:\t\tselect OF_EARLY_FLATTREE if OF\n  12:\t\tselect IRQ_MSI_LIB if X86\n  13:\t\thelp\n  14:\t\t  Select this option to run Linux as a Hyper-V client operating\n  15:\t\t  system.\n  16:\t\n  17:\tconfig HYPERV_VTL_MODE\n  18:\t\tbool \"Enable Linux to boot in VTL context\"\n  19:\t\tdepends on (X86_64 \u0026\u0026 HAVE_STATIC_CALL) || ARM64\n  20:\t\tdepends on HYPERV\n  21:\t\tdepends on SMP\n  22:\t\tdefault n\n  23:\t\thelp\n  24:\t\t  Virtual Secure Mode (VSM) is a set of hypervisor capabilities and\n  25:\t\t  enlightenments offered to host and guest partitions which enables\n  26:\t\t  the creation and management of new security boundaries within\n  27:\t\t  operating system software.\n  28:\t\n  29:\t\t  VSM achieves and maintains isolation through Virtual Trust Levels\n  30:\t\t  (VTLs). Virtual Trust Levels are hierarchical, with higher levels\n"
}

55/2 2026/10/07 21:59 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 144657
							output: 406
							thoughts: 2033
						

Thoughts:
**Analysis of UIO and Hyper-V Driver Modifications for Fuzzing**

Okay, let's break this down. First, I need to identify the relevant kernel configurations. I see that the `HYPERV_VMBUS` driver is present, and it depends on `HYPERV`. Then there's `HYPERV_NET`, depending on `HYPERV_VMBUS`, and `UIO_HV_GENERIC`, which depends on both `HYPERV_VMBUS` and `UIO`. I also need to make sure I include `TARGET_CORE` and `TCM_USER2`, given what I know about the target subsystems. So, my initial list of configurations to enable is `UIO`, `UIO_HV_GENERIC`, `HYPERV`, `HYPERV_VMBUS`, `HYPERV_NET`, `TARGET_CORE`, and `TCM_USER2`. This covers the core dependencies within the Hyper-V and UIO subsystems.

Next, I need to pinpoint the specific functions to target. The instructions tell me to avoid ubiquitous functions and focus on the core logic being added or altered. I need to identify entrypoints for the feature under review. I see that the core UIO driver, `drivers/uio/uio.c`, is modified with `uio_mmap` handling vm_ops. Then, `drivers/uio/uio_hv_generic.c` has new implementations for `hv_uio_mmap_prepare` and alterations for `hv_uio_ring_mmap_prepare`. The Hyper-V side of things involves significant new and modified functions in `drivers/hv/channel.c` (`vmbus_alloc_buffer_owned`, `vmbus_release_buffer`, `vmbus_buffer_pin_pages`, `vmbus_buffer_unpin_pages`, `vmbus_buffer_reclaim_work`, `vmbus_gpadl_teardown_request`, `vmbus_teardown_gpadl_owned`, `vmbus_establish_gpadl_owned`). In `drivers/hv/vmbus_drv.c`, I see a modified mmap wrapper function, `hv_mmap_ring_buffer_wrapper`.  Network driver modifications include `netvsc_send_completion`, `netvsc_send_tx_complete`, `netvsc_send_acct` in `drivers/net/hyperv/netvsc.c`, and `rndis_build_page_buffers` and an altered `get_rndis_request` in `drivers/net/hyperv/rndis_filter.c`.

I need to confirm these functions are actually defined in .c files and are not static inline functions defined in headers. I've verified that all the functions are indeed defined in their respective .c files. Importantly, these functions are *not* general memory allocators, page fault handlers, or common lock primitives; they're all specific to UIO and Hyper-V features, exactly what I need.

Finally, I need to justify the "WorthFuzzing" decision.  This patch modifies `uio_mmap` in core UIO, potentially affecting how UIO devices interact with VMAs, and thus has an impact on the interface with `target_core_user`, which is reachable via configfs. Moreover, there are extensive changes to buffer management, asynchronous page reclaim, and GPADL teardown within the Hyper-V drivers.  No strict exclusion criteria apply, because this patch series touches kernel code, is not exclusive to specific hardware, and involves important changes beyond just hotunplug handling. Thus, fuzzing these changes is highly relevant to uncover memory lifetime and error-path regressions, especially considering how they touch core, reachable subsystems.  I'm confident in saying that the changes justify the fuzzing effort.



56/2 2026/10/07 21:59 tool set-results
0m Args:
{
  "EnableConfigs": [
    "UIO",
    "TARGET_CORE",
    "TCM_USER2",
    "HYPERV",
    "HYPERV_VMBUS",
    "HYPERV_NET",
    "UIO_HV_GENERIC"
  ],
  "FocusSymbols": [
    "uio_mmap",
    "hv_uio_mmap_prepare",
    "hv_uio_ring_mmap_prepare",
    "vmbus_alloc_buffer_owned",
    "vmbus_release_buffer",
    "vmbus_buffer_pin_pages",
    "vmbus_buffer_unpin_pages",
    "vmbus_buffer_reclaim_work",
    "vmbus_gpadl_teardown_request",
    "vmbus_teardown_gpadl_owned",
    "vmbus_establish_gpadl_owned",
    "hv_mmap_ring_buffer_wrapper",
    "netvsc_send_completion",
    "netvsc_send_tx_complete",
    "netvsc_send_acct",
    "rndis_build_page_buffers",
    "get_rndis_request"
  ],
  "Reasoning": "The patch modifies core UIO subsystem mmap logic in drivers/uio/uio.c (uio_mmap), changing VMA state installation and invoking vma-\u003evm_ops-\u003eclose() on mmap failure for drivers providing mmap_prepare (which directly affects reachable virtual subsystems like TCMU / target_core_user). It also significantly refactors buffer allocation, page pinning, asynchronous deferred page reclaim, and GPADL lifecycle management across Hyper-V VMBus and netvsc. These logic alterations and error-path cleanups warrant fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "UIO",
    "TARGET_CORE",
    "TCM_USER2",
    "HYPERV",
    "HYPERV_VMBUS",
    "HYPERV_NET",
    "UIO_HV_GENERIC"
  ],
  "FocusSymbols": [
    "uio_mmap",
    "hv_uio_mmap_prepare",
    "hv_uio_ring_mmap_prepare",
    "vmbus_alloc_buffer_owned",
    "vmbus_release_buffer",
    "vmbus_buffer_pin_pages",
    "vmbus_buffer_unpin_pages",
    "vmbus_buffer_reclaim_work",
    "vmbus_gpadl_teardown_request",
    "vmbus_teardown_gpadl_owned",
    "vmbus_establish_gpadl_owned",
    "hv_mmap_ring_buffer_wrapper",
    "netvsc_send_completion",
    "netvsc_send_tx_complete",
    "netvsc_send_acct",
    "rndis_build_page_buffers",
    "get_rndis_request"
  ],
  "Reasoning": "The patch modifies core UIO subsystem mmap logic in drivers/uio/uio.c (uio_mmap), changing VMA state installation and invoking vma-\u003evm_ops-\u003eclose() on mmap failure for drivers providing mmap_prepare (which directly affects reachable virtual subsystems like TCMU / target_core_user). It also significantly refactors buffer allocation, page pinning, asynchronous deferred page reclaim, and GPADL lifecycle management across Hyper-V VMBus and netvsc. These logic alterations and error-path cleanups warrant fuzzing.",
  "WorthFuzzing": true
}

57/1 2026/10/07 21:59 action If
2m Args:
{
  "WorthFuzzing": true
}

Results:
null

58/2 2026/10/07 21:59 agent kmsan-evaluator
2m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series enhances memory lifetime and GPADL management across Hyper-V VMBus (hv_vmbus), NetVSC (hv_netvsc), and UIO (uio_hv_generic) drivers, addressing use-after-free and synchronization issues when buffer pages are reclaimed while mapped into user space or pending host teardown. It also updates high-order allocations to use kvzalloc_obj() and adds KUnit unit test suites.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory / Info-leak Risk (KMSAN):\n   - All newly introduced or modified heap and stack data structures (e.g. struct vmbus_buffer, struct vmbus_buffer_retained, struct vmbus_buffer_pin, struct hv_uio_pin, struct rndis_request, requestor arrays, bitmaps) are explicitly zero-initialized upon allocation using kzalloc_obj(), kvzalloc_obj(), vzalloc(), memset(), or {0} initializers.\n   - Memory mapped to user space via UIO / sysfs mmap interfaces uses vzalloc() or zero-initialized pages (__GFP_ZERO and memset()), preventing uninitialized memory disclosure to userspace.\n   - No kernel data structures or uninitialized paddings are copied to user space via copy_to_user, put_user, ioctl outputs, or netlink messages.\n   - No conditional branches or control flow rely on uninitialized values.\n\n2. Memory Safety / Concurrency Risks (KASAN, LOCKDEP):\n   - The primary hazards addressed and introduced by the changes involve page lifetime, reference counting (folio/page refcounts), race conditions between buffer release and mmap pinning, delayed workqueue teardown, and potential use-after-free on reclaim.\n   - These bugs are comprehensively monitored by standard sanitizers and debuggers already enabled in standard builds (KASAN for use-after-free and out-of-bounds accesses, LOCKDEP for vmbus_buffer_owners_lock locking correctness).\n\nBecause the changes introduce no uninitialized memory hazards or info-leak vectors that would require KMSAN, a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit b46a7f3a76fb605ed8bbd8f5217b7a13200e774b
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Oct 7 21:53:22 2026 +0000

    syz-cluster: applied patch under review

diff --git a/drivers/hv/Kconfig b/drivers/hv/Kconfig
index aa11bcefddf2c..d44dd60fbc237 100644
--- a/drivers/hv/Kconfig
+++ b/drivers/hv/Kconfig
@@ -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)
diff --git a/drivers/hv/Makefile b/drivers/hv/Makefile
index 888a748cc7cb9..80d33e9c0e572 100644
--- a/drivers/hv/Makefile
+++ b/drivers/hv/Makefile
@@ -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
diff --git a/drivers/hv/channel.c b/drivers/hv/channel.c
index 7e4cc6f55237a..c7f3f5c6c0d28 100644
--- a/drivers/hv/channel.c
+++ b/drivers/hv/channel.c
@@ -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>
@@ -21,11 +23,378 @@
 #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
+ * therefore not static; nothing outside hv_vmbus links against them.
+ */
+int vmbus_buffer_round_size(u32 size, u32 *rounded_size)
+{
+	if (!size)
+		return -EINVAL;
+
+	if (size > U32_MAX - (u32)PAGE_SIZE + 1)
+		return -EOVERFLOW;
+
+	*rounded_size = round_up(size, (u32)PAGE_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)
+{
+	return min_t(unsigned int, max_order, ilog2(remaining));
+}
+
+bool vmbus_buffer_lower_order(unsigned int *order)
+{
+	if (!*order)
+		return false;
+
+	(*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 &&
+	       !buffer->gpadl.gpadl_handle;
+}
+
+/* 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
  *
@@ -42,7 +411,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 +471,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 +521,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,25 +537,21 @@ 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;
+	int ret;
 
-	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)
-		return -ENOMEM;
+	ret = vmbus_alloc_buffer_owned(newchannel, size,
+				       newchannel->co_ring_buffer, buffer);
+	if (ret)
+		return ret;
 
-	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;
 
 	return 0;
@@ -440,20 +801,106 @@ 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)
+{
+	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;
+}
+
+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,
-				   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_gpadl_body *gpadl_body;
 	struct vmbus_channel_msginfo *msginfo = NULL;
-	struct vmbus_channel_msginfo *submsginfo;
-	struct list_head *curr;
+	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;
 
+	gpadl->leak = false;
+
 	next_gpadl_handle =
 		(atomic_inc_return(&vmbus_connection.next_gpadl_handle) - 1);
 
@@ -463,9 +910,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.
@@ -479,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;
 		}
@@ -504,45 +954,22 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 		goto cleanup;
 	}
 
-	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 (posted && owner)
+		vmbus_buffer_update_host_ownership(owner, true);
+	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) {
-		pr_err("Failed to establish GPADL: err = 0x%x\n",
-		       msginfo->response.gpadl_created.creation_status);
-
-		ret = -EDQUOT;
-		goto cleanup;
-	}
-
-	if (channel->rescind) {
-		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;
 	}
 
@@ -550,7 +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);
@@ -559,34 +987,44 @@ static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
 
 	vmbus_free_channel_msginfo(msginfo);
 
-	if (ret) {
-		/*
-		 * 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;
-		}
-	}
+	if (ret && posted)
+		gpadl->leak = true;
+	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, 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);
 
@@ -600,13 +1038,23 @@ EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
  * @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,
-					   struct vmbus_gpadl *gpadl)
+					  void *kbuffer, u32 size,
+					  struct vmbus_gpadl *gpadl)
 {
-	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER_DECRYPTED,
-				       kbuffer, size, 0U, 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);
 
@@ -632,7 +1080,8 @@ void vmbus_free_buffer(void *addr, struct page **chunks, u32 chunk_cnt)
 		return;
 	}
 
-	vunmap(addr);
+	if (addr)
+		vunmap(addr);
 
 	for (i = 0; i < chunk_cnt; i++) {
 		unsigned long vaddr =
@@ -648,14 +1097,162 @@ 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)
+{
+	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");
+
+	memset(buffer, 0, sizeof(*buffer));
+	vmbus_buffer_schedule_reclaim_locked(owner);
+	mutex_unlock(&vmbus_buffer_owners_lock);
+}
+EXPORT_SYMBOL_GPL(vmbus_release_buffer);
+
 /**
- * vmbus_alloc_buffer - allocate a host-visible, virtually-contiguous 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)
+{
+	(void)context;
+	return alloc_pages_node(nid, gfp, order);
+}
+
+/**
+ * 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)
- * @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
+ * @confidential: keep the buffer private to the guest
+ * @buffer: output descriptor that owns the allocation and its backing pages
  *
  * Buffers not requiring decryption are allocated with vzalloc().
  *
@@ -665,66 +1262,88 @@ EXPORT_SYMBOL_GPL(vmbus_free_buffer);
  * 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.
  */
-void *vmbus_alloc_buffer(struct vmbus_channel *channel,
-			 u32 size,
-			 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)
 {
-	unsigned long nr_pages = PFN_UP(size);
-	unsigned long remaining = nr_pages;
+	u32 rounded_size;
+	unsigned long nr_pages;
+	unsigned long remaining;
 	unsigned long page_idx = 0;
-	struct page **chunks = NULL;
-	struct page **pages = NULL;
-	int order = MAX_PAGE_ORDER;
-	u32 chunk_cnt = 0;
-	void *addr;
+	struct vmbus_buffer_retained *owner;
+	unsigned int order = MAX_PAGE_ORDER;
+	bool hv_isolation;
+	bool guest_mem_encrypted;
 	u32 i;
 	int ret;
 
-	*chunks_out = NULL;
-	*chunk_cnt_out = 0;
+	memset(buffer, 0, sizeof(*buffer));
 
-	if (!nr_pages)
-		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 (!hv_is_isolation_supported() || channel->co_external_memory)
-		return vzalloc(nr_pages << PAGE_SHIFT);
+	if (!vmbus_needs_shared_pages(hv_isolation, guest_mem_encrypted,
+				      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) {
 		struct page *page;
 		gfp_t gfp;
+		int nid;
 
-		order = min(order, ilog2(remaining));
+		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 (!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;
+
+		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);
@@ -733,32 +1352,57 @@ 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, nr_pages << PAGE_SHIFT);
-
-	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;
+}
+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)
+{
+	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);
 
@@ -767,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;
 
@@ -792,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;
 
@@ -801,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;
 	}
 
@@ -820,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,
@@ -832,7 +1497,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 +1525,22 @@ 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),
-				      (send_pages + recv_pages) << PAGE_SHIFT,
+	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING, buffer,
 				      newchannel->ringbuffer_send_offset << PAGE_SHIFT,
-				      &newchannel->ringbuffer_gpadlhandle);
+				      true);
 	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 +1562,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 +1620,7 @@ static int __vmbus_open(struct vmbus_channel *newchannel,
 error_free_info:
 	kfree(open_info);
 error_free_gpadl:
-	vmbus_teardown_gpadl(newchannel, &newchannel->ringbuffer_gpadlhandle);
+	vmbus_teardown_gpadl_owned(newchannel, buffer);
 error_clean_ring:
 	hv_ringbuffer_cleanup(&newchannel->outbound);
 	hv_ringbuffer_cleanup(&newchannel->inbound);
@@ -1002,71 +1666,164 @@ 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);
-	if (!info)
-		return -ENOMEM;
+	info = alloc_info();
+	if (!info) {
+		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 = channel->offermsg.child_relid;
-	msg->gpadl = gpadl->gpadl_handle;
+	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);
 
-	if (channel->rescind)
-		goto post_msg_err;
+	spin_lock_irqsave(&connection->channelmsg_lock, flags);
+	list_add_tail(&info->msglistentry, &connection->chn_msg_list);
+	spin_unlock_irqrestore(&connection->channelmsg_lock, flags);
 
-	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),
-			     true);
+	if (channel->offermsg.child_relid != relid ||
+	    (READ_ONCE(channel->rescind) &&
+	     !READ_ONCE(channel->rescind_from_host)))
+		goto cleanup;
 
-	trace_vmbus_teardown_gpadl(msg, ret);
+	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 (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);
+retain:
+	if (ret) {
+		gpadl->leak = true;
+		if (owner)
+			vmbus_buffer_update_host_ownership(owner, true);
+	}
 
-	gpadl->decrypted = ret;
+	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) {
+			pr_warn("Failed to re-encrypt GPADL buffer: %d\n",
+				encrypt_ret);
+			ret = encrypt_ret;
+		}
+		gpadl->decrypted = !!encrypt_ret;
+	}
 
 	return ret;
 }
@@ -1142,8 +1899,8 @@ 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_owned(channel, &channel->ringbuffer);
 		if (ret) {
 			pr_err("Close failed: teardown gpadl return %d\n", ret);
 			/*
diff --git a/drivers/hv/channel_mgmt.c b/drivers/hv/channel_mgmt.c
index a044fd3b3c4e7..be0f70a3541cd 100644
--- a/drivers/hv/channel_mgmt.c
+++ b/drivers/hv/channel_mgmt.c
@@ -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[] = {
@@ -170,14 +172,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 +960,10 @@ 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);
+
 	/*
 	 * Setup state for signalling the host.
 	 */
@@ -1159,7 +1168,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 +1248,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
@@ -1477,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;
 
@@ -1514,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);
 }
 
 /*
@@ -1555,12 +1568,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 +1615,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 +1624,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);
 }
 
diff --git a/drivers/hv/hv_trace.h b/drivers/hv/hv_trace.h
index c02a1719e92f2..a3eeb817b00ea 100644
--- a/drivers/hv/hv_trace.h
+++ b/drivers/hv/hv_trace.h
@@ -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),
diff --git a/drivers/hv/hyperv_vmbus.h b/drivers/hv/hyperv_vmbus.h
index 33923621a5a3f..9819a6b686cec 100644
--- a/drivers/hv/hyperv_vmbus.h
+++ b/drivers/hv/hyperv_vmbus.h
@@ -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);
 
@@ -354,6 +354,7 @@ struct vmbus_channel_message_table_entry {
 extern const struct vmbus_channel_message_table_entry
 	channel_message_table[CHANNELMSG_COUNT];
 
+void vmbus_buffer_reclaimer_shutdown(void);
 
 /* General vmbus interface */
 
@@ -551,4 +552,111 @@ int hv_create_ring_sysfs(struct vmbus_channel *channel,
 							    struct vm_area_desc *desc));
 int hv_remove_ring_sysfs(struct vmbus_channel *channel);
 
+/*
+ * Retained buffer owner. One per channel-keyed allocation; freed only
+ * after GPADL, page-state and mapping-reference gates all clear.
+ */
+struct vmbus_buffer_retained {
+	struct list_head list;
+	struct delayed_work reclaim_work;
+	u64 channel_id;
+	u64 owner_id;
+	void *addr;
+	struct page **chunks;
+	struct page **pages;
+	u32 chunk_cnt;
+	u32 page_cnt;
+	u32 size;
+	bool released;
+	bool host_may_own;
+	bool needs_encrypt;
+	bool raw_decrypted;
+	bool encryption_unknown;
+	bool permanent_leak;
+	bool work_active;
+	bool reclaiming;
+};
+
+/*
+ * 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.
+ */
+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);
+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);
+
+/*
+ * Owner lifetime and reclaim-gate helpers, shared with
+ * vmbus_buffer_test.c for the same reason as the sizing helpers.
+ * Defined in channel.c, unexported.
+ */
+bool vmbus_buffer_owner_can_reclaim(const struct vmbus_buffer_retained *owner);
+bool vmbus_buffer_owner_should_schedule(const struct vmbus_buffer_retained *owner,
+					bool stopping, bool queue_live);
+bool vmbus_buffer_pages_busy(struct vmbus_buffer_retained *owner);
+void vmbus_buffer_owner_drain(struct vmbus_buffer_retained *owner,
+			      struct workqueue_struct *wq);
+struct vmbus_buffer_retained *
+vmbus_buffer_owner_alloc(struct vmbus_channel *channel);
+
+/*
+ * 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);
+typedef struct vmbus_channel_msginfo *(*vmbus_gpadl_info_alloc_fn)(void);
+typedef int (*vmbus_gpadl_teardown_post_fn)(struct vmbus_connection *connection,
+					 struct vmbus_channel_msginfo *info);
+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);
+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 */
diff --git a/drivers/hv/ring_buffer.c b/drivers/hv/ring_buffer.c
index 592a9601faaaf..16b1c29107890 100644
--- a/drivers/hv/ring_buffer.c
+++ b/drivers/hv/ring_buffer.c
@@ -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,
diff --git a/drivers/hv/vmbus_buffer_test.c b/drivers/hv/vmbus_buffer_test.c
new file mode 100644
index 0000000000000..d0102dabef737
--- /dev/null
+++ b/drivers/hv/vmbus_buffer_test.c
@@ -0,0 +1,976 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for Hyper-V VMBus buffer allocation and GPADL lifetime.
+ *
+ * Built into the hv_vmbus object rather than a separate module so the
+ * cases can reach the internal helpers declared in hyperv_vmbus.h
+ * without exporting them.
+ */
+#include <kunit/test.h>
+#include <linux/completion.h>
+#include <linux/hyperv.h>
+#include <linux/mm.h>
+#include <linux/sizes.h>
+#include <linux/slab.h>
+#include <linux/vmalloc.h>
+
+#include "hyperv_vmbus.h"
+
+static void vmbus_buffer_size_rounding_test(struct kunit *test)
+{
+	u32 rounded_size;
+
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(1, &rounded_size), 0);
+	KUNIT_EXPECT_EQ(test, rounded_size, (u32)PAGE_SIZE);
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(PAGE_SIZE, &rounded_size), 0);
+	KUNIT_EXPECT_EQ(test, rounded_size, (u32)PAGE_SIZE);
+}
+
+static void vmbus_buffer_size_overflow_test(struct kunit *test)
+{
+	u32 rounded_size = 0;
+	int ret;
+
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_round_size(0, &rounded_size), -EINVAL);
+	ret = vmbus_buffer_round_size(U32_MAX, &rounded_size);
+	KUNIT_EXPECT_EQ(test, ret, -EOVERFLOW);
+	ret = vmbus_buffer_round_size(U32_MAX - PAGE_SIZE + 1, &rounded_size);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, rounded_size,
+			(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_buffer_owner_reclaim_gate_test(struct kunit *test)
+{
+	struct vmbus_buffer_retained owner = {
+		.released = false,
+	};
+
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+	owner.released = true;
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.host_may_own = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.host_may_own = false;	/* GPADL teardown acknowledgment */
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.permanent_leak = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+
+	owner.permanent_leak = false;
+	owner.encryption_unknown = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+}
+
+static void vmbus_buffer_reclaim_schedule_gate_test(struct kunit *test)
+{
+	struct vmbus_buffer_retained owner = {
+		.released = true,
+	};
+
+	KUNIT_EXPECT_TRUE(test,
+			  vmbus_buffer_owner_should_schedule(&owner, false, true));
+	owner.work_active = true;
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, false, true));
+	owner.work_active = false;
+	owner.reclaiming = true;
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, false, true));
+	owner.reclaiming = false;
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, true, true));
+	KUNIT_EXPECT_FALSE(test,
+			   vmbus_buffer_owner_should_schedule(&owner, false, false));
+}
+
+struct vmbus_reclaim_test_work {
+	struct vmbus_buffer_retained owner;
+	struct workqueue_struct *wq;
+	struct completion entered;
+	struct completion proceed;
+	atomic_t calls;
+	bool claim_owner;
+};
+
+static void vmbus_reclaim_test_callback(struct work_struct *work)
+{
+	struct vmbus_buffer_retained *owner =
+		container_of(to_delayed_work(work),
+			     struct vmbus_buffer_retained, reclaim_work);
+	struct vmbus_reclaim_test_work *ctx =
+		container_of(owner, struct vmbus_reclaim_test_work, owner);
+
+	atomic_inc(&ctx->calls);
+	if (ctx->claim_owner)
+		owner->reclaiming = true;
+	complete(&ctx->entered);
+	wait_for_completion(&ctx->proceed);
+}
+
+static void vmbus_reclaim_test_cleanup(void *data)
+{
+	struct vmbus_reclaim_test_work *ctx = data;
+
+	complete_all(&ctx->proceed);
+	cancel_delayed_work_sync(&ctx->owner.reclaim_work);
+	destroy_workqueue(ctx->wq);
+}
+
+static struct vmbus_reclaim_test_work *
+vmbus_reclaim_test_init(struct kunit *test)
+{
+	struct vmbus_reclaim_test_work *ctx;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return NULL;
+	init_completion(&ctx->entered);
+	init_completion(&ctx->proceed);
+	atomic_set(&ctx->calls, 0);
+	ctx->owner.released = true;
+	ctx->owner.work_active = true;
+	INIT_DELAYED_WORK(&ctx->owner.reclaim_work,
+			  vmbus_reclaim_test_callback);
+	ctx->wq = alloc_workqueue("vmbus-reclaim-test",
+				  WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
+	if (!ctx->wq)
+		return NULL;
+	if (kunit_add_action_or_reset(test, vmbus_reclaim_test_cleanup, ctx))
+		return NULL;
+	return ctx;
+}
+
+static void vmbus_reclaim_running_test(struct kunit *test, bool claim_owner)
+{
+	struct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->claim_owner = claim_owner;
+	KUNIT_ASSERT_TRUE(test,
+			  queue_delayed_work(ctx->wq, &ctx->owner.reclaim_work, 0));
+	KUNIT_ASSERT_NE(test,
+			wait_for_completion_timeout(&ctx->entered,
+						    msecs_to_jiffies(1000)), 0UL);
+
+	/*
+	 * The native workqueue cleared pending before entering the callback.
+	 * Test both windows around the callback taking ownership. Keep the
+	 * fixture alive so an incorrect second queue fails without a UAF.
+	 */
+	vmbus_buffer_owner_drain(&ctx->owner, ctx->wq);
+	KUNIT_EXPECT_FALSE(test, delayed_work_pending(&ctx->owner.reclaim_work));
+	KUNIT_EXPECT_TRUE(test, ctx->owner.work_active);
+	complete_all(&ctx->proceed);
+	flush_workqueue(ctx->wq);
+	KUNIT_EXPECT_EQ(test, atomic_read(&ctx->calls), 1);
+}
+
+static void vmbus_reclaim_shutdown_before_claim_test(struct kunit *test)
+{
+	vmbus_reclaim_running_test(test, false);
+}
+
+static void vmbus_reclaim_shutdown_during_reclaim_test(struct kunit *test)
+{
+	vmbus_reclaim_running_test(test, true);
+}
+
+static void vmbus_reclaim_shutdown_pending_test(struct kunit *test)
+{
+	struct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	KUNIT_ASSERT_TRUE(test,
+			  queue_delayed_work(ctx->wq, &ctx->owner.reclaim_work,
+					     msecs_to_jiffies(60000)));
+	complete_all(&ctx->proceed);
+	vmbus_buffer_owner_drain(&ctx->owner, ctx->wq);
+	flush_workqueue(ctx->wq);
+	KUNIT_EXPECT_EQ(test, atomic_read(&ctx->calls), 1);
+}
+
+static void vmbus_reclaim_shutdown_unsafe_pending_test(struct kunit *test)
+{
+	struct vmbus_reclaim_test_work *ctx = vmbus_reclaim_test_init(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->owner.host_may_own = true;
+	KUNIT_ASSERT_TRUE(test,
+			  queue_delayed_work(ctx->wq, &ctx->owner.reclaim_work,
+					     msecs_to_jiffies(60000)));
+	vmbus_buffer_owner_drain(&ctx->owner, ctx->wq);
+	KUNIT_EXPECT_FALSE(test, delayed_work_pending(&ctx->owner.reclaim_work));
+	KUNIT_EXPECT_FALSE(test, ctx->owner.work_active);
+	flush_workqueue(ctx->wq);
+	KUNIT_EXPECT_EQ(test, atomic_read(&ctx->calls), 0);
+}
+
+static struct vmbus_channel_msginfo *vmbus_test_alloc_teardown_fail(void)
+{
+	return NULL;
+}
+
+static void vmbus_buffer_rescind_retains_gpadl_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rescind = true };
+	struct vmbus_buffer_retained owner = {
+		.released = true,
+		.host_may_own = true,
+	};
+	struct vmbus_buffer buffer = { .owner = &owner };
+	unsigned int origin, pending;
+	u32 handle;
+	int ret;
+
+	/* Exercise the request core without touching the live connection. */
+	for (origin = 0; origin < 2; origin++) {
+		channel.rescind_from_host = origin;
+		for (pending = 0; pending < 2; pending++) {
+			buffer.gpadl.gpadl_handle = pending ? 0 : 17;
+			buffer.gpadl.leak = pending;
+			handle = buffer.gpadl.gpadl_handle;
+			ret = vmbus_gpadl_teardown_request(&channel, &buffer,
+							   vmbus_test_alloc_teardown_fail,
+							   NULL, NULL, 1);
+			KUNIT_EXPECT_EQ(test, ret, !origin ? -ENODEV :
+					  pending ? -EINPROGRESS : -ENOMEM);
+			KUNIT_EXPECT_EQ(test, buffer.gpadl.gpadl_handle, handle);
+			KUNIT_EXPECT_TRUE(test, buffer.gpadl.leak);
+			KUNIT_EXPECT_TRUE(test, owner.host_may_own);
+			KUNIT_EXPECT_FALSE(test, owner.work_active);
+			KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+			KUNIT_EXPECT_FALSE(test, vmbus_buffer_owner_can_reclaim(&owner));
+		}
+	}
+}
+
+enum vmbus_test_teardown_reply {
+	VMBUS_TEST_REPLY_ACK,
+	VMBUS_TEST_REPLY_NONE,
+	VMBUS_TEST_REPLY_WRONG_HANDLE,
+	VMBUS_TEST_REPLY_WRONG_TYPE,
+	VMBUS_TEST_REPLY_POST_FAILURE,
+};
+
+struct vmbus_teardown_test_context {
+	struct vmbus_connection connection;
+	struct vmbus_channel channel;
+	struct vmbus_buffer buffer;
+	struct vmbus_buffer_retained owner;
+	struct kunit *test;
+	enum vmbus_test_teardown_reply reply;
+	unsigned int post_calls;
+};
+
+static struct vmbus_channel_msginfo *vmbus_test_alloc_teardown(void)
+{
+	return kzalloc(sizeof(struct vmbus_channel_msginfo) +
+		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
+}
+
+static int vmbus_test_post_teardown(struct vmbus_connection *connection,
+				    struct vmbus_channel_msginfo *info)
+{
+	struct vmbus_teardown_test_context *ctx =
+		container_of(connection, struct vmbus_teardown_test_context,
+			     connection);
+	struct vmbus_channel_gpadl_teardown *msg = (void *)info->msg;
+	struct vmbus_channel_gpadl_torndown response = {
+		.header.msgtype = CHANNELMSG_GPADL_TORNDOWN,
+		.gpadl = msg->gpadl,
+	};
+
+	ctx->post_calls++;
+	KUNIT_EXPECT_EQ(ctx->test, msg->header.msgtype, CHANNELMSG_GPADL_TEARDOWN);
+	KUNIT_EXPECT_EQ(ctx->test, msg->child_relid, 71U);
+	KUNIT_EXPECT_EQ(ctx->test, msg->gpadl, 51U);
+	KUNIT_EXPECT_PTR_EQ(ctx->test, info->waiting_channel, NULL);
+	if (ctx->reply == VMBUS_TEST_REPLY_POST_FAILURE)
+		return -EIO;
+	if (ctx->reply == VMBUS_TEST_REPLY_NONE)
+		return 0;
+	if (ctx->reply == VMBUS_TEST_REPLY_WRONG_HANDLE)
+		response.gpadl++;
+	if (ctx->reply == VMBUS_TEST_REPLY_WRONG_TYPE)
+		response.header.msgtype = CHANNELMSG_GPADL_CREATED;
+	vmbus_complete_gpadl_teardown(connection, &response);
+	return 0;
+}
+
+static struct vmbus_teardown_test_context *
+vmbus_test_teardown_context(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return NULL;
+	ctx->test = test;
+	ctx->buffer.gpadl.gpadl_handle = 51;
+	ctx->buffer.owner = &ctx->owner;
+	ctx->owner.host_may_own = true;
+	ctx->channel.rescind = true;
+	ctx->channel.rescind_from_host = true;
+	ctx->channel.offermsg.child_relid = 71;
+	INIT_LIST_HEAD(&ctx->connection.chn_msg_list);
+	spin_lock_init(&ctx->connection.channelmsg_lock);
+	return ctx;
+}
+
+static int vmbus_test_teardown_request(struct vmbus_teardown_test_context *ctx)
+{
+	return vmbus_gpadl_teardown_request(&ctx->channel, &ctx->buffer,
+					  vmbus_test_alloc_teardown,
+					  &ctx->connection,
+					  vmbus_test_post_teardown, 1);
+}
+
+static void vmbus_host_rescind_teardown_ack_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), 0);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 1U);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 0U);
+	KUNIT_EXPECT_FALSE(test, ctx->buffer.gpadl.leak);
+	KUNIT_EXPECT_FALSE(test, ctx->owner.host_may_own);
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_should_free(&ctx->buffer));
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->connection.chn_msg_list));
+}
+
+static void vmbus_test_teardown_failure(struct kunit *test,
+					enum vmbus_test_teardown_reply reply,
+					int expected)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->reply = reply;
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), expected);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 1U);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&ctx->buffer));
+	KUNIT_EXPECT_TRUE(test, ctx->owner.host_may_own);
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->connection.chn_msg_list));
+}
+
+static void vmbus_host_rescind_teardown_timeout_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_NONE, -ETIMEDOUT);
+}
+
+static void vmbus_host_rescind_teardown_wrong_handle_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_WRONG_HANDLE,
+				    -ETIMEDOUT);
+}
+
+static void vmbus_host_rescind_teardown_wrong_type_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_WRONG_TYPE, -ENODEV);
+}
+
+static void vmbus_host_rescind_teardown_post_failure_test(struct kunit *test)
+{
+	vmbus_test_teardown_failure(test, VMBUS_TEST_REPLY_POST_FAILURE, -EIO);
+}
+
+static void vmbus_local_rescind_skips_teardown_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->channel.rescind_from_host = false;
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), -ENODEV);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 0U);
+	KUNIT_EXPECT_TRUE(test, ctx->buffer.gpadl.leak);
+	KUNIT_EXPECT_TRUE(test, ctx->owner.host_may_own);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+}
+
+static void vmbus_invalid_relid_skips_teardown_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->channel.offermsg.child_relid = INVALID_RELID;
+	KUNIT_EXPECT_EQ(test, vmbus_test_teardown_request(ctx), -ENODEV);
+	KUNIT_EXPECT_EQ(test, ctx->post_calls, 0U);
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+}
+
+static void vmbus_host_rescind_teardown_late_ack_test(struct kunit *test)
+{
+	struct vmbus_teardown_test_context *ctx = vmbus_test_teardown_context(test);
+	struct vmbus_channel_gpadl_torndown response = {
+		.header.msgtype = CHANNELMSG_GPADL_TORNDOWN,
+		.gpadl = 51,
+	};
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->reply = VMBUS_TEST_REPLY_NONE;
+	KUNIT_ASSERT_EQ(test, vmbus_test_teardown_request(ctx), -ETIMEDOUT);
+	/* Run the production response matcher after its waiter has been freed. */
+	vmbus_complete_gpadl_teardown(&ctx->connection, &response);
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->connection.chn_msg_list));
+	KUNIT_EXPECT_EQ(test, ctx->buffer.gpadl.gpadl_handle, 51U);
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&ctx->buffer));
+	KUNIT_EXPECT_TRUE(test, ctx->owner.host_may_own);
+}
+
+static void vmbus_buffer_mapping_reference_test(struct kunit *test)
+{
+	struct vmbus_buffer_retained owner = {};
+	struct page *page;
+	struct page *pages[1];
+
+	page = alloc_page(GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, page);
+	pages[0] = page;
+	owner.pages = pages;
+	owner.page_cnt = ARRAY_SIZE(pages);
+
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_pages_busy(&owner));
+	get_page(page); /* vm_insert_pages() holds one reference per mapping */
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_pages_busy(&owner));
+	put_page(page);
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_pages_busy(&owner));
+	__free_page(page);
+}
+
+static void vmbus_buffer_repeated_owner_release_test(struct kunit *test)
+{
+	struct vmbus_channel channel = {};
+	struct vmbus_buffer buffer = {};
+	struct vmbus_buffer empty = {};
+
+	buffer.addr = vzalloc(PAGE_SIZE);
+	KUNIT_ASSERT_NOT_NULL(test, buffer.addr);
+	buffer.owner = vmbus_buffer_owner_alloc(&channel);
+	if (!buffer.owner) {
+		vfree(buffer.addr);
+		KUNIT_FAIL(test, "failed to allocate a VMBus buffer owner");
+		return;
+	}
+	buffer.size = PAGE_SIZE;
+	empty.owner = vmbus_buffer_owner_alloc(&channel);
+	if (!empty.owner) {
+		vmbus_release_buffer(&buffer);
+		KUNIT_FAIL(test, "failed to allocate a second VMBus buffer owner");
+		return;
+	}
+	KUNIT_EXPECT_TRUE(test, empty.owner->owner_id != buffer.owner->owner_id);
+	vmbus_release_buffer(&empty);
+	KUNIT_EXPECT_PTR_EQ(test, empty.owner, NULL);
+
+	vmbus_release_buffer(&buffer);
+	KUNIT_EXPECT_PTR_EQ(test, buffer.addr, NULL);
+	KUNIT_EXPECT_PTR_EQ(test, buffer.owner, NULL);
+	vmbus_release_buffer(&buffer);
+}
+
+static void vmbus_ring_fallback_order_zero_test(struct kunit *test)
+{
+	unsigned int order;
+
+	order = vmbus_buffer_order(1UL << MAX_PAGE_ORDER, MAX_PAGE_ORDER);
+	KUNIT_EXPECT_EQ(test, order, (unsigned int)MAX_PAGE_ORDER);
+	while (order)
+		KUNIT_ASSERT_TRUE(test, vmbus_buffer_lower_order(&order));
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_lower_order(&order));
+	KUNIT_EXPECT_EQ(test, order, 0U);
+	KUNIT_EXPECT_EQ(test, vmbus_buffer_order(3, MAX_PAGE_ORDER), 1U);
+}
+
+static void vmbus_buffer_failed_teardown_leaks_test(struct kunit *test)
+{
+	struct vmbus_buffer buffer = {
+		.addr = (void *)1,
+		.gpadl.gpadl_handle = 1,
+	};
+
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+	buffer.gpadl.gpadl_handle = 0;
+	buffer.gpadl.leak = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+	buffer.gpadl.leak = false;
+	buffer.leak = true;
+	KUNIT_EXPECT_FALSE(test, vmbus_buffer_should_free(&buffer));
+	buffer.leak = false;
+	KUNIT_EXPECT_TRUE(test, vmbus_buffer_should_free(&buffer));
+}
+
+static void vmbus_buffer_partial_allocation_cleanup_test(struct kunit *test)
+{
+	struct page **chunks;
+	struct vmbus_buffer buffer = {};
+
+	chunks = kmalloc_obj(*chunks, GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, chunks);
+	vmbus_free_buffer(NULL, chunks, 0);
+
+	buffer.addr = vzalloc(PAGE_SIZE);
+	KUNIT_ASSERT_NOT_NULL(test, buffer.addr);
+	vmbus_release_buffer(&buffer);
+	KUNIT_EXPECT_PTR_EQ(test, buffer.addr, NULL);
+	vmbus_release_buffer(&buffer);
+}
+
+struct vmbus_gpadl_post_test_context {
+	struct kunit *test;
+	unsigned int call_count;
+	unsigned int fail_call;
+	u32 first_msgtype;
+	u32 expected_gpadl;
+};
+
+static int vmbus_gpadl_test_post(void *context, void *buffer,
+				 size_t buflen, bool can_sleep)
+{
+	struct vmbus_gpadl_post_test_context *test_context = context;
+	struct vmbus_channel_message_header *header = buffer;
+
+	KUNIT_EXPECT_TRUE(test_context->test, can_sleep);
+	KUNIT_EXPECT_GT(test_context->test, buflen,
+			(size_t)sizeof(*header));
+	test_context->call_count++;
+	KUNIT_EXPECT_EQ(test_context->test, header->msgtype,
+			test_context->call_count == 1 ?
+			test_context->first_msgtype : CHANNELMSG_GPADL_BODY);
+	switch (header->msgtype) {
+	case CHANNELMSG_GPADL_HEADER: {
+		struct vmbus_channel_gpadl_header *gpadl_header = buffer;
+
+		KUNIT_EXPECT_EQ(test_context->test, gpadl_header->gpadl,
+				test_context->expected_gpadl);
+		break;
+	}
+	case CHANNELMSG_GPADL_BODY: {
+		struct vmbus_channel_gpadl_body *gpadl_body = buffer;
+
+		KUNIT_EXPECT_EQ(test_context->test, gpadl_body->gpadl,
+				test_context->expected_gpadl);
+		break;
+	}
+	case CHANNELMSG_GPADL_TEARDOWN: {
+		struct vmbus_channel_gpadl_teardown *teardown = buffer;
+
+		KUNIT_EXPECT_EQ(test_context->test, teardown->gpadl,
+				test_context->expected_gpadl);
+		KUNIT_EXPECT_EQ(test_context->test, teardown->child_relid,
+				7U);
+		break;
+	}
+	default:
+		KUNIT_FAIL(test_context->test,
+			   "unexpected GPADL message type: %d",
+			   header->msgtype);
+	}
+	if (test_context->call_count == test_context->fail_call)
+		return -EIO;
+
+	return 0;
+}
+
+static struct vmbus_channel_msginfo *
+vmbus_gpadl_test_msginfo(struct kunit *test, unsigned int body_count)
+{
+	struct vmbus_channel_msginfo *msginfo;
+	struct vmbus_channel_msginfo *body_info;
+	unsigned int i;
+
+	msginfo = kunit_kzalloc(test, sizeof(*msginfo) +
+			       sizeof(struct vmbus_channel_gpadl_header),
+			       GFP_KERNEL);
+	if (!msginfo)
+		return NULL;
+
+	msginfo->msgsize = sizeof(*msginfo) +
+			   sizeof(struct vmbus_channel_gpadl_header);
+	INIT_LIST_HEAD(&msginfo->submsglist);
+
+	for (i = 0; i < body_count; i++) {
+		body_info = kunit_kzalloc(test,
+					  sizeof(*body_info) +
+					  sizeof(struct vmbus_channel_gpadl_body),
+					  GFP_KERNEL);
+		if (!body_info)
+			return NULL;
+
+		body_info->msgsize = sizeof(*body_info) +
+				     sizeof(struct vmbus_channel_gpadl_body);
+		INIT_LIST_HEAD(&body_info->msglistentry);
+		list_add_tail(&body_info->msglistentry, &msginfo->submsglist);
+	}
+
+	return msginfo;
+}
+
+static void vmbus_gpadl_post_failure_test(struct kunit *test)
+{
+	unsigned int fail_call;
+
+	for (fail_call = 1; fail_call <= 3; fail_call++) {
+		struct vmbus_gpadl_post_test_context context = {
+			.test = test,
+			.fail_call = fail_call,
+			.first_msgtype = CHANNELMSG_GPADL_HEADER,
+			.expected_gpadl = 17,
+		};
+		struct vmbus_channel_msginfo *msginfo;
+		bool posted = false;
+		int ret;
+
+		msginfo = vmbus_gpadl_test_msginfo(test, 2);
+		KUNIT_ASSERT_NOT_NULL(test, msginfo);
+
+		ret = vmbus_post_gpadl_messages(msginfo, 17, &posted,
+						vmbus_gpadl_test_post, &context);
+		KUNIT_EXPECT_EQ(test, ret, -EIO);
+		KUNIT_EXPECT_EQ(test, context.call_count, fail_call);
+		KUNIT_EXPECT_TRUE(test, posted);
+	}
+}
+
+static void vmbus_gpadl_post_success_test(struct kunit *test)
+{
+	struct vmbus_gpadl_post_test_context context = {
+		.test = test,
+		.first_msgtype = CHANNELMSG_GPADL_HEADER,
+		.expected_gpadl = 17,
+	};
+	struct vmbus_channel_msginfo *msginfo;
+	bool posted = false;
+	int ret;
+
+	msginfo = vmbus_gpadl_test_msginfo(test, 2);
+	KUNIT_ASSERT_NOT_NULL(test, msginfo);
+
+	ret = vmbus_post_gpadl_messages(msginfo, 17, &posted,
+					vmbus_gpadl_test_post, &context);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, context.call_count, 3U);
+	KUNIT_EXPECT_TRUE(test, posted);
+}
+
+static void vmbus_gpadl_response_state_test(struct kunit *test)
+{
+	bool posted = true;
+
+	KUNIT_EXPECT_EQ(test, vmbus_gpadl_response_status(0, false, &posted), 0);
+	KUNIT_EXPECT_FALSE(test, posted);
+
+	posted = true;
+	KUNIT_EXPECT_EQ(test,
+			vmbus_gpadl_response_status(1, false, &posted), -EDQUOT);
+	KUNIT_EXPECT_FALSE(test, posted);
+
+	posted = true;
+	KUNIT_EXPECT_EQ(test,
+			vmbus_gpadl_response_status(0, true, &posted), -ENODEV);
+	KUNIT_EXPECT_TRUE(test, posted);
+}
+
+static void vmbus_gpadl_teardown_post_failure_test(struct kunit *test)
+{
+	struct vmbus_gpadl_post_test_context context = {
+		.test = test,
+		.fail_call = 1,
+		.first_msgtype = CHANNELMSG_GPADL_TEARDOWN,
+		.expected_gpadl = 17,
+	};
+	struct vmbus_channel_gpadl_teardown msg = {};
+	int ret;
+
+	ret = vmbus_post_gpadl_teardown(7, &msg, 17,
+					vmbus_gpadl_test_post, &context);
+	KUNIT_EXPECT_EQ(test, ret, -EIO);
+	KUNIT_EXPECT_EQ(test, context.call_count, 1U);
+}
+
+struct vmbus_buffer_page_alloc_test_context {
+	struct kunit *test;
+	unsigned int attempts;
+	unsigned int expected_order;
+	bool fail_order_zero;
+};
+
+static struct page *vmbus_buffer_test_alloc_page(void *context, int nid,
+						 gfp_t gfp,
+						 unsigned int order)
+{
+	struct vmbus_buffer_page_alloc_test_context *test_context = context;
+
+	(void)nid;
+	KUNIT_EXPECT_EQ(test_context->test, order,
+			test_context->expected_order);
+	test_context->attempts++;
+	if (test_context->expected_order)
+		test_context->expected_order--;
+
+	if (order)
+		return NULL;
+	if (test_context->fail_order_zero)
+		return NULL;
+
+	return alloc_pages(gfp, 0);
+}
+
+static void vmbus_buffer_order_zero_allocation_test(struct kunit *test)
+{
+	struct vmbus_buffer_page_alloc_test_context context = {
+		.test = test,
+		.expected_order = MAX_PAGE_ORDER,
+	};
+	struct page *page;
+	unsigned int order = MAX_PAGE_ORDER;
+
+	page = vmbus_alloc_pages_with_fallback(0, GFP_KERNEL, &order,
+					       vmbus_buffer_test_alloc_page, &context);
+	KUNIT_ASSERT_NOT_NULL(test, page);
+	KUNIT_EXPECT_EQ(test, order, 0U);
+	KUNIT_EXPECT_EQ(test, context.expected_order, 0U);
+	KUNIT_EXPECT_EQ(test, context.attempts, (unsigned int)MAX_PAGE_ORDER + 1);
+	__free_pages(page, 0);
+
+	context.attempts = 0;
+	context.expected_order = MAX_PAGE_ORDER;
+	context.fail_order_zero = true;
+	order = MAX_PAGE_ORDER;
+	page = vmbus_alloc_pages_with_fallback(0, GFP_KERNEL, &order,
+					       vmbus_buffer_test_alloc_page, &context);
+	KUNIT_EXPECT_PTR_EQ(test, page, NULL);
+	KUNIT_EXPECT_EQ(test, order, 0U);
+	KUNIT_EXPECT_EQ(test, context.expected_order, 0U);
+	KUNIT_EXPECT_EQ(test, context.attempts, (unsigned int)MAX_PAGE_ORDER + 1);
+}
+
+/*
+ * Requestor metadata must use vmalloc backing because both the array and its
+ * bitmap can require multiple pages. The requestor is guest-private
+ * bookkeeping: the host never sees the slot values, so this mapping has no
+ * Confidential Computing implication and needs no set_memory_decrypted().
+ * Cover a typical 8 KiB array, a requestor whose bitmap exceeds one page,
+ * and a size beyond KMALLOC_MAX_SIZE without memory pressure.
+ */
+static void vmbus_requestor_alloc_free_test(struct kunit *test)
+{
+	struct vmbus_requestor rqstor = {};
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(&rqstor, 4), 0);
+	KUNIT_EXPECT_EQ(test, rqstor.size, 4U);
+	KUNIT_EXPECT_EQ(test, rqstor.next_request_id, 0U);
+	KUNIT_EXPECT_NOT_NULL(test, rqstor.req_arr);
+	KUNIT_EXPECT_NOT_NULL(test, rqstor.req_bitmap);
+
+	/* The free list links 0->1->2->3 and terminates in U64_MAX. */
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[0], 1U);
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[1], 2U);
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[2], 3U);
+	KUNIT_EXPECT_EQ(test, rqstor.req_arr[3], U64_MAX);
+
+	vmbus_free_requestor(&rqstor);
+}
+
+static void vmbus_requestor_vmalloc_backing_test(struct kunit *test)
+{
+	/*
+	 * Cover the small array, a requestor whose bitmap exceeds one page,
+	 * and a size beyond KMALLOC_MAX_SIZE. All requestor metadata must use
+	 * vmalloc backing regardless of size or allocator pressure.
+	 */
+	u32 small_size = 1024;
+	u32 bitmap_size = (PAGE_SIZE / sizeof(unsigned long)) * BITS_PER_LONG + 1;
+	u32 size = (KMALLOC_MAX_SIZE / sizeof(u64)) + 1;
+	struct vmbus_requestor rqstor = {};
+	u64 *req_arr;
+
+	KUNIT_EXPECT_PTR_EQ(test, request_arr_init(0), NULL);
+
+	req_arr = request_arr_init(small_size);
+	KUNIT_ASSERT_NOT_NULL(test, req_arr);
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(req_arr));
+	KUNIT_EXPECT_EQ(test, req_arr[0], 1U);
+	KUNIT_EXPECT_EQ(test, req_arr[small_size - 1], U64_MAX);
+	vfree(req_arr);
+
+	req_arr = request_arr_init(size);
+	KUNIT_ASSERT_NOT_NULL(test, req_arr);
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(req_arr));
+	KUNIT_EXPECT_EQ(test, req_arr[0], 1U);
+	KUNIT_EXPECT_EQ(test, req_arr[size - 1], U64_MAX);
+	vfree(req_arr);
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(&rqstor, bitmap_size), 0);
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(rqstor.req_arr));
+	KUNIT_EXPECT_TRUE(test, is_vmalloc_addr(rqstor.req_bitmap));
+	vmbus_free_requestor(&rqstor);
+}
+
+static void vmbus_requestor_id_lifecycle_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rqstor_size = 4 };
+	struct vmbus_requestor *rqstor = &channel.requestor;
+	u64 id0, id1, id2, id3, addr;
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 4), 0);
+
+	/* IDs are 1-based; 0 is reserved for unsolicited host messages. */
+	id0 = vmbus_next_request_id(&channel, 0x1000);
+	KUNIT_EXPECT_EQ(test, id0, 1U);
+	id1 = vmbus_next_request_id(&channel, 0x2000);
+	KUNIT_EXPECT_EQ(test, id1, 2U);
+
+	/* Consumption returns the registered address and frees the slot. */
+	addr = vmbus_request_addr_match(&channel, id0, VMBUS_RQST_ADDR_ANY);
+	KUNIT_EXPECT_EQ(test, addr, 0x1000U);
+	addr = vmbus_request_addr_match(&channel, id1, 0x2000);
+	KUNIT_EXPECT_EQ(test, addr, 0x2000U);
+
+	/*
+	 * Consumed slots are reusable. The free list is LIFO -- each
+	 * consume pushes its slot onto the head -- so the slot freed last
+	 * is the one handed out first. Freeing id0 then id1 leaves slot 1
+	 * at the head, and the next ID is therefore id1 again, not id0.
+	 */
+	id2 = vmbus_next_request_id(&channel, 0x3000);
+	KUNIT_EXPECT_EQ(test, id2, id1);
+	id3 = vmbus_next_request_id(&channel, 0x4000);
+	KUNIT_EXPECT_EQ(test, id3, id0);
+
+	vmbus_free_requestor(rqstor);
+}
+
+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),
+			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);
+
+	/* A wrong expected address does not consume the slot. */
+	addr = vmbus_request_addr_match(&channel, id, 0x9999);
+	KUNIT_EXPECT_EQ(test, addr, 0xABCDU);
+
+	/* The slot is still live and a matching lookup consumes it once. */
+	addr = vmbus_request_addr_match(&channel, id, 0xABCD);
+	KUNIT_EXPECT_EQ(test, addr, 0xABCDU);
+
+	/* Replay: the slot is gone. */
+	addr = vmbus_request_addr_match(&channel, id, VMBUS_RQST_ADDR_ANY);
+	KUNIT_EXPECT_EQ(test, addr, VMBUS_RQST_ERROR);
+
+	vmbus_free_requestor(rqstor);
+}
+
+static void vmbus_requestor_exhaustion_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .rqstor_size = 2 };
+	struct vmbus_requestor *rqstor = &channel.requestor;
+
+	KUNIT_ASSERT_EQ(test, vmbus_alloc_requestor(rqstor, 2), 0);
+
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x1), 1U);
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x2), 2U);
+
+	/* Both slots taken: the free list is empty and the API says so. */
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x3),
+			VMBUS_RQST_ERROR);
+
+	/* An uninitialized requestor is not a full one. */
+	channel.rqstor_size = 0;
+	KUNIT_EXPECT_EQ(test, vmbus_next_request_id(&channel, 0x4),
+			VMBUS_NO_RQSTOR);
+
+	vmbus_free_requestor(rqstor);
+}
+
+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_owner_reclaim_gate_test),
+	KUNIT_CASE(vmbus_buffer_reclaim_schedule_gate_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_before_claim_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_during_reclaim_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_pending_test),
+	KUNIT_CASE(vmbus_reclaim_shutdown_unsafe_pending_test),
+	KUNIT_CASE(vmbus_buffer_rescind_retains_gpadl_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_ack_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_timeout_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_wrong_handle_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_wrong_type_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_post_failure_test),
+	KUNIT_CASE(vmbus_local_rescind_skips_teardown_test),
+	KUNIT_CASE(vmbus_invalid_relid_skips_teardown_test),
+	KUNIT_CASE(vmbus_host_rescind_teardown_late_ack_test),
+	KUNIT_CASE(vmbus_buffer_mapping_reference_test),
+	KUNIT_CASE(vmbus_buffer_partial_allocation_cleanup_test),
+	KUNIT_CASE(vmbus_buffer_repeated_owner_release_test),
+	KUNIT_CASE(vmbus_buffer_order_zero_allocation_test),
+	KUNIT_CASE(vmbus_gpadl_post_failure_test),
+	KUNIT_CASE(vmbus_gpadl_post_success_test),
+	KUNIT_CASE(vmbus_gpadl_response_state_test),
+	KUNIT_CASE(vmbus_gpadl_teardown_post_failure_test),
+	KUNIT_CASE(vmbus_requestor_alloc_free_test),
+	KUNIT_CASE(vmbus_requestor_vmalloc_backing_test),
+	KUNIT_CASE(vmbus_requestor_id_lifecycle_test),
+	KUNIT_CASE(vmbus_requestor_invalid_ids_test),
+	KUNIT_CASE(vmbus_requestor_exhaustion_test),
+	{}
+};
+
+static struct kunit_suite vmbus_buffer_test_suite = {
+	.name = "hyperv-vmbus-buffer",
+	.test_cases = vmbus_buffer_test_cases,
+};
+
+kunit_test_suite(vmbus_buffer_test_suite);
diff --git a/drivers/hv/vmbus_drv.c b/drivers/hv/vmbus_drv.c
index 5ebdbe24b5a1e..198b43d240510 100644
--- a/drivers/hv/vmbus_drv.c
+++ b/drivers/hv/vmbus_drv.c
@@ -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);
 }
@@ -1926,6 +1929,7 @@ static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,
 {
 	struct vmbus_channel *channel = container_of(kobj, struct vmbus_channel, kobj);
 	struct vm_area_desc desc;
+	struct vmbus_buffer_pin *pin;
 	int err;
 
 	/*
@@ -1937,9 +1941,55 @@ static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,
 	if (err)
 		return err;
 
-	return __compat_vma_mmap(&desc, vma);
+	/*
+	 * This is a kernfs bin attribute. kernfs_fop_mmap() rejects a VMA
+	 * whose vm_ops carry .close, because kernfs has to replace the set
+	 * with its own and cannot wrap close. So the prepare callback has
+	 * to pick one of two ownership contracts, and this wrapper honors
+	 * whichever it installed. Each contract has exactly one release
+	 * site, reached on every outcome.
+	 *
+	 * With vm_ops, the callback handed the per-VMA state to an abandon
+	 * path in vm_ops->close and typically to vm_ops->mapped. Install
+	 * both 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. Note
+	 * that such a set is rejected by kernfs after this returns, so a
+	 * prepare callback that wants a successful mapping must not choose
+	 * this contract.
+	 *
+	 * Without vm_ops, desc.private_data is a plain struct
+	 * vmbus_buffer_pin and this wrapper is its only owner. Release it
+	 * when __compat_vma_mmap() returns: on success insert_pages() has
+	 * already taken a folio reference for every page the VMA maps, and
+	 * on failure the attempt is over. Clear vma->vm_private_data first
+	 * so the freed pin is never reachable from the VMA that outlives
+	 * this call.
+	 */
+	if (desc.vm_ops) {
+		vma->vm_ops = desc.vm_ops;
+		vma->vm_private_data = desc.private_data;
+
+		err = __compat_vma_mmap(&desc, vma);
+		if (err && vma->vm_ops && vma->vm_ops->close)
+			vma->vm_ops->close(vma);
+		return err;
+	}
+
+	pin = desc.private_data;
+	err = __compat_vma_mmap(&desc, vma);
+	vma->vm_private_data = NULL;
+	vmbus_buffer_unpin_pages(pin);
+	kfree(pin);
+	return err;
 }
 
+#if IS_ENABLED(CONFIG_HYPERV_VMBUS_KUNIT_TEST)
+#include "vmbus_mmap_test.c"
+#endif
+
 static struct bin_attribute chan_attr_ring_buffer = {
 	.attr = {
 		.name = "ring",
@@ -3072,6 +3122,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();
diff --git a/drivers/hv/vmbus_mmap_test.c b/drivers/hv/vmbus_mmap_test.c
new file mode 100644
index 0000000000000..50b961f2b782d
--- /dev/null
+++ b/drivers/hv/vmbus_mmap_test.c
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Included beside the production sysfs wrapper; no VMBus device is touched. */
+#include <kunit/test.h>
+#include <linux/mman.h>
+#include <linux/uaccess.h>
+
+struct vmbus_mmap_test_context {
+	struct vmbus_channel channel;
+	struct page *pages[3];
+	struct page *blocker;
+};
+
+static void vmbus_mmap_test_put_page(void *page)
+{
+	__free_page(page);
+}
+
+static struct page *vmbus_mmap_test_page(struct kunit *test, u8 value)
+{
+	struct page *page = alloc_page(GFP_KERNEL);
+
+	if (!page)
+		return NULL;
+	if (kunit_add_action_or_reset(test, vmbus_mmap_test_put_page, page))
+		return NULL;
+	memset(page_address(page), value, PAGE_SIZE);
+	return page;
+}
+
+static int vmbus_mmap_test_prepare(struct vmbus_channel *channel,
+				   struct vm_area_desc *desc)
+{
+	struct vmbus_buffer_pin *pin;
+	int ret;
+
+	pin = kzalloc_obj(*pin);
+	if (!pin)
+		return -ENOMEM;
+	ret = vmbus_buffer_pin_pages(&channel->ringbuffer, pin);
+	if (ret) {
+		kfree(pin);
+		return ret;
+	}
+	mmap_action_map_kernel_pages(desc, desc->start, pin->pages,
+				     pin->page_count);
+	desc->vm_ops = NULL;
+	desc->private_data = pin;
+	return 0;
+}
+
+static struct vmbus_mmap_test_context *
+vmbus_mmap_test_context(struct kunit *test)
+{
+	struct vmbus_mmap_test_context *ctx;
+	unsigned int i;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return NULL;
+	for (i = 0; i < ARRAY_SIZE(ctx->pages); i++) {
+		ctx->pages[i] = vmbus_mmap_test_page(test, 0x61 + i);
+		if (!ctx->pages[i])
+			return NULL;
+	}
+	ctx->blocker = vmbus_mmap_test_page(test, 0xcc);
+	if (!ctx->blocker)
+		return NULL;
+	ctx->channel.mmap_prepare_ring_buffer = vmbus_mmap_test_prepare;
+	ctx->channel.ringbuffer.pages = ctx->pages;
+	ctx->channel.ringbuffer.page_cnt = ARRAY_SIZE(ctx->pages);
+	return ctx;
+}
+
+static void vmbus_mmap_test_action(struct kunit *test, bool partial)
+{
+	struct vmbus_mmap_test_context *ctx = vmbus_mmap_test_context(test);
+	struct vm_area_struct *vma;
+	unsigned long start;
+	unsigned int i;
+	u8 value = 0;
+	int ret;
+
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	start = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE,
+			      MAP_SHARED | MAP_ANONYMOUS, 0);
+	KUNIT_ASSERT_NE(test, start, 0UL);
+	KUNIT_ASSERT_LT(test, start, (unsigned long)TASK_SIZE);
+
+	mmap_write_lock(current->mm);
+	vma = find_vma(current->mm, start);
+	if (!vma) {
+		mmap_write_unlock(current->mm);
+		KUNIT_FAIL(test, "managed VMA missing");
+		return;
+	}
+	if (partial) {
+		ret = vm_insert_page(vma, start + PAGE_SIZE, ctx->blocker);
+		if (ret) {
+			mmap_write_unlock(current->mm);
+			KUNIT_FAIL(test, "owned blocking PTE could not be installed");
+			return;
+		}
+	}
+	ret = hv_mmap_ring_buffer_wrapper(vma->vm_file, &ctx->channel.kobj,
+					  NULL, vma);
+	KUNIT_EXPECT_EQ(test, ret, partial ? -EBUSY : 0);
+	KUNIT_EXPECT_NULL(test, vma->vm_private_data);
+	KUNIT_EXPECT_NULL(test, vma->vm_ops);
+	for (i = 0; i < ARRAY_SIZE(ctx->pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(ctx->pages[i]),
+				partial && i ? 1 : 2);
+	KUNIT_EXPECT_EQ(test, page_ref_count(ctx->blocker), partial ? 2 : 1);
+	mmap_write_unlock(current->mm);
+
+	/* The first insertion really happened, including on the partial error. */
+	KUNIT_EXPECT_EQ(test, copy_from_user(&value, (void __user *)start, 1), 0UL);
+	KUNIT_EXPECT_EQ(test, value, (u8)0x61);
+	KUNIT_ASSERT_EQ(test, vm_munmap(start, 3 * PAGE_SIZE), 0);
+	for (i = 0; i < ARRAY_SIZE(ctx->pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(ctx->pages[i]), 1);
+	KUNIT_EXPECT_EQ(test, page_ref_count(ctx->blocker), 1);
+}
+
+static void vmbus_sysfs_mmap_success_test(struct kunit *test)
+{
+	vmbus_mmap_test_action(test, false);
+}
+
+static void vmbus_sysfs_mmap_partial_insert_test(struct kunit *test)
+{
+	vmbus_mmap_test_action(test, true);
+}
+
+static struct kunit_case vmbus_mmap_test_cases[] = {
+	KUNIT_CASE(vmbus_sysfs_mmap_success_test),
+	KUNIT_CASE(vmbus_sysfs_mmap_partial_insert_test),
+	{}
+};
+
+static struct kunit_suite vmbus_mmap_test_suite = {
+	.name = "hyperv-vmbus-mmap",
+	.test_cases = vmbus_mmap_test_cases,
+};
+
+kunit_test_suite(vmbus_mmap_test_suite);
diff --git a/drivers/net/hyperv/Kconfig b/drivers/net/hyperv/Kconfig
index 982964c1a9fb9..226728fd77d71 100644
--- a/drivers/net/hyperv/Kconfig
+++ b/drivers/net/hyperv/Kconfig
@@ -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.
diff --git a/drivers/net/hyperv/Makefile b/drivers/net/hyperv/Makefile
index 0db7ccaec4a4c..b2d22855fd8a0 100644
--- a/drivers/net/hyperv/Makefile
+++ b/drivers/net/hyperv/Makefile
@@ -2,3 +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
diff --git a/drivers/net/hyperv/hyperv_net.h b/drivers/net/hyperv/hyperv_net.h
index 4841367fdab2f..be3a63a168cfa 100644
--- a/drivers/net/hyperv/hyperv_net.h
+++ b/drivers/net/hyperv/hyperv_net.h
@@ -210,14 +210,40 @@ struct rndis_device {
 	u8 rss_key[NETVSC_HASH_KEYLEN];
 };
 
+#define RNDIS_EXT_LEN HV_HYP_PAGE_SIZE
 
-/* Interface */
+/* Full definitions are below, after the RNDIS message format. */
+struct rndis_request;
 struct rndis_message;
+
+/* Interface */
 struct ndis_offload_params;
 struct netvsc_device;
 struct netvsc_channel;
 struct net_device_context;
 
+struct rndis_request *get_rndis_request(struct rndis_device *dev,
+					u32 msg_type, u32 msg_len);
+void put_rndis_request(struct rndis_device *dev, struct rndis_request *req);
+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);
@@ -1158,21 +1184,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;
@@ -1785,6 +1805,36 @@ struct rndis_message {
 	union rndis_message_container msg;
 };
 
+/*
+ * RNDIS request descriptor. Declared here so the KUnit cases can reach
+ * the layout the response-copy bound in rndis_filter_receive_resp()
+ * relies on. The two RNDIS_EXT_LEN tails are what make the object
+ * larger than KMALLOC_MAX_CACHE_SIZE.
+ */
+struct rndis_request {
+	struct list_head list_ent;
+	struct completion  wait_event;
+
+	struct rndis_message response_msg;
+	/*
+	 * The buffer for extended info after the RNDIS response message. It's
+	 * referenced based on the data offset in the RNDIS message. Its size
+	 * is enough for current needs, and should be sufficient for the near
+	 * future.
+	 */
+	u8 response_ext[RNDIS_EXT_LEN];
+
+	/* Simplify allocation by having a netvsc packet inline */
+	struct hv_netvsc_packet	pkt;
+
+	struct rndis_message request_msg;
+	/*
+	 * The buffer for the extended info after the RNDIS request message.
+	 * It is referenced and sized in a similar way as response_ext.
+	 */
+	u8 request_ext[RNDIS_EXT_LEN];
+};
+
 
 /* Handy macros */
 
diff --git a/drivers/net/hyperv/netvsc.c b/drivers/net/hyperv/netvsc.c
index 5cd084e5696cd..8ea7c993baac0 100644
--- a/drivers/net/hyperv/netvsc.c
+++ b/drivers/net/hyperv/netvsc.c
@@ -134,10 +134,8 @@ static void __free_netvsc_device(struct netvsc_device *nvdev)
 
 	kfree(nvdev->extension);
 
-	vmbus_free_buffer(nvdev->recv_buf, nvdev->recv_buf_chunks,
-			  nvdev->recv_buf_chunk_cnt);
-	vmbus_free_buffer(nvdev->send_buf, nvdev->send_buf_chunks,
-			  nvdev->send_buf_chunk_cnt);
+	vmbus_release_buffer(&nvdev->recv_buffer);
+	vmbus_release_buffer(&nvdev->send_buffer);
 	bitmap_free(nvdev->send_section_map);
 
 	for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
@@ -146,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)
@@ -173,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;
 
@@ -308,9 +306,9 @@ static void netvsc_teardown_recv_gpadl(struct hv_device *device,
 {
 	int ret;
 
-	if (net_device->recv_buf_gpadl_handle.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(device->channel,
-					   &net_device->recv_buf_gpadl_handle);
+	if (net_device->recv_buffer.gpadl.gpadl_handle) {
+		ret = vmbus_teardown_gpadl_owned(device->channel,
+						 &net_device->recv_buffer);
 
 		/* If we failed here, we might as well return and have a leak
 		 * rather than continue and a bugchk
@@ -329,9 +327,9 @@ static void netvsc_teardown_send_gpadl(struct hv_device *device,
 {
 	int ret;
 
-	if (net_device->send_buf_gpadl_handle.gpadl_handle) {
-		ret = vmbus_teardown_gpadl(device->channel,
-					   &net_device->send_buf_gpadl_handle);
+	if (net_device->send_buffer.gpadl.gpadl_handle) {
+		ret = vmbus_teardown_gpadl_owned(device->channel,
+						 &net_device->send_buffer);
 
 		/* If we failed here, we might as well return and have a leak
 		 * rather than continue and a bugchk
@@ -377,15 +375,13 @@ static int netvsc_init_buf(struct hv_device *device,
 		buf_size = min_t(unsigned int, buf_size,
 				 NETVSC_RECEIVE_BUFFER_SIZE_LEGACY);
 
-	net_device->recv_buf =
-		vmbus_alloc_buffer(device->channel, buf_size,
-				   &net_device->recv_buf_chunks,
-				   &net_device->recv_buf_chunk_cnt);
-	if (!net_device->recv_buf) {
+	ret = vmbus_alloc_buffer_owned(device->channel, buf_size,
+				       device->channel->co_external_memory,
+				       &net_device->recv_buffer);
+	if (ret) {
 		netdev_err(ndev,
 			   "unable to allocate receive buffer of size %u\n",
 			   buf_size);
-		ret = -ENOMEM;
 		goto cleanup;
 	}
 
@@ -396,10 +392,8 @@ static int netvsc_init_buf(struct hv_device *device,
 	 * channel.  Note: This call uses the vmbus connection rather
 	 * than the channel to establish the gpadl handle.
 	 */
-	ret = vmbus_establish_gpadl_caller_decrypted(device->channel,
-						     net_device->recv_buf,
-						     buf_size,
-						     &net_device->recv_buf_gpadl_handle);
+	ret = vmbus_establish_gpadl_owned(device->channel,
+					  &net_device->recv_buffer);
 	if (ret != 0) {
 		netdev_err(ndev,
 			"unable to establish receive buffer's gpadl\n");
@@ -411,7 +405,7 @@ static int netvsc_init_buf(struct hv_device *device,
 	memset(init_packet, 0, sizeof(struct nvsp_message));
 	init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_RECV_BUF;
 	init_packet->msg.v1_msg.send_recv_buf.
-		gpadl_handle = net_device->recv_buf_gpadl_handle.gpadl_handle;
+		gpadl_handle = net_device->recv_buffer.gpadl.gpadl_handle;
 	init_packet->msg.v1_msg.
 		send_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
 
@@ -487,14 +481,12 @@ static int netvsc_init_buf(struct hv_device *device,
 	buf_size = device_info->send_sections * device_info->send_section_size;
 	buf_size = round_up(buf_size, PAGE_SIZE);
 
-	net_device->send_buf =
-		vmbus_alloc_buffer(device->channel, buf_size,
-				   &net_device->send_buf_chunks,
-				   &net_device->send_buf_chunk_cnt);
-	if (!net_device->send_buf) {
+	ret = vmbus_alloc_buffer_owned(device->channel, buf_size,
+				       device->channel->co_external_memory,
+				       &net_device->send_buffer);
+	if (ret) {
 		netdev_err(ndev, "unable to allocate send buffer of size %u\n",
 			   buf_size);
-		ret = -ENOMEM;
 		goto cleanup;
 	}
 	net_device->send_buf_size = buf_size;
@@ -503,10 +495,8 @@ static int netvsc_init_buf(struct hv_device *device,
 	 * channel.  Note: This call uses the vmbus connection rather
 	 * than the channel to establish the gpadl handle.
 	 */
-	ret = vmbus_establish_gpadl_caller_decrypted(device->channel,
-						     net_device->send_buf,
-						     buf_size,
-						     &net_device->send_buf_gpadl_handle);
+	ret = vmbus_establish_gpadl_owned(device->channel,
+					  &net_device->send_buffer);
 	if (ret != 0) {
 		netdev_err(ndev,
 			   "unable to establish send buffer's gpadl\n");
@@ -518,7 +508,7 @@ static int netvsc_init_buf(struct hv_device *device,
 	memset(init_packet, 0, sizeof(struct nvsp_message));
 	init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_SEND_BUF;
 	init_packet->msg.v1_msg.send_send_buf.gpadl_handle =
-		net_device->send_buf_gpadl_handle.gpadl_handle;
+		net_device->send_buffer.gpadl.gpadl_handle;
 	init_packet->msg.v1_msg.send_send_buf.id = NETVSC_SEND_BUFFER_ID;
 
 	trace_nvsp_send(ndev, init_packet);
@@ -774,20 +764,45 @@ static inline void netvsc_free_send_slot(struct netvsc_device *net_device,
 	sync_change_bit(index, net_device->send_section_map);
 }
 
-static 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_acct(struct net_device *ndev,
+		      struct netvsc_device *net_device,
+		      struct vmbus_channel *channel,
+		      u16 q_idx)
+{
+	struct net_device_context *ndev_ctx = netdev_priv(ndev);
+	int queue_sends;
+
+	queue_sends =
+		atomic_dec_return(&net_device->chan_table[q_idx].queue_sends);
+
+	if (unlikely(net_device->destroy)) {
+		if (queue_sends == 0)
+			wake_up(&net_device->wait_drain);
+	} else {
+		struct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);
+
+		if (netif_tx_queue_stopped(txq) && !net_device->tx_disable &&
+		    (hv_get_avail_to_write_percent(&channel->outbound) >
+		     RING_AVAIL_PERCENT_HIWATER || queue_sends < 1)) {
+			netif_tx_wake_queue(txq);
+			ndev_ctx->eth_stats.wake_queue++;
+		}
+	}
+}
+
+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)
 {
 	struct net_device_context *ndev_ctx = netdev_priv(ndev);
 	struct sk_buff *skb;
 	u16 q_idx = 0;
-	int queue_sends;
 	u64 cmd_rqst;
 
 	cmd_rqst = channel->request_addr_callback(channel, desc->trans_id);
-	if (cmd_rqst == VMBUS_RQST_ERROR) {
+	if (cmd_rqst == VMBUS_RQST_ERROR || cmd_rqst == VMBUS_NO_RQSTOR) {
 		netdev_err(ndev, "Invalid transaction ID %llx\n", desc->trans_id);
 		return;
 	}
@@ -816,29 +831,14 @@ static void netvsc_send_tx_complete(struct net_device *ndev,
 		napi_consume_skb(skb, budget);
 	}
 
-	queue_sends =
-		atomic_dec_return(&net_device->chan_table[q_idx].queue_sends);
-
-	if (unlikely(net_device->destroy)) {
-		if (queue_sends == 0)
-			wake_up(&net_device->wait_drain);
-	} else {
-		struct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);
-
-		if (netif_tx_queue_stopped(txq) && !net_device->tx_disable &&
-		    (hv_get_avail_to_write_percent(&channel->outbound) >
-		     RING_AVAIL_PERCENT_HIWATER || queue_sends < 1)) {
-			netif_tx_wake_queue(txq);
-			ndev_ctx->eth_stats.wake_queue++;
-		}
-	}
+	netvsc_send_acct(ndev, net_device, channel, q_idx);
 }
 
-static 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)
+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)
 {
 	const struct nvsp_message *nvsp_packet;
 	u32 msglen = hv_pkt_datalen(desc);
@@ -850,11 +850,24 @@ static void netvsc_send_completion(struct net_device *ndev,
 	if (!msglen) {
 		cmd_rqst = incoming_channel->request_addr_callback(incoming_channel,
 								   desc->trans_id);
-		if (cmd_rqst == VMBUS_RQST_ERROR) {
+		if (cmd_rqst == VMBUS_RQST_ERROR || cmd_rqst == VMBUS_NO_RQSTOR) {
 			netdev_err(ndev, "Invalid transaction ID %llx\n", desc->trans_id);
 			return;
 		}
 
+		/*
+		 * netvsc_send_pkt() registers (ulong)skb as the request
+		 * address. Control RNDIS sends carry no skb, so the
+		 * registered address is NULL and there is no nvsp_message
+		 * to inspect. The request id is consumed above, so this
+		 * completion owns the send accounting -- the same thing
+		 * netvsc_send_tx_complete() does when it sees a NULL skb.
+		 */
+		if (!cmd_rqst) {
+			netvsc_send_acct(ndev, net_device, incoming_channel, 0);
+			return;
+		}
+
 		pkt_rqst = (struct nvsp_message *)(uintptr_t)cmd_rqst;
 		switch (pkt_rqst->hdr.msg_type) {
 		case NVSP_MSG4_TYPE_SWITCH_DATA_PATH:
@@ -968,7 +981,7 @@ static void netvsc_copy_to_send_buf(struct netvsc_device *net_device,
 				    struct hv_page_buffer *pb,
 				    bool xmit_more)
 {
-	char *start = net_device->send_buf;
+	char *start = net_device->send_buffer.addr;
 	char *dest = start + (section_index * net_device->send_section_size)
 		     + pend_size;
 	int i;
@@ -1475,7 +1488,7 @@ static int netvsc_receive(struct net_device *ndev,
 	const struct nvsp_message *nvsp = hv_pkt_data(desc);
 	u32 msglen = hv_pkt_datalen(desc);
 	u16 q_idx = channel->offermsg.offer.sub_channel_index;
-	char *recv_buf = net_device->recv_buf;
+	char *recv_buf = net_device->recv_buffer.addr;
 	u32 status = NVSP_STAT_SUCCESS;
 	int i;
 	int count = 0;
diff --git a/drivers/net/hyperv/netvsc_completion_test.c b/drivers/net/hyperv/netvsc_completion_test.c
new file mode 100644
index 0000000000000..2614b1ece2327
--- /dev/null
+++ b/drivers/net/hyperv/netvsc_completion_test.c
@@ -0,0 +1,439 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for empty and skb-backed netvsc completion handling.
+ *
+ * Built into the hv_netvsc object rather than a separate module so the
+ * cases can reach the internal helpers declared in hyperv_net.h
+ * without exporting them.
+ */
+#include <kunit/test.h>
+#include <linux/etherdevice.h>
+#include <linux/hyperv.h>
+#include <linux/netdevice.h>
+#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/wait.h>
+
+#include "hyperv_net.h"
+
+/*
+ * Scripted requestor. request_addr_callback() only receives the channel
+ * and the transaction id, so the fixture is hung off a file-scope
+ * pointer. KUnit runs suite cases serially; one active fixture is
+ * enough and keeps the callback signature untouched.
+ */
+struct netvsc_completion_fixture {
+	struct net_device *ndev;
+	struct netvsc_device *nvdev;
+	struct vmbus_channel *channel;
+	/* Address returned on first use, then VMBUS_NO_RQSTOR: the id is
+	 * consumed exactly once, as vmbus_request_addr_match() does.
+	 */
+	u64 once_addr;
+	unsigned int calls;
+	u64 seen_ids[8];
+	unsigned int skb_frees;
+};
+
+static struct netvsc_completion_fixture *active_fx;
+
+static u64 test_request_addr(struct vmbus_channel *channel, u64 rqst_id)
+{
+	struct netvsc_completion_fixture *fx = active_fx;
+
+	if (fx->calls < ARRAY_SIZE(fx->seen_ids))
+		fx->seen_ids[fx->calls] = rqst_id;
+	fx->calls++;
+
+	if (fx->calls == 1)
+		return fx->once_addr;
+	return VMBUS_NO_RQSTOR;
+}
+
+/*
+ * A completion carrying no payload: hv_pkt_datalen() == 0. The
+ * empty-completion path looks the request up by trans_id and reads its
+ * message type, so the request itself is a separate object the fixture
+ * hands back through request_addr_callback().
+ */
+struct netvsc_empty_desc {
+	struct vmpacket_descriptor desc;
+} __packed;
+
+static void make_empty_desc(struct netvsc_empty_desc *pkt, u64 trans_id)
+{
+	memset(pkt, 0, sizeof(*pkt));
+	pkt->desc.offset8 = sizeof(pkt->desc) / 8;
+	pkt->desc.len8 = pkt->desc.offset8;
+	pkt->desc.trans_id = trans_id;
+}
+
+/*
+ * The production path never dereferences a net_device queue while
+ * tx_disable is set: netif_tx_queue_stopped() && !tx_disable
+ * short-circuits before hv_get_avail_to_write_percent() reads the
+ * ring. Set it here so a test needs no live outbound ring.
+ */
+static int netvsc_completion_fixture_init(struct netvsc_completion_fixture *fx)
+{
+	fx->ndev = alloc_netdev_mqs(sizeof(struct net_device_context),
+				    "hvcompl%d", NET_NAME_UNKNOWN,
+				    ether_setup, 2, 2);
+	if (!fx->ndev)
+		return -ENOMEM;
+
+	fx->nvdev = kzalloc_obj(*fx->nvdev, GFP_KERNEL);
+	if (!fx->nvdev) {
+		free_netdev(fx->ndev);
+		return -ENOMEM;
+	}
+
+	fx->channel = kzalloc_obj(*fx->channel, GFP_KERNEL);
+	if (!fx->channel) {
+		kfree(fx->nvdev);
+		free_netdev(fx->ndev);
+		return -ENOMEM;
+	}
+
+	init_waitqueue_head(&fx->nvdev->wait_drain);
+	init_completion(&fx->nvdev->channel_init_wait);
+	fx->nvdev->tx_disable = true;
+	fx->channel->request_addr_callback = test_request_addr;
+	fx->once_addr = 0;
+	fx->calls = 0;
+	memset(fx->seen_ids, 0, sizeof(fx->seen_ids));
+	active_fx = fx;
+	return 0;
+}
+
+static void netvsc_completion_fixture_exit(struct netvsc_completion_fixture *fx)
+{
+	active_fx = NULL;
+	kfree(fx->channel);
+	kfree(fx->nvdev);
+	free_netdev(fx->ndev);
+}
+
+static int netvsc_send_sends(struct netvsc_completion_fixture *fx, u16 q_idx)
+{
+	return atomic_read(&fx->nvdev->chan_table[q_idx].queue_sends);
+}
+
+/* Empty completion, request address NULL: owns the send accounting. */
+static void netvsc_completion_null_address_acct_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x11);
+	/* once_addr = 0 is the control-path NULL skb case. */
+	fx.once_addr = 0;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+	KUNIT_EXPECT_EQ(test, fx.calls, 1U);
+	KUNIT_EXPECT_EQ(test, fx.seen_ids[0], 0x11U);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* VMBUS_RQST_ERROR is rejected: no accounting, no completion. */
+static void netvsc_completion_rqst_error_sentinel_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x22);
+	fx.once_addr = VMBUS_RQST_ERROR;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* VMBUS_NO_RQSTOR is rejected the same way. */
+static void netvsc_completion_no_rqstor_sentinel_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x33);
+	fx.once_addr = VMBUS_NO_RQSTOR;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/*
+ * A real request address whose message type is SWITCH_DATA_PATH
+ * completes the channel-init wait. It is not send accounting: the
+ * control request was not a send.
+ */
+static void netvsc_completion_switch_data_path_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+	struct nvsp_message req = {};
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x44);
+	req.hdr.msg_type = NVSP_MSG4_TYPE_SWITCH_DATA_PATH;
+	fx.once_addr = (u64)(unsigned long)&req;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_TRUE(test, completion_done(&fx.nvdev->channel_init_wait));
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* An unexpected message type takes neither the complete nor the acct path. */
+static void netvsc_completion_unknown_msg_type_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+	struct nvsp_message req = {};
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x55);
+	req.hdr.msg_type = 0xdead;
+	fx.once_addr = (u64)(unsigned long)&req;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+
+	KUNIT_EXPECT_FALSE(test, completion_done(&fx.nvdev->channel_init_wait));
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 3);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/*
+ * A repeated completion for an already-consumed transaction id must not
+ * account twice. The requestor returns VMBUS_NO_RQSTOR on the second
+ * use and the empty-completion path rejects it.
+ */
+static void netvsc_completion_duplicate_completion_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x66);
+	fx.once_addr = 0;
+
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+	KUNIT_EXPECT_EQ(test, fx.calls, 1U);
+
+	/* Second completion for the same id: already consumed. */
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+	KUNIT_EXPECT_EQ(test, fx.calls, 2U);
+	KUNIT_EXPECT_EQ(test, fx.seen_ids[0], 0x66U);
+	KUNIT_EXPECT_EQ(test, fx.seen_ids[1], 0x66U);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/* N completions decrement the queue exactly N times. */
+static void netvsc_completion_single_decrement_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+	int i;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 5);
+
+	for (i = 0; i < 5; i++) {
+		make_empty_desc(&pkt, 0x100 + i);
+		fx.once_addr = 0;
+		fx.calls = 0;
+		netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel,
+				       &pkt.desc, 0);
+		KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 4 - i);
+		KUNIT_EXPECT_EQ(test, fx.calls, 1U);
+	}
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 0);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+static int netvsc_test_wake(struct wait_queue_entry *wq_entry,
+			    unsigned int mode, int flags, void *key)
+{
+	unsigned int *woken = wq_entry->private;
+
+	(*woken)++;
+	return 0;
+}
+
+/* destroy + a decrement that reaches zero wakes the drain wait. */
+static void netvsc_send_acct_drain_wake_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct wait_queue_entry entry;
+	unsigned int woken = 0;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	fx.nvdev->destroy = true;
+
+	memset(&entry, 0, sizeof(entry));
+	entry.func = netvsc_test_wake;
+	entry.private = &woken;
+	add_wait_queue(&fx.nvdev->wait_drain, &entry);
+
+	/* Non-zero remainder: the drain wait is not woken. */
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 2);
+	netvsc_send_acct(fx.ndev, fx.nvdev, fx.channel, 0);
+	KUNIT_EXPECT_EQ(test, woken, 0U);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 1);
+
+	/* Exactly zero: the drain wait is woken once. */
+	netvsc_send_acct(fx.ndev, fx.nvdev, fx.channel, 0);
+	KUNIT_EXPECT_EQ(test, woken, 1U);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 0);
+
+	remove_wait_queue(&fx.nvdev->wait_drain, &entry);
+	netvsc_completion_fixture_exit(&fx);
+}
+
+/*
+ * netvsc_send_tx_complete() applies the same sentinel rejection and
+ * still accounts a NULL skb.
+ */
+static void netvsc_tx_complete_null_skb_acct_test(struct kunit *test)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct netvsc_empty_desc pkt;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 3);
+	make_empty_desc(&pkt, 0x77);
+	fx.once_addr = 0;
+
+	netvsc_send_tx_complete(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+
+	/* The sentinel is rejected before any accounting. */
+	make_empty_desc(&pkt, 0x78);
+	fx.once_addr = VMBUS_RQST_ERROR;
+	fx.calls = 0;
+	netvsc_send_tx_complete(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 2);
+
+	netvsc_completion_fixture_exit(&fx);
+}
+
+static void netvsc_test_skb_destructor(struct sk_buff *skb)
+{
+	active_fx->skb_frees++;
+}
+
+static void netvsc_tx_complete_skb(struct kunit *test, u32 status)
+{
+	struct netvsc_completion_fixture fx = {};
+	struct {
+		struct vmpacket_descriptor desc;
+		struct nvsp_message message;
+	} pkt = {};
+	unsigned long send_slots = BIT(3);
+	struct hv_netvsc_packet *packet;
+	struct netvsc_stats_tx *stats;
+	struct sk_buff *skb;
+
+	KUNIT_ASSERT_EQ(test, netvsc_completion_fixture_init(&fx), 0);
+	skb = alloc_skb(64, GFP_KERNEL);
+	if (!skb) {
+		KUNIT_FAIL(test, "skb allocation failed");
+		goto out;
+	}
+	skb->destructor = netvsc_test_skb_destructor;
+	packet = (struct hv_netvsc_packet *)skb->cb;
+	memset(packet, 0, sizeof(*packet));
+	packet->send_buf_index = 3;
+	packet->q_idx = 1;
+	packet->total_packets = 2;
+	packet->total_bytes = 64;
+	fx.nvdev->send_section_map = &send_slots;
+	stats = &fx.nvdev->chan_table[1].tx_stats;
+	u64_stats_init(&stats->syncp);
+	atomic_set(&fx.nvdev->chan_table[0].queue_sends, 7);
+	atomic_set(&fx.nvdev->chan_table[1].queue_sends, 3);
+	fx.once_addr = (u64)(unsigned long)skb;
+	pkt.desc.offset8 = sizeof(pkt.desc) / 8;
+	pkt.desc.len8 = DIV_ROUND_UP(sizeof(pkt), 8);
+	pkt.desc.trans_id = 0x79;
+	pkt.message.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE;
+	pkt.message.msg.v1_msg.send_rndis_pkt_complete.status = status;
+
+	/* Budget zero consumes the real skb synchronously, outside NAPI. */
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, send_slots, 0UL);
+	KUNIT_EXPECT_EQ(test, fx.skb_frees, 1U);
+	KUNIT_EXPECT_EQ(test, stats->packets, 2ULL);
+	KUNIT_EXPECT_EQ(test, stats->bytes, 64ULL);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 0), 7);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 1), 2);
+
+	/* The consumed transaction cannot free or account the skb twice. */
+	netvsc_send_completion(fx.ndev, fx.nvdev, fx.channel, &pkt.desc, 0);
+	KUNIT_EXPECT_EQ(test, send_slots, 0UL);
+	KUNIT_EXPECT_EQ(test, fx.skb_frees, 1U);
+	KUNIT_EXPECT_EQ(test, stats->packets, 2ULL);
+	KUNIT_EXPECT_EQ(test, stats->bytes, 64ULL);
+	KUNIT_EXPECT_EQ(test, netvsc_send_sends(&fx, 1), 2);
+out:
+	netvsc_completion_fixture_exit(&fx);
+}
+
+static void netvsc_tx_complete_skb_success_test(struct kunit *test)
+{
+	netvsc_tx_complete_skb(test, NVSP_STAT_SUCCESS);
+}
+
+static void netvsc_tx_complete_skb_error_test(struct kunit *test)
+{
+	netvsc_tx_complete_skb(test, NVSP_STAT_FAIL);
+}
+
+static struct kunit_case netvsc_completion_test_cases[] = {
+	KUNIT_CASE(netvsc_completion_null_address_acct_test),
+	KUNIT_CASE(netvsc_completion_rqst_error_sentinel_test),
+	KUNIT_CASE(netvsc_completion_no_rqstor_sentinel_test),
+	KUNIT_CASE(netvsc_completion_switch_data_path_test),
+	KUNIT_CASE(netvsc_completion_unknown_msg_type_test),
+	KUNIT_CASE(netvsc_completion_duplicate_completion_test),
+	KUNIT_CASE(netvsc_completion_single_decrement_test),
+	KUNIT_CASE(netvsc_send_acct_drain_wake_test),
+	KUNIT_CASE(netvsc_tx_complete_null_skb_acct_test),
+	KUNIT_CASE(netvsc_tx_complete_skb_success_test),
+	KUNIT_CASE(netvsc_tx_complete_skb_error_test),
+	{}
+};
+
+static struct kunit_suite netvsc_completion_test_suite = {
+	.name = "hyperv-netvsc-completion",
+	.test_cases = netvsc_completion_test_cases,
+};
+
+kunit_test_suite(netvsc_completion_test_suite);
diff --git a/drivers/net/hyperv/rndis_filter.c b/drivers/net/hyperv/rndis_filter.c
index 9b6c44979b4ea..1ce40baa2d239 100644
--- a/drivers/net/hyperv/rndis_filter.c
+++ b/drivers/net/hyperv/rndis_filter.c
@@ -16,6 +16,7 @@
 #include <linux/if_ether.h>
 #include <linux/netdevice.h>
 #include <linux/if_vlan.h>
+#include <linux/mm.h>
 #include <linux/nls.h>
 #include <linux/vmalloc.h>
 #include <linux/rtnetlink.h>
@@ -27,31 +28,6 @@
 
 static void rndis_set_multicast(struct work_struct *w);
 
-#define RNDIS_EXT_LEN HV_HYP_PAGE_SIZE
-struct rndis_request {
-	struct list_head list_ent;
-	struct completion  wait_event;
-
-	struct rndis_message response_msg;
-	/*
-	 * The buffer for extended info after the RNDIS response message. It's
-	 * referenced based on the data offset in the RNDIS message. Its size
-	 * is enough for current needs, and should be sufficient for the near
-	 * future.
-	 */
-	u8 response_ext[RNDIS_EXT_LEN];
-
-	/* Simplify allocation by having a netvsc packet inline */
-	struct hv_netvsc_packet	pkt;
-
-	struct rndis_message request_msg;
-	/*
-	 * The buffer for the extended info after the RNDIS request message.
-	 * It is referenced and sized in a similar way as response_ext.
-	 */
-	u8 request_ext[RNDIS_EXT_LEN];
-};
-
 static const u8 netvsc_hash_key[NETVSC_HASH_KEYLEN] = {
 	0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2,
 	0x41, 0x67, 0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0,
@@ -78,16 +54,27 @@ static struct rndis_device *get_rndis_device(void)
 	return device;
 }
 
-static struct rndis_request *get_rndis_request(struct rndis_device *dev,
-					     u32 msg_type,
-					     u32 msg_len)
+struct rndis_request *get_rndis_request(struct rndis_device *dev,
+					u32 msg_type,
+					u32 msg_len)
 {
 	struct rndis_request *request;
 	struct rndis_message *rndis_msg;
 	struct rndis_set_request *set;
 	unsigned long flags;
 
-	request = kzalloc_obj(struct rndis_request);
+	/*
+	 * struct rndis_request embeds two RNDIS_EXT_LEN (4 KiB) protocol
+	 * tails and is larger than KMALLOC_MAX_CACHE_SIZE, so
+	 * kzalloc_obj() needs an order-2 compound page. That high-order
+	 * allocation can fail under buddy fragmentation. kvzalloc_obj()
+	 * keeps the zeroing semantics while allowing vmalloc backing when
+	 * a suitable kmalloc allocation is unavailable. The request payload
+	 * is sent as GPADL-direct page buffers, so rndis_filter_send_request()
+	 * must describe each backing page instead of assuming virt_to_phys()
+	 * yields one contiguous physical range.
+	 */
+	request = kvzalloc_obj(struct rndis_request);
 	if (!request)
 		return NULL;
 
@@ -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;
 
@@ -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);
 }
 
 static void dump_rndis_message(struct net_device *netdev,
@@ -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)
+{
+	const u8 *addr = data;
+	u32 count = 0;
+
+	if (!data || !len || !page_bufs || !page_buf_cnt)
+		return -EINVAL;
+
+	*page_buf_cnt = 0;
+
+	while (len) {
+		struct page *page;
+		phys_addr_t phys;
+		u32 offset, chunk;
+		unsigned long page_offset = offset_in_page(addr);
+
+		if (count == MAX_PAGE_BUFFER_COUNT)
+			return -E2BIG;
+
+		if (is_vmalloc_addr(addr))
+			page = vmalloc_to_page(addr);
+		else if (virt_addr_valid(addr))
+			page = virt_to_page(addr);
+		else
+			return -EFAULT;
+
+		if (!page)
+			return -EFAULT;
+
+		phys = page_to_phys(page) + page_offset;
+		offset = offset_in_hvpage(phys);
+		chunk = min_t(u32, len, PAGE_SIZE - page_offset);
+		chunk = min_t(u32, chunk, HV_HYP_PAGE_SIZE - offset);
+
+		page_bufs[count].pfn = phys >> HV_HYP_PAGE_SHIFT;
+		page_bufs[count].offset = offset;
+		page_bufs[count].len = chunk;
+
+		addr += chunk;
+		len -= chunk;
+		count++;
+	}
+
+	*page_buf_cnt = count;
+	return 0;
+}
+
 static int rndis_filter_send_request(struct rndis_device *dev,
 				  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);
+	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();
 
 	return ret;
diff --git a/drivers/net/hyperv/rndis_request_test.c b/drivers/net/hyperv/rndis_request_test.c
new file mode 100644
index 0000000000000..6affa916e74e3
--- /dev/null
+++ b/drivers/net/hyperv/rndis_request_test.c
@@ -0,0 +1,216 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for RNDIS request descriptor allocation.
+ *
+ * Built into the hv_netvsc object rather than a separate module so the
+ * cases can reach the internal helpers declared in hyperv_net.h
+ * without exporting them.
+ */
+#include <kunit/test.h>
+#include <linux/hyperv.h>
+#include <linux/mm.h>
+#include <linux/slab.h>
+#include <linux/stddef.h>
+#include <linux/vmalloc.h>
+
+#include "hyperv_net.h"
+
+static int rndis_test_device_init(struct rndis_device *dev)
+{
+	memset(dev, 0, sizeof(*dev));
+	atomic_set(&dev->new_req_id, 0);
+	spin_lock_init(&dev->request_lock);
+	INIT_LIST_HEAD(&dev->req_list);
+	return 0;
+}
+
+/*
+ * The premise of the kvzalloc_obj() conversion: the descriptor embeds
+ * two RNDIS_EXT_LEN protocol tails and sits past
+ * KMALLOC_MAX_CACHE_SIZE, so kzalloc_obj() reached kmalloc_large() and
+ * took an order-2 compound page on the subchannel open path. If the
+ * struct ever drops back inside the cache, the conversion stops being
+ * about high-order allocation and this assertion is the reminder.
+ */
+static void rndis_request_size_premise_test(struct kunit *test)
+{
+	KUNIT_EXPECT_GT(test, sizeof(struct rndis_request),
+			(size_t)KMALLOC_MAX_CACHE_SIZE);
+	/*
+	 * The copy bound in rndis_filter_receive_resp() is
+	 * sizeof(struct rndis_message) + RNDIS_EXT_LEN. That is exactly
+	 * the response_msg + response_ext tail of the object. A reorder
+	 * or a resize of either member makes the bound lie.
+	 */
+	KUNIT_EXPECT_EQ(test,
+			offsetofend(struct rndis_request, response_ext),
+			offsetof(struct rndis_request, response_msg) +
+				sizeof(struct rndis_message) + RNDIS_EXT_LEN);
+	KUNIT_EXPECT_EQ(test,
+			offsetofend(struct rndis_request, request_ext),
+			offsetof(struct rndis_request, request_msg) +
+				sizeof(struct rndis_message) + RNDIS_EXT_LEN);
+}
+
+/*
+ * kvzalloc_obj() keeps the zeroing kzalloc_obj() provided. The two
+ * protocol tails are the fields a response is copied into; a stale
+ * tail is a stale response.
+ */
+static void rndis_request_alloc_zeroed_test(struct kunit *test)
+{
+	struct rndis_device dev;
+	struct rndis_request *req;
+
+	KUNIT_ASSERT_EQ(test, rndis_test_device_init(&dev), 0);
+	req = get_rndis_request(&dev, RNDIS_MSG_INIT, 0x20);
+	KUNIT_ASSERT_NOT_NULL(test, req);
+
+	KUNIT_EXPECT_EQ(test, req->response_ext[0], 0);
+	KUNIT_EXPECT_EQ(test, req->response_ext[RNDIS_EXT_LEN - 1], 0);
+	KUNIT_EXPECT_EQ(test, req->request_ext[0], 0);
+	KUNIT_EXPECT_EQ(test, req->request_ext[RNDIS_EXT_LEN - 1], 0);
+	KUNIT_EXPECT_EQ(test, req->response_msg.msg_len, 0U);
+
+	put_rndis_request(&dev, req);
+}
+
+/* Request ids come from a per-device counter and the list tracks the live set. */
+static void rndis_request_id_lifecycle_test(struct kunit *test)
+{
+	struct rndis_device dev;
+	struct rndis_request *req0, *req1;
+	struct rndis_request *cursor;
+	unsigned int n = 0;
+
+	KUNIT_ASSERT_EQ(test, rndis_test_device_init(&dev), 0);
+
+	req0 = get_rndis_request(&dev, RNDIS_MSG_INIT, 0x20);
+	KUNIT_ASSERT_NOT_NULL(test, req0);
+	req1 = get_rndis_request(&dev, RNDIS_MSG_QUERY, 0x20);
+	KUNIT_ASSERT_NOT_NULL(test, req1);
+
+	/*
+	 * get_rndis_request() stamps the id through the set_req template,
+	 * which shares the union slot with every other request body. Read
+	 * it back through the same member the producer used.
+	 */
+	KUNIT_EXPECT_EQ(test,
+			req0->request_msg.msg.set_req.req_id, 1U);
+	KUNIT_EXPECT_EQ(test,
+			req1->request_msg.msg.set_req.req_id, 2U);
+
+	list_for_each_entry(cursor, &dev.req_list, list_ent)
+		n++;
+	KUNIT_EXPECT_EQ(test, n, 2U);
+
+	/*
+	 * put_rndis_request() is the cleanup path every error and
+	 * timeout branch takes. It unlinks before it frees.
+	 */
+	put_rndis_request(&dev, req0);
+	n = 0;
+	list_for_each_entry(cursor, &dev.req_list, list_ent)
+		n++;
+	KUNIT_EXPECT_EQ(test, n, 1U);
+	KUNIT_EXPECT_TRUE(test,
+			  list_first_entry(&dev.req_list, struct rndis_request,
+					   list_ent) == req1);
+
+	put_rndis_request(&dev, req1);
+	KUNIT_EXPECT_TRUE(test, list_empty(&dev.req_list));
+}
+
+/*
+ * A request left on the list after a completed exchange is a leak of
+ * the descriptor and of its slot in the outstanding set. Repeated
+ * get/put cycles must return to the empty list every time.
+ */
+static void rndis_request_put_cleanup_test(struct kunit *test)
+{
+	struct rndis_device dev;
+	struct rndis_request *req;
+	int i;
+
+	KUNIT_ASSERT_EQ(test, rndis_test_device_init(&dev), 0);
+
+	for (i = 0; i < 4; i++) {
+		req = get_rndis_request(&dev, RNDIS_MSG_INIT, 0x20);
+		KUNIT_ASSERT_NOT_NULL(test, req);
+		KUNIT_EXPECT_FALSE(test, list_empty(&dev.req_list));
+		put_rndis_request(&dev, req);
+		KUNIT_EXPECT_TRUE(test, list_empty(&dev.req_list));
+	}
+}
+
+/*
+ * kvzalloc_obj() may return a vmalloc address under fragmentation. RNDIS
+ * requests are GPA-direct packets, so each backing page must be represented
+ * explicitly instead of deriving a single PFN with virt_to_phys().
+ */
+static void rndis_request_vmalloc_page_buffers_test(struct kunit *test)
+{
+	struct hv_page_buffer page_bufs[MAX_PAGE_BUFFER_COUNT];
+	const u32 data_len = 16;
+	u8 *allocation = vzalloc(2 * PAGE_SIZE);
+	const u8 *cursor;
+	phys_addr_t phys;
+	u32 count = 0, remaining = data_len, i;
+	int ret;
+
+	if (!allocation) {
+		KUNIT_FAIL(test, "could not allocate vmalloc test buffer");
+		return;
+	}
+
+	cursor = allocation + PAGE_SIZE - 8;
+	ret = rndis_build_page_buffers(cursor, data_len, page_bufs, &count);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto out;
+
+	KUNIT_EXPECT_EQ(test, count, 2U);
+	for (i = 0; i < count; i++) {
+		struct page *page = vmalloc_to_page(cursor);
+		unsigned long page_offset = offset_in_page(cursor);
+		u32 offset, chunk;
+
+		if (!page) {
+			KUNIT_FAIL(test, "vmalloc test buffer has no backing page");
+			goto out;
+		}
+
+		phys = page_to_phys(page) + page_offset;
+		offset = offset_in_hvpage(phys);
+		chunk = min_t(u32, remaining, PAGE_SIZE - page_offset);
+		chunk = min_t(u32, chunk, HV_HYP_PAGE_SIZE - offset);
+
+		KUNIT_EXPECT_EQ(test, page_bufs[i].pfn,
+				(u64)(phys >> HV_HYP_PAGE_SHIFT));
+		KUNIT_EXPECT_EQ(test, page_bufs[i].offset, offset);
+		KUNIT_EXPECT_EQ(test, page_bufs[i].len, chunk);
+
+		cursor += chunk;
+		remaining -= chunk;
+	}
+	KUNIT_EXPECT_EQ(test, remaining, 0U);
+
+out:
+	vfree(allocation);
+}
+
+static struct kunit_case rndis_request_test_cases[] = {
+	KUNIT_CASE(rndis_request_size_premise_test),
+	KUNIT_CASE(rndis_request_alloc_zeroed_test),
+	KUNIT_CASE(rndis_request_id_lifecycle_test),
+	KUNIT_CASE(rndis_request_put_cleanup_test),
+	KUNIT_CASE(rndis_request_vmalloc_page_buffers_test),
+	{}
+};
+
+static struct kunit_suite rndis_request_test_suite = {
+	.name = "hyperv-rndis-request",
+	.test_cases = rndis_request_test_cases,
+};
+
+kunit_test_suite(rndis_request_test_suite);
diff --git a/drivers/uio/Kconfig b/drivers/uio/Kconfig
index 9242e77385c64..0a01906bd6cdc 100644
--- a/drivers/uio/Kconfig
+++ b/drivers/uio/Kconfig
@@ -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
diff --git a/drivers/uio/uio.c b/drivers/uio/uio.c
index f8fa205226601..4767ed0661f74 100644
--- a/drivers/uio/uio.c
+++ b/drivers/uio/uio.c
@@ -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;
 	}
 
diff --git a/drivers/uio/uio_hv_generic.c b/drivers/uio/uio_hv_generic.c
index 7b4cc456c4534..91cb25d019be9 100644
--- a/drivers/uio/uio_hv_generic.c
+++ b/drivers/uio/uio_hv_generic.c
@@ -25,6 +25,7 @@
 #include <linux/uio_driver.h>
 #include <linux/netdevice.h>
 #include <linux/if_ether.h>
+#include <linux/mm.h>
 #include <linux/skbuff.h>
 #include <linux/hyperv.h>
 #include <linux/vmalloc.h>
@@ -55,13 +56,13 @@ struct hv_uio_private_data {
 	struct uio_info info;
 	struct hv_device *device;
 	atomic_t refcnt;
+	struct page *int_pages[1];
+	struct page *monitor_pages[1];
 
-	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];
 };
 
@@ -123,49 +124,310 @@ static void hv_uio_channel_cb(void *context)
 	uio_event_notify(&pdata->info);
 }
 
+/* Function used for mmap of the ring buffer sysfs interface. */
+static bool hv_uio_mmap_range_valid(unsigned long map_pages,
+				    pgoff_t offset,
+				    unsigned long pages)
+{
+	return pages && offset < map_pages && pages <= map_pages - offset;
+}
+
+struct hv_uio_mmap_region {
+	struct page **pages;
+	unsigned long page_count;
+	struct vmbus_buffer *buffer;
+	bool decrypted;
+};
+
+static int hv_uio_mmap_get_region(struct hv_uio_private_data *pdata,
+				  unsigned int map_index,
+				  struct hv_uio_mmap_region *region)
+{
+	struct hv_device *dev = pdata->device;
+	struct vmbus_channel *channel = dev->channel;
+
+	if (map_index >= MAX_UIO_MAPS || !pdata->info.mem[map_index].size)
+		return -EINVAL;
+
+	/*
+	 * Buffer-backed regions are not described here. Their page array
+	 * and protection state are only meaningful as the locked snapshot
+	 * from vmbus_buffer_pin_pages(): reading the descriptor outside
+	 * that lock can describe a buffer a concurrent release has already
+	 * cleared. Only the owning buffer is selected at this stage.
+	 */
+	region->buffer = NULL;
+	region->pages = NULL;
+	region->page_count = 0;
+	region->decrypted = false;
+
+	switch (map_index) {
+	case TXRX_RING_MAP:
+		if (channel->state != CHANNEL_OPENED_STATE)
+			return -ENODEV;
+		region->buffer = &channel->ringbuffer;
+		return 0;
+	case INT_PAGE_MAP:
+		region->pages = pdata->int_pages;
+		region->page_count = ARRAY_SIZE(pdata->int_pages);
+		region->decrypted = false;
+		break;
+	case MON_PAGE_MAP:
+		region->pages = pdata->monitor_pages;
+		region->page_count = ARRAY_SIZE(pdata->monitor_pages);
+		region->decrypted = true;
+		break;
+	case RECV_BUF_MAP:
+		region->buffer = &pdata->recv_buffer;
+		return 0;
+	case SEND_BUF_MAP:
+		region->buffer = &pdata->send_buffer;
+		return 0;
+	default:
+		return -EINVAL;
+	}
+
+	if (!region->pages || !region->page_count)
+		return -EINVAL;
+
+	return 0;
+}
+
+static int hv_uio_mmap_prepare_pages(struct vm_area_desc *desc,
+				     struct page **pages,
+				     unsigned long page_count,
+				     pgoff_t offset,
+				     bool decrypted)
+{
+	unsigned long nr_pages = vma_desc_pages(desc);
+
+	if (!vma_desc_test(desc, VMA_SHARED_BIT))
+		return -EINVAL;
+
+	if (!pages || !hv_uio_mmap_range_valid(page_count, offset, nr_pages))
+		return -EINVAL;
+
+	vma_desc_set_flags(desc, VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT);
+	if (decrypted)
+		desc->page_prot = pgprot_decrypted(desc->page_prot);
+
+	mmap_action_map_kernel_pages(desc, desc->start, pages + offset,
+				     nr_pages);
+	return 0;
+}
+
 /*
- * Callback from vmbus_event when channel is rescinded.
- * It is meant for rescind of primary channels only.
+ * mmap_action_map_kernel_pages() only stores the page-array pointer. The
+ * mapping takes its own folio references inside insert_pages(), which runs
+ * after the prepare callback has returned. Dropping the pin therefore has
+ * to wait for the VMA to be established (mapped) or for the attempt to be
+ * abandoned. Release is one-shot: the establish and abandon paths can both
+ * be reached for the same attempt.
+ *
+ * Two surfaces, two ownership contracts. /dev/uioN is a character device,
+ * so kernfs is not in the path and vm_ops->close is a legal abandon path.
+ * The sysfs "ring" bin attribute is kernfs: fs/kernfs/file.c rejects any
+ * VMA whose vm_ops carry .close, because kernfs has to wrap the operations
+ * and cannot wrap close. That surface installs no vm_ops at all and its
+ * synchronous legacy .mmap wrapper owns the pin for the whole window.
  */
-static void hv_uio_rescind(struct vmbus_channel *channel)
+#define HV_UIO_PIN_MAGIC 0x48565049UL /* "HVPI" */
+
+struct hv_uio_pin {
+	unsigned long magic;
+	struct vmbus_buffer_pin snap;
+};
+
+static void hv_uio_pin_release(void *data)
 {
-	struct hv_device *hv_dev = channel->device_obj;
-	struct hv_uio_private_data *pdata = hv_get_drvdata(hv_dev);
+	struct hv_uio_pin *pin = data;
 
+	if (!pin)
+		return;
 	/*
-	 * Turn off the interrupt file handle
-	 * Next read for event will return -EIO
+	 * close() can be reached with a private_data that this driver did
+	 * not install. A foreign pointer must not be freed or unpinned.
 	 */
-	pdata->info.irq = 0;
+	if (pin->magic != HV_UIO_PIN_MAGIC)
+		return;
+	pin->magic = 0;
+	vmbus_buffer_unpin_pages(&pin->snap);
+	kfree(pin);
+}
 
-	/* Wake up reader */
-	uio_event_notify(&pdata->info);
+static int hv_uio_pin_vma_mapped(unsigned long start, unsigned long end,
+				 pgoff_t pgoff, const struct file *file,
+				 void **vm_private_data)
+{
+	/*
+	 * insert_pages() has taken a folio reference for every page the
+	 * VMA now maps, so the reclaim worker can no longer free them
+	 * under the mapping. The bridge pin is done.
+	 */
+	hv_uio_pin_release(*vm_private_data);
+	*vm_private_data = NULL;
+	return 0;
+}
 
+static void hv_uio_pin_vma_close(struct vm_area_struct *vma)
+{
 	/*
-	 * With rescind callback registered, rescind path will not unregister the device
-	 * from vmbus when the primary channel is rescinded.
-	 * Without it, rescind handling is incomplete and next onoffer msg does not come.
-	 * Unregister the device from vmbus here.
+	 * Reached with the pin still held when the VMA is torn down before
+	 * mapped() ran (an insert_pages() failure, or a merge that never
+	 * calls mapped), and with nothing left to do when it already ran.
 	 */
-	vmbus_device_unregister(channel->device_obj);
+	hv_uio_pin_release(vma->vm_private_data);
+	vma->vm_private_data = NULL;
 }
 
-/* Function used for mmap of ring buffer sysfs interface.
- * The ring buffer is allocated as contiguous memory by vmbus_open
+/*
+ * Character-device surface only. The sysfs ring must never adopt this set:
+ * see the kernfs contract above.
+ */
+static const struct vm_operations_struct hv_uio_pin_vm_ops = {
+	.mapped = hv_uio_pin_vma_mapped,
+	.close = hv_uio_pin_vma_close,
+};
+
+/*
+ * Install @snap as the VMA's per-mapping state under @ops. Consumes @snap:
+ * returns 0 with the pin owned by @desc and @snap cleared, or -ENOMEM with
+ * the references dropped here. The caller must not drop the references on
+ * the success path: mapped() and close() own them from here.
  */
+static int hv_uio_pin_install(struct vm_area_desc *desc,
+			      const struct vm_operations_struct *ops,
+			      struct vmbus_buffer_pin *snap)
+{
+	struct hv_uio_pin *pin;
+
+	pin = kzalloc_obj(*pin);
+	if (!pin) {
+		vmbus_buffer_unpin_pages(snap);
+		return -ENOMEM;
+	}
+	pin->magic = HV_UIO_PIN_MAGIC;
+	pin->snap = *snap;
+	snap->pages = NULL;
+	snap->page_count = 0;
+
+	desc->vm_ops = ops;
+	desc->private_data = pin;
+	return 0;
+}
+
+static int hv_uio_mmap_prepare(struct uio_info *info,
+			       struct vm_area_desc *desc)
+{
+	struct hv_uio_private_data *pdata = info->priv;
+	struct hv_uio_mmap_region region;
+	struct vmbus_buffer_pin pin = {};
+	struct page **pages;
+	unsigned long page_count;
+	bool decrypted;
+	int ret;
+
+	/* UIO encodes the map index in pgoff; mmap offsets start at the map. */
+	if (desc->pgoff >= MAX_UIO_MAPS)
+		return -EINVAL;
+
+	ret = hv_uio_mmap_get_region(pdata, desc->pgoff, &region);
+	if (ret)
+		return ret;
+
+	/*
+	 * Buffer-backed maps race with the reclaim worker: the page
+	 * array and the pages themselves can be freed between the
+	 * selection above and the mapping below. Hold references until
+	 * the VMA holds its own. The pin is also the only safe source of
+	 * the protection state: it is taken in the same critical section
+	 * that reads the page array.
+	 */
+	if (region.buffer) {
+		ret = vmbus_buffer_pin_pages(region.buffer, &pin);
+		if (ret)
+			return ret;
+		pages = pin.pages;
+		page_count = pin.page_count;
+		decrypted = pin.decrypted;
+	} else {
+		pages = region.pages;
+		page_count = region.page_count;
+		decrypted = region.decrypted;
+	}
+
+	ret = hv_uio_mmap_prepare_pages(desc, pages, page_count, 0, decrypted);
+	if (ret) {
+		if (region.buffer)
+			vmbus_buffer_unpin_pages(&pin);
+		return ret;
+	}
+
+	if (!region.buffer)
+		return 0;
+
+	return hv_uio_pin_install(desc, &hv_uio_pin_vm_ops, &pin);
+}
+
 static int
-hv_uio_ring_mmap_prepare(struct vmbus_channel *channel, struct vm_area_desc *desc)
+hv_uio_ring_mmap_prepare(struct vmbus_channel *channel,
+			 struct vm_area_desc *desc)
 {
-	void *ring_buffer = page_address(channel->ringbuffer_page);
+	struct vmbus_buffer *buffer = &channel->ringbuffer;
+	struct vmbus_buffer_pin *pin;
+	pgoff_t offset = desc->pgoff;
+	int ret;
 
 	if (channel->state != CHANNEL_OPENED_STATE)
 		return -ENODEV;
 
-	mmap_action_simple_ioremap(desc, virt_to_phys(ring_buffer),
-			channel->ringbuffer_pagecount << PAGE_SHIFT);
+	pin = kzalloc_obj(*pin);
+	if (!pin)
+		return -ENOMEM;
+
+	ret = vmbus_buffer_pin_pages(buffer, pin);
+	if (ret) {
+		kfree(pin);
+		return ret;
+	}
+
+	ret = hv_uio_mmap_prepare_pages(desc, pin->pages, pin->page_count,
+					offset, pin->decrypted);
+	if (ret) {
+		vmbus_buffer_unpin_pages(pin);
+		kfree(pin);
+		return ret;
+	}
+
+	/*
+	 * Install no vm_ops. kernfs_fop_mmap() returns -EINVAL for a VMA
+	 * whose vm_ops carry .close, and a successful mapping still has to
+	 * survive that check, so this surface cannot carry an abandon path
+	 * in vm_ops at all. The caller is hv_mmap_ring_buffer_wrapper(),
+	 * a synchronous legacy .mmap: it holds @pin across
+	 * __compat_vma_mmap() and frees it when that returns, exactly once,
+	 * on every outcome. desc->private_data is a plain
+	 * struct vmbus_buffer_pin for that wrapper to release.
+	 */
+	desc->vm_ops = NULL;
+	desc->private_data = pin;
 	return 0;
 }
 
+/* Caller has withdrawn UIO callbacks before removing its backing memory. */
+static int hv_uio_disconnect_if_open(struct vmbus_channel *channel,
+				     int (*disconnect)(struct vmbus_channel *))
+{
+	if (channel->state != CHANNEL_OPENED_STATE)
+		return 0;
+
+	return disconnect(channel);
+}
+
+#if defined(CONFIG_UIO_HV_GENERIC_KUNIT_TEST)
+#include "uio_hv_generic_mmap_test.c"
+#endif
+
 /* Callback from VMBUS subsystem when new channel created. */
 static void
 hv_uio_new_channel(struct vmbus_channel *new_sc)
@@ -195,17 +457,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) {
-		vmbus_teardown_gpadl(dev->channel, &pdata->send_gpadl);
-		if (!pdata->send_gpadl.decrypted)
-			vfree(pdata->send_buf);
-	}
+	if (pdata->send_buffer.gpadl.gpadl_handle)
+		vmbus_teardown_gpadl_owned(dev->channel, &pdata->send_buffer);
+	vmbus_release_buffer(&pdata->send_buffer);
 
-	if (pdata->recv_gpadl.gpadl_handle) {
-		vmbus_teardown_gpadl(dev->channel, &pdata->recv_gpadl);
-		if (!pdata->recv_gpadl.decrypted)
-			vfree(pdata->recv_buf);
-	}
+	if (pdata->recv_buffer.gpadl.gpadl_handle)
+		vmbus_teardown_gpadl_owned(dev->channel, &pdata->recv_buffer);
+	vmbus_release_buffer(&pdata->recv_buffer);
 }
 
 /* VMBus primary channel is opened on first use */
@@ -220,7 +478,6 @@ hv_uio_open(struct uio_info *info, struct inode *inode)
 	if (atomic_inc_return(&pdata->refcnt) != 1)
 		return 0;
 
-	vmbus_set_chn_rescind_callback(dev->channel, hv_uio_rescind);
 	vmbus_set_sc_create_callback(dev->channel, hv_uio_new_channel);
 
 	ret = vmbus_connect_ring(dev->channel,
@@ -276,6 +533,7 @@ hv_uio_probe(struct hv_device *dev,
 	pdata->info.name = "uio_hv_generic";
 	pdata->info.version = DRIVER_VERSION;
 	pdata->info.irqcontrol = hv_uio_irqcontrol;
+	pdata->info.mmap_prepare = hv_uio_mmap_prepare;
 	pdata->info.open = hv_uio_open;
 	pdata->info.release = hv_uio_release;
 	pdata->info.irq = UIO_IRQ_CUSTOM;
@@ -283,66 +541,60 @@ 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
 		= (uintptr_t)vmbus_connection.int_page;
 	pdata->info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
 	pdata->info.mem[INT_PAGE_MAP].memtype = UIO_MEM_LOGICAL;
+	pdata->int_pages[0] = virt_to_page(vmbus_connection.int_page);
 
 	pdata->info.mem[MON_PAGE_MAP].name = "monitor_page";
 	pdata->info.mem[MON_PAGE_MAP].addr
 		= (uintptr_t)vmbus_connection.monitor_pages[1];
 	pdata->info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
 	pdata->info.mem[MON_PAGE_MAP].memtype = UIO_MEM_LOGICAL;
+	pdata->monitor_pages[0] =
+		virt_to_page(vmbus_connection.monitor_pages[1]);
 
 	if (channel->device_id == HV_NIC) {
-		pdata->recv_buf = vzalloc(RECV_BUFFER_SIZE);
-		if (!pdata->recv_buf) {
-			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_buf,
-					    RECV_BUFFER_SIZE, &pdata->recv_gpadl);
-		if (ret) {
-			if (!pdata->recv_gpadl.decrypted)
-				vfree(pdata->recv_buf);
+		ret = vmbus_establish_gpadl_owned(channel, &pdata->recv_buffer);
+		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) {
-			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_buf,
-					    SEND_BUFFER_SIZE, &pdata->send_gpadl);
-		if (ret) {
-			if (!pdata->send_gpadl.decrypted)
-				vfree(pdata->send_buf);
+		ret = vmbus_establish_gpadl_owned(channel, &pdata->send_buffer);
+		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;
 	}
@@ -385,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);
+	/* 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);
+	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);
diff --git a/drivers/uio/uio_hv_generic_mmap_test.c b/drivers/uio/uio_hv_generic_mmap_test.c
new file mode 100644
index 0000000000000..615df78b266e7
--- /dev/null
+++ b/drivers/uio/uio_hv_generic_mmap_test.c
@@ -0,0 +1,875 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * KUnit tests for the UIO Hyper-V generic mmap paths.
+ *
+ * This file is included from uio_hv_generic.c so the cases can reach the
+ * static helpers that select, validate and pin the mapped pages.
+ *
+ * Two ownership contracts are under test:
+ *   - the /dev/uioN character-device path installs hv_uio_pin_vm_ops
+ *     (.mapped + .close) and a struct hv_uio_pin;
+ *   - the sysfs "ring" bin attribute cannot, because kernfs_fop_mmap()
+ *     rejects a vm_operations_struct that carries .close. That path
+ *     installs no vm_ops and hands a bare struct vmbus_buffer_pin to its
+ *     synchronous .mmap wrapper, which is the single release site.
+ */
+#include <kunit/test.h>
+
+/*
+ * Release exactly what hv_mmap_ring_buffer_wrapper() releases after
+ * __compat_vma_mmap() returns: the bare pin's references, then the pin.
+ */
+static void sysfs_pin_release(struct vmbus_buffer_pin *pin)
+{
+	vmbus_buffer_unpin_pages(pin);
+	kfree(pin);
+}
+
+static void hv_uio_ring_mmap_range_test(struct kunit *test)
+{
+	KUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 0, 8));
+	KUNIT_EXPECT_TRUE(test, hv_uio_mmap_range_valid(8, 4, 4));
+	KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 8, 1));
+	KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 7, 2));
+	KUNIT_EXPECT_FALSE(test, hv_uio_mmap_range_valid(8, 0, 0));
+	KUNIT_EXPECT_FALSE(test,
+			   hv_uio_mmap_range_valid(8, U64_MAX, 1));
+}
+
+static void hv_uio_ring_mmap_prepare_test(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 8,
+		},
+	};
+	struct page *pages[8] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = PAGE_SIZE,
+		.end = 5 * PAGE_SIZE,
+		.pgoff = 2,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	/* Mapping pins real pages; the array cannot hold NULL entries. */
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages, &pages[2]);
+	KUNIT_EXPECT_EQ(test, desc.action.map_kernel.nr_pages, 4UL);
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTEXPAND_BIT));
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTDUMP_BIT));
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(pgprot_decrypted(PAGE_SHARED)));
+
+	/*
+	 * The sysfs surface installs no vm_ops at all: see the kernfs
+	 * contract in the comment at the top of this file. The wrapper
+	 * holds the pin and is the only thing that releases it.
+	 */
+	KUNIT_EXPECT_NULL(test, desc.vm_ops);
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	KUNIT_EXPECT_TRUE(test, pin->decrypted);
+	KUNIT_EXPECT_EQ(test, pin->page_count, ARRAY_SIZE(pages));
+	sysfs_pin_release(pin);
+
+	desc.vma_flags = EMPTY_VMA_FLAGS;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	desc.start = PAGE_SIZE;
+	desc.end = 3 * PAGE_SIZE;
+	desc.pgoff = 7;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+
+	channel.state = CHANNEL_OPEN_STATE;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -ENODEV);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+static void hv_uio_mmap_region_select_test(struct kunit *test)
+{
+	struct hv_uio_private_data pdata = {};
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct hv_uio_mmap_region region;
+	struct page *ring_pages[4] = {};
+	struct page *recv_pages[3] = {};
+	struct page *send_pages[2] = {};
+	struct page *chunks[1] = {};
+	int ret;
+
+	pdata.device = &dev;
+	pdata.info.mem[TXRX_RING_MAP].size =
+		ARRAY_SIZE(ring_pages) * PAGE_SIZE;
+	pdata.info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata.info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata.info.mem[RECV_BUF_MAP].size =
+		ARRAY_SIZE(recv_pages) * PAGE_SIZE;
+	pdata.info.mem[SEND_BUF_MAP].size =
+		ARRAY_SIZE(send_pages) * PAGE_SIZE;
+	channel.ringbuffer.pages = ring_pages;
+	channel.ringbuffer.page_cnt = ARRAY_SIZE(ring_pages);
+	channel.ringbuffer.chunks = chunks;
+	pdata.int_pages[0] = ring_pages[0];
+	pdata.monitor_pages[0] = ring_pages[1];
+	pdata.recv_buffer.pages = recv_pages;
+	pdata.recv_buffer.page_cnt = ARRAY_SIZE(recv_pages);
+	pdata.recv_buffer.chunks = chunks;
+	pdata.send_buffer.pages = send_pages;
+	pdata.send_buffer.page_cnt = ARRAY_SIZE(send_pages);
+
+	/*
+	 * Buffer-backed maps are described only by their owning buffer.
+	 * The page array and the protection state are deliberately absent
+	 * here: reading them outside vmbus_buffer_owners_lock can describe
+	 * a buffer a concurrent release has already cleared. The locked
+	 * pin snapshot is the only safe source.
+	 */
+	ret = hv_uio_mmap_get_region(&pdata, TXRX_RING_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, region.buffer, &channel.ringbuffer);
+	KUNIT_EXPECT_NULL(test, region.pages);
+	KUNIT_EXPECT_EQ(test, region.page_count, 0UL);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, INT_PAGE_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, region.buffer);
+	KUNIT_EXPECT_PTR_EQ(test, region.pages, &pdata.int_pages[0]);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, MON_PAGE_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, region.buffer);
+	KUNIT_EXPECT_PTR_EQ(test, region.pages, &pdata.monitor_pages[0]);
+	KUNIT_EXPECT_TRUE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, RECV_BUF_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, region.buffer, &pdata.recv_buffer);
+	KUNIT_EXPECT_NULL(test, region.pages);
+	KUNIT_EXPECT_EQ(test, region.page_count, 0UL);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	ret = hv_uio_mmap_get_region(&pdata, SEND_BUF_MAP, &region);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, region.buffer, &pdata.send_buffer);
+	KUNIT_EXPECT_NULL(test, region.pages);
+	KUNIT_EXPECT_EQ(test, region.page_count, 0UL);
+	KUNIT_EXPECT_FALSE(test, region.decrypted);
+
+	KUNIT_EXPECT_EQ(test,
+			hv_uio_mmap_get_region(&pdata, MAX_UIO_MAPS, &region),
+			-EINVAL);
+	channel.state = CHANNEL_OPEN_STATE;
+	KUNIT_EXPECT_EQ(test,
+			hv_uio_mmap_get_region(&pdata, TXRX_RING_MAP, &region),
+			-ENODEV);
+}
+
+static void hv_uio_mmap_prepare_test(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[4] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = PAGE_SIZE,
+		.end = 3 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	/* Mapping pins real pages; the array cannot hold NULL entries. */
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages, &pages[0]);
+	KUNIT_EXPECT_EQ(test, desc.action.map_kernel.nr_pages, 2UL);
+	/*
+	 * The protection state comes from the locked pin snapshot, not
+	 * from a second read of the buffer descriptor. chunks is set, so
+	 * the snapshot says decrypted.
+	 */
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(pgprot_decrypted(PAGE_SHARED)));
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTEXPAND_BIT));
+	KUNIT_EXPECT_TRUE(test, vma_desc_test(&desc, VMA_DONTDUMP_BIT));
+	/*
+	 * Character-device maps can carry an abandon path: kernfs is not
+	 * in this path, so .close is legal here and illegal on "ring".
+	 */
+	KUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, &hv_uio_pin_vm_ops);
+	KUNIT_ASSERT_NOT_NULL(test, desc.vm_ops->mapped);
+	KUNIT_ASSERT_NOT_NULL(test, desc.vm_ops->close);
+	/* Buffer-backed maps leave the pin held for mapped()/close(). */
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+	hv_uio_pin_release(desc.private_data);
+	desc.private_data = NULL;
+
+	desc.vma_flags = EMPTY_VMA_FLAGS;
+	KUNIT_EXPECT_EQ(test, hv_uio_mmap_prepare(&pdata->info, &desc), -EINVAL);
+
+	desc.pgoff = INT_PAGE_MAP;
+	pdata->info.mem[INT_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata->int_pages[0] = pages[0];
+	desc.end = 2 * PAGE_SIZE;
+	desc.page_prot = PAGE_SHARED;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages,
+			    &pdata->int_pages[0]);
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(PAGE_SHARED));
+	/* int_pages is not a vmbus_buffer, so nothing is pinned. */
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+
+	desc.pgoff = MON_PAGE_MAP;
+	pdata->info.mem[MON_PAGE_MAP].size = HV_HYP_PAGE_SIZE;
+	pdata->monitor_pages[0] = pages[1];
+	desc.page_prot = PAGE_SHARED;
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_PTR_EQ(test, desc.action.map_kernel.pages,
+			    &pdata->monitor_pages[0]);
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(pgprot_decrypted(PAGE_SHARED)));
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+
+	desc.pgoff = SEND_BUF_MAP;
+	pdata->info.mem[SEND_BUF_MAP].size = PAGE_SIZE;
+	pdata->send_buffer.pages = pages;
+	pdata->send_buffer.page_cnt = ARRAY_SIZE(pages);
+	desc.page_prot = PAGE_SHARED;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	/* send_buffer has no chunks, so the snapshot says encrypted. */
+	KUNIT_EXPECT_EQ(test, pgprot_val(desc.page_prot),
+			pgprot_val(PAGE_SHARED));
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+	hv_uio_pin_release(desc.private_data);
+	desc.private_data = NULL;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The reclaim race this driver closes is a lifetime question: the pin has
+ * to span the gap between mmap_prepare() returning and insert_pages()
+ * taking its own folio references. Dropping it inside the prepare hook
+ * leaves the pages freeable before the mapping exists.
+ *
+ * This is the character-device contract: mapped() and close() share the
+ * release, and release is one-shot.
+ */
+static void hv_uio_pin_lifetime_test(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[4] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 4 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	struct vm_area_struct *vma;
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	/*
+	 * Prepare must hold a reference on every page: the mapping is not
+	 * installed until insert_pages() runs after the hook returns.
+	 */
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	KUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, &hv_uio_pin_vm_ops);
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+
+	/* mapped(): the mapping holds its own refs, so the pin is released. */
+	ret = desc.vm_ops->mapped(desc.start, desc.end, 0, NULL,
+				  &desc.private_data);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* close() after mapped() must not unpin again. */
+	vma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, vma);
+	vma->vm_ops = desc.vm_ops;
+	vma->vm_private_data = desc.private_data;
+	desc.vm_ops->close(vma);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The abandonment path: when the mapping is torn down before mapped() ran
+ * (insert_pages() failure, or a merge that never calls mapped()), close()
+ * must still drop the pin. A foreign private_data must be left alone.
+ */
+static void hv_uio_pin_close_before_mapped_test(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	struct vm_area_struct *vma;
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+
+	vma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, vma);
+	vma->vm_ops = desc.vm_ops;
+	vma->vm_private_data = desc.private_data;
+	desc.vm_ops->close(vma);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* A second close is a no-op, not a double unpin. */
+	desc.vm_ops->close(vma);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* A pointer this driver did not install must not be freed. */
+	vma->vm_private_data = &pages[0];
+	desc.vm_ops->close(vma);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The kernfs contract, named. fs/kernfs/file.c returns -EINVAL for a VMA
+ * whose vm_ops carry .close, and it performs that check after the .mmap
+ * hook has already succeeded. A successful sysfs mapping therefore cannot
+ * carry an abandon path in vm_ops at all.
+ */
+static void sysfs_ring_mmap_ops_have_no_close(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 1,
+		},
+	};
+	struct page *pages[1] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	int ret;
+
+	pages[0] = alloc_page(GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pages[0]);
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	/* The exact predicate kernfs_fop_mmap() applies must be false. */
+	KUNIT_EXPECT_NULL(test, desc.vm_ops);
+	KUNIT_EXPECT_FALSE(test, desc.vm_ops && desc.vm_ops->close);
+
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	sysfs_pin_release(pin);
+
+	__free_page(pages[0]);
+}
+
+/*
+ * The character-device counterpart: a buffer-backed map prepares and
+ * installs the ops that carry the abandon path, then mapped() releases.
+ */
+static void uio_buffer_mmap_success(struct kunit *test)
+{
+	struct hv_uio_private_data *pdata;
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+	};
+	struct hv_device dev = {
+		.channel = &channel,
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = RECV_BUF_MAP,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+
+	pdata = kunit_kzalloc(test, sizeof(*pdata), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pdata);
+	pdata->device = &dev;
+	pdata->info.priv = pdata;
+	pdata->info.mem[RECV_BUF_MAP].size = ARRAY_SIZE(pages) * PAGE_SIZE;
+	pdata->recv_buffer.pages = pages;
+	pdata->recv_buffer.page_cnt = ARRAY_SIZE(pages);
+	pdata->recv_buffer.chunks = chunks;
+
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	ret = hv_uio_mmap_prepare(&pdata->info, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_EQ(test, desc.action.type, MMAP_MAP_KERNEL_PAGES);
+	KUNIT_EXPECT_PTR_EQ(test, desc.vm_ops, &hv_uio_pin_vm_ops);
+	KUNIT_ASSERT_NOT_NULL(test, desc.private_data);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	ret = desc.vm_ops->mapped(desc.start, desc.end, 0, NULL,
+				  &desc.private_data);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_NULL(test, desc.private_data);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * A prepare that refuses must not leave references behind. Each failure
+ * mode is checked against the page reference count, which is the only
+ * externally visible record of a leaked pin.
+ */
+static void sysfs_mmap_prepare_failure_releases_pin(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 2,
+		},
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+
+	/* Not shared: refused before anything is pinned. */
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* pgoff past the end of the pin: refused before anything is pinned. */
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+	desc.pgoff = 2;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -EINVAL);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	/* Channel not open: refused before anything is pinned. */
+	desc.pgoff = 0;
+	channel.state = CHANNEL_OPEN_STATE;
+	KUNIT_EXPECT_EQ(test, hv_uio_ring_mmap_prepare(&channel, &desc), -ENODEV);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * Prepare succeeded and the pin is installed, but the mapping never
+ * becomes established (insert_pages() fails part-way, or the attempt is
+ * otherwise abandoned). The wrapper is the only owner on this surface and
+ * releases with one unpin plus one free, whether or not any VMA ever held
+ * the pages. This proves the object it is handed is fully releasable that
+ * way, and that releasing twice is not possible to observe.
+ */
+static void sysfs_mmap_partial_insert_failure_releases_pin(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 3,
+		},
+	};
+	struct page *pages[3] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 3 * PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	/* The wrapper's abandon path: one unpin, one free. */
+	sysfs_pin_release(pin);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+}
+
+/*
+ * The window the pin exists to close. Between the snapshot and the point
+ * where the mapping holds its own references, a concurrent
+ * vmbus_release_buffer() can drop the buffer's reference to each page.
+ * The pin must keep the pages alive for the whole window, and must be the
+ * thing that drops the last reference.
+ */
+static void sysfs_mmap_release_during_insert_keeps_pages_alive(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 2,
+		},
+	};
+	struct page *pages[2] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin *pin;
+	struct vm_area_desc desc = {
+		.start = 0,
+		.end = 2 * PAGE_SIZE,
+		.pgoff = 0,
+		.page_prot = PAGE_SHARED,
+	};
+	unsigned int i;
+	int ret;
+
+	for (i = 0; i < ARRAY_SIZE(pages); i++) {
+		pages[i] = alloc_page(GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, pages[i]);
+	}
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+	vma_desc_set_flags(&desc, VMA_SHARED_BIT);
+
+	ret = hv_uio_ring_mmap_prepare(&channel, &desc);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	pin = desc.private_data;
+	KUNIT_ASSERT_NOT_NULL(test, pin);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 2);
+
+	/*
+	 * Concurrent release: the buffer drops its own reference to each
+	 * page. The pages must still be alive, held only by the pin, so a
+	 * mapping that is mid-insert cannot walk freed memory.
+	 */
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		__free_page(pages[i]);
+	for (i = 0; i < ARRAY_SIZE(pages); i++)
+		KUNIT_EXPECT_EQ(test, page_ref_count(pages[i]), 1);
+	KUNIT_EXPECT_PTR_EQ(test, pin->pages, &pages[0]);
+	KUNIT_EXPECT_EQ(test, pin->page_count, ARRAY_SIZE(pages));
+
+	/* The pin is what drops the last reference. */
+	sysfs_pin_release(pin);
+}
+
+/*
+ * KCA-23: the protection state has to travel with the pin. The snapshot is
+ * taken in the same critical section as the page array, so a later
+ * vmbus_release_buffer() clearing the descriptor cannot change what this
+ * mapping is told about the pages it holds.
+ */
+static void ring_mmap_release_preserves_protection_snapshot(struct kunit *test)
+{
+	struct vmbus_channel channel = {
+		.state = CHANNEL_OPENED_STATE,
+		.ringbuffer = {
+			.page_cnt = 1,
+		},
+	};
+	struct page *pages[1] = {};
+	struct page *chunks[1] = {};
+	struct vmbus_buffer_pin pin = {};
+	int ret;
+
+	pages[0] = alloc_page(GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, pages[0]);
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.chunks = chunks;
+
+	ret = vmbus_buffer_pin_pages(&channel.ringbuffer, &pin);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_TRUE(test, pin.decrypted);
+	KUNIT_EXPECT_EQ(test, pin.page_count, 1UL);
+
+	/*
+	 * A concurrent release clears the descriptor. The pin must still
+	 * describe the pages it holds, not the cleared descriptor.
+	 */
+	channel.ringbuffer.chunks = NULL;
+	channel.ringbuffer.pages = NULL;
+	channel.ringbuffer.page_cnt = 0;
+	KUNIT_EXPECT_TRUE(test, pin.decrypted);
+	KUNIT_EXPECT_PTR_EQ(test, pin.pages, &pages[0]);
+	KUNIT_EXPECT_EQ(test, pin.page_count, 1UL);
+
+	vmbus_buffer_unpin_pages(&pin);
+	KUNIT_EXPECT_NULL(test, pin.pages);
+	KUNIT_EXPECT_EQ(test, pin.page_count, 0UL);
+
+	/* A buffer that never took the shared-page path is not decrypted. */
+	channel.ringbuffer.pages = pages;
+	channel.ringbuffer.page_cnt = 1;
+	channel.ringbuffer.chunks = NULL;
+	ret = vmbus_buffer_pin_pages(&channel.ringbuffer, &pin);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+	KUNIT_EXPECT_FALSE(test, pin.decrypted);
+	vmbus_buffer_unpin_pages(&pin);
+
+	__free_page(pages[0]);
+}
+
+static unsigned int hv_uio_disconnect_calls;
+static int hv_uio_disconnect_result;
+
+static int hv_uio_test_disconnect(struct vmbus_channel *channel)
+{
+	hv_uio_disconnect_calls++;
+	channel->state = CHANNEL_OPEN_STATE;
+	return hv_uio_disconnect_result;
+}
+
+static void hv_uio_remove_disconnects_open_channel_test(struct kunit *test)
+{
+	struct vmbus_channel channel = { .state = CHANNEL_OPEN_STATE };
+
+	hv_uio_disconnect_calls = 0;
+	hv_uio_disconnect_result = 0;
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), 0);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 0U);
+	channel.state = CHANNEL_OPENED_STATE;
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), 0);
+	KUNIT_EXPECT_EQ(test, channel.state, CHANNEL_OPEN_STATE);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 1U);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), 0);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 1U);
+
+	channel.state = CHANNEL_OPENED_STATE;
+	hv_uio_disconnect_result = -EIO;
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_if_open(&channel,
+							hv_uio_test_disconnect), -EIO);
+	KUNIT_EXPECT_EQ(test, hv_uio_disconnect_calls, 2U);
+}
+
+static int hv_uio_test_reader_wake(struct wait_queue_entry *wait,
+				   unsigned int mode, int flags, void *key)
+{
+	unsigned int *wakes = wait->private;
+
+	(*wakes)++;
+	return 1;
+}
+
+static void hv_uio_unregister_wakes_reader_test(struct kunit *test)
+{
+	struct uio_info info = {
+		.name = "hv-uio-withdrawal-test",
+		.version = "1",
+		.irq = UIO_IRQ_CUSTOM,
+	};
+	struct uio_device *idev;
+	struct device *parent;
+	wait_queue_entry_t wait;
+	unsigned int wakes = 0;
+	int ret;
+
+	parent = root_device_register("hv-uio-withdrawal-test");
+	KUNIT_ASSERT_FALSE(test, IS_ERR(parent));
+	ret = uio_register_device(parent, &info);
+	if (ret) {
+		root_device_unregister(parent);
+		KUNIT_FAIL(test, "UIO registration failed: %d", ret);
+		return;
+	}
+	idev = info.uio_dev;
+	get_device(&idev->dev);
+	init_waitqueue_func_entry(&wait, hv_uio_test_reader_wake);
+	wait.private = &wakes;
+	add_wait_queue(&idev->wait, &wait);
+
+	uio_unregister_device(&info);
+	KUNIT_EXPECT_PTR_EQ(test, idev->info, NULL);
+	KUNIT_EXPECT_EQ(test, wakes, 1U);
+	remove_wait_queue(&idev->wait, &wait);
+	put_device(&idev->dev);
+	root_device_unregister(parent);
+}
+
+static struct kunit_case hv_uio_ring_mmap_test_cases[] = {
+	KUNIT_CASE(hv_uio_unregister_wakes_reader_test),
+	KUNIT_CASE(hv_uio_remove_disconnects_open_channel_test),
+	KUNIT_CASE(hv_uio_ring_mmap_range_test),
+	KUNIT_CASE(hv_uio_ring_mmap_prepare_test),
+	KUNIT_CASE(hv_uio_mmap_region_select_test),
+	KUNIT_CASE(hv_uio_mmap_prepare_test),
+	KUNIT_CASE(hv_uio_pin_lifetime_test),
+	KUNIT_CASE(hv_uio_pin_close_before_mapped_test),
+	KUNIT_CASE(sysfs_ring_mmap_ops_have_no_close),
+	KUNIT_CASE(uio_buffer_mmap_success),
+	KUNIT_CASE(sysfs_mmap_prepare_failure_releases_pin),
+	KUNIT_CASE(sysfs_mmap_partial_insert_failure_releases_pin),
+	KUNIT_CASE(sysfs_mmap_release_during_insert_keeps_pages_alive),
+	KUNIT_CASE(ring_mmap_release_preserves_protection_snapshot),
+	{}
+};
+
+static struct kunit_suite hv_uio_ring_mmap_test_suite = {
+	.name = "hyperv-uio-mmap",
+	.test_cases = hv_uio_ring_mmap_test_cases,
+};
+
+kunit_test_suite(hv_uio_ring_mmap_test_suite);
diff --git a/include/linux/hyperv.h b/include/linux/hyperv.h
index 9e109d91aa143..f0e8f1af8e757 100644
--- a/include/linux/hyperv.h
+++ b/include/linux/hyperv.h
@@ -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,21 @@ struct vmbus_gpadl {
 	u32 size;
 	void *buffer;
 	bool decrypted;
+	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 {
@@ -800,13 +814,13 @@ 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 */
+	u64 lifetime_id;
 	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 */
@@ -1110,7 +1124,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);
 
@@ -1201,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,
@@ -1211,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,
@@ -1220,6 +1235,43 @@ extern void *vmbus_alloc_buffer(struct vmbus_channel *channel,
 
 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);
+
+/**
+ * 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,

59/3 2026/10/07 21:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 80475
							output: 39
							thoughts: 2501
						

Thoughts:
**KMSAN Evaluation for Hyper-V Driver Patch Series**

Okay, let's break this down. My goal is to determine if this patch series warrants a dedicated KMSAN fuzzing session. The rules are clear: KMSAN is a resource hog and should *only* be used if KASAN and other standard detectors won't catch the bugs. My focus is on uninitialized memory reads and kernel-to-user information leaks.

First, I looked at the files touched. It's a fairly extensive set of changes within the Hyper-V drivers: `hv`, `net/hyperv`, and `uio`. So, I'll need to be thorough.

I started by reading through the code, focusing on potential problem areas outlined in the KMSAN guidelines: kernel structures going to user space, conditional logic depending on uninitialized data, and allocation of complex structures.

In `channel.c`, there's a lot of buffer management and allocation using functions like `kzalloc_obj`, `vzalloc`, `kvcalloc`, and `kvmalloc_array` with `GFP_KERNEL | __GFP_ZERO`, and explicit `memset` calls, which are all good signs. The `vmbus_alloc_buffer_owned` calls, the `gpadl` setup, and the `request_arr_init` look safe, because memory is zeroed, which is exactly what I'm looking for. The teardown info also appears safely initialized.

In `channel_mgmt.c` and `vmbus_drv.c`, the changes seem focused on lifecycle management and memory mapping but don't seem like they are immediately problematic.

In `netvsc.c`, it's mostly about refactoring allocations using the `vmbus_alloc_buffer_owned` and `vmbus_establish_gpadl_owned` functions, and a lot of the allocation functions start with `kzalloc_obj`. No apparent direct risks. The completion handling is important, so I checked it to see if there were any issues; the code is checking the command request.

`rndis_filter.c` looks safe because, again, there's `kvzalloc_obj`. I scanned `rndis_build_page_buffers` to determine if bounds checks were happening. The code checks `count == MAX_PAGE_BUFFER_COUNT`, which looks safe.

`uio.c` and `uio_hv_generic.c` are where it gets interesting. I need to make sure I don't miss anything here because this is user interface code. The `uio_mmap` function looks like it's setting up memory mapping. I'm looking for data being sent to userspace. The `hv_uio_mmap_get_region` and `hv_uio_pin_install` functions look OK, with their `kzalloc_obj` allocations and initializations. The `hv_uio_mmap_prepare` seems to build on those.

Now, the KUnit tests... `copy_from_user` in `vmbus_mmap_test.c`, but that's for testing, so it's a non-issue. I did, however, find `uio.c` and `uio_hv_generic.c` exposing sysfs attributes, particularly, the `pdata->info.mem` fields. This is my potential weak point. I need to check how `pdata` and its `info` members are populated, especially whether they are zeroed before being exposed via sysfs. I need to verify that these sysfs entries don't leak uninitialized kernel memory.

In `hv_uio_probe`, where `pdata` is allocated, either `kzalloc_obj` or `devm_kzalloc` is used. This zeroes the memory.

Therefore, because `pdata` and `info.mem` seem to be properly initialized, and with all the careful initialization of all of the allocations, I don't see any obvious KMSAN-specific risks in this patch series. My conclusion is: **no, a dedicated KMSAN session is not justified for this set of changes. Standard KASAN and code review are sufficient.**



60/3 2026/10/07 22:00 tool grepper
0m Args:
{
  "Expression": "kzalloc.*pdata",
  "PathPrefixes": [
    "drivers/uio/uio_hv_generic.c"
  ]
}

Results:
{
  "Output": "drivers/uio/uio_hv_generic.c=507=hv_uio_probe(struct hv_device *dev,\n--\ndrivers/uio/uio_hv_generic.c-521-\ndrivers/uio/uio_hv_generic.c:522:\tpdata = devm_kzalloc(\u0026dev-\u003edevice, sizeof(*pdata), GFP_KERNEL);\ndrivers/uio/uio_hv_generic.c-523-\tif (!pdata)\n"
}

61/3 2026/10/07 22:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 84048
							output: 35
							thoughts: 923
						

Thoughts:
**Analyzing `rndis_filter_send_request` and `page_bufs`**

Okay, so `pdata` is allocated with `devm_kzalloc`, which means everything in it is zero-initialized. Good to know. Now, let's dive into `rndis_filter_send_request`. I need to understand how the data is being sent.

The function prepares a packet, `req->pkt`, and sets the total data length. It then calls `rndis_build_page_buffers` to handle breaking down the request message into page buffers. Hold on, `page_bufs` is declared on the stack: `struct hv_page_buffer page_bufs[MAX_PAGE_BUFFER_COUNT];`.  That immediately makes me wonder about initialization. Is it initialized, or does `rndis_build_page_buffers` handle that?

Let's look at `rndis_build_page_buffers`.  Okay, I see the loop that iterates through the data. It seems to be calculating the physical address and length of each page. Critically, it *does* initialize the `page_bufs` array elements: `page_bufs[count].pfn = ...`, `page_bufs[count].offset = ...`, and `page_bufs[count].len = ...`. So, `page_bufs` is initialized within the function. It increments a counter `count` and returns the final count through the `page_buf_cnt` pointer.

Back in `rndis_filter_send_request`, the code sets `packet->page_buf_cnt = page_buf_cnt;` after `rndis_build_page_buffers` returns. It then calls `netvsc_send`, passing `page_bufs`.  Therefore, `page_bufs[0]` through `page_bufs[count-1]` are validly initialized, while the remaining elements might contain garbage.

Now, I need to investigate how `netvsc_send` actually *uses* the `page_bufs` to ensure there are no off-by-one errors or uninitialized memory reads. I should grep for `netvsc_send(` and see how those buffers are handled.



62/3 2026/10/07 22:00 tool grepper
0m Args:
{
  "Expression": "int netvsc_send\\(",
  "PathPrefixes": [
    "drivers/net/hyperv/"
  ]
}

Results:
{
  "Output": "drivers/net/hyperv/hyperv_net.h=254=void netvsc_device_remove(struct hv_device *device);\ndrivers/net/hyperv/hyperv_net.h:255:int netvsc_send(struct net_device *net,\ndrivers/net/hyperv/hyperv_net.h-256-\t\tstruct hv_netvsc_packet *packet,\n--\ndrivers/net/hyperv/netvsc.c=1235=static inline void move_pkt_msd(struct hv_netvsc_packet **msd_send,\n--\ndrivers/net/hyperv/netvsc.c-1266- */\ndrivers/net/hyperv/netvsc.c:1267:int netvsc_send(struct net_device *ndev,\ndrivers/net/hyperv/netvsc.c-1268-\t\tstruct hv_netvsc_packet *packet,\n"
}

63/3 2026/10/07 22:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 85720
							output: 41
							thoughts: 26
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Diving into `netvsc_send`**

Alright, let's get down to it. Time to dig into `netvsc_send`, specifically the implementation nestled within `drivers/net/hyperv/netvsc.c`. I need to refresh my understanding of the data transmission path for Hyper-V network virtualization. This is where the rubber meets the road, isn't it? I want to see how the driver handles packet queuing, DMA setup, completion interrupts, and potential error handling. It's the core of performance, and I'm interested in looking for any potential bottlenecks or areas for optimization. Also, is this function the right one to start with, or is this particular function only a step in the process? And if so, how does this function relate to the other related netvsc functions? Let's get to the code.



64/3 2026/10/07 22:00 tool read-file
0m Args:
{
  "File": "drivers/net/hyperv/netvsc.c",
  "FirstLine": 1267,
  "LineCount": 80
}

Results:
{
  "Contents": "1267:\tint netvsc_send(struct net_device *ndev,\n1268:\t\t\tstruct hv_netvsc_packet *packet,\n1269:\t\t\tstruct rndis_message *rndis_msg,\n1270:\t\t\tstruct hv_page_buffer *pb,\n1271:\t\t\tstruct sk_buff *skb,\n1272:\t\t\tbool xdp_tx)\n1273:\t{\n1274:\t\tstruct net_device_context *ndev_ctx = netdev_priv(ndev);\n1275:\t\tstruct netvsc_device *net_device\n1276:\t\t\t= rcu_dereference_bh(ndev_ctx-\u003envdev);\n1277:\t\tstruct hv_device *device = ndev_ctx-\u003edevice_ctx;\n1278:\t\tint ret = 0;\n1279:\t\tstruct netvsc_channel *nvchan;\n1280:\t\tu32 pktlen = packet-\u003etotal_data_buflen, msd_len = 0;\n1281:\t\tunsigned int section_index = NETVSC_INVALID_INDEX;\n1282:\t\tstruct multi_send_data *msdp;\n1283:\t\tstruct hv_netvsc_packet *msd_send = NULL, *cur_send = NULL;\n1284:\t\tstruct sk_buff *msd_skb = NULL;\n1285:\t\tbool try_batch, xmit_more;\n1286:\t\n1287:\t\t/* If device is rescinded, return error and packet will get dropped. */\n1288:\t\tif (unlikely(!net_device || net_device-\u003edestroy))\n1289:\t\t\treturn -ENODEV;\n1290:\t\n1291:\t\tnvchan = \u0026net_device-\u003echan_table[packet-\u003eq_idx];\n1292:\t\tpacket-\u003esend_buf_index = NETVSC_INVALID_INDEX;\n1293:\t\tpacket-\u003ecp_partial = false;\n1294:\t\n1295:\t\t/* Send a control message or XDP packet directly without accessing\n1296:\t\t * msd (Multi-Send Data) field which may be changed during data packet\n1297:\t\t * processing.\n1298:\t\t */\n1299:\t\tif (!skb || xdp_tx)\n1300:\t\t\treturn netvsc_send_pkt(device, packet, net_device, pb, skb);\n1301:\t\n1302:\t\t/* batch packets in send buffer if possible */\n1303:\t\tmsdp = \u0026nvchan-\u003emsd;\n1304:\t\tif (msdp-\u003epkt)\n1305:\t\t\tmsd_len = msdp-\u003epkt-\u003etotal_data_buflen;\n1306:\t\n1307:\t\ttry_batch =  msd_len \u003e 0 \u0026\u0026 msdp-\u003ecount \u003c net_device-\u003emax_pkt;\n1308:\t\tif (try_batch \u0026\u0026 msd_len + pktlen + net_device-\u003epkt_align \u003c\n1309:\t\t    net_device-\u003esend_section_size) {\n1310:\t\t\tsection_index = msdp-\u003epkt-\u003esend_buf_index;\n1311:\t\n1312:\t\t} else if (try_batch \u0026\u0026 msd_len + packet-\u003ermsg_size \u003c\n1313:\t\t\t   net_device-\u003esend_section_size) {\n1314:\t\t\tsection_index = msdp-\u003epkt-\u003esend_buf_index;\n1315:\t\t\tpacket-\u003ecp_partial = true;\n1316:\t\n1317:\t\t} else if (pktlen + net_device-\u003epkt_align \u003c\n1318:\t\t\t   net_device-\u003esend_section_size) {\n1319:\t\t\tsection_index = netvsc_get_next_send_section(net_device);\n1320:\t\t\tif (unlikely(section_index == NETVSC_INVALID_INDEX)) {\n1321:\t\t\t\t++ndev_ctx-\u003eeth_stats.tx_send_full;\n1322:\t\t\t} else {\n1323:\t\t\t\tmove_pkt_msd(\u0026msd_send, \u0026msd_skb, msdp);\n1324:\t\t\t\tmsd_len = 0;\n1325:\t\t\t}\n1326:\t\t}\n1327:\t\n1328:\t\t/* Keep aggregating only if stack says more data is coming\n1329:\t\t * and not doing mixed modes send and not flow blocked\n1330:\t\t */\n1331:\t\txmit_more = netdev_xmit_more() \u0026\u0026\n1332:\t\t\t!packet-\u003ecp_partial \u0026\u0026\n1333:\t\t\t!netif_xmit_stopped(netdev_get_tx_queue(ndev, packet-\u003eq_idx));\n1334:\t\n1335:\t\tif (section_index != NETVSC_INVALID_INDEX) {\n1336:\t\t\tnetvsc_copy_to_send_buf(net_device,\n1337:\t\t\t\t\t\tsection_index, msd_len,\n1338:\t\t\t\t\t\tpacket, rndis_msg, pb, xmit_more);\n1339:\t\n1340:\t\t\tpacket-\u003esend_buf_index = section_index;\n1341:\t\n1342:\t\t\tif (packet-\u003ecp_partial) {\n1343:\t\t\t\tpacket-\u003epage_buf_cnt--;\n1344:\t\t\t\tpacket-\u003etotal_data_buflen = msd_len + packet-\u003ermsg_size;\n1345:\t\t\t} else {\n1346:\t\t\t\tpacket-\u003epage_buf_cnt = 0;\n"
}

65/3 2026/10/07 22:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 87421
							output: 41
							thoughts: 49
						

Thoughts:
Here's my analysis of the provided snippet, framed as my own thought process:

**Diving into the Network Virtualization Send Path**

Alright, the objective is pretty clear: figure out what's going on when we call `!skb`. The first thing that jumps out is this call to `netvsc_send_pkt`. That's the entry point, it seems. My experience tells me that `netvsc_send_pkt` is likely the key function in the Hyper-V network virtualization stack for actually sending the packet. It takes the device, the packet (`skb`), the network device itself, a protocol block (`pb`) and the socket buffer (`skb`) as parameters, which feels pretty standard for a send path in this sort of driver.

Okay, let's drill down into `netvsc_send_pkt`. We'll need to dissect its implementation to really understand the logic flow, but this initial call gives us the starting point and parameters that we can work with. Now we can see the data structure flow and identify where issues might be.



66/3 2026/10/07 22:00 tool read-file
0m Args:
{
  "File": "drivers/net/hyperv/netvsc.c",
  "FirstLine": 1150,
  "LineCount": 85
}

Results:
{
  "Contents": "1150:\t\tstruct netdev_queue *txq = netdev_get_tx_queue(ndev, packet-\u003eq_idx);\n1151:\t\tu64 req_id;\n1152:\t\tint ret;\n1153:\t\tu32 ring_avail = hv_get_avail_to_write_percent(\u0026out_channel-\u003eoutbound);\n1154:\t\n1155:\t\tmemset(\u0026nvmsg, 0, sizeof(struct nvsp_message));\n1156:\t\tnvmsg.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT;\n1157:\t\tif (skb)\n1158:\t\t\trpkt-\u003echannel_type = 0;\t\t/* 0 is RMC_DATA */\n1159:\t\telse\n1160:\t\t\trpkt-\u003echannel_type = 1;\t\t/* 1 is RMC_CONTROL */\n1161:\t\n1162:\t\trpkt-\u003esend_buf_section_index = packet-\u003esend_buf_index;\n1163:\t\tif (packet-\u003esend_buf_index == NETVSC_INVALID_INDEX)\n1164:\t\t\trpkt-\u003esend_buf_section_size = 0;\n1165:\t\telse\n1166:\t\t\trpkt-\u003esend_buf_section_size = packet-\u003etotal_data_buflen;\n1167:\t\n1168:\t\treq_id = (ulong)skb;\n1169:\t\n1170:\t\tif (out_channel-\u003erescind)\n1171:\t\t\treturn -ENODEV;\n1172:\t\n1173:\t\ttrace_nvsp_send_pkt(ndev, out_channel, rpkt);\n1174:\t\n1175:\t\tpacket-\u003edma_range = NULL;\n1176:\t\tif (packet-\u003epage_buf_cnt) {\n1177:\t\t\tstruct vmbus_channel_packet_page_buffer desc;\n1178:\t\t\tu32 desc_size;\n1179:\t\n1180:\t\t\tif (packet-\u003ecp_partial)\n1181:\t\t\t\tpb++;\n1182:\t\n1183:\t\t\tret = netvsc_dma_map(ndev_ctx-\u003edevice_ctx, packet, pb);\n1184:\t\t\tif (ret) {\n1185:\t\t\t\tret = -EAGAIN;\n1186:\t\t\t\tgoto exit;\n1187:\t\t\t}\n1188:\t\n1189:\t\t\tnetvsc_build_mpb_array(pb, packet-\u003epage_buf_cnt,\n1190:\t\t\t\t\t(struct vmbus_packet_mpb_array *)\u0026desc,\n1191:\t\t\t\t\t \u0026desc_size);\n1192:\t\t\tret = vmbus_sendpacket_mpb_desc(out_channel,\n1193:\t\t\t\t\t(struct vmbus_packet_mpb_array *)\u0026desc,\n1194:\t\t\t\t\tdesc_size, \u0026nvmsg, sizeof(nvmsg), req_id);\n1195:\t\t\tif (ret)\n1196:\t\t\t\tnetvsc_dma_unmap(ndev_ctx-\u003edevice_ctx, packet);\n1197:\t\t} else {\n1198:\t\t\tret = vmbus_sendpacket(out_channel,\n1199:\t\t\t\t\t       \u0026nvmsg, sizeof(nvmsg),\n1200:\t\t\t\t\t       req_id, VM_PKT_DATA_INBAND,\n1201:\t\t\t\t\t       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);\n1202:\t\t}\n1203:\t\n1204:\texit:\n1205:\t\tif (ret == 0) {\n1206:\t\t\tatomic_inc_return(\u0026nvchan-\u003equeue_sends);\n1207:\t\n1208:\t\t\tif (ring_avail \u003c RING_AVAIL_PERCENT_LOWATER) {\n1209:\t\t\t\tnetif_tx_stop_queue(txq);\n1210:\t\t\t\tndev_ctx-\u003eeth_stats.stop_queue++;\n1211:\t\t\t}\n1212:\t\t} else if (ret == -EAGAIN) {\n1213:\t\t\tnetif_tx_stop_queue(txq);\n1214:\t\t\tndev_ctx-\u003eeth_stats.stop_queue++;\n1215:\t\t} else {\n1216:\t\t\tnetdev_err(ndev,\n1217:\t\t\t\t   \"Unable to send packet pages %u len %u, ret %d\\n\",\n1218:\t\t\t\t   packet-\u003epage_buf_cnt, packet-\u003etotal_data_buflen,\n1219:\t\t\t\t   ret);\n1220:\t\t}\n1221:\t\n1222:\t\tif (netif_tx_queue_stopped(txq) \u0026\u0026\n1223:\t\t    atomic_read(\u0026nvchan-\u003equeue_sends) \u003c 1 \u0026\u0026\n1224:\t\t    !net_device-\u003etx_disable) {\n1225:\t\t\tnetif_tx_wake_queue(txq);\n1226:\t\t\tndev_ctx-\u003eeth_stats.wake_queue++;\n1227:\t\t\tif (ret == -EAGAIN)\n1228:\t\t\t\tret = -ENOSPC;\n1229:\t\t}\n1230:\t\n1231:\t\treturn ret;\n1232:\t}\n1233:\t\n1234:\t/* Move packet out of multi send data (msd), and clear msd */\n"
}

67/3 2026/10/07 22:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 89146
							output: 38
							thoughts: 44
						

Thoughts:
Okay, here's my take on those thoughts, framed as an expert's internal monologue:

**Analyzing `netvsc_build_mpb_array`**

Right, let's see... the core function here, `netvsc_build_mpb_array`, seems to be responsible for constructing a Multiple Page Buffer (MPB) array. My initial concern is how it's interacting with the `pb` data structure. Specifically, I need to understand the relationship between what `netvsc_build_mpb_array` *reads* and what `packet->page_buf_cnt` *indicates*. The snippet clearly states it reads up to `packet->page_buf_cnt` from the pointer `pb`. I need to dig into the function itself to verify that `pb` is being properly initialized and populated, and, more importantly, that `packet->page_buf_cnt` accurately reflects the number of valid page buffers. I'll need to confirm if there are any potential off-by-one errors or boundary condition issues lurking there. Time to pull up the source and meticulously analyze `netvsc_build_mpb_array`.



68/3 2026/10/07 22:00 tool grepper
0m Args:
{
  "Expression": "netvsc_build_mpb_array",
  "PathPrefixes": [
    "drivers/net/hyperv/"
  ]
}

Results:
{
  "Output": "drivers/net/hyperv/netvsc.c=1060=static int netvsc_dma_map(struct hv_device *hv_dev,\n--\ndrivers/net/hyperv/netvsc.c-1109- */\ndrivers/net/hyperv/netvsc.c:1110:static inline void netvsc_build_mpb_array(struct hv_page_buffer *pb,\ndrivers/net/hyperv/netvsc.c-1111-\t\t\t\tu32 page_buffer_count,\n--\ndrivers/net/hyperv/netvsc.c=1135=static inline int netvsc_send_pkt(\n--\ndrivers/net/hyperv/netvsc.c-1188-\ndrivers/net/hyperv/netvsc.c:1189:\t\tnetvsc_build_mpb_array(pb, packet-\u003epage_buf_cnt,\ndrivers/net/hyperv/netvsc.c-1190-\t\t\t\t(struct vmbus_packet_mpb_array *)\u0026desc,\n"
}

69/3 2026/10/07 22:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 89749
							output: 41
							thoughts: 30
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, as requested, targeting an expert audience:

**Diving into `netvsc.c` for Context**

Alright, I need to get a handle on what's going on with this network virtualization component. Let's start with a specific area; I'm going to jump straight into `drivers/net/hyperv/netvsc.c`, focusing on lines 1110 through 1134. Knowing the Hyper-V network stack, this block of code is likely handling something crucial related to… well, it could be anything from initialization or teardown of a virtual NIC, queue management, packet processing logic within the VM, or even error handling of a specific type. Given the file and the general structure of these drivers, I’m guessing it’s either a configuration area, or an error handling path for the virtual network driver. It's time to dig in and see precisely what kind of operations are being implemented within that range. My intuition is telling me that this section is probably focused on a specific edge case or an important flow. I'll need to rapidly parse the code for clues related to the context I'm looking for.



70/3 2026/10/07 22:00 tool read-file
0m Args:
{
  "File": "drivers/net/hyperv/netvsc.c",
  "FirstLine": 1110,
  "LineCount": 25
}

Results:
{
  "Contents": "1110:\tstatic inline void netvsc_build_mpb_array(struct hv_page_buffer *pb,\n1111:\t\t\t\t\tu32 page_buffer_count,\n1112:\t\t\t\t\tstruct vmbus_packet_mpb_array *desc,\n1113:\t\t\t\t\tu32 *desc_size)\n1114:\t{\n1115:\t\tstruct hv_mpb_array *mpb_entry = \u0026desc-\u003erange;\n1116:\t\tint i, j;\n1117:\t\n1118:\t\tfor (i = 0; i \u003c page_buffer_count; i++) {\n1119:\t\t\tu32 offset = pb[i].offset;\n1120:\t\t\tu32 len = pb[i].len;\n1121:\t\n1122:\t\t\tmpb_entry-\u003eoffset = offset;\n1123:\t\t\tmpb_entry-\u003elen = len;\n1124:\t\n1125:\t\t\tfor (j = 0; j \u003c HVPFN_UP(offset + len); j++)\n1126:\t\t\t\tmpb_entry-\u003epfn_array[j] = pb[i].pfn + j;\n1127:\t\n1128:\t\t\tmpb_entry = (struct hv_mpb_array *)\u0026mpb_entry-\u003epfn_array[j];\n1129:\t\t}\n1130:\t\n1131:\t\tdesc-\u003erangecount = page_buffer_count;\n1132:\t\t*desc_size = (char *)mpb_entry - (char *)desc;\n1133:\t}\n1134:\t\n"
}

71/3 2026/10/07 22:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 90501
							output: 36
							thoughts: 407
						

Thoughts:
**Analyzing the Data Buffer Management in the Network Virtualization Driver**

Okay, so I'm digging into this code, specifically how it handles page buffers. It looks like the system is using `pb` up to `page_buffer_count`, and all the `pb` entries from `0` to `page_buf_cnt - 1` were set up by `rndis_build_page_buffers`. Fine, that's straightforward.

Now, I'm a little puzzled by `netvsc_build_mpb_array`. Specifically, I'm wondering about this `desc` variable. What exactly *is* that? Ah, here it is in `netvsc_send_pkt`: `struct vmbus_channel_packet_page_buffer desc;`.  Does `netvsc_build_mpb_array` initialize `desc`?

Aha! In `netvsc_build_mpb_array`, I see: `desc->rangecount = page_buffer_count;`. So, it *does* touch `desc`, but what about the other fields within the `desc` structure? That's what I really need to understand.

Let me take a look at the existing code to see how `desc` is used.  Right, `struct vmbus_channel_packet_page_buffer desc;` was already defined *before* the patch. Okay, I see. Before the patch, they were setting up the page buffer manually:

```c
-	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);
+	if (ret)
+		return ret;
+	packet->page_buf_cnt = page_buf_cnt;
```

Interesting. Now, how does `vmbus_sendpacket_mpb_desc` actually work with this `desc`? I'd better go and examine `vmbus_sendpacket_mpb_desc`. That's where the real magic happens, I bet!



72/3 2026/10/07 22:01 tool grepper
0m Args:
{
  "Expression": "vmbus_sendpacket_mpb_desc",
  "PathPrefixes": [
    "drivers/hv/"
  ]
}

Results:
{
  "Output": "drivers/hv/channel.c=2033=EXPORT_SYMBOL(vmbus_sendpacket);\n--\ndrivers/hv/channel.c-2035-/*\ndrivers/hv/channel.c:2036: * vmbus_sendpacket_mpb_desc - Send one or more multi-page buffer packets\ndrivers/hv/channel.c-2037- * using a GPADL Direct packet type.\n--\ndrivers/hv/channel.c-2040- */\ndrivers/hv/channel.c:2041:int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,\ndrivers/hv/channel.c-2042-\t\t\t      struct vmbus_packet_mpb_array *desc,\n--\ndrivers/hv/channel.c-2070-}\ndrivers/hv/channel.c:2071:EXPORT_SYMBOL_GPL(vmbus_sendpacket_mpb_desc);\ndrivers/hv/channel.c-2072-\n"
}

73/3 2026/10/07 22:01 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 91750
							output: 36
							thoughts: 25
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, and written as if they are my own internal monologue:

**Diving into vmbus_sendpacket_mpb_desc**

Right, let's zero in on `vmbus_sendpacket_mpb_desc`, specifically around line 2041. I need to refresh my memory on the critical nuances of how this function is handling the Multi-Packet Buffer (MPB) descriptor. I'm probably looking for something specific, a potential race condition perhaps, a missed edge case in error handling, or maybe a subtle interaction with memory management that's causing grief down the line. It could be related to how the descriptors are chained, or how the completion status is being propagated. The details of the MPB descriptor management, especially when the packet is large and needs to be fragmented across multiple buffers, is something I really want to refresh. Let's see if the code around that line offers any clues. I’m thinking I will need to understand the sequencing and synchronization involved in sending and receiving MPB packets, in particular around line 2041. My goal is to use this line as an entry point to quickly understand how the MPB descriptor functions work.



74/3 2026/10/07 22:01 tool read-file
0m Args:
{
  "File": "drivers/hv/channel.c",
  "FirstLine": 2038,
  "LineCount": 35
}

Results:
{
  "Contents": "2038:\t * The desc argument must include space for the VMBus descriptor. The\n2039:\t * rangecount field must already be set.\n2040:\t */\n2041:\tint vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,\n2042:\t\t\t\t      struct vmbus_packet_mpb_array *desc,\n2043:\t\t\t\t      u32 desc_size,\n2044:\t\t\t\t      void *buffer, u32 bufferlen, u64 requestid)\n2045:\t{\n2046:\t\tu32 packetlen;\n2047:\t\tu32 packetlen_aligned;\n2048:\t\tstruct kvec bufferlist[3];\n2049:\t\tu64 aligned_data = 0;\n2050:\t\n2051:\t\tpacketlen = desc_size + bufferlen;\n2052:\t\tpacketlen_aligned = ALIGN(packetlen, sizeof(u64));\n2053:\t\n2054:\t\t/* Setup the descriptor */\n2055:\t\tdesc-\u003etype = VM_PKT_DATA_USING_GPA_DIRECT;\n2056:\t\tdesc-\u003eflags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;\n2057:\t\tdesc-\u003edataoffset8 = desc_size \u003e\u003e 3; /* in 8-bytes granularity */\n2058:\t\tdesc-\u003elength8 = (u16)(packetlen_aligned \u003e\u003e 3);\n2059:\t\tdesc-\u003etransactionid = VMBUS_RQST_ERROR; /* will be updated in hv_ringbuffer_write() */\n2060:\t\tdesc-\u003ereserved = 0;\n2061:\t\n2062:\t\tbufferlist[0].iov_base = desc;\n2063:\t\tbufferlist[0].iov_len = desc_size;\n2064:\t\tbufferlist[1].iov_base = buffer;\n2065:\t\tbufferlist[1].iov_len = bufferlen;\n2066:\t\tbufferlist[2].iov_base = \u0026aligned_data;\n2067:\t\tbufferlist[2].iov_len = (packetlen_aligned - packetlen);\n2068:\t\n2069:\t\treturn hv_ringbuffer_write(channel, bufferlist, 3, requestid, NULL);\n2070:\t}\n2071:\tEXPORT_SYMBOL_GPL(vmbus_sendpacket_mpb_desc);\n2072:\t\n"
}

75/3 2026/10/07 22:01 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 92718
							output: 35
							thoughts: 2042
						

Thoughts:
**Analyzing VMBus Buffer and GPADL Handling**

Okay, so I'm diving into this patch series. First, `vmbus_sendpacket_mpb_desc` seems straightforward; the descriptor fields are initialized as expected. No surprises there.

Now, let's look at how the `vmbus_buffer_pin` struct is used. It stores pages, their count, and a flag. I've tracked its use through `vmbus_buffer_pin_pages`. Here, all the fields of the `pin` struct are explicitly assigned from a `vmbus_buffer`. Nothing odd so far.

Next, `hv_uio_mmap_prepare` caught my eye. The `vmbus_buffer_pin pin = {};` there is initialized to zero. The `region` struct is fully initialized in `hv_uio_mmap_get_region`, and I can see that all paths of execution ensure its members get populated, and no uninitialized value is used.

But wait, `hv_uio_ring_mmap_prepare` uses `kzalloc_obj(*pin)`, also zero initializing the struct. I've verified that `vmbus_buffer_pin_pages` populates it afterwards.

Now, on to `vmbus_post_gpadl_messages`. I noticed the use of a `msginfo` structure and I need to check where it gets allocated. It looks like it is allocated using `kzalloc`. I'll need to go back and verify exactly how much is allocated, to make sure there's enough room for both the header and submessages. I'll check around line 900 of `drivers/hv/channel.c` to be sure.



76/3 2026/10/07 22:01 tool read-file
0m Args:
{
  "File": "drivers/hv/channel.c",
  "FirstLine": 900,
  "LineCount": 60
}

Results:
{
  "Contents": " 900:\t\tint ret = 0;\n 901:\t\n 902:\t\tgpadl-\u003eleak = false;\n 903:\t\n 904:\t\tnext_gpadl_handle =\n 905:\t\t\t(atomic_inc_return(\u0026vmbus_connection.next_gpadl_handle) - 1);\n 906:\t\n 907:\t\tret = create_gpadl_header(type, kbuffer, size, send_offset, \u0026msginfo);\n 908:\t\tif (ret) {\n 909:\t\t\tgpadl-\u003edecrypted = false;\n 910:\t\t\treturn ret;\n 911:\t\t}\n 912:\t\n 913:\t\tgpadl-\u003edecrypted = !memory_prepared \u0026\u0026\n 914:\t\t\t!((channel-\u003eco_external_memory \u0026\u0026 type == HV_GPADL_BUFFER) ||\n 915:\t\t\t  (channel-\u003eco_ring_buffer \u0026\u0026 type == HV_GPADL_RING));\n 916:\t\tif (gpadl-\u003edecrypted) {\n 917:\t\t\t/*\n 918:\t\t\t * The \"decrypted\" flag being true assumes that set_memory_decrypted() succeeds.\n 919:\t\t\t * But if it fails, the encryption state of the memory is unknown. In that case,\n 920:\t\t\t * leave \"decrypted\" as true to ensure the memory is leaked instead of going back\n 921:\t\t\t * on the free list.\n 922:\t\t\t */\n 923:\t\t\tret = set_memory_decrypted((unsigned long)kbuffer,\n 924:\t\t\t\t\t\tPFN_UP(size));\n 925:\t\t\tif (ret) {\n 926:\t\t\t\tdev_warn(\u0026channel-\u003edevice_obj-\u003edevice,\n 927:\t\t\t\t\t\"Failed to set host visibility for new GPADL %d.\\n\",\n 928:\t\t\t\t\tret);\n 929:\t\t\t\tif (owner)\n 930:\t\t\t\t\towner-\u003eencryption_unknown = true;\n 931:\t\t\t\tgpadl-\u003eleak = true;\n 932:\t\t\t\tvmbus_free_channel_msginfo(msginfo);\n 933:\t\t\t\treturn ret;\n 934:\t\t\t}\n 935:\t\t}\n 936:\t\n 937:\t\tinit_completion(\u0026msginfo-\u003ewaitevent);\n 938:\t\tmsginfo-\u003ewaiting_channel = channel;\n 939:\t\n 940:\t\tgpadlmsg = (struct vmbus_channel_gpadl_header *)msginfo-\u003emsg;\n 941:\t\tgpadlmsg-\u003eheader.msgtype = CHANNELMSG_GPADL_HEADER;\n 942:\t\tgpadlmsg-\u003echild_relid = channel-\u003eoffermsg.child_relid;\n 943:\t\tgpadlmsg-\u003egpadl = next_gpadl_handle;\n 944:\t\n 945:\t\n 946:\t\tspin_lock_irqsave(\u0026vmbus_connection.channelmsg_lock, flags);\n 947:\t\tlist_add_tail(\u0026msginfo-\u003emsglistentry,\n 948:\t\t\t      \u0026vmbus_connection.chn_msg_list);\n 949:\t\n 950:\t\tspin_unlock_irqrestore(\u0026vmbus_connection.channelmsg_lock, flags);\n 951:\t\n 952:\t\tif (channel-\u003erescind) {\n 953:\t\t\tret = -ENODEV;\n 954:\t\t\tgoto cleanup;\n 955:\t\t}\n 956:\t\n 957:\t\tret = vmbus_post_gpadl_messages(msginfo, next_gpadl_handle, \u0026posted,\n 958:\t\t\t\t\t\tvmbus_gpadl_post_real, NULL);\n 959:\t\tif (posted \u0026\u0026 owner)\n"
}

77/3 2026/10/07 22:01 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 96154
							output: 22
							thoughts: 1775
						

Thoughts:
**Analyzing VMBus Memory Management and Initialization**

Okay, let's break this down systematically. My immediate concern is ensuring that memory is properly initialized across the VMBus, especially in the context of data structures passed between the host and guest.

First, I examine `create_gpadl_header`, noting that it sets up headers and sub-messages. That's a good starting point, but I need to dive deeper. I check `vmbus_gpadl_teardown_request`. The key here is `alloc_info()`, which is `vmbus_alloc_teardown_info`. This uses `kzalloc`, so the memory allocated for the teardown info is guaranteed to be zeroed. The code then explicitly initializes all the fields of the `msg` structure, which is also a good sign.

Next, I look at `vmbus_buffer_trace_owner`. The function is straightforward; it extracts scalar values from the `owner` structure. `owner` is allocated via `kzalloc_obj`, which means this should also be properly initialized.

Now, I shift my focus to ring buffer allocation using `vmbus_alloc_ring` within `channel.c`. I see that the ring buffer is created via `vmbus_alloc_buffer_owned`, and before that, it calls `memset` on the buffer. This confirms proper initialization of the buffer.

Then, I dig into the `hv_ringbuffer_init` function. The code uses `kvcalloc` to allocate `pages_wraparound`, which is a zeroed array and the entries in it are also explicitly assigned after allocation. Then, I look for a potential problem. If `vmalloc_to_page(addr)` could return something weird if `addr` is not a vmalloc address. However, the `buffer->addr` is assigned via `vzalloc` or `vmap` which are vmalloc addresses. So this is safe.

Next I review `vmbus_free_ring`, confirming that `vmbus_release_buffer` is called and this would also release the memory.

Finally, I got concerned by a function called `hv_mmap_ring_buffer_wrapper`. I notice that the `struct vm_area_desc desc;` is allocated on the stack *without* initialization. This is a potential vulnerability! If the following function uses this uninitialized `desc` variable, we could be looking at a serious issue. I need to investigate the implementation of `channel->mmap_prepare_ring_buffer` to see how `desc` is used. I'll need to use grep to search for where this is implemented to see the full picture.



78/3 2026/10/07 22:01 tool grepper
0m Args:
{
  "Expression": "mmap_prepare_ring_buffer"
}

Results:
{
  "Output": "drivers/hv/hyperv_vmbus.h=550=int hv_create_ring_sysfs(struct vmbus_channel *channel,\ndrivers/hv/hyperv_vmbus.h:551:\t\t\t int (*hv_mmap_prepare_ring_buffer)(struct vmbus_channel *channel,\ndrivers/hv/hyperv_vmbus.h-552-\t\t\t\t\t\t\t    struct vm_area_desc *desc));\n--\ndrivers/hv/vmbus_drv.c=1926=static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,\n--\ndrivers/hv/vmbus_drv.c-1936-\t * hv_(create|remove)_ring_sysfs implementation ensures that\ndrivers/hv/vmbus_drv.c:1937:\t * mmap_prepare_ring_buffer is not NULL.\ndrivers/hv/vmbus_drv.c-1938-\t */\ndrivers/hv/vmbus_drv.c-1939-\tcompat_set_desc_from_vma(\u0026desc, filp, vma);\ndrivers/hv/vmbus_drv.c:1940:\terr = channel-\u003emmap_prepare_ring_buffer(channel, \u0026desc);\ndrivers/hv/vmbus_drv.c-1941-\tif (err)\n--\ndrivers/hv/vmbus_drv.c=2074=static const struct kobj_type vmbus_chan_ktype = {\n--\ndrivers/hv/vmbus_drv.c-2081- * @channel: Pointer to vmbus_channel structure\ndrivers/hv/vmbus_drv.c:2082: * @hv_mmap_prepare_ring_buffer: function pointer for initializing the function to be called on mmap\ndrivers/hv/vmbus_drv.c-2083- *                       channel's \"ring\" sysfs node, which is for the ring buffer of that channel.\ndrivers/hv/vmbus_drv.c-2084- *                       Function pointer is of below type:\ndrivers/hv/vmbus_drv.c:2085: *                       int (*hv_mmap_prepare_ring_buffer)(struct vmbus_channel *channel,\ndrivers/hv/vmbus_drv.c-2086- *                                                          struct vm_area_desc *desc))\n--\ndrivers/hv/vmbus_drv.c=2104=int hv_create_ring_sysfs(struct vmbus_channel *channel,\ndrivers/hv/vmbus_drv.c:2105:\t\t\t int (*hv_mmap_prepare_ring_buffer)(struct vmbus_channel *channel,\ndrivers/hv/vmbus_drv.c-2106-\t\t\t\t\t\t\t    struct vm_area_desc *desc))\n--\ndrivers/hv/vmbus_drv.c-2109-\ndrivers/hv/vmbus_drv.c:2110:\tchannel-\u003emmap_prepare_ring_buffer = hv_mmap_prepare_ring_buffer;\ndrivers/hv/vmbus_drv.c-2111-\tchannel-\u003ering_sysfs_visible = true;\n--\ndrivers/hv/vmbus_drv.c=2125=int hv_remove_ring_sysfs(struct vmbus_channel *channel)\n--\ndrivers/hv/vmbus_drv.c-2131-\tret = sysfs_update_group(kobj, \u0026vmbus_chan_group);\ndrivers/hv/vmbus_drv.c:2132:\tchannel-\u003emmap_prepare_ring_buffer = NULL;\ndrivers/hv/vmbus_drv.c-2133-\treturn ret;\n--\ndrivers/hv/vmbus_mmap_test.c=52=vmbus_mmap_test_context(struct kunit *test)\n--\ndrivers/hv/vmbus_mmap_test.c-67-\t\treturn NULL;\ndrivers/hv/vmbus_mmap_test.c:68:\tctx-\u003echannel.mmap_prepare_ring_buffer = vmbus_mmap_test_prepare;\ndrivers/hv/vmbus_mmap_test.c-69-\tctx-\u003echannel.ringbuffer.pages = ctx-\u003epages;\n--\ninclude/linux/hyperv.h=801=struct vmbus_channel {\n--\ninclude/linux/hyperv.h-1032-\t/*  function to mmap ring buffer memory to the channel's sysfs ring attribute */\ninclude/linux/hyperv.h:1033:\tint (*mmap_prepare_ring_buffer)(struct vmbus_channel *channel, struct vm_area_desc *desc);\ninclude/linux/hyperv.h-1034-\n"
}

79/3 2026/10/07 22:01 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 99720
							output: 40
							thoughts: 66
						

Thoughts:
Here's my analysis of what I'm seeing:

**Diving into the VMBus Driver**

Okay, I'm digging into `vmbus_drv.c` and I've just hit a potential point of interest. Specifically, I'm eyeing line 1939: `compat_set_desc_from_vma(&desc, filp, vma);`. I immediately need to understand the context. So, I'm going to back up a few lines, let's say around line 1935, and start reading from there within the `drivers/hv/vmbus_drv.c` file. I need to grasp how this `compat_set_desc_from_vma` function fits into the overall data flow and what it's trying to achieve. I'm looking for clues about the `desc`, `filp`, and `vma` variables – what they represent, where they come from, and how they relate to the VMBus operation. Time to get to work.



80/3 2026/10/07 22:01 tool read-file
0m Args:
{
  "File": "drivers/hv/vmbus_drv.c",
  "FirstLine": 1930,
  "LineCount": 25
}

Results:
{
  "Contents": "1930:\t\tstruct vmbus_channel *channel = container_of(kobj, struct vmbus_channel, kobj);\n1931:\t\tstruct vm_area_desc desc;\n1932:\t\tstruct vmbus_buffer_pin *pin;\n1933:\t\tint err;\n1934:\t\n1935:\t\t/*\n1936:\t\t * hv_(create|remove)_ring_sysfs implementation ensures that\n1937:\t\t * mmap_prepare_ring_buffer is not NULL.\n1938:\t\t */\n1939:\t\tcompat_set_desc_from_vma(\u0026desc, filp, vma);\n1940:\t\terr = channel-\u003emmap_prepare_ring_buffer(channel, \u0026desc);\n1941:\t\tif (err)\n1942:\t\t\treturn err;\n1943:\t\n1944:\t\t/*\n1945:\t\t * This is a kernfs bin attribute. kernfs_fop_mmap() rejects a VMA\n1946:\t\t * whose vm_ops carry .close, because kernfs has to replace the set\n1947:\t\t * with its own and cannot wrap close. So the prepare callback has\n1948:\t\t * to pick one of two ownership contracts, and this wrapper honors\n1949:\t\t * whichever it installed. Each contract has exactly one release\n1950:\t\t * site, reached on every outcome.\n1951:\t\t *\n1952:\t\t * With vm_ops, the callback handed the per-VMA state to an abandon\n1953:\t\t * path in vm_ops-\u003eclose and typically to vm_ops-\u003emapped. Install\n1954:\t\t * both before __compat_vma_mmap() so a failure in\n"
}

81/3 2026/10/07 22:01 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 100498
							output: 24
							thoughts: 68
						

Thoughts:
Okay, let's break this down.

**Ensuring Complete Initialization for Ring Buffer Mapping**

My primary concern here is the proper initialization of the descriptor (`desc`) used for mapping a ring buffer. The code uses `compat_set_desc_from_vma(&desc, filp, vma)` to populate this descriptor before handing it off to `mmap_prepare_ring_buffer`. I need to be *absolutely certain* that `compat_set_desc_from_vma` fully and correctly initializes every relevant field of `desc` based on the provided `vma` (virtual memory area) and `filp` (file pointer). Any missing or incorrect initialization at this stage would lead to serious issues later in the mapping process. This could result in memory corruption or security vulnerabilities. So, I need to verify that `compat_set_desc_from_vma` does exactly what I expect. I'll need to go through its implementation to be sure.



82/3 2026/10/07 22:01 tool grepper
0m Args:
{
  "Expression": "compat_set_desc_from_vma"
}

Results:
{
  "Output": "drivers/hv/vmbus_drv.c=1926=static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,\n--\ndrivers/hv/vmbus_drv.c-1938-\t */\ndrivers/hv/vmbus_drv.c:1939:\tcompat_set_desc_from_vma(\u0026desc, filp, vma);\ndrivers/hv/vmbus_drv.c-1940-\terr = channel-\u003emmap_prepare_ring_buffer(channel, \u0026desc);\n--\ndrivers/uio/uio.c=820=static int uio_mmap(struct file *filep, struct vm_area_struct *vma)\n--\ndrivers/uio/uio.c-855-\ndrivers/uio/uio.c:856:\t\tcompat_set_desc_from_vma(\u0026desc, filep, vma);\ndrivers/uio/uio.c-857-\t\tret = idev-\u003einfo-\u003emmap_prepare(idev-\u003einfo, \u0026desc);\n--\ninclude/linux/fs.h=2040=static inline bool can_mmap_file(struct file *file)\n--\ninclude/linux/fs.h-2053-\ninclude/linux/fs.h:2054:void compat_set_desc_from_vma(struct vm_area_desc *desc, const struct file *file,\ninclude/linux/fs.h-2055-\t\t\t      const struct vm_area_struct *vma);\n--\nmm/util.c=1163=EXPORT_SYMBOL(flush_dcache_folio);\n--\nmm/util.c-1166-/**\nmm/util.c:1167: * compat_set_desc_from_vma() - assigns VMA descriptor @desc fields from a VMA.\nmm/util.c-1168- * @desc: A VMA descriptor whose fields need to be set.\n--\nmm/util.c-1179- */\nmm/util.c:1180:void compat_set_desc_from_vma(struct vm_area_desc *desc,\nmm/util.c-1181-\t\t\t      const struct file *file,\n--\nmm/util.c-1199-}\nmm/util.c:1200:EXPORT_SYMBOL(compat_set_desc_from_vma);\nmm/util.c-1201-\n--\nmm/util.c-1210- * The function assumes that you have obtained a VMA descriptor @desc from\nmm/util.c:1211: * compat_set_desc_from_vma(), and already executed the mmap_prepare() hook upon\nmm/util.c-1212- * it.\n--\nmm/util.c=1266=int compat_vma_mmap(struct file *file, struct vm_area_struct *vma)\n--\nmm/util.c-1271-\nmm/util.c:1272:\tcompat_set_desc_from_vma(\u0026desc, file, vma);\nmm/util.c-1273-\terr = vfs_mmap_prepare(file, \u0026desc);\n--\ntools/testing/vma/include/dup.h=1299=static inline void compat_set_vma_from_desc(struct vm_area_struct *vma,\n--\ntools/testing/vma/include/dup.h-1301-\ntools/testing/vma/include/dup.h:1302:static inline void compat_set_desc_from_vma(struct vm_area_desc *desc,\ntools/testing/vma/include/dup.h-1303-\t\t\t      const struct file *file,\n--\ntools/testing/vma/include/dup.h=1380=static inline int compat_vma_mmap(struct file *file, struct vm_area_struct *vma)\n--\ntools/testing/vma/include/dup.h-1385-\ntools/testing/vma/include/dup.h:1386:\tcompat_set_desc_from_vma(\u0026desc, file, vma);\ntools/testing/vma/include/dup.h-1387-\terr = vfs_mmap_prepare(file, \u0026desc);\n"
}

83/3 2026/10/07 22:01 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 101883
							output: 492
							thoughts: 6477
						

Thoughts:
**Analysis of Hyper-V VMBus Memory Management and Safety**

Okay, so I've been digging into this Hyper-V code, and it's all about making sure we're managing memory correctly, especially when we're dealing with userspace mappings and channel teardowns. I'm focusing on potential use-after-free, memory leaks, and any concurrency issues.

My initial thought is to check how `desc` is being initialized. I see that `compat_set_desc_from_vma` and the VMA are initializing the `desc`. This is important for understanding how the memory is being allocated and managed for the UIO interface, so I check `uio.c`.

I then went over `drivers/hv/vmbus_drv.c`, I noticed a few important updates. The `onmessage_work_context` now has a `host_generated` boolean, and I see how this gets set in `__vmbus_on_msg_dpc` (true) and `vmbus_force_channel_rescinded` (false). The `vmbus_onmessage` function's behavior is based on this boolean. I need to keep this in mind as I continue to trace the memory usage, I then check how these are initialized and used. I then check that `channel->rescind` and `channel->rescind_from_host` are properly initialized.

Then I moved to `vmbus_establish_gpadl`. I note the explicit initialization of `.addr`, `.size`, and `.gpadl` in the `struct vmbus_buffer`, with all other fields zero-initialized using the designated initializer syntax, as is the case in the variants as well. I then see that `vmbus_alloc_buffer` also zero-initializes the `vmbus_buffer` structure. I made sure to check the code that relies on these values.

Now let's check `hv_ringbuffer_init` which uses `void *addr`. I then look at how that is used in `__vmbus_open` and how `buffer->addr` is valid by the call to `vmbus_alloc_ring` and ensuring it is within the bounds of `size`.

I then dove deep into `request_arr_init` and `vmbus_alloc_requestor`, confirming that those allocations uses `vzalloc` which zeroes memory, and that the bitmap is zeroed as well.

I looked at `vmbus_buffer_reclaim_work` to understand the delayed workqueue worker. This is important to ensure memory is properly freed later. I also check `vmbus_release_buffer` which clears the buffer with `memset` to avoid potential issues.

Then I check the `vmbus_buffer_round_size` to make sure it always assigns the `rounded_size` variable. I then make sure `*posted` is properly assigned within `vmbus_gpadl_response_status`. I confirmed this by checking all the callers of this function. I took a closer look at those callers and how the `posted` variable is used.

I then check for possible user space interactions. I scan through all changed files and check that there were no `copy_to_user`, `put_user`, netlink, or any other user space write or read operations, that were newly introduced. I was checking for uninitialized memory and info leaks, which are normally caught by KMSAN. I did find a `copy_from_user` in a KUnit test, but that just copies from the userspace test memory into a kernel variable.

Now, let's list the different memory allocations that user space mappings are doing, which includes checking to see if they're zeroed to prevent info leaks. I note the use of `vzalloc` or zeroed pages (`__GFP_ZERO` / `memset`). Now, with all of this information I can confidently say the buffers being mapped to user space are zeroed, and this avoids all of the concerns for KMSAN. I confirm this in the shared page branch of `vmbus_alloc_buffer_owned`.

I then read the commit messages. I notice the focus on memory lifetime, avoiding use-after-free conditions, protecting against concurrency, and preventing memory leaks in CoCo VMs. These are all critical areas. I also check that no code introduced any new uninitialized memory vulnerabilities, and that the code protects against memory corruption or out-of-bounds access. I made sure that all allocations were using `kzalloc`, `vzalloc`, and `memset`, to prevent any such vulnerabilities. The checks related to sizing with `check_add_overflow` and `check_mul_overflow` also prevent integer overflows.

Finally, I checked each of the four criteria for KMSAN


84/3 2026/10/07 22:02 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series enhances memory lifetime and GPADL management across Hyper-V VMBus (hv_vmbus), NetVSC (hv_netvsc), and UIO (uio_hv_generic) drivers, addressing use-after-free and synchronization issues when buffer pages are reclaimed while mapped into user space or pending host teardown. It also updates high-order allocations to use kvzalloc_obj() and adds KUnit unit test suites.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory / Info-leak Risk (KMSAN):\n   - All newly introduced or modified heap and stack data structures (e.g. struct vmbus_buffer, struct vmbus_buffer_retained, struct vmbus_buffer_pin, struct hv_uio_pin, struct rndis_request, requestor arrays, bitmaps) are explicitly zero-initialized upon allocation using kzalloc_obj(), kvzalloc_obj(), vzalloc(), memset(), or {0} initializers.\n   - Memory mapped to user space via UIO / sysfs mmap interfaces uses vzalloc() or zero-initialized pages (__GFP_ZERO and memset()), preventing uninitialized memory disclosure to userspace.\n   - No kernel data structures or uninitialized paddings are copied to user space via copy_to_user, put_user, ioctl outputs, or netlink messages.\n   - No conditional branches or control flow rely on uninitialized values.\n\n2. Memory Safety / Concurrency Risks (KASAN, LOCKDEP):\n   - The primary hazards addressed and introduced by the changes involve page lifetime, reference counting (folio/page refcounts), race conditions between buffer release and mmap pinning, delayed workqueue teardown, and potential use-after-free on reclaim.\n   - These bugs are comprehensively monitored by standard sanitizers and debuggers already enabled in standard builds (KASAN for use-after-free and out-of-bounds accesses, LOCKDEP for vmbus_buffer_owners_lock locking correctness).\n\nBecause the changes introduce no uninitialized memory hazards or info-leak vectors that would require KMSAN, a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series enhances memory lifetime and GPADL management across Hyper-V VMBus (hv_vmbus), NetVSC (hv_netvsc), and UIO (uio_hv_generic) drivers, addressing use-after-free and synchronization issues when buffer pages are reclaimed while mapped into user space or pending host teardown. It also updates high-order allocations to use kvzalloc_obj() and adds KUnit unit test suites.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory / Info-leak Risk (KMSAN):\n   - All newly introduced or modified heap and stack data structures (e.g. struct vmbus_buffer, struct vmbus_buffer_retained, struct vmbus_buffer_pin, struct hv_uio_pin, struct rndis_request, requestor arrays, bitmaps) are explicitly zero-initialized upon allocation using kzalloc_obj(), kvzalloc_obj(), vzalloc(), memset(), or {0} initializers.\n   - Memory mapped to user space via UIO / sysfs mmap interfaces uses vzalloc() or zero-initialized pages (__GFP_ZERO and memset()), preventing uninitialized memory disclosure to userspace.\n   - No kernel data structures or uninitialized paddings are copied to user space via copy_to_user, put_user, ioctl outputs, or netlink messages.\n   - No conditional branches or control flow rely on uninitialized values.\n\n2. Memory Safety / Concurrency Risks (KASAN, LOCKDEP):\n   - The primary hazards addressed and introduced by the changes involve page lifetime, reference counting (folio/page refcounts), race conditions between buffer release and mmap pinning, delayed workqueue teardown, and potential use-after-free on reclaim.\n   - These bugs are comprehensively monitored by standard sanitizers and debuggers already enabled in standard builds (KASAN for use-after-free and out-of-bounds accesses, LOCKDEP for vmbus_buffer_owners_lock locking correctness).\n\nBecause the changes introduce no uninitialized memory hazards or info-leak vectors that would require KMSAN, a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)