Skip to contentSkip to conversation

Hyper-V: Add para-virtualized IOMMU support for Linux guests

PATCH Superseded Yu Zhang 6 participants 39 messages May 11 – May 21

Subsystems (7)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Yu Zhang

author
#0 lore raw

cover Hyper-V: Add para-virtualized IOMMU support for Linux guests

This patch series introduces a para-virtualized IOMMU driver for Linux guests running on Microsoft Hyper-V. The driver enables two primary use cases:
1) In-kernel DMA protection for devices assigned to the guest.
2) Device assignment to guest user space (e.g., via VFIO).

The driver implements the following core functionality:
* Hypercall-based Enumeration
Unlike traditional ACPI-based discovery (e.g., DMAR/IVRS), this driver enumerates the Hyper-V IOMMU capabilities directly via hypercalls. This approach allows the guest to discover IOMMU presence and features without requiring specific virtual firmware extensions or modifications.

* Domain Management
The driver manages IOMMU domains through a new set of Hyper-V hypercall interfaces, handling domain allocation, attachment, and detachment for endpoint devices.

* Nested Translation Support
This implementation leverages guest-managed stage-1 I/O page tables nested with host stage-2 translations. It is built upon the consolidated IOMMU page table framework (IOMMU_PT). This design eliminates the need for emulating map operations. Both Intel VT-d and AMD IOMMU platforms are supported.

* IOTLB Invalidation
IOTLB invalidation requests are marshaled and issued to the hypervisor through the same hypercall mechanism. Both domain- selective and page-selective flushes are supported.

Implementation Notes:
* Platform Support
The current implementation targets x86 platforms with Intel VT-d and AMD IOMMU hardware.

* MSI Region Handling
The hardware MSI region is hard-coded to the standard x86 interrupt range (0xfee00000 - 0xfeefffff). Future updates may allow this configuration to be queried via hypercalls if new hardware platforms are to be supported.

* Reserved Regions (RMRR)
There is currently no requirement to support assigned devices with ACPI RMRR limitations. Consequently, this patch series does not specify or query reserved memory regions.

Testing:
This series has been validated with the following configurations:
- Intel DSA devices assigned to the guest, tested with dmatest.
- NVMe devices assigned to the guest on AMD platforms, tested with fio.
- dma_map_benchmark for DMA mapping performance evaluation.

Changes since RFC v1 [1]:
- Scoped platform support to x86 only (Intel VT-d and AMD IOMMU); initialization now uses x86_init.iommu.iommu_init
- Added page-selective IOTLB flush support (new Patch 4)
- Disable device ATS in hv_iommu_release_device()
- Addressed review comments from Michael Kelley:
- Reversed dependency: pvIOMMU exports registration API for pci-hyperv to call, instead of pci-hyperv exporting hv_build_logical_dev_id()
- Dropped separate output page allocation patch; hypercall input and output now share the same per-CPU page
- Cleaned up Kconfig (removed PCI_HYPERV dependency, unnecessary selects)
- Removed dev_list, per-domain spinlock, and syscore_ops
- Removed forward declarations by reordering functions
- Fixed typos, cleaned up Kconfig selects, improved pr_info messages, etc.

[1] https://lore.kernel.org/linux-hyperv/[email protected]/

Easwar Hariharan (1):
iommu: Move Hyper-V IOMMU driver to its own subdirectory

Wei Liu (1):
hyperv: Introduce new hypercall interfaces used by Hyper-V guest IOMMU

Yu Zhang (2):
iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest iommu/hyperv: Add page-selective IOTLB flush support

 MAINTAINERS                                   |   2 +-
 arch/x86/hyperv/hv_init.c                     |   4 +
 arch/x86/include/asm/mshyperv.h               |   4 +
 drivers/iommu/Kconfig                         |  10 +-
 drivers/iommu/Makefile                        |   2 +-
 drivers/iommu/hyperv/Kconfig                  |  27 +
 drivers/iommu/hyperv/Makefile                 |   3 +
 drivers/iommu/hyperv/iommu.c                  | 794 ++++++++++++++++++
 drivers/iommu/hyperv/iommu.h                  |  54 ++
 .../irq_remapping.c}                          |   2 +-
 drivers/pci/controller/pci-hyperv.c           |  19 +-
 include/asm-generic/mshyperv.h                |  12 +
 include/hyperv/hvgdk_mini.h                   |   9 +
 include/hyperv/hvhdk_mini.h                   | 141 ++++
 14 files changed, 1070 insertions(+), 13 deletions(-)
 create mode 100644 drivers/iommu/hyperv/Kconfig
 create mode 100644 drivers/iommu/hyperv/Makefile
 create mode 100644 drivers/iommu/hyperv/iommu.c
 create mode 100644 drivers/iommu/hyperv/iommu.h
 rename drivers/iommu/{hyperv-iommu.c => hyperv/irq_remapping.c} (99%)
Signature · 1 line
2.52.0
author
#1 lore raw

PATCH 1/4 iommu: Move Hyper-V IOMMU driver to its own subdirectory

From: Easwar Hariharan <[email protected]>

The Hyper-V IOMMU driver currently only supports IRQ remapping. As it will be adding DMA remapping support, prepare a directory to contain all the different feature files.

This is a simple rename commit and has no functional changes.

---
 MAINTAINERS                                            |  2 +-
 drivers/iommu/Kconfig                                  | 10 +---------
 drivers/iommu/Makefile                                 |  2 +-
 drivers/iommu/hyperv/Kconfig                           | 10 ++++++++++
 drivers/iommu/hyperv/Makefile                          |  2 ++
 .../iommu/{hyperv-iommu.c => hyperv/irq_remapping.c}   |  2 +-
 6 files changed, 16 insertions(+), 12 deletions(-)
 create mode 100644 drivers/iommu/hyperv/Kconfig
 create mode 100644 drivers/iommu/hyperv/Makefile
 rename drivers/iommu/{hyperv-iommu.c => hyperv/irq_remapping.c} (99%)
MAINTAINERS +1 -1
index b2040011a386..1519de2a2a09 100644
@@ -11979,7 +11979,7 @@ F:	drivers/clocksource/hyperv_timer.c
 F:	drivers/hid/hid-hyperv.c
 F:	drivers/hv/
 F:	drivers/input/serio/hyperv-keyboard.c
-F:	drivers/iommu/hyperv-iommu.c
+F:	drivers/iommu/hyperv/
 F:	drivers/net/ethernet/microsoft/
 F:	drivers/net/hyperv/
 F:	drivers/pci/controller/pci-hyperv-intf.c
drivers/iommu/Kconfig +1 -9
index f86262b11416..0bdf2ac3d782 100644
@@ -195,6 +195,7 @@ config MSM_IOMMU
 source "drivers/iommu/amd/Kconfig"
 source "drivers/iommu/arm/Kconfig"
 source "drivers/iommu/intel/Kconfig"
+source "drivers/iommu/hyperv/Kconfig"
 source "drivers/iommu/iommufd/Kconfig"
 source "drivers/iommu/riscv/Kconfig"
 
@@ -351,15 +352,6 @@ config MTK_IOMMU_V1
 
 	  if unsure, say N here.
 
-config HYPERV_IOMMU
-	bool "Hyper-V IRQ Handling"
-	depends on HYPERV && X86
-	select IOMMU_API
-	default HYPERV
-	help
-	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux
-	  guest and root partitions.
-
 config VIRTIO_IOMMU
 	tristate "Virtio IOMMU driver"
 	depends on VIRTIO
drivers/iommu/Makefile +1 -1
index 0275821f4ef9..32f3ca758556 100644
@@ -4,6 +4,7 @@ obj-$(CONFIG_AMD_IOMMU) += amd/
 obj-$(CONFIG_INTEL_IOMMU) += intel/
 obj-$(CONFIG_RISCV_IOMMU) += riscv/
 obj-$(CONFIG_GENERIC_PT) += generic_pt/fmt/
+obj-$(CONFIG_HYPERV_IOMMU) += hyperv/
 obj-$(CONFIG_IOMMU_API) += iommu.o
 obj-$(CONFIG_IOMMU_SUPPORT) += iommu-pages.o
 obj-$(CONFIG_IOMMU_API) += iommu-traces.o
@@ -30,7 +31,6 @@ obj-$(CONFIG_TEGRA_IOMMU_SMMU) += tegra-smmu.o
 obj-$(CONFIG_EXYNOS_IOMMU) += exynos-iommu.o
 obj-$(CONFIG_FSL_PAMU) += fsl_pamu.o fsl_pamu_domain.o
 obj-$(CONFIG_S390_IOMMU) += s390-iommu.o
-obj-$(CONFIG_HYPERV_IOMMU) += hyperv-iommu.o
 obj-$(CONFIG_VIRTIO_IOMMU) += virtio-iommu.o
 obj-$(CONFIG_IOMMU_SVA) += iommu-sva.o
 obj-$(CONFIG_IOMMU_IOPF) += io-pgfault.o
drivers/iommu/hyperv/Kconfig new file +10 -0
new file mode 100644
index 000000000000..30f40d867036
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# HyperV paravirtualized IOMMU support
+config HYPERV_IOMMU
+	bool "Hyper-V IRQ Handling"
+	depends on HYPERV && X86
+	select IOMMU_API
+	default HYPERV
+	help
+	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux
+	  guest and root partitions.
drivers/iommu/hyperv/Makefile new file +2 -0
new file mode 100644
index 000000000000..9f557bad94ff
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_HYPERV_IOMMU) += irq_remapping.o
drivers/iommu/hyperv/irq_remapping.c renamed from drivers/iommu/hyperv-iommu.c +1 -1
similarity index 99%
rename from drivers/iommu/hyperv-iommu.c
rename to drivers/iommu/hyperv/irq_remapping.c
index 479103261ae6..62a94a8c9e95 100644
@@ -22,7 +22,7 @@
 #include <asm/hypervisor.h>
 #include <asm/mshyperv.h>
 
-#include "irq_remapping.h"
+#include "../irq_remapping.h"
 
 #ifdef CONFIG_IRQ_REMAP
 
Signature · 1 line
2.52.0
#2 lore raw

Re: [PATCH v1 1/4] iommu: Move Hyper-V IOMMU driver to its own subdirectory

Quoted 5 lines · Yu Zhang

From: Easwar Hariharan <[email protected]>

The Hyper-V IOMMU driver currently only supports IRQ remapping. As it will be adding DMA remapping support, prepare a directory to contain all the different feature files.

Any possibility we could put the irq remapping thing under the irq directory?

The other drivers have it here because they are co-mingled with their iommu HW, will hyperv have the same issue?

Jason

author
#3 lore raw

Re: [PATCH v1 1/4] iommu: Move Hyper-V IOMMU driver to its own subdirectory

Quoted 7 lines · Jason Gunthorpe
Quoted 5 lines · Yu Zhang

From: Easwar Hariharan <[email protected]>

The Hyper-V IOMMU driver currently only supports IRQ remapping. As it will be adding DMA remapping support, prepare a directory to contain all the different feature files.

Quoted 6 lines

Any possibility we could put the irq remapping thing under the irq directory?

The other drivers have it here because they are co-mingled with their iommu HW, will hyperv have the same issue?

Good question. I don't think Hyper-V have the same co-mingling issue.

But from a code organization perspective, I think drivers/iommu/hyperv/ is still the most natural place:

- The IRQ remapping framework itself (drivers/iommu/irq_remapping.c and its internal header irq_remapping.h) lives under drivers/iommu/, and all three backends (intel/, amd/, hyperv/) sit there today. hyperv/irq_remapping.c includes that internal header directly.

- irq_remapping_prepare() references the extern hyperv_irq_remap_ops declared in that header, so the provider naturally belongs in the same tree.

Moving it to e.g. drivers/irqchip/ would break that symmetry.

Yu

Quoted 2 lines

Jason

#4 lore raw

Re: [PATCH v1 1/4] iommu: Move Hyper-V IOMMU driver to its own subdirectory

Quoted 17 lines · Yu Zhang
Quoted 7 lines · Jason Gunthorpe
Quoted 5 lines · Yu Zhang

From: Easwar Hariharan <[email protected]>

The Hyper-V IOMMU driver currently only supports IRQ remapping. As it will be adding DMA remapping support, prepare a directory to contain all the different feature files.

Quoted 6 lines

Any possibility we could put the irq remapping thing under the irq directory?

The other drivers have it here because they are co-mingled with their iommu HW, will hyperv have the same issue?

Good question. I don't think Hyper-V have the same co-mingling issue.

Quoted 7 lines

But from a code organization perspective, I think drivers/iommu/hyperv/ is still the most natural place:

- The IRQ remapping framework itself (drivers/iommu/irq_remapping.c and its internal header irq_remapping.h) lives under drivers/iommu/, and all three backends (intel/, amd/, hyperv/) sit there today. hyperv/irq_remapping.c includes that internal header directly.

IMHO it is a fair question if that even belongs under iommu.

I think it was dumped into here because of the co-mingled drivers..

Jason

author
#5 lore raw

PATCH 2/4 hyperv: Introduce new hypercall interfaces used by Hyper-V guest IOMMU

In reply to Yu Zhang

From: Wei Liu <[email protected]>

Hyper-V guest IOMMU is a para-virtualized IOMMU based on hypercalls. Introduce the hypercalls used by the child partition to interact with this facility.

These hypercalls fall into below categories:
- Detection and capability: HVCALL_GET_IOMMU_CAPABILITIES is used to detect the existence and capabilities of the guest IOMMU.

- Device management: HVCALL_GET_LOGICAL_DEVICE_PROPERTY is used to check whether an endpoint device is managed by the guest IOMMU.

- Domain management: A set of hypercalls is provided to handle the creation, configuration, and deletion of guest domains, as well as the attachment/detachment of endpoint devices to/from those domains.

- IOTLB flushing: HVCALL_FLUSH_DEVICE_DOMAIN is used to ask Hyper-V for a domain-selective IOTLB flush (which in its handler may flush the device TLB as well).

---
 include/hyperv/hvgdk_mini.h |   8 +++
 include/hyperv/hvhdk_mini.h | 124 ++++++++++++++++++++++++++++++++++++
 2 files changed, 132 insertions(+)
include/hyperv/hvgdk_mini.h +8 -0
index 6a4e8b9d570f..5bdbb44da112 100644
@@ -486,10 +486,16 @@ union hv_vp_assist_msr_contents {	 /* HV_REGISTER_VP_ASSIST_PAGE */
 #define HVCALL_GET_VP_INDEX_FROM_APIC_ID		0x009a
 #define HVCALL_FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE	0x00af
 #define HVCALL_FLUSH_GUEST_PHYSICAL_ADDRESS_LIST	0x00b0
+#define HVCALL_CREATE_DEVICE_DOMAIN			0x00b1
+#define HVCALL_ATTACH_DEVICE_DOMAIN			0x00b2
 #define HVCALL_SIGNAL_EVENT_DIRECT			0x00c0
 #define HVCALL_POST_MESSAGE_DIRECT			0x00c1
 #define HVCALL_DISPATCH_VP				0x00c2
+#define HVCALL_DETACH_DEVICE_DOMAIN			0x00c4
+#define HVCALL_DELETE_DEVICE_DOMAIN			0x00c5
 #define HVCALL_GET_GPA_PAGES_ACCESS_STATES		0x00c9
+#define HVCALL_CONFIGURE_DEVICE_DOMAIN			0x00ce
+#define HVCALL_FLUSH_DEVICE_DOMAIN			0x00d0
 #define HVCALL_ACQUIRE_SPARSE_SPA_PAGE_HOST_ACCESS	0x00d7
 #define HVCALL_RELEASE_SPARSE_SPA_PAGE_HOST_ACCESS	0x00d8
 #define HVCALL_MODIFY_SPARSE_GPA_PAGE_HOST_VISIBILITY	0x00db
@@ -502,6 +508,8 @@ union hv_vp_assist_msr_contents {	 /* HV_REGISTER_VP_ASSIST_PAGE */
 #define HVCALL_MMIO_READ				0x0106
 #define HVCALL_MMIO_WRITE				0x0107
 #define HVCALL_DISABLE_HYP_EX                           0x010f
+#define HVCALL_GET_IOMMU_CAPABILITIES			0x0125
+#define HVCALL_GET_LOGICAL_DEVICE_PROPERTY		0x0127
 #define HVCALL_MAP_STATS_PAGE2				0x0131
 
 /* HV_HYPERCALL_INPUT */
include/hyperv/hvhdk_mini.h +124 -0

128 lines not on this page · raw message

Signature · 1 line
2.52.0
#6 lore raw

Re: [PATCH v1 2/4] hyperv: Introduce new hypercall interfaces used by Hyper-V guest IOMMU

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Low] Missing 4-byte padding in `struct hv_input_create_device_domain` resulting in an unaligned ABI…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] Missing 4-byte padding in struct hv_input_create_device_domain resulting in an unaligned ABI structure size.
- [Low] Preprocessor macros are defined inside structure definitions.
--

commit 424b106dd2a0b2fe17c666987a01e49923b0b297
Author: Wei Liu <[email protected]>

hyperv: Introduce new hypercall interfaces used by Hyper-V guest IOMMU

This commit introduces new hypercall interfaces to support the Hyper-V guest IOMMU, which allows child partitions to interact with the facility for device, domain, and IOTLB management.

Quoted 4 lines
include/hyperv/hvhdk_mini.h +0 -0
index b4cb2fa26e9bc..493608e791b45 100644

[ ... ]

include/hyperv/hvhdk_mini.h union hv_device_id { /* HV_DEVICE_ID */ · line 585

Quoted 4 lines
include/hyperv/hvhdk_mini.h +4 -0
+struct hv_input_create_device_domain {
+	struct hv_input_device_domain device_domain;
+	union hv_create_device_domain_flags create_device_domain_flags;
+} __packed;

Should this structure include a 4-byte padding field at the end?

Since the device_domain field is 24 bytes and the create_device_domain_flags field is 4 bytes, the structure size is exactly 28 bytes. Other hypercall structures in this file explicitly use padding to maintain an 8-byte aligned size.

While this might work for a single invocation, if this structure is ever used in a rep (array) hypercall, would the 28-byte stride misalign subsequent elements and cause the hypercall to fail?

[ ... ]

include/hyperv/hvhdk_mini.h union hv_device_id { /* HV_DEVICE_ID */ · line 644

Quoted 13 lines
include/hyperv/hvhdk_mini.h +13 -0
+struct hv_output_get_iommu_capabilities {
+	u32 size;
+	u16 reserved;
+	u8  max_iova_width;
+	u8  max_pasid_width;
+
+#define HV_IOMMU_CAP_PRESENT (1ULL << 0)
+#define HV_IOMMU_CAP_S2 (1ULL << 1)
+#define HV_IOMMU_CAP_S1 (1ULL << 2)
+#define HV_IOMMU_CAP_S1_5LVL (1ULL << 3)
+#define HV_IOMMU_CAP_PASID (1ULL << 4)
+#define HV_IOMMU_CAP_ATS (1ULL << 5)
+#define HV_IOMMU_CAP_PRI (1ULL << 6)

This isn't a bug, but should these preprocessor macros be moved outside of the structure definition?

Macros do not respect C scope, so placing them inside the structure definition violates standard kernel coding style conventions and might falsely imply they are locally scoped.

Quoted 4 lines
include/hyperv/hvhdk_mini.h +4 -0
+
+	u64 iommu_cap;
+	u64 pgsize_bitmap;
+} __packed;

[ ... ]

include/hyperv/hvhdk_mini.h union hv_device_id { /* HV_DEVICE_ID */ · line 663

Quoted 2 lines
include/hyperv/hvhdk_mini.h +2 -0
+struct hv_output_get_logical_device_property {
+#define HV_DEVICE_IOMMU_ENABLED (1ULL << 0)

Similarly, could this macro be moved outside the structure definition to adhere to conventional kernel styling?

Quoted 3 lines
include/hyperv/hvhdk_mini.h +3 -0
+	u64 device_iommu;
+	u64 reserved;
+} __packed;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#7 lore raw

PATCH 3/4 iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

In reply to Yu Zhang

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

---
 arch/x86/hyperv/hv_init.c           |   4 +
 arch/x86/include/asm/mshyperv.h     |   4 +
 drivers/iommu/hyperv/Kconfig        |  17 +
 drivers/iommu/hyperv/Makefile       |   1 +
 drivers/iommu/hyperv/iommu.c        | 705 ++++++++++++++++++++++++++++
 drivers/iommu/hyperv/iommu.h        |  54 +++
 drivers/pci/controller/pci-hyperv.c |  19 +-
 include/asm-generic/mshyperv.h      |  12 +
 8 files changed, 815 insertions(+), 1 deletion(-)
 create mode 100644 drivers/iommu/hyperv/iommu.c
 create mode 100644 drivers/iommu/hyperv/iommu.h
arch/x86/hyperv/hv_init.c +4 -0
index 323adc93f2dc..2c8ff8e06249 100644
@@ -578,6 +578,10 @@ void __init hyperv_init(void)
 	old_setup_percpu_clockev = x86_init.timers.setup_percpu_clockev;
 	x86_init.timers.setup_percpu_clockev = hv_stimer_setup_percpu_clockev;
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+	x86_init.iommu.iommu_init = hv_iommu_init;
+#endif
+
 	hv_apic_init();
 
 	x86_init.pci.arch_init = hv_pci_init;
arch/x86/include/asm/mshyperv.h +4 -0
index f64393e853ee..20d947c2c758 100644
@@ -313,6 +313,10 @@ static inline void mshv_vtl_return_hypercall(void) {}
 static inline void __mshv_vtl_return_call(struct mshv_vtl_cpu_context *vtl0) {}
 #endif
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+int __init hv_iommu_init(void);
+#endif
+
 #include <asm-generic/mshyperv.h>
 
 #endif
drivers/iommu/hyperv/Kconfig +17 -0
index 30f40d867036..9e658d5c9a77 100644
@@ -8,3 +8,20 @@ config HYPERV_IOMMU
 	help
 	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux
 	  guest and root partitions.
+
+if HYPERV_IOMMU
+config HYPERV_PVIOMMU
+	bool "Microsoft Hypervisor para-virtualized IOMMU support"
+	depends on X86 && HYPERV
+	select IOMMU_API
+	select GENERIC_PT
+	select IOMMU_PT
+	select IOMMU_PT_X86_64
+	select IOMMU_IOVA
+	default HYPERV
+	help
+	  Para-virtualized IOMMU driver for Linux guests running on
+	  Microsoft Hyper-V. Provides DMA remapping and IOTLB
+	  flush support to enable DMA isolation for devices
+	  assigned to the guest.
+endif
drivers/iommu/hyperv/Makefile +1 -0
index 9f557bad94ff..8669741c0a51 100644
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_HYPERV_IOMMU) += irq_remapping.o
+obj-$(CONFIG_HYPERV_PVIOMMU) += iommu.o
drivers/iommu/hyperv/iommu.c new file +705 -0

705 lines not on this page · raw message

drivers/iommu/hyperv/iommu.h new file +54 -0

54 lines not on this page · raw message

drivers/pci/controller/pci-hyperv.c +18 -1
index cfc8fa403dad..a4af9c8c2220 100644
@@ -3715,6 +3715,7 @@ static int hv_pci_probe(struct hv_device *hdev,
 	struct hv_pcibus_device *hbus;
 	int ret, dom;
 	u16 dom_req;
+	u32 prefix;
 	char *name;
 
 	bridge = devm_pci_alloc_host_bridge(&hdev->device, 0);
@@ -3857,13 +3858,25 @@ static int hv_pci_probe(struct hv_device *hdev,
 
 	hbus->state = hv_pcibus_probed;
 
-	ret = create_root_hv_pci_bus(hbus);
+	/* Notify pvIOMMU before any device on the bus is scanned. */
+	prefix = (hdev->dev_instance.b[5] << 24) |
+		 (hdev->dev_instance.b[4] << 16) |
+		 (hdev->dev_instance.b[7] <<  8) |
+		 (hdev->dev_instance.b[6] & 0xf8);
+
+	ret = hv_iommu_register_pci_bus(dom, prefix);
 	if (ret)
 		goto free_windows;
 
+	ret = create_root_hv_pci_bus(hbus);
+	if (ret)
+		goto unregister_pviommu;
+
 	mutex_unlock(&hbus->state_lock);
 	return 0;
 
+unregister_pviommu:
+	hv_iommu_unregister_pci_bus(dom);
 free_windows:
 	hv_pci_free_bridge_windows(hbus);
 exit_d0:
@@ -3974,8 +3987,10 @@ static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs)
 static void hv_pci_remove(struct hv_device *hdev)
 {
 	struct hv_pcibus_device *hbus;
+	int dom;
 
 	hbus = hv_get_drvdata(hdev);
+	dom = hbus->bridge->domain_nr;
 	if (hbus->state == hv_pcibus_installed) {
 		tasklet_disable(&hdev->channel->callback_event);
 		hbus->state = hv_pcibus_removing;
@@ -3994,6 +4009,8 @@ static void hv_pci_remove(struct hv_device *hdev)
 		hv_pci_remove_slots(hbus);
 		pci_remove_root_bus(hbus->bridge->bus);
 		pci_unlock_rescan_remove();
+
+		hv_iommu_unregister_pci_bus(dom);
 	}
 
 	hv_pci_bus_exit(hdev, false);
include/asm-generic/mshyperv.h +12 -0
index bf601d67cecb..b71345c74568 100644
@@ -73,6 +73,18 @@ extern enum hv_partition_type hv_curr_partition_type;
 extern void * __percpu *hyperv_pcpu_input_arg;
 extern void * __percpu *hyperv_pcpu_output_arg;
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+int  hv_iommu_register_pci_bus(int pci_domain_nr, u32 logical_dev_id_prefix);
+void hv_iommu_unregister_pci_bus(int pci_domain_nr);
+#else
+static inline int hv_iommu_register_pci_bus(int pci_domain_nr,
+					    u32 logical_dev_id_prefix)
+{
+	return 0;
+}
+static inline void hv_iommu_unregister_pci_bus(int pci_domain_nr) { }
+#endif
+
 u64 hv_do_hypercall(u64 control, void *inputaddr, void *outputaddr);
 u64 hv_do_fast_hypercall8(u16 control, u64 input8);
 u64 hv_do_fast_hypercall16(u16 control, u64 input1, u64 input2);
Signature · 1 line
2.52.0
#8 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] Sleeping in atomic context on PREEMPT_RT due to spin_lock() inside local_irq_save(). - [High]…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Sleeping in atomic context on PREEMPT_RT due to spin_lock() inside local_irq_save().
- [High] Global state corruption and dangling pointer on IOMMU initialization failure.
- [Medium] Undefined behavior and potential integer overflow in IOMMU geometry calculation.
- [Medium] IOMMU driver destructively clears generic dma_ops in release_device.
- [Low] Missing ida_destroy() on the error cleanup path in hv_iommu_init().
--

commit d1b032eaf8fbec1a7366bf47848a4dfd4a2d21b6
Author: Yu Zhang <[email protected]>
Subject: iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

This patch adds a para-virtualized IOMMU driver for Linux guests on Hyper-V. It implements stage-1 IO translation via hypercalls and manages x86-compatible page tables in guest memory.

Quoted 5 lines
drivers/iommu/hyperv/iommu.c new file +0 -0
new file mode 100644
index 0000000000000..e5fc625314b55

[ ... ]

Quoted 1 line
drivers/iommu/hyperv/iommu.c new file +0 -0
@@ -215,14 +230,19 @@ static void hv_iommu_detach_dev(struct iommu_domain *domain, struct device *dev)

[ ... ]

drivers/iommu/hyperv/iommu.c line 236

Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	if (hv_iommu_lookup_logical_dev_id(pdev, &input->device_id.as_uint64)) {

Could this cause a sleeping in atomic context BUG on PREEMPT_RT kernels?

When hardware interrupts are disabled via local_irq_save(), this code calls hv_iommu_lookup_logical_dev_id(), which does:

    spin_lock(&hv_iommu_pci_bus_lock);

On PREEMPT_RT, spinlock_t maps to an rt_mutex which can sleep. Acquiring a sleepable lock while hardware interrupts are disabled will cause a crash.

Would it be safer to hoist the ID lookup outside the local_irq_save() block, since it does not appear to rely on the per-CPU input page state? Similar logic is also present in hv_iommu_attach_dev() and hv_iommu_get_logical_device_property().

[ ... ]

drivers/iommu/hyperv/iommu.c line 376

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

Is it safe to explicitly clear the generic dma_ops here?

Device DMA operations are typically managed by the core DMA mapping subsystem. Clearing them directly strips the device of fallback operations like SWIOTLB during device teardown or unbind.

If there are outstanding DMA mappings, could this cause subsequent unmap calls to execute without valid operations, potentially leaking bounce buffers?

[ ... ]

Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+static void __init hv_init_iommu_device(struct hv_iommu_dev *hv_iommu,
+			struct hv_output_get_iommu_capabilities *hv_iommu_cap)
+{
+	ida_init(&hv_iommu->domain_ids);

[ ... ]

drivers/iommu/hyperv/iommu.c line 623

Quoted 3 lines
drivers/iommu/hyperv/iommu.c new file +3 -0
+	hv_iommu->geometry = (struct iommu_domain_geometry) {
+		.aperture_start = 0,
+		.aperture_end = (((u64)1) << hv_iommu->max_iova_width) - 1,

Can this shift result in undefined behavior if the hypervisor returns a max_iova_width of 64 or greater?

If 5-level paging is supported, there doesn't appear to be an upper bound validation on max_iova_width. On x86, shifting by 64 or more will be masked modulo 64, making 1ULL << 64 evaluate to 1, and resulting in an aperture_end of 0.

Would it be better to cap max_iova_width at a safe maximum before performing this calculation?

[ ... ]

Quoted 2 lines
drivers/iommu/hyperv/iommu.c new file +2 -0
+int __init hv_iommu_init(void)
+{

[ ... ]

Quoted 14 lines
drivers/iommu/hyperv/iommu.c new file +14 -0
+	iommu_detected = 1;
+	pci_request_acs();
+
+	hv_iommu = kzalloc_obj(*hv_iommu, GFP_KERNEL);
+	if (!hv_iommu)
+		return -ENOMEM;
+
+	hv_init_iommu_device(hv_iommu, &hv_iommu_cap);
+
+	ret = hv_initialize_static_domains();
+	if (ret) {
+		pr_err("static domains init failed: %d\n", ret);
+		goto err_free;
+	}

[ ... ]

drivers/iommu/hyperv/iommu.c line 705

Quoted 9 lines
drivers/iommu/hyperv/iommu.c new file +9 -0
+err_sysfs_remove:
+	iommu_device_sysfs_remove(&hv_iommu->iommu);
+err_delete_static_domains:
+	hv_delete_device_domain(&hv_blocking_domain);
+	hv_delete_device_domain(&hv_identity_domain);
+err_free:
+	kfree(hv_iommu);
+	return ret;
+}

If initialization fails and we jump to err_free, does this leave global state corrupted?

The global pointer hv_iommu_device is assigned to hv_iommu during hv_init_iommu_device(), and iommu_detected is set to 1. When hv_iommu is freed, these globals aren't cleared.

Could this leave a dangling pointer and trick the core architecture into believing a hardware IOMMU is functional, potentially skipping fallback mechanisms like SWIOTLB?

Also, should there be a call to ida_destroy(&hv_iommu->domain_ids) in this cleanup path to prevent leaking internal XArray nodes allocated by ida_init()?

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

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

In reply to Yu Zhang

Hi Yu,

Quoted 82 lines · On Tue, 12 May 2026 00:24:07 +0800 Yu Zhang <[email protected]>…

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

Co-developed-by Easwar Hariharan

<[email protected]> Signed-off-by: Easwar Hariharan <[email protected]> Signed-off-by: Yu Zhang <[email protected]> ---

 arch/x86/hyperv/hv_init.c           |   4 +
 arch/x86/include/asm/mshyperv.h     |   4 +
 drivers/iommu/hyperv/Kconfig        |  17 +
 drivers/iommu/hyperv/Makefile       |   1 +
 drivers/iommu/hyperv/iommu.c        | 705
++++++++++++++++++++++++++++ drivers/iommu/hyperv/iommu.h        |
54 +++ drivers/pci/controller/pci-hyperv.c |  19 +-
 include/asm-generic/mshyperv.h      |  12 +
 8 files changed, 815 insertions(+), 1 deletion(-)
 create mode 100644 drivers/iommu/hyperv/iommu.c
 create mode 100644 drivers/iommu/hyperv/iommu.h
arch/x86/hyperv/hv_init.c +0 -0
index 323adc93f2dc..2c8ff8e06249 100644
@@ -578,6 +578,10 @@ void __init hyperv_init(void)
 	old_setup_percpu_clockev =
 x86_init.timers.setup_percpu_clockev;

x86_init.timers.setup_percpu_clockev = hv_stimer_setup_percpu_clockev; +#ifdef CONFIG_HYPERV_PVIOMMU

arch/x86/hyperv/hv_init.c +3 -0
+	x86_init.iommu.iommu_init = hv_iommu_init;
+#endif
+
 	hv_apic_init();
 
 	x86_init.pci.arch_init = hv_pci_init;
(quoted diff) +0 -0

b/arch/x86/include/asm/mshyperv.h index f64393e853ee..20d947c2c758 100644 --- a/arch/x86/include/asm/mshyperv.h
+++ b/arch/x86/include/asm/mshyperv.h

(quoted diff) +0 -0
@@ -313,6 +313,10 @@ static inline void

mshv_vtl_return_hypercall(void) {} static inline void __mshv_vtl_return_call(struct mshv_vtl_cpu_context *vtl0) {} #endif

arch/x86/include/asm/mshyperv.h +4 -0
+#ifdef CONFIG_HYPERV_PVIOMMU
+int __init hv_iommu_init(void);
+#endif
+
 #include <asm-generic/mshyperv.h>
 
 #endif
(quoted diff) +0 -0

b/drivers/iommu/hyperv/Kconfig index 30f40d867036..9e658d5c9a77 100644

drivers/iommu/hyperv/Kconfig +0 -0
@@ -8,3 +8,20 @@ config HYPERV_IOMMU
 	help
 	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux

drivers/iommu/hyperv/Kconfig config HYPERV_IOMMU · line 19

Quoted 10 lines
drivers/iommu/hyperv/Kconfig +9 -0
 	  guest and root partitions.
+
+if HYPERV_IOMMU
+config HYPERV_PVIOMMU
+	bool "Microsoft Hypervisor para-virtualized IOMMU support"
+	depends on X86 && HYPERV
+	select IOMMU_API
+	select GENERIC_PT
+	select IOMMU_PT
+	select IOMMU_PT_X86_64

nit:
If HYPERV_PVIOMMU is enabled on a (hypothetical) platform with GENERIC_ATOMIC64=y, the select would force-enable IOMMU_PT_X86_64 even though its depends on is unsatisfied — leading to a build failure.

In practice this can't happen today because HYPERV_PVIOMMU already depends on X86 && HYPERV, and x86 never sets GENERIC_ATOMIC64. But adding the explicit guard is more defensive.
i.e.
depends on !GENERIC_ATOMIC64 # for cmpxchg64 in IOMMU_PT

Quoted 138 lines
drivers/iommu/hyperv/Kconfig +8 -0
+	select IOMMU_IOVA
+	default HYPERV
+	help
+	  Para-virtualized IOMMU driver for Linux guests running on
+	  Microsoft Hyper-V. Provides DMA remapping and IOTLB
+	  flush support to enable DMA isolation for devices
+	  assigned to the guest.
+endif
(quoted diff) +0 -0

b/drivers/iommu/hyperv/Makefile index 9f557bad94ff..8669741c0a51 100644 --- a/drivers/iommu/hyperv/Makefile
+++ b/drivers/iommu/hyperv/Makefile

drivers/iommu/hyperv/Makefile +1 -0
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_HYPERV_IOMMU) += irq_remapping.o
+obj-$(CONFIG_HYPERV_PVIOMMU) += iommu.o
(quoted diff) +0 -0

b/drivers/iommu/hyperv/iommu.c new file mode 100644 index 000000000000..e5fc625314b5

drivers/iommu/hyperv/iommu.c new file +28 -0
@@ -0,0 +1,705 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Hyper-V IOMMU driver.
+ *
+ * Copyright (C) 2019, 2024-2026 Microsoft, Inc.
+ */
+
+#define pr_fmt(fmt) "Hyper-V pvIOMMU: " fmt
+#define dev_fmt(fmt) pr_fmt(fmt)
+
+#include <linux/iommu.h>
+#include <linux/pci.h>
+#include <linux/dma-map-ops.h>
+#include <linux/generic_pt/iommu.h>
+#include <linux/pci-ats.h>
+
+#include <asm/iommu.h>
+#include <asm/hypervisor.h>
+#include <asm/mshyperv.h>
+
+#include "iommu.h"
+#include "../iommu-pages.h"
+
+struct hv_iommu_dev *hv_iommu_device;
+
+/*
+ * Identity and blocking domains are static singletons: identity is

a 1:1
+ * passthrough with no page table, blocking rejects all DMA. Neither holds
+ * per-IOMMU state, so one instance suffices even with multiple vIOMMUs.
+ */

drivers/iommu/hyperv/iommu.c new file +9 -0
+static struct hv_iommu_domain hv_identity_domain;
+static struct hv_iommu_domain hv_blocking_domain;
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops;
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops;
+static struct iommu_ops hv_iommu_ops;
+static LIST_HEAD(hv_iommu_pci_bus_list);
+static DEFINE_SPINLOCK(hv_iommu_pci_bus_lock);
+
+#define hv_iommu_present(iommu_cap) (iommu_cap &

HV_IOMMU_CAP_PRESENT) +#define hv_iommu_s1_domain_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1) +#define hv_iommu_5lvl_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1_5LVL) +#define hv_iommu_ats_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_ATS) + +int hv_iommu_register_pci_bus(int pci_domain_nr, u32 logical_dev_id_prefix) +{

drivers/iommu/hyperv/iommu.c new file +16 -0
+	struct hv_pci_busdata *bus, *new;
+	int ret = 0;
+
+	if (no_iommu || !iommu_detected)
+		return 0;
+
+	new = kzalloc_obj(*new, GFP_KERNEL);
+	if (!new)
+		return -ENOMEM;
+
+	spin_lock(&hv_iommu_pci_bus_lock);
+	list_for_each_entry(bus, &hv_iommu_pci_bus_list, list) {
+		if (bus->pci_domain_nr != pci_domain_nr)
+			continue;
+
+		if (bus->logical_dev_id_prefix !=

logical_dev_id_prefix) {

drivers/iommu/hyperv/iommu.c new file +1 -0
+			pr_err("stale registration for PCI domain %d

(old prefix 0x%08x, new 0x%08x)\n",

drivers/iommu/hyperv/iommu.c new file +1 -0
+			       pci_domain_nr,

bus->logical_dev_id_prefix,

drivers/iommu/hyperv/iommu.c new file +26 -0
+			       logical_dev_id_prefix);
+			ret = -EEXIST;
+		}
+
+		goto out_free;
+	}
+
+	new->pci_domain_nr = pci_domain_nr;
+	new->logical_dev_id_prefix = logical_dev_id_prefix;
+	list_add(&new->list, &hv_iommu_pci_bus_list);
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	return 0;
+
+out_free:
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	kfree(new);
+	return ret;
+}
+EXPORT_SYMBOL_FOR_MODULES(hv_iommu_register_pci_bus, "pci-hyperv");
+
+void hv_iommu_unregister_pci_bus(int pci_domain_nr)
+{
+	struct hv_pci_busdata *bus, *tmp;
+
+	spin_lock(&hv_iommu_pci_bus_lock);
+	list_for_each_entry_safe(bus, tmp, &hv_iommu_pci_bus_list,

list) {

drivers/iommu/hyperv/iommu.c new file +12 -0
+		if (bus->pci_domain_nr == pci_domain_nr) {
+			list_del(&bus->list);
+			kfree(bus);
+			break;
+		}
+	}
+	spin_unlock(&hv_iommu_pci_bus_lock);
+}
+EXPORT_SYMBOL_FOR_MODULES(hv_iommu_unregister_pci_bus, "pci-hyperv");
+
+/*
+ * Look up the logical device ID for a vPCI device. Returns 0 on

success
+ * with *logical_id filled in; -ENODEV if no entry registered for this
+ * device's vPCI bus.
+ */
+static int hv_iommu_lookup_logical_dev_id(struct pci_dev *pdev, u64 *logical_id) +{

drivers/iommu/hyperv/iommu.c line 112

Quoted 5 lines
drivers/iommu/hyperv/iommu.c new file +5 -0
+	struct hv_pci_busdata *bus;
+	int domain = pci_domain_nr(pdev->bus);
+	int ret = -ENODEV;
+
+	spin_lock(&hv_iommu_pci_bus_lock);

this is called under local_irq_save, should use raw_spinlock_t for RT kernel?

Quoted 272 lines
drivers/iommu/hyperv/iommu.c new file +3 -0
+	list_for_each_entry(bus, &hv_iommu_pci_bus_list, list) {
+		if (bus->pci_domain_nr == domain) {
+			*logical_id =

(u64)bus->logical_dev_id_prefix |

drivers/iommu/hyperv/iommu.c new file +10 -0
+				      PCI_FUNC(pdev->devfn);
+			ret = 0;
+			break;
+		}
+	}
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	return ret;
+}
+
+static int hv_create_device_domain(struct hv_iommu_domain

*hv_domain, u32 domain_stage) +{

drivers/iommu/hyperv/iommu.c new file +7 -0
+	int ret;
+	u64 status;
+	unsigned long flags;
+	struct hv_input_create_device_domain *input;
+
+	ret = ida_alloc_range(&hv_iommu_device->domain_ids,
+			hv_iommu_device->first_domain,

hv_iommu_device->last_domain,

drivers/iommu/hyperv/iommu.c new file +15 -0
+			GFP_KERNEL);
+	if (ret < 0)
+		return ret;
+
+	hv_domain->device_domain.partition_id = HV_PARTITION_ID_SELF;
+	hv_domain->device_domain.domain_id.type = domain_stage;
+	hv_domain->device_domain.domain_id.id = ret;
+	hv_domain->hv_iommu = hv_iommu_device;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	input->create_device_domain_flags.forward_progress_required

= 1;

drivers/iommu/hyperv/iommu.c new file +2 -0
+	input->create_device_domain_flags.inherit_owning_vtl = 0;
+	status = hv_do_hypercall(HVCALL_CREATE_DEVICE_DOMAIN, input,

NULL); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status)) {
+		pr_err("HVCALL_CREATE_DEVICE_DOMAIN failed, status

%lld\n", status);

drivers/iommu/hyperv/iommu.c new file +1 -0
+		ida_free(&hv_iommu_device->domain_ids,

hv_domain->device_domain.domain_id.id);

drivers/iommu/hyperv/iommu.c new file +6 -0
+	}
+
+	return hv_result_to_errno(status);
+}
+
+static void hv_delete_device_domain(struct hv_iommu_domain

*hv_domain) +{

drivers/iommu/hyperv/iommu.c new file +10 -0
+	u64 status;
+	unsigned long flags;
+	struct hv_input_delete_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	status = hv_do_hypercall(HVCALL_DELETE_DEVICE_DOMAIN, input,

NULL); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_DELETE_DEVICE_DOMAIN failed, status

%lld\n", status); +

drivers/iommu/hyperv/iommu.c new file +1 -0
+	ida_free(&hv_domain->hv_iommu->domain_ids,

hv_domain->device_domain.domain_id.id); +}

drivers/iommu/hyperv/iommu.c new file +25 -0
+
+static bool hv_iommu_capable(struct device *dev, enum iommu_cap cap)
+{
+	switch (cap) {
+	case IOMMU_CAP_CACHE_COHERENCY:
+		return true;
+	case IOMMU_CAP_DEFERRED_FLUSH:
+		return true;
+	default:
+		return false;
+	}
+}
+
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN, input,

NULL); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN failed, status

%lld\n", status); +}

drivers/iommu/hyperv/iommu.c new file +2 -0
+
+static void hv_iommu_detach_dev(struct iommu_domain *domain, struct

device *dev) +{

drivers/iommu/hyperv/iommu.c new file +5 -0
+	u64 status;
+	unsigned long flags;
+	struct hv_input_detach_device_domain *input;
+	struct pci_dev *pdev;
+	struct hv_iommu_domain *hv_domain =

to_hv_iommu_domain(domain);

drivers/iommu/hyperv/iommu.c new file +9 -0
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+
+	/* See the attach function, only PCI devices for now */
+	if (!dev_is_pci(dev) || vdev->hv_domain != hv_domain)
+		return;
+
+	pdev = to_pci_dev(dev);
+
+	dev_dbg(dev, "detaching from domain %d\n",

hv_domain->device_domain.domain_id.id); +

drivers/iommu/hyperv/iommu.c new file +6 -0
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	if (hv_iommu_lookup_logical_dev_id(pdev,

&input->device_id.as_uint64)) {

drivers/iommu/hyperv/iommu.c new file +2 -0
+		local_irq_restore(flags);
+		dev_warn(&pdev->dev, "no IOMMU registration for vPCI

bus on detach\n");

drivers/iommu/hyperv/iommu.c new file +3 -0
+		return;
+	}
+	status = hv_do_hypercall(HVCALL_DETACH_DEVICE_DOMAIN, input,

NULL); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_DETACH_DEVICE_DOMAIN failed, status

%lld\n", status); +

drivers/iommu/hyperv/iommu.c new file +6 -0
+	hv_flush_device_domain(hv_domain);
+
+	vdev->hv_domain = NULL;
+}
+
+static int hv_iommu_attach_dev(struct iommu_domain *domain, struct

device *dev,

drivers/iommu/hyperv/iommu.c new file +8 -0
+			       struct iommu_domain *old)
+{
+	u64 status;
+	unsigned long flags;
+	struct pci_dev *pdev;
+	struct hv_input_attach_device_domain *input;
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct hv_iommu_domain *hv_domain =

to_hv_iommu_domain(domain);

drivers/iommu/hyperv/iommu.c new file +22 -0
+	int ret;
+
+	/* Only allow PCI devices for now */
+	if (!dev_is_pci(dev))
+		return -EINVAL;
+
+	if (vdev->hv_domain == hv_domain)
+		return 0;
+
+	if (vdev->hv_domain)
+		hv_iommu_detach_dev(&vdev->hv_domain->domain, dev);
+
+	pdev = to_pci_dev(dev);
+	dev_dbg(dev, "attaching to domain %d\n",
+		hv_domain->device_domain.domain_id.id);
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	ret = hv_iommu_lookup_logical_dev_id(pdev,

&input->device_id.as_uint64);

drivers/iommu/hyperv/iommu.c new file +3 -0
+	if (ret) {
+		local_irq_restore(flags);
+		dev_err(&pdev->dev, "no IOMMU registration for vPCI

bus\n");

drivers/iommu/hyperv/iommu.c new file +3 -0
+		return ret;
+	}
+	status = hv_do_hypercall(HVCALL_ATTACH_DEVICE_DOMAIN, input,

NULL); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_ATTACH_DEVICE_DOMAIN failed, status

%lld\n", status);

drivers/iommu/hyperv/iommu.c new file +9 -0
+	else
+		vdev->hv_domain = hv_domain;
+
+	return hv_result_to_errno(status);
+}
+
+static int hv_iommu_get_logical_device_property(struct device *dev,
+					u32 code,
+					struct

hv_output_get_logical_device_property *property) +{

drivers/iommu/hyperv/iommu.c new file +10 -0
+	u64 status, lid;
+	unsigned long flags;
+	int ret;
+	struct hv_input_get_logical_device_property *input;
+	struct hv_output_get_logical_device_property *output;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	output = *this_cpu_ptr(hyperv_pcpu_input_arg) +

sizeof(*input);

drivers/iommu/hyperv/iommu.c new file +10 -0
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	ret = hv_iommu_lookup_logical_dev_id(to_pci_dev(dev), &lid);
+	if (ret) {
+		local_irq_restore(flags);
+		return ret;
+	}
+	input->logical_device_id = lid;
+	input->code = code;
+	status = hv_do_hypercall(HVCALL_GET_LOGICAL_DEVICE_PROPERTY,

input, output);

drivers/iommu/hyperv/iommu.c new file +6 -0
+	*property = *output;
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_GET_LOGICAL_DEVICE_PROPERTY failed,

status %lld\n", status); +

drivers/iommu/hyperv/iommu.c new file +8 -0
+	return hv_result_to_errno(status);
+}
+
+static struct iommu_device *hv_iommu_probe_device(struct device *dev)
+{
+	struct pci_dev *pdev;
+	struct hv_iommu_endpoint *vdev;
+	struct hv_output_get_logical_device_property

device_iommu_property = {0}; +

drivers/iommu/hyperv/iommu.c new file +7 -0
+	if (!dev_is_pci(dev))
+		return ERR_PTR(-ENODEV);
+
+	pdev = to_pci_dev(dev);
+
+	if (hv_iommu_get_logical_device_property(dev,
+

HV_LOGICAL_DEVICE_PROPERTY_PVIOMMU,
+
&device_iommu_property) ||

drivers/iommu/hyperv/iommu.c new file +1 -0
+	    !(device_iommu_property.device_iommu &

HV_DEVICE_IOMMU_ENABLED))

drivers/iommu/hyperv/iommu.c new file +13 -0
+		return ERR_PTR(-ENODEV);
+
+	vdev = kzalloc_obj(*vdev, GFP_KERNEL);
+	if (!vdev)
+		return ERR_PTR(-ENOMEM);
+
+	vdev->dev = dev;
+	vdev->hv_iommu = hv_iommu_device;
+	dev_iommu_priv_set(dev, vdev);
+
+	if (hv_iommu_ats_supported(hv_iommu_device->cap) &&
+	    pci_ats_supported(pdev))
+		pci_enable_ats(pdev,

__ffs(hv_iommu_device->pgsize_bitmap)); +

drivers/iommu/hyperv/iommu.c new file +3 -0
+	return &vdev->hv_iommu->iommu;
+}
+

drivers/iommu/hyperv/iommu.c line 376

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

I don't think this is necessary.

drivers/iommu/hyperv/iommu.c line 386

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+
+	kfree(vdev);
+}
+
+static struct iommu_group *hv_iommu_device_group(struct device *dev)
+{
+	if (dev_is_pci(dev))
+		return pci_device_group(dev);
+	else
+		return generic_device_group(dev);

non pci device already rejected during attach, maybe we should warn here?

        WARN_ON_ONCE(1);
        return generic_device_group(dev);
Quoted 17 lines
drivers/iommu/hyperv/iommu.c new file +3 -0
+}
+
+static int hv_configure_device_domain(struct hv_iommu_domain

*hv_domain, u32 domain_type) +{

drivers/iommu/hyperv/iommu.c new file +11 -0
+	u64 status;
+	unsigned long flags;
+	struct pt_iommu_x86_64_hw_info pt_info;
+	struct hv_input_configure_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	input->settings.flags.blocked = (domain_type ==

IOMMU_DOMAIN_BLOCKED);

drivers/iommu/hyperv/iommu.c new file +1 -0
+	input->settings.flags.translation_enabled = (domain_type !=
Quoted 1 line

IOMMU_DOMAIN_IDENTITY); +

Should this be:
input->settings.flags.translation_enabled =

     (domain_type & __IOMMU_DOMAIN_PAGING);

Otherwise, blocked domain will have translation enabled. Maybe add some explanation of what HV expects.

Quoted 466 lines
drivers/iommu/hyperv/iommu.c new file +2 -0
+	if (domain_type & __IOMMU_DOMAIN_PAGING) {
+		pt_iommu_x86_64_hw_info(&hv_domain->pt_iommu_x86_64,

&pt_info);

drivers/iommu/hyperv/iommu.c new file +5 -0
+		input->settings.page_table_root = pt_info.gcr3_pt;
+		input->settings.flags.first_stage_paging_mode =
+			pt_info.levels == 5;
+	}
+	status = hv_do_hypercall(HVCALL_CONFIGURE_DEVICE_DOMAIN,

input, NULL); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_CONFIGURE_DEVICE_DOMAIN failed,

status %lld\n", status); +

drivers/iommu/hyperv/iommu.c new file +12 -0
+	return hv_result_to_errno(status);
+}
+
+static int __init hv_initialize_static_domains(void)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+
+	/* Default stage-1 identity domain */
+	hv_domain = &hv_identity_domain;
+
+	ret = hv_create_device_domain(hv_domain,

HV_DEVICE_DOMAIN_TYPE_S1);

drivers/iommu/hyperv/iommu.c new file +4 -0
+	if (ret)
+		return ret;
+
+	ret = hv_configure_device_domain(hv_domain,

IOMMU_DOMAIN_IDENTITY);

drivers/iommu/hyperv/iommu.c new file +8 -0
+	if (ret)
+		goto delete_identity_domain;
+
+	hv_domain->domain.type = IOMMU_DOMAIN_IDENTITY;
+	hv_domain->domain.ops = &hv_iommu_identity_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap =

hv_iommu_device->pgsize_bitmap; +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	/* Default stage-1 blocked domain */
+	hv_domain = &hv_blocking_domain;
+
+	ret = hv_create_device_domain(hv_domain,

HV_DEVICE_DOMAIN_TYPE_S1);

drivers/iommu/hyperv/iommu.c new file +4 -0
+	if (ret)
+		goto delete_identity_domain;
+
+	ret = hv_configure_device_domain(hv_domain,

IOMMU_DOMAIN_BLOCKED);

drivers/iommu/hyperv/iommu.c new file +8 -0
+	if (ret)
+		goto delete_blocked_domain;
+
+	hv_domain->domain.type = IOMMU_DOMAIN_BLOCKED;
+	hv_domain->domain.ops = &hv_iommu_blocking_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap =

hv_iommu_device->pgsize_bitmap; +

drivers/iommu/hyperv/iommu.c new file +18 -0
+	return 0;
+
+delete_blocked_domain:
+	hv_delete_device_domain(&hv_blocking_domain);
+delete_identity_domain:
+	hv_delete_device_domain(&hv_identity_domain);
+	return ret;
+}
+
+#define INTERRUPT_RANGE_START	(0xfee00000)
+#define INTERRUPT_RANGE_END	(0xfeefffff)
+static void hv_iommu_get_resv_regions(struct device *dev,
+		struct list_head *head)
+{
+	struct iommu_resv_region *region;
+
+	region = iommu_alloc_resv_region(INTERRUPT_RANGE_START,
+				      INTERRUPT_RANGE_END -

INTERRUPT_RANGE_START + 1,

drivers/iommu/hyperv/iommu.c new file +14 -0
+				      0, IOMMU_RESV_MSI, GFP_KERNEL);
+	if (!region)
+		return;
+
+	list_add_tail(&region->list, head);
+}
+
+static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+}
+
+static void hv_iommu_iotlb_sync(struct iommu_domain *domain,
+				struct iommu_iotlb_gather

*iotlb_gather) +{

drivers/iommu/hyperv/iommu.c new file +8 -0
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+
+	iommu_put_pages_list(&iotlb_gather->freelist);
+}
+
+static void hv_iommu_paging_domain_free(struct iommu_domain *domain)
+{
+	struct hv_iommu_domain *hv_domain =

to_hv_iommu_domain(domain); +

drivers/iommu/hyperv/iommu.c new file +25 -0
+	/* Free all remaining mappings */
+	pt_iommu_deinit(&hv_domain->pt_iommu);
+
+	hv_delete_device_domain(hv_domain);
+
+	kfree(hv_domain);
+}
+
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops hv_iommu_paging_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+	IOMMU_PT_DOMAIN_OPS(x86_64),
+	.flush_iotlb_all = hv_iommu_flush_iotlb_all,
+	.iotlb_sync = hv_iommu_iotlb_sync,
+	.free = hv_iommu_paging_domain_free,
+};
+
+static struct iommu_domain *hv_iommu_domain_alloc_paging(struct

device *dev) +{

drivers/iommu/hyperv/iommu.c new file +9 -0
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+	struct pt_iommu_x86_64_cfg cfg = {};
+
+	hv_domain = kzalloc_obj(*hv_domain, GFP_KERNEL);
+	if (!hv_domain)
+		return ERR_PTR(-ENOMEM);
+
+	ret = hv_create_device_domain(hv_domain,

HV_DEVICE_DOMAIN_TYPE_S1);

drivers/iommu/hyperv/iommu.c new file +11 -0
+	if (ret) {
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->pt_iommu.nid = dev_to_node(dev);
+
+	cfg.common.hw_max_vasz_lg2 = hv_iommu_device->max_iova_width;
+	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.top_level = (hv_iommu_device->max_iova_width > 48) ? 4 :

3; +

drivers/iommu/hyperv/iommu.c new file +1 -0
+	ret = pt_iommu_x86_64_init(&hv_domain->pt_iommu_x86_64,

&cfg, GFP_KERNEL);

drivers/iommu/hyperv/iommu.c new file +8 -0
+	if (ret) {
+		hv_delete_device_domain(hv_domain);
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	/* Constrain to page sizes the hypervisor supports */
+	hv_domain->domain.pgsize_bitmap &=

hv_iommu_device->pgsize_bitmap; +

drivers/iommu/hyperv/iommu.c new file +3 -0
+	hv_domain->domain.ops = &hv_iommu_paging_domain_ops;
+
+	ret = hv_configure_device_domain(hv_domain,

__IOMMU_DOMAIN_PAGING);

drivers/iommu/hyperv/iommu.c new file +20 -0
+	if (ret) {
+		pt_iommu_deinit(&hv_domain->pt_iommu);
+		hv_delete_device_domain(hv_domain);
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	return &hv_domain->domain;
+}
+
+static struct iommu_ops hv_iommu_ops = {
+	.capable		  = hv_iommu_capable,
+	.domain_alloc_paging	  = hv_iommu_domain_alloc_paging,
+	.probe_device		  = hv_iommu_probe_device,
+	.release_device		  = hv_iommu_release_device,
+	.device_group		  = hv_iommu_device_group,
+	.get_resv_regions	  = hv_iommu_get_resv_regions,
+	.owner			  = THIS_MODULE,
+	.identity_domain	  = &hv_identity_domain.domain,
+	.blocked_domain		  =

&hv_blocking_domain.domain,

drivers/iommu/hyperv/iommu.c new file +1 -0
+	.release_domain		  =

&hv_blocking_domain.domain, +};

drivers/iommu/hyperv/iommu.c new file +2 -0
+
+static int hv_iommu_detect(struct hv_output_get_iommu_capabilities

*hv_iommu_cap) +{

drivers/iommu/hyperv/iommu.c new file +9 -0
+	u64 status;
+	unsigned long flags;
+	struct hv_input_get_iommu_capabilities *input;
+	struct hv_output_get_iommu_capabilities *output;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	output = *this_cpu_ptr(hyperv_pcpu_input_arg) +

sizeof(*input);

drivers/iommu/hyperv/iommu.c new file +3 -0
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	status = hv_do_hypercall(HVCALL_GET_IOMMU_CAPABILITIES,

input, output);

drivers/iommu/hyperv/iommu.c new file +6 -0
+	*hv_iommu_cap = *output;
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_GET_IOMMU_CAPABILITIES failed, status

%lld\n", status); +

drivers/iommu/hyperv/iommu.c new file +4 -0
+	return hv_result_to_errno(status);
+}
+
+static void __init hv_init_iommu_device(struct hv_iommu_dev

*hv_iommu,

drivers/iommu/hyperv/iommu.c new file +1 -0
+			struct hv_output_get_iommu_capabilities

*hv_iommu_cap) +{

drivers/iommu/hyperv/iommu.c new file +7 -0
+	ida_init(&hv_iommu->domain_ids);
+
+	hv_iommu->cap = hv_iommu_cap->iommu_cap;
+	hv_iommu->max_iova_width = hv_iommu_cap->max_iova_width;
+	if (!hv_iommu_5lvl_supported(hv_iommu->cap) &&
+	    hv_iommu->max_iova_width > 48) {
+		pr_info("5-level paging not supported, limiting iova

width to 48.\n");

drivers/iommu/hyperv/iommu.c new file +6 -0
+		hv_iommu->max_iova_width = 48;
+	}
+
+	hv_iommu->geometry = (struct iommu_domain_geometry) {
+		.aperture_start = 0,
+		.aperture_end = (((u64)1) <<

hv_iommu->max_iova_width) - 1,

drivers/iommu/hyperv/iommu.c new file +10 -0
+		.force_aperture = true,
+	};
+
+	hv_iommu->first_domain = HV_DEVICE_DOMAIN_ID_DEFAULT + 1;
+	hv_iommu->last_domain = HV_DEVICE_DOMAIN_ID_NULL - 1;
+	/* Only x86 page sizes (4K/2M/1G) are supported */
+	hv_iommu->pgsize_bitmap = hv_iommu_cap->pgsize_bitmap &
+				  (SZ_4K | SZ_2M | SZ_1G);
+	if (hv_iommu->pgsize_bitmap != hv_iommu_cap->pgsize_bitmap)
+		pr_warn("unsupported page sizes masked: 0x%llx ->

0x%llx\n",

drivers/iommu/hyperv/iommu.c new file +1 -0
+			hv_iommu_cap->pgsize_bitmap,

hv_iommu->pgsize_bitmap);

drivers/iommu/hyperv/iommu.c new file +2 -0
+	if (!hv_iommu->pgsize_bitmap) {
+		pr_warn("no supported page sizes, defaulting to

4K\n");

drivers/iommu/hyperv/iommu.c new file +20 -0
+		hv_iommu->pgsize_bitmap = SZ_4K;
+	}
+	hv_iommu_device = hv_iommu;
+}
+
+int __init hv_iommu_init(void)
+{
+	int ret = 0;
+	struct hv_iommu_dev *hv_iommu = NULL;
+	struct hv_output_get_iommu_capabilities hv_iommu_cap = {0};
+
+	if (no_iommu || iommu_detected)
+		return -ENODEV;
+
+	if (!hv_is_hyperv_initialized())
+		return -ENODEV;
+
+	ret = hv_iommu_detect(&hv_iommu_cap);
+	if (ret) {
+		pr_err("HVCALL_GET_IOMMU_CAPABILITIES failed: %d\n",

ret);

drivers/iommu/hyperv/iommu.c new file +6 -0
+		return -ENODEV;
+	}
+
+	if (!hv_iommu_present(hv_iommu_cap.iommu_cap) ||
+	    !hv_iommu_s1_domain_supported(hv_iommu_cap.iommu_cap)) {
+		pr_err("IOMMU capabilities not sufficient:

cap=0x%llx\n",

drivers/iommu/hyperv/iommu.c new file +20 -0
+		       hv_iommu_cap.iommu_cap);
+		return -ENODEV;
+	}
+
+	iommu_detected = 1;
+	pci_request_acs();
+
+	hv_iommu = kzalloc_obj(*hv_iommu, GFP_KERNEL);
+	if (!hv_iommu)
+		return -ENOMEM;
+
+	hv_init_iommu_device(hv_iommu, &hv_iommu_cap);
+
+	ret = hv_initialize_static_domains();
+	if (ret) {
+		pr_err("static domains init failed: %d\n", ret);
+		goto err_free;
+	}
+
+	ret = iommu_device_sysfs_add(&hv_iommu->iommu, NULL, NULL,

"%s", "hv-iommu");

drivers/iommu/hyperv/iommu.c new file +6 -0
+	if (ret) {
+		pr_err("iommu_device_sysfs_add failed: %d\n", ret);
+		goto err_delete_static_domains;
+	}
+
+	ret = iommu_device_register(&hv_iommu->iommu, &hv_iommu_ops,

NULL);

drivers/iommu/hyperv/iommu.c new file +17 -0
+	if (ret) {
+		pr_err("iommu_device_register failed: %d\n", ret);
+		goto err_sysfs_remove;
+	}
+
+	pr_info("successfully initialized\n");
+	return 0;
+
+err_sysfs_remove:
+	iommu_device_sysfs_remove(&hv_iommu->iommu);
+err_delete_static_domains:
+	hv_delete_device_domain(&hv_blocking_domain);
+	hv_delete_device_domain(&hv_identity_domain);
+err_free:
+	kfree(hv_iommu);
+	return ret;
+}
(quoted diff) +0 -0

b/drivers/iommu/hyperv/iommu.h new file mode 100644 index 000000000000..43f20d371245

drivers/iommu/hyperv/iommu.h new file +54 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Hyper-V IOMMU driver.
+ *
+ * Copyright (C) 2024-2025, Microsoft, Inc.
+ *
+ */
+
+#ifndef _HYPERV_IOMMU_H
+#define _HYPERV_IOMMU_H
+
+struct hv_iommu_dev {
+	struct iommu_device iommu;
+	struct ida domain_ids;
+
+	/* Device configuration */
+	u8  max_iova_width;
+	u8  max_pasid_width;
+	u64 cap;
+	u64 pgsize_bitmap;
+
+	struct iommu_domain_geometry geometry;
+	u64 first_domain;
+	u64 last_domain;
+};
+
+struct hv_iommu_domain {
+	union {
+		struct iommu_domain    domain;
+		struct pt_iommu        pt_iommu;
+		struct pt_iommu_x86_64 pt_iommu_x86_64;
+	};
+	struct hv_iommu_dev *hv_iommu;
+	struct hv_input_device_domain device_domain;
+	u64		pgsize_bitmap;
+};
+
+struct hv_pci_busdata {
+	int               pci_domain_nr;
+	u32               logical_dev_id_prefix;
+	struct list_head  list;
+};
+
+struct hv_iommu_endpoint {
+	struct device *dev;
+	struct hv_iommu_dev *hv_iommu;
+	struct hv_iommu_domain *hv_domain;
+};
+
+#define to_hv_iommu_domain(d) \
+	container_of(d, struct hv_iommu_domain, domain)
+
+#endif /* _HYPERV_IOMMU_H */
(quoted diff) +0 -0

b/drivers/pci/controller/pci-hyperv.c index cfc8fa403dad..a4af9c8c2220 100644 --- a/drivers/pci/controller/pci-hyperv.c +++ b/drivers/pci/controller/pci-hyperv.c @@ -3715,6 +3715,7 @@ static int hv_pci_probe(struct hv_device *hdev, struct hv_pcibus_device *hbus; int ret, dom;

drivers/pci/controller/pci-hyperv.c +18 -1
 	u16 dom_req;
+	u32 prefix;
 	char *name;
 
 	bridge = devm_pci_alloc_host_bridge(&hdev->device, 0);
@@ -3857,13 +3858,25 @@ static int hv_pci_probe(struct hv_device
 *hdev, 
 	hbus->state = hv_pcibus_probed;
 
-	ret = create_root_hv_pci_bus(hbus);
+	/* Notify pvIOMMU before any device on the bus is scanned. */
+	prefix = (hdev->dev_instance.b[5] << 24) |
+		 (hdev->dev_instance.b[4] << 16) |
+		 (hdev->dev_instance.b[7] <<  8) |
+		 (hdev->dev_instance.b[6] & 0xf8);
+
+	ret = hv_iommu_register_pci_bus(dom, prefix);
 	if (ret)
 		goto free_windows;
 
+	ret = create_root_hv_pci_bus(hbus);
+	if (ret)
+		goto unregister_pviommu;
+
 	mutex_unlock(&hbus->state_lock);
 	return 0;
 
+unregister_pviommu:
+	hv_iommu_unregister_pci_bus(dom);
 free_windows:
 	hv_pci_free_bridge_windows(hbus);
 exit_d0:
@@ -3974,8 +3987,10 @@ static int hv_pci_bus_exit(struct hv_device
 *hdev, bool keep_devs) static void hv_pci_remove(struct hv_device
 *hdev) {
 	struct hv_pcibus_device *hbus;
+	int dom;
 
 	hbus = hv_get_drvdata(hdev);
+	dom = hbus->bridge->domain_nr;
 	if (hbus->state == hv_pcibus_installed) {
 		tasklet_disable(&hdev->channel->callback_event);
 		hbus->state = hv_pcibus_removing;
@@ -3994,6 +4009,8 @@ static void hv_pci_remove(struct hv_device
 *hdev) hv_pci_remove_slots(hbus);
 		pci_remove_root_bus(hbus->bridge->bus);
 		pci_unlock_rescan_remove();
+
+		hv_iommu_unregister_pci_bus(dom);
 	}
 
 	hv_pci_bus_exit(hdev, false);
(quoted diff) +0 -0

b/include/asm-generic/mshyperv.h index bf601d67cecb..b71345c74568 100644 --- a/include/asm-generic/mshyperv.h
+++ b/include/asm-generic/mshyperv.h

include/asm-generic/mshyperv.h +2 -0
@@ -73,6 +73,18 @@ extern enum hv_partition_type
 hv_curr_partition_type; extern void * __percpu *hyperv_pcpu_input_arg;
 extern void * __percpu *hyperv_pcpu_output_arg;
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+int  hv_iommu_register_pci_bus(int pci_domain_nr, u32

logical_dev_id_prefix); +void hv_iommu_unregister_pci_bus(int pci_domain_nr); +#else

(quoted diff) +2 -0
+static inline int hv_iommu_register_pci_bus(int pci_domain_nr,
+					    u32

logical_dev_id_prefix) +{

include/asm-generic/mshyperv.h +5 -0
+	return 0;
+}
+static inline void hv_iommu_unregister_pci_bus(int pci_domain_nr) { }
+#endif
+
 u64 hv_do_hypercall(u64 control, void *inputaddr, void *outputaddr);
 u64 hv_do_fast_hypercall8(u16 control, u64 input8);
 u64 hv_do_fast_hypercall16(u16 control, u64 input1, u64 input2);
author
#10 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

[...]

Quoted 22 lines
Quoted 7 lines
(quoted diff) +0 -0

b/drivers/iommu/hyperv/Kconfig index 30f40d867036..9e658d5c9a77 100644

drivers/iommu/hyperv/Kconfig +0 -0
@@ -8,3 +8,20 @@ config HYPERV_IOMMU
 	help
 	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux

drivers/iommu/hyperv/Kconfig config HYPERV_IOMMU · line 19

Quoted 10 lines
drivers/iommu/hyperv/Kconfig +9 -0
 	  guest and root partitions.
+
+if HYPERV_IOMMU
+config HYPERV_PVIOMMU
+	bool "Microsoft Hypervisor para-virtualized IOMMU support"
+	depends on X86 && HYPERV
+	select IOMMU_API
+	select GENERIC_PT
+	select IOMMU_PT
+	select IOMMU_PT_X86_64

nit:
If HYPERV_PVIOMMU is enabled on a (hypothetical) platform with GENERIC_ATOMIC64=y, the select would force-enable IOMMU_PT_X86_64 even though its depends on is unsatisfied — leading to a build failure.

Quoted 6 lines

In practice this can't happen today because HYPERV_PVIOMMU already depends on X86 && HYPERV, and x86 never sets GENERIC_ATOMIC64. But adding the explicit guard is more defensive.
i.e.
depends on !GENERIC_ATOMIC64 # for cmpxchg64 in IOMMU_PT

Good point. Will add "depends on !GENERIC_ATOMIC64".

[...]

Quoted 9 lines
Quoted 9 lines
drivers/iommu/hyperv/Kconfig +3 -0
+
+/*
+ * Look up the logical device ID for a vPCI device. Returns 0 on

success
+ * with *logical_id filled in; -ENODEV if no entry registered for this
+ * device's vPCI bus.
+ */
+static int hv_iommu_lookup_logical_dev_id(struct pci_dev *pdev, u64

Quoted 9 lines

drivers/iommu/hyperv/Kconfig

Quoted 6 lines

*logical_id) +{

drivers/iommu/hyperv/Kconfig +5 -0
+	struct hv_pci_busdata *bus;
+	int domain = pci_domain_nr(pdev->bus);
+	int ret = -ENODEV;
+
+	spin_lock(&hv_iommu_pci_bus_lock);

this is called under local_irq_save, should use raw_spinlock_t for RT kernel?

Yes, this is problematic on PREEMPT_RT. Michael also suggested hoisting the lookup before the local_irq_save() section instead of using a raw spinlock, which I think is a great idea - all 3 call sites (detach_dev, attach_dev, get_logical_device_property) will be changed.

Quoted 13 lines
Quoted 13 lines
drivers/iommu/hyperv/Kconfig +3 -0
+	list_for_each_entry(bus, &hv_iommu_pci_bus_list, list) {
+		if (bus->pci_domain_nr == domain) {
+			*logical_id =

(u64)bus->logical_dev_id_prefix |

drivers/iommu/hyperv/Kconfig +9 -0
+				      PCI_FUNC(pdev->devfn);
+			ret = 0;
+			break;
+		}
+	}
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	return ret;
+}
+

[...]

Quoted 12 lines

drivers/iommu/hyperv/Kconfig

Quoted 10 lines
drivers/iommu/hyperv/Kconfig +10 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

I don't think this is necessary.

Oh, yes. Thanks!

Quoted 12 lines

drivers/iommu/hyperv/Kconfig

Quoted 10 lines
drivers/iommu/hyperv/Kconfig +10 -0
+
+	kfree(vdev);
+}
+
+static struct iommu_group *hv_iommu_device_group(struct device *dev)
+{
+	if (dev_is_pci(dev))
+		return pci_device_group(dev);
+	else
+		return generic_device_group(dev);

non pci device already rejected during attach, maybe we should warn here?

Quoted 3 lines
        WARN_ON_ONCE(1);
        return generic_device_group(dev);

Good idea. Will add WARN_ON_ONCE(1).

Quoted 20 lines
Quoted 17 lines
drivers/iommu/hyperv/Kconfig +3 -0
+}
+
+static int hv_configure_device_domain(struct hv_iommu_domain

*hv_domain, u32 domain_type) +{

drivers/iommu/hyperv/Kconfig +11 -0
+	u64 status;
+	unsigned long flags;
+	struct pt_iommu_x86_64_hw_info pt_info;
+	struct hv_input_configure_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	input->settings.flags.blocked = (domain_type ==

IOMMU_DOMAIN_BLOCKED);

drivers/iommu/hyperv/Kconfig +1 -0
+	input->settings.flags.translation_enabled = (domain_type !=
Quoted 1 line

IOMMU_DOMAIN_IDENTITY); +

Should this be:
input->settings.flags.translation_enabled =

Quoted 4 lines
     (domain_type & __IOMMU_DOMAIN_PAGING);

Otherwise, blocked domain will have translation enabled. Maybe add some explanation of what HV expects.

I do agree this is not intuitive, but current hypervisor implementation requires "blocked == 1" to be paired with "translation_enabled = 1", otherwise it returns HV_STATUS_INVALID_PARAMETER. But I can add some comment at least.

Thanks for the thorough review, Jacob!

B.R.
Yu

#11 lore raw

RE: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

In reply to Yu Zhang

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 21 lines

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Quoted 5 lines

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

As you are probably aware, Mukesh's patch series to support PCI pass-thru devices also needs to get the logical device ID. Maybe the registration mechanism needs to move somewhere that can be shared with his code.

Quoted 54 lines
---
 arch/x86/hyperv/hv_init.c           |   4 +
 arch/x86/include/asm/mshyperv.h     |   4 +
 drivers/iommu/hyperv/Kconfig        |  17 +
 drivers/iommu/hyperv/Makefile       |   1 +
 drivers/iommu/hyperv/iommu.c        | 705 ++++++++++++++++++++++++++++
 drivers/iommu/hyperv/iommu.h        |  54 +++
 drivers/pci/controller/pci-hyperv.c |  19 +-
 include/asm-generic/mshyperv.h      |  12 +
 8 files changed, 815 insertions(+), 1 deletion(-)
 create mode 100644 drivers/iommu/hyperv/iommu.c
 create mode 100644 drivers/iommu/hyperv/iommu.h
arch/x86/hyperv/hv_init.c +4 -0
index 323adc93f2dc..2c8ff8e06249 100644
@@ -578,6 +578,10 @@ void __init hyperv_init(void)
 	old_setup_percpu_clockev = x86_init.timers.setup_percpu_clockev;
 	x86_init.timers.setup_percpu_clockev = hv_stimer_setup_percpu_clockev;
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+	x86_init.iommu.iommu_init = hv_iommu_init;
+#endif
+
 	hv_apic_init();
 
 	x86_init.pci.arch_init = hv_pci_init;
arch/x86/include/asm/mshyperv.h +4 -0
index f64393e853ee..20d947c2c758 100644
@@ -313,6 +313,10 @@ static inline void mshv_vtl_return_hypercall(void) {}
 static inline void __mshv_vtl_return_call(struct mshv_vtl_cpu_context *vtl0) {}
 #endif
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+int __init hv_iommu_init(void);
+#endif
+
 #include <asm-generic/mshyperv.h>
 
 #endif
drivers/iommu/hyperv/Kconfig +0 -0
index 30f40d867036..9e658d5c9a77 100644

drivers/iommu/hyperv/Kconfig config HYPERV_IOMMU · line 15

Quoted 8 lines
drivers/iommu/hyperv/Kconfig +5 -0
@@ -8,3 +8,20 @@ config HYPERV_IOMMU
 	help
 	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux
 	  guest and root partitions.
+
+if HYPERV_IOMMU
+config HYPERV_PVIOMMU
+	bool "Microsoft Hypervisor para-virtualized IOMMU support"
+	depends on X86 && HYPERV

What is the intent w.r.t. 32-bit builds? Using X86 instead of X86_64 allows it. I did a 32-bit build and didn't get any build failures, which is good. But I can't run it to see if the pvIOMMU actually works in a 32-bit build. I don't know how building X86_64 generic PT entries would fare.

Quoted 221 lines
drivers/iommu/hyperv/Kconfig +12 -0
+	select IOMMU_API
+	select GENERIC_PT
+	select IOMMU_PT
+	select IOMMU_PT_X86_64
+	select IOMMU_IOVA
+	default HYPERV
+	help
+	  Para-virtualized IOMMU driver for Linux guests running on
+	  Microsoft Hyper-V. Provides DMA remapping and IOTLB
+	  flush support to enable DMA isolation for devices
+	  assigned to the guest.
+endif
drivers/iommu/hyperv/Makefile +1 -0
index 9f557bad94ff..8669741c0a51 100644
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_HYPERV_IOMMU) += irq_remapping.o
+obj-$(CONFIG_HYPERV_PVIOMMU) += iommu.o
drivers/iommu/hyperv/iommu.c new file +195 -0
new file mode 100644
index 000000000000..e5fc625314b5
@@ -0,0 +1,705 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Hyper-V IOMMU driver.
+ *
+ * Copyright (C) 2019, 2024-2026 Microsoft, Inc.
+ */
+
+#define pr_fmt(fmt) "Hyper-V pvIOMMU: " fmt
+#define dev_fmt(fmt) pr_fmt(fmt)
+
+#include <linux/iommu.h>
+#include <linux/pci.h>
+#include <linux/dma-map-ops.h>
+#include <linux/generic_pt/iommu.h>
+#include <linux/pci-ats.h>
+
+#include <asm/iommu.h>
+#include <asm/hypervisor.h>
+#include <asm/mshyperv.h>
+
+#include "iommu.h"
+#include "../iommu-pages.h"
+
+struct hv_iommu_dev *hv_iommu_device;
+
+/*
+ * Identity and blocking domains are static singletons: identity is a 1:1
+ * passthrough with no page table, blocking rejects all DMA. Neither holds
+ * per-IOMMU state, so one instance suffices even with multiple vIOMMUs.
+ */
+static struct hv_iommu_domain hv_identity_domain;
+static struct hv_iommu_domain hv_blocking_domain;
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops;
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops;
+static struct iommu_ops hv_iommu_ops;
+static LIST_HEAD(hv_iommu_pci_bus_list);
+static DEFINE_SPINLOCK(hv_iommu_pci_bus_lock);
+
+#define hv_iommu_present(iommu_cap) (iommu_cap & HV_IOMMU_CAP_PRESENT)
+#define hv_iommu_s1_domain_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1)
+#define hv_iommu_5lvl_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1_5LVL)
+#define hv_iommu_ats_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_ATS)
+
+int hv_iommu_register_pci_bus(int pci_domain_nr, u32 logical_dev_id_prefix)
+{
+	struct hv_pci_busdata *bus, *new;
+	int ret = 0;
+
+	if (no_iommu || !iommu_detected)
+		return 0;
+
+	new = kzalloc_obj(*new, GFP_KERNEL);
+	if (!new)
+		return -ENOMEM;
+
+	spin_lock(&hv_iommu_pci_bus_lock);
+	list_for_each_entry(bus, &hv_iommu_pci_bus_list, list) {
+		if (bus->pci_domain_nr != pci_domain_nr)
+			continue;
+
+		if (bus->logical_dev_id_prefix != logical_dev_id_prefix) {
+			pr_err("stale registration for PCI domain %d (old prefix 0x%08x, new 0x%08x)\n",
+			       pci_domain_nr, bus->logical_dev_id_prefix,
+			       logical_dev_id_prefix);
+			ret = -EEXIST;
+		}
+
+		goto out_free;
+	}
+
+	new->pci_domain_nr = pci_domain_nr;
+	new->logical_dev_id_prefix = logical_dev_id_prefix;
+	list_add(&new->list, &hv_iommu_pci_bus_list);
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	return 0;
+
+out_free:
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	kfree(new);
+	return ret;
+}
+EXPORT_SYMBOL_FOR_MODULES(hv_iommu_register_pci_bus, "pci-hyperv");
+
+void hv_iommu_unregister_pci_bus(int pci_domain_nr)
+{
+	struct hv_pci_busdata *bus, *tmp;
+
+	spin_lock(&hv_iommu_pci_bus_lock);
+	list_for_each_entry_safe(bus, tmp, &hv_iommu_pci_bus_list, list) {
+		if (bus->pci_domain_nr == pci_domain_nr) {
+			list_del(&bus->list);
+			kfree(bus);
+			break;
+		}
+	}
+	spin_unlock(&hv_iommu_pci_bus_lock);
+}
+EXPORT_SYMBOL_FOR_MODULES(hv_iommu_unregister_pci_bus, "pci-hyperv");
+
+/*
+ * Look up the logical device ID for a vPCI device. Returns 0 on success
+ * with *logical_id filled in; -ENODEV if no entry registered for this
+ * device's vPCI bus.
+ */
+static int hv_iommu_lookup_logical_dev_id(struct pci_dev *pdev, u64 *logical_id)
+{
+	struct hv_pci_busdata *bus;
+	int domain = pci_domain_nr(pdev->bus);
+	int ret = -ENODEV;
+
+	spin_lock(&hv_iommu_pci_bus_lock);
+	list_for_each_entry(bus, &hv_iommu_pci_bus_list, list) {
+		if (bus->pci_domain_nr == domain) {
+			*logical_id = (u64)bus->logical_dev_id_prefix |
+				      PCI_FUNC(pdev->devfn);
+			ret = 0;
+			break;
+		}
+	}
+	spin_unlock(&hv_iommu_pci_bus_lock);
+	return ret;
+}
+
+static int hv_create_device_domain(struct hv_iommu_domain *hv_domain, u32 domain_stage)
+{
+	int ret;
+	u64 status;
+	unsigned long flags;
+	struct hv_input_create_device_domain *input;
+
+	ret = ida_alloc_range(&hv_iommu_device->domain_ids,
+			hv_iommu_device->first_domain, hv_iommu_device->last_domain,
+			GFP_KERNEL);
+	if (ret < 0)
+		return ret;
+
+	hv_domain->device_domain.partition_id = HV_PARTITION_ID_SELF;
+	hv_domain->device_domain.domain_id.type = domain_stage;
+	hv_domain->device_domain.domain_id.id = ret;
+	hv_domain->hv_iommu = hv_iommu_device;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	input->create_device_domain_flags.forward_progress_required = 1;
+	input->create_device_domain_flags.inherit_owning_vtl = 0;
+	status = hv_do_hypercall(HVCALL_CREATE_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status)) {
+		pr_err("HVCALL_CREATE_DEVICE_DOMAIN failed, status %lld\n", status);
+		ida_free(&hv_iommu_device->domain_ids, hv_domain->device_domain.domain_id.id);
+	}
+
+	return hv_result_to_errno(status);
+}
+
+static void hv_delete_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_delete_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	status = hv_do_hypercall(HVCALL_DELETE_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_DELETE_DEVICE_DOMAIN failed, status %lld\n", status);
+
+	ida_free(&hv_domain->hv_iommu->domain_ids, hv_domain->device_domain.domain_id.id);
+}
+
+static bool hv_iommu_capable(struct device *dev, enum iommu_cap cap)
+{
+	switch (cap) {
+	case IOMMU_CAP_CACHE_COHERENCY:
+		return true;
+	case IOMMU_CAP_DEFERRED_FLUSH:
+		return true;
+	default:
+		return false;
+	}
+}
+
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)

drivers/iommu/hyperv/iommu.c line 205

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;

The previous version of this patch had code to set several other fields in the input. I wanted to confirm that not setting them in this version is intentional. Were they not needed?

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+	status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN failed, status %lld\n", status);
+}
+
+static void hv_iommu_detach_dev(struct iommu_domain *domain, struct device *dev)
+{

drivers/iommu/hyperv/iommu.c line 225

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+	u64 status;
+	unsigned long flags;
+	struct hv_input_detach_device_domain *input;
+	struct pci_dev *pdev;
+	struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain);
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+
+	/* See the attach function, only PCI devices for now */
+	if (!dev_is_pci(dev) || vdev->hv_domain != hv_domain)
+		return;

Are these sanity checks necessary? The only caller is hv_iommu_attach_dev() and it has already done the checks.

drivers/iommu/hyperv/iommu.c line 236

Quoted 11 lines
drivers/iommu/hyperv/iommu.c new file +11 -0
+
+	pdev = to_pci_dev(dev);
+
+	dev_dbg(dev, "detaching from domain %d\n", hv_domain->device_domain.domain_id.id);
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	if (hv_iommu_lookup_logical_dev_id(pdev, &input->device_id.as_uint64)) {

As Sashiko and Jacob Pan pointed out, doing the lookup while interrupts are disabled is problematic. My suggestion would be to just do the lookup into a local variable before disabling interrupts (rather than using a raw spin lock as Jacob suggested).

Same situation occurs in hv_iommu_attach_dev() and hv_iommu_get_logical_device_property().

Quoted 68 lines
drivers/iommu/hyperv/iommu.c new file +68 -0
+		local_irq_restore(flags);
+		dev_warn(&pdev->dev, "no IOMMU registration for vPCI bus on detach\n");
+		return;
+	}
+	status = hv_do_hypercall(HVCALL_DETACH_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_DETACH_DEVICE_DOMAIN failed, status %lld\n", status);
+
+	hv_flush_device_domain(hv_domain);
+
+	vdev->hv_domain = NULL;
+}
+
+static int hv_iommu_attach_dev(struct iommu_domain *domain, struct device *dev,
+			       struct iommu_domain *old)
+{
+	u64 status;
+	unsigned long flags;
+	struct pci_dev *pdev;
+	struct hv_input_attach_device_domain *input;
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain);
+	int ret;
+
+	/* Only allow PCI devices for now */
+	if (!dev_is_pci(dev))
+		return -EINVAL;
+
+	if (vdev->hv_domain == hv_domain)
+		return 0;
+
+	if (vdev->hv_domain)
+		hv_iommu_detach_dev(&vdev->hv_domain->domain, dev);
+
+	pdev = to_pci_dev(dev);
+	dev_dbg(dev, "attaching to domain %d\n",
+		hv_domain->device_domain.domain_id.id);
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	ret = hv_iommu_lookup_logical_dev_id(pdev, &input->device_id.as_uint64);
+	if (ret) {
+		local_irq_restore(flags);
+		dev_err(&pdev->dev, "no IOMMU registration for vPCI bus\n");
+		return ret;
+	}
+	status = hv_do_hypercall(HVCALL_ATTACH_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_ATTACH_DEVICE_DOMAIN failed, status %lld\n", status);
+	else
+		vdev->hv_domain = hv_domain;
+
+	return hv_result_to_errno(status);
+}
+
+static int hv_iommu_get_logical_device_property(struct device *dev,
+					u32 code,
+					struct hv_output_get_logical_device_property *property)
+{

drivers/iommu/hyperv/iommu.c line 314

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+	u64 status, lid;
+	unsigned long flags;
+	int ret;
+	struct hv_input_get_logical_device_property *input;
+	struct hv_output_get_logical_device_property *output;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	output = *this_cpu_ptr(hyperv_pcpu_input_arg) + sizeof(*input);

Nit: The other way to set output is:

	output = input + 1;

I think this produces slightly better code because of not needing to reference the per-cpu variable hyperv_pcpu_input_arg a 2nd time.

Quoted 52 lines
drivers/iommu/hyperv/iommu.c new file +52 -0
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	ret = hv_iommu_lookup_logical_dev_id(to_pci_dev(dev), &lid);
+	if (ret) {
+		local_irq_restore(flags);
+		return ret;
+	}
+	input->logical_device_id = lid;
+	input->code = code;
+	status = hv_do_hypercall(HVCALL_GET_LOGICAL_DEVICE_PROPERTY, input, output);
+	*property = *output;
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_GET_LOGICAL_DEVICE_PROPERTY failed, status %lld\n", status);
+
+	return hv_result_to_errno(status);
+}
+
+static struct iommu_device *hv_iommu_probe_device(struct device *dev)
+{
+	struct pci_dev *pdev;
+	struct hv_iommu_endpoint *vdev;
+	struct hv_output_get_logical_device_property device_iommu_property = {0};
+
+	if (!dev_is_pci(dev))
+		return ERR_PTR(-ENODEV);
+
+	pdev = to_pci_dev(dev);
+
+	if (hv_iommu_get_logical_device_property(dev,
+						 HV_LOGICAL_DEVICE_PROPERTY_PVIOMMU,
+						 &device_iommu_property) ||
+	    !(device_iommu_property.device_iommu & HV_DEVICE_IOMMU_ENABLED))
+		return ERR_PTR(-ENODEV);
+
+	vdev = kzalloc_obj(*vdev, GFP_KERNEL);
+	if (!vdev)
+		return ERR_PTR(-ENOMEM);
+
+	vdev->dev = dev;
+	vdev->hv_iommu = hv_iommu_device;
+	dev_iommu_priv_set(dev, vdev);
+
+	if (hv_iommu_ats_supported(hv_iommu_device->cap) &&
+	    pci_ats_supported(pdev))
+		pci_enable_ats(pdev, __ffs(hv_iommu_device->pgsize_bitmap));
+
+	return &vdev->hv_iommu->iommu;
+}
+

drivers/iommu/hyperv/iommu.c line 376

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

Quoted 182 lines
drivers/iommu/hyperv/iommu.c new file +182 -0
+
+	kfree(vdev);
+}
+
+static struct iommu_group *hv_iommu_device_group(struct device *dev)
+{
+	if (dev_is_pci(dev))
+		return pci_device_group(dev);
+	else
+		return generic_device_group(dev);
+}
+
+static int hv_configure_device_domain(struct hv_iommu_domain *hv_domain, u32 domain_type)
+{
+	u64 status;
+	unsigned long flags;
+	struct pt_iommu_x86_64_hw_info pt_info;
+	struct hv_input_configure_device_domain *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;
+	input->settings.flags.blocked = (domain_type == IOMMU_DOMAIN_BLOCKED);
+	input->settings.flags.translation_enabled = (domain_type != IOMMU_DOMAIN_IDENTITY);
+
+	if (domain_type & __IOMMU_DOMAIN_PAGING) {
+		pt_iommu_x86_64_hw_info(&hv_domain->pt_iommu_x86_64, &pt_info);
+		input->settings.page_table_root = pt_info.gcr3_pt;
+		input->settings.flags.first_stage_paging_mode =
+			pt_info.levels == 5;
+	}
+	status = hv_do_hypercall(HVCALL_CONFIGURE_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_CONFIGURE_DEVICE_DOMAIN failed, status %lld\n", status);
+
+	return hv_result_to_errno(status);
+}
+
+static int __init hv_initialize_static_domains(void)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+
+	/* Default stage-1 identity domain */
+	hv_domain = &hv_identity_domain;
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret)
+		return ret;
+
+	ret = hv_configure_device_domain(hv_domain, IOMMU_DOMAIN_IDENTITY);
+	if (ret)
+		goto delete_identity_domain;
+
+	hv_domain->domain.type = IOMMU_DOMAIN_IDENTITY;
+	hv_domain->domain.ops = &hv_iommu_identity_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap = hv_iommu_device->pgsize_bitmap;
+
+	/* Default stage-1 blocked domain */
+	hv_domain = &hv_blocking_domain;
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret)
+		goto delete_identity_domain;
+
+	ret = hv_configure_device_domain(hv_domain, IOMMU_DOMAIN_BLOCKED);
+	if (ret)
+		goto delete_blocked_domain;
+
+	hv_domain->domain.type = IOMMU_DOMAIN_BLOCKED;
+	hv_domain->domain.ops = &hv_iommu_blocking_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap = hv_iommu_device->pgsize_bitmap;
+
+	return 0;
+
+delete_blocked_domain:
+	hv_delete_device_domain(&hv_blocking_domain);
+delete_identity_domain:
+	hv_delete_device_domain(&hv_identity_domain);
+	return ret;
+}
+
+#define INTERRUPT_RANGE_START	(0xfee00000)
+#define INTERRUPT_RANGE_END	(0xfeefffff)
+static void hv_iommu_get_resv_regions(struct device *dev,
+		struct list_head *head)
+{
+	struct iommu_resv_region *region;
+
+	region = iommu_alloc_resv_region(INTERRUPT_RANGE_START,
+				      INTERRUPT_RANGE_END - INTERRUPT_RANGE_START + 1,
+				      0, IOMMU_RESV_MSI, GFP_KERNEL);
+	if (!region)
+		return;
+
+	list_add_tail(&region->list, head);
+}
+
+static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+}
+
+static void hv_iommu_iotlb_sync(struct iommu_domain *domain,
+				struct iommu_iotlb_gather *iotlb_gather)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+
+	iommu_put_pages_list(&iotlb_gather->freelist);
+}
+
+static void hv_iommu_paging_domain_free(struct iommu_domain *domain)
+{
+	struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain);
+
+	/* Free all remaining mappings */
+	pt_iommu_deinit(&hv_domain->pt_iommu);
+
+	hv_delete_device_domain(hv_domain);
+
+	kfree(hv_domain);
+}
+
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops hv_iommu_paging_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+	IOMMU_PT_DOMAIN_OPS(x86_64),
+	.flush_iotlb_all = hv_iommu_flush_iotlb_all,
+	.iotlb_sync = hv_iommu_iotlb_sync,
+	.free = hv_iommu_paging_domain_free,
+};
+
+static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+	struct pt_iommu_x86_64_cfg cfg = {};
+
+	hv_domain = kzalloc_obj(*hv_domain, GFP_KERNEL);
+	if (!hv_domain)
+		return ERR_PTR(-ENOMEM);
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret) {
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->pt_iommu.nid = dev_to_node(dev);
+
+	cfg.common.hw_max_vasz_lg2 = hv_iommu_device->max_iova_width;
+	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.top_level = (hv_iommu_device->max_iova_width > 48) ? 4 : 3;
+
+	ret = pt_iommu_x86_64_init(&hv_domain->pt_iommu_x86_64, &cfg, GFP_KERNEL);
+	if (ret) {
+		hv_delete_device_domain(hv_domain);
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	/* Constrain to page sizes the hypervisor supports */
+	hv_domain->domain.pgsize_bitmap &= hv_iommu_device->pgsize_bitmap;
+
+	hv_domain->domain.ops = &hv_iommu_paging_domain_ops;

drivers/iommu/hyperv/iommu.c line 568

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+
+	ret = hv_configure_device_domain(hv_domain, __IOMMU_DOMAIN_PAGING);
+	if (ret) {
+		pt_iommu_deinit(&hv_domain->pt_iommu);
+		hv_delete_device_domain(hv_domain);
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	return &hv_domain->domain;

I think this function would be better if the error paths did "goto" a cascading set of error labels. That's the typical pattern, and it's what you use in hv_iommu_init(), for example.

Quoted 16 lines
drivers/iommu/hyperv/iommu.c new file +16 -0
+}
+
+static struct iommu_ops hv_iommu_ops = {
+	.capable		  = hv_iommu_capable,
+	.domain_alloc_paging	  = hv_iommu_domain_alloc_paging,
+	.probe_device		  = hv_iommu_probe_device,
+	.release_device		  = hv_iommu_release_device,
+	.device_group		  = hv_iommu_device_group,
+	.get_resv_regions	  = hv_iommu_get_resv_regions,
+	.owner			  = THIS_MODULE,
+	.identity_domain	  = &hv_identity_domain.domain,
+	.blocked_domain		  = &hv_blocking_domain.domain,
+	.release_domain		  = &hv_blocking_domain.domain,
+};
+
+static int hv_iommu_detect(struct hv_output_get_iommu_capabilities *hv_iommu_cap)

drivers/iommu/hyperv/iommu.c line 594

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_get_iommu_capabilities *input;
+	struct hv_output_get_iommu_capabilities *output;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	output = *this_cpu_ptr(hyperv_pcpu_input_arg) + sizeof(*input);

Potentially use "output = input + 1" here as well.

Quoted 184 lines
drivers/iommu/hyperv/iommu.c new file +111 -0
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	status = hv_do_hypercall(HVCALL_GET_IOMMU_CAPABILITIES, input, output);
+	*hv_iommu_cap = *output;
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_GET_IOMMU_CAPABILITIES failed, status %lld\n", status);
+
+	return hv_result_to_errno(status);
+}
+
+static void __init hv_init_iommu_device(struct hv_iommu_dev *hv_iommu,
+			struct hv_output_get_iommu_capabilities *hv_iommu_cap)
+{
+	ida_init(&hv_iommu->domain_ids);
+
+	hv_iommu->cap = hv_iommu_cap->iommu_cap;
+	hv_iommu->max_iova_width = hv_iommu_cap->max_iova_width;
+	if (!hv_iommu_5lvl_supported(hv_iommu->cap) &&
+	    hv_iommu->max_iova_width > 48) {
+		pr_info("5-level paging not supported, limiting iova width to 48.\n");
+		hv_iommu->max_iova_width = 48;
+	}
+
+	hv_iommu->geometry = (struct iommu_domain_geometry) {
+		.aperture_start = 0,
+		.aperture_end = (((u64)1) << hv_iommu->max_iova_width) - 1,
+		.force_aperture = true,
+	};
+
+	hv_iommu->first_domain = HV_DEVICE_DOMAIN_ID_DEFAULT + 1;
+	hv_iommu->last_domain = HV_DEVICE_DOMAIN_ID_NULL - 1;
+	/* Only x86 page sizes (4K/2M/1G) are supported */
+	hv_iommu->pgsize_bitmap = hv_iommu_cap->pgsize_bitmap &
+				  (SZ_4K | SZ_2M | SZ_1G);
+	if (hv_iommu->pgsize_bitmap != hv_iommu_cap->pgsize_bitmap)
+		pr_warn("unsupported page sizes masked: 0x%llx -> 0x%llx\n",
+			hv_iommu_cap->pgsize_bitmap, hv_iommu->pgsize_bitmap);
+	if (!hv_iommu->pgsize_bitmap) {
+		pr_warn("no supported page sizes, defaulting to 4K\n");
+		hv_iommu->pgsize_bitmap = SZ_4K;
+	}
+	hv_iommu_device = hv_iommu;
+}
+
+int __init hv_iommu_init(void)
+{
+	int ret = 0;
+	struct hv_iommu_dev *hv_iommu = NULL;
+	struct hv_output_get_iommu_capabilities hv_iommu_cap = {0};
+
+	if (no_iommu || iommu_detected)
+		return -ENODEV;
+
+	if (!hv_is_hyperv_initialized())
+		return -ENODEV;
+
+	ret = hv_iommu_detect(&hv_iommu_cap);
+	if (ret) {
+		pr_err("HVCALL_GET_IOMMU_CAPABILITIES failed: %d\n", ret);
+		return -ENODEV;
+	}
+
+	if (!hv_iommu_present(hv_iommu_cap.iommu_cap) ||
+	    !hv_iommu_s1_domain_supported(hv_iommu_cap.iommu_cap)) {
+		pr_err("IOMMU capabilities not sufficient: cap=0x%llx\n",
+		       hv_iommu_cap.iommu_cap);
+		return -ENODEV;
+	}
+
+	iommu_detected = 1;
+	pci_request_acs();
+
+	hv_iommu = kzalloc_obj(*hv_iommu, GFP_KERNEL);
+	if (!hv_iommu)
+		return -ENOMEM;
+
+	hv_init_iommu_device(hv_iommu, &hv_iommu_cap);
+
+	ret = hv_initialize_static_domains();
+	if (ret) {
+		pr_err("static domains init failed: %d\n", ret);
+		goto err_free;
+	}
+
+	ret = iommu_device_sysfs_add(&hv_iommu->iommu, NULL, NULL, "%s", "hv-iommu");
+	if (ret) {
+		pr_err("iommu_device_sysfs_add failed: %d\n", ret);
+		goto err_delete_static_domains;
+	}
+
+	ret = iommu_device_register(&hv_iommu->iommu, &hv_iommu_ops, NULL);
+	if (ret) {
+		pr_err("iommu_device_register failed: %d\n", ret);
+		goto err_sysfs_remove;
+	}
+
+	pr_info("successfully initialized\n");
+	return 0;
+
+err_sysfs_remove:
+	iommu_device_sysfs_remove(&hv_iommu->iommu);
+err_delete_static_domains:
+	hv_delete_device_domain(&hv_blocking_domain);
+	hv_delete_device_domain(&hv_identity_domain);
+err_free:
+	kfree(hv_iommu);
+	return ret;
+}
drivers/iommu/hyperv/iommu.h new file +54 -0
new file mode 100644
index 000000000000..43f20d371245
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Hyper-V IOMMU driver.
+ *
+ * Copyright (C) 2024-2025, Microsoft, Inc.
+ *
+ */
+
+#ifndef _HYPERV_IOMMU_H
+#define _HYPERV_IOMMU_H
+
+struct hv_iommu_dev {
+	struct iommu_device iommu;
+	struct ida domain_ids;
+
+	/* Device configuration */
+	u8  max_iova_width;
+	u8  max_pasid_width;
+	u64 cap;
+	u64 pgsize_bitmap;
+
+	struct iommu_domain_geometry geometry;
+	u64 first_domain;
+	u64 last_domain;
+};
+
+struct hv_iommu_domain {
+	union {
+		struct iommu_domain    domain;
+		struct pt_iommu        pt_iommu;
+		struct pt_iommu_x86_64 pt_iommu_x86_64;
+	};
+	struct hv_iommu_dev *hv_iommu;
+	struct hv_input_device_domain device_domain;
+	u64		pgsize_bitmap;
+};
+
+struct hv_pci_busdata {
+	int               pci_domain_nr;
+	u32               logical_dev_id_prefix;
+	struct list_head  list;
+};
+
+struct hv_iommu_endpoint {
+	struct device *dev;
+	struct hv_iommu_dev *hv_iommu;
+	struct hv_iommu_domain *hv_domain;
+};
+
+#define to_hv_iommu_domain(d) \
+	container_of(d, struct hv_iommu_domain, domain)
+
+#endif /* _HYPERV_IOMMU_H */
drivers/pci/controller/pci-hyperv.c +1 -0
index cfc8fa403dad..a4af9c8c2220 100644
@@ -3715,6 +3715,7 @@ static int hv_pci_probe(struct hv_device *hdev,
 	struct hv_pcibus_device *hbus;
 	int ret, dom;
 	u16 dom_req;
+	u32 prefix;
 	char *name;
 
 	bridge = devm_pci_alloc_host_bridge(&hdev->device, 0);

drivers/pci/controller/pci-hyperv.c static int hv_pci_probe(struct hv_device *hdev, · line 3865

Quoted 9 lines
drivers/pci/controller/pci-hyperv.c +5 -1
@@ -3857,13 +3858,25 @@ static int hv_pci_probe(struct hv_device *hdev,
 
 	hbus->state = hv_pcibus_probed;
 
-	ret = create_root_hv_pci_bus(hbus);
+	/* Notify pvIOMMU before any device on the bus is scanned. */
+	prefix = (hdev->dev_instance.b[5] << 24) |
+		 (hdev->dev_instance.b[4] << 16) |
+		 (hdev->dev_instance.b[7] <<  8) |
+		 (hdev->dev_instance.b[6] & 0xf8);

This assembling of the logical device id prefix duplicates the code in hv_irq_retarget_interrupt(). Could this code save the prefix in struct hv_pcibus_device, and then have hv_irq_retarget_interrupt() use it? Then it would be clear that HVCALL_RETARGET_INTERRUPT is using exactly the same logical device id as the IOMMU hypercalls.

Quoted 18 lines
drivers/pci/controller/pci-hyperv.c +8 -0
+
+	ret = hv_iommu_register_pci_bus(dom, prefix);
 	if (ret)
 		goto free_windows;
 
+	ret = create_root_hv_pci_bus(hbus);
+	if (ret)
+		goto unregister_pviommu;
+
 	mutex_unlock(&hbus->state_lock);
 	return 0;
 
+unregister_pviommu:
+	hv_iommu_unregister_pci_bus(dom);
 free_windows:
 	hv_pci_free_bridge_windows(hbus);
 exit_d0:

drivers/pci/controller/pci-hyperv.c static int hv_pci_bus_exit(struct hv_device *hdev, bool · line 3994

Quoted 8 lines
drivers/pci/controller/pci-hyperv.c +2 -0
@@ -3974,8 +3987,10 @@ static int hv_pci_bus_exit(struct hv_device *hdev, bool
 keep_devs)
 static void hv_pci_remove(struct hv_device *hdev)
 {
 	struct hv_pcibus_device *hbus;
+	int dom;
 
 	hbus = hv_get_drvdata(hdev);
+	dom = hbus->bridge->domain_nr;

Nit: Setting "dom" here feels a little weird because the value is only needed under the "if" statement. The value must be read before the root bus is removed, but even so moving it under the "if" statement would make more sense to me.

Quoted 38 lines
drivers/pci/controller/pci-hyperv.c +0 -0
 	if (hbus->state == hv_pcibus_installed) {
 		tasklet_disable(&hdev->channel->callback_event);
drivers/pci/controller/pci-hyperv.c +2 -0
 		hbus->state = hv_pcibus_removing;
@@ -3994,6 +4009,8 @@ static void hv_pci_remove(struct hv_device *hdev)
 		hv_pci_remove_slots(hbus);
 		pci_remove_root_bus(hbus->bridge->bus);
 		pci_unlock_rescan_remove();
+
+		hv_iommu_unregister_pci_bus(dom);
 	}
 
 	hv_pci_bus_exit(hdev, false);
include/asm-generic/mshyperv.h +12 -1
index bf601d67cecb..b71345c74568 100644
@@ -73,6 +73,18 @@ extern enum hv_partition_type hv_curr_partition_type;
 extern void * __percpu *hyperv_pcpu_input_arg;
 extern void * __percpu *hyperv_pcpu_output_arg;
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+int  hv_iommu_register_pci_bus(int pci_domain_nr, u32 logical_dev_id_prefix);
+void hv_iommu_unregister_pci_bus(int pci_domain_nr);
+#else
+static inline int hv_iommu_register_pci_bus(int pci_domain_nr,
+					    u32 logical_dev_id_prefix)
+{
+	return 0;
+}
+static inline void hv_iommu_unregister_pci_bus(int pci_domain_nr) { }
+#endif
+
 u64 hv_do_hypercall(u64 control, void *inputaddr, void *outputaddr);
 u64 hv_do_fast_hypercall8(u16 control, u64 input8);
 u64 hv_do_fast_hypercall16(u16 control, u64 input1, u64 input2);
--

2.52.0

author
#12 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Quoted 28 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 21 lines

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Quoted 5 lines

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

Quoted 5 lines

As you are probably aware, Mukesh's patch series to support PCI pass-thru devices also needs to get the logical device ID. Maybe the registration mechanism needs to move somewhere that can be shared with his code.

Thank you so much for the review, Michael!

Yes, I looked at Mukesh's series and noticed his hv_pci_vmbus_device_id() in pci-hyperv.c has the same dev_instance byte manipulation. We do need a common registration mechanism.

Any suggestion on where to put it? drivers/hv/hv_common.c seems like a natural place, but the register/lookup functions are currently only meaningful when CONFIG_HYPERV_PVIOMMU is set. If Mukesh's pass-thru code also needs them, we might need a new shared Kconfig option that both can select. Open to better ideas.

Adding Mukesh to the loop. :)

Quoted 60 lines
Quoted 60 lines
---
 arch/x86/hyperv/hv_init.c           |   4 +
 arch/x86/include/asm/mshyperv.h     |   4 +
 drivers/iommu/hyperv/Kconfig        |  17 +
 drivers/iommu/hyperv/Makefile       |   1 +
 drivers/iommu/hyperv/iommu.c        | 705 ++++++++++++++++++++++++++++
 drivers/iommu/hyperv/iommu.h        |  54 +++
 drivers/pci/controller/pci-hyperv.c |  19 +-
 include/asm-generic/mshyperv.h      |  12 +
 8 files changed, 815 insertions(+), 1 deletion(-)
 create mode 100644 drivers/iommu/hyperv/iommu.c
 create mode 100644 drivers/iommu/hyperv/iommu.h
arch/x86/hyperv/hv_init.c +4 -0
index 323adc93f2dc..2c8ff8e06249 100644
@@ -578,6 +578,10 @@ void __init hyperv_init(void)
 	old_setup_percpu_clockev = x86_init.timers.setup_percpu_clockev;
 	x86_init.timers.setup_percpu_clockev = hv_stimer_setup_percpu_clockev;
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+	x86_init.iommu.iommu_init = hv_iommu_init;
+#endif
+
 	hv_apic_init();
 
 	x86_init.pci.arch_init = hv_pci_init;
arch/x86/include/asm/mshyperv.h +4 -0
index f64393e853ee..20d947c2c758 100644
@@ -313,6 +313,10 @@ static inline void mshv_vtl_return_hypercall(void) {}
 static inline void __mshv_vtl_return_call(struct mshv_vtl_cpu_context *vtl0) {}
 #endif
 
+#ifdef CONFIG_HYPERV_PVIOMMU
+int __init hv_iommu_init(void);
+#endif
+
 #include <asm-generic/mshyperv.h>
 
 #endif
drivers/iommu/hyperv/Kconfig +3 -0
index 30f40d867036..9e658d5c9a77 100644
@@ -8,3 +8,20 @@ config HYPERV_IOMMU
 	help
 	  Stub IOMMU driver to handle IRQs to support Hyper-V Linux
 	  guest and root partitions.
+
+if HYPERV_IOMMU
+config HYPERV_PVIOMMU
Quoted 9 lines

drivers/iommu/hyperv/Kconfig config HYPERV_IOMMU · line 15

Quoted 2 lines
drivers/iommu/hyperv/Kconfig +2 -0
+	bool "Microsoft Hypervisor para-virtualized IOMMU support"
+	depends on X86 && HYPERV

What is the intent w.r.t. 32-bit builds? Using X86 instead of X86_64 allows it. I did a 32-bit build and didn't get any build failures, which is good. But I can't run it to see if the pvIOMMU actually works in a 32-bit build. I don't know how building X86_64 generic PT entries would fare.

Sorry, no intent to support 32-bit. I'll change to depends on X86_64 && HYPERV

[...]

Quoted 7 lines
Quoted 7 lines
drivers/iommu/hyperv/Kconfig +7 -0
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
Quoted 9 lines

drivers/iommu/hyperv/Kconfig config HYPERV_IOMMU · line 26

Quoted 4 lines
drivers/iommu/hyperv/Kconfig +4 -0
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;

The previous version of this patch had code to set several other fields in the input. I wanted to confirm that not setting them in this version is intentional. Were they not needed?

Oh. The RFC v1 set partition_id, owner_vtl, domain_id.type, and domain_id.id individually. In this version, I just simplified it to a struct assignment. No functional change.

Quoted 15 lines
Quoted 15 lines
drivers/iommu/hyperv/Kconfig +15 -0
+	status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN failed, status %lld\n", status);
+}
+
+static void hv_iommu_detach_dev(struct iommu_domain *domain, struct device *dev)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_detach_device_domain *input;
+	struct pci_dev *pdev;
+	struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain);
Quoted 8 lines

drivers/iommu/hyperv/Kconfig

Quoted 5 lines
drivers/iommu/hyperv/Kconfig +5 -0
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+
+	/* See the attach function, only PCI devices for now */
+	if (!dev_is_pci(dev) || vdev->hv_domain != hv_domain)
+		return;

Are these sanity checks necessary? The only caller is hv_iommu_attach_dev() and it has already done the checks.

You're right, they're redundant.

Quoted 16 lines

drivers/iommu/hyperv/Kconfig

Quoted 11 lines
drivers/iommu/hyperv/Kconfig +11 -0
+
+	pdev = to_pci_dev(dev);
+
+	dev_dbg(dev, "detaching from domain %d\n", hv_domain->device_domain.domain_id.id);
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	if (hv_iommu_lookup_logical_dev_id(pdev, &input->device_id.as_uint64)) {

As Sashiko and Jacob Pan pointed out, doing the lookup while interrupts are disabled is problematic. My suggestion would be to just do the lookup into a local variable before disabling interrupts (rather than using a raw spin lock as Jacob suggested).

Quoted 3 lines

Same situation occurs in hv_iommu_attach_dev() and hv_iommu_get_logical_device_property().

Thanks! I would also prefer to look up before disabling interrupts.

Quoted 16 lines
Quoted 16 lines
drivers/iommu/hyperv/Kconfig +16 -0
+		local_irq_restore(flags);
+		dev_warn(&pdev->dev, "no IOMMU registration for vPCI bus on detach\n");
+		return;
+	}
+	status = hv_do_hypercall(HVCALL_DETACH_DEVICE_DOMAIN, input, NULL);
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_DETACH_DEVICE_DOMAIN failed, status %lld\n", status);
+
+	hv_flush_device_domain(hv_domain);
+
+	vdev->hv_domain = NULL;
+}
+

[...]

Quoted 17 lines
Quoted 4 lines
drivers/iommu/hyperv/Kconfig +4 -0
+static int hv_iommu_get_logical_device_property(struct device *dev,
+					u32 code,
+					struct hv_output_get_logical_device_property *property)
+{

drivers/iommu/hyperv/Kconfig

Quoted 10 lines
drivers/iommu/hyperv/Kconfig +10 -0
+	u64 status, lid;
+	unsigned long flags;
+	int ret;
+	struct hv_input_get_logical_device_property *input;
+	struct hv_output_get_logical_device_property *output;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	output = *this_cpu_ptr(hyperv_pcpu_input_arg) + sizeof(*input);

Nit: The other way to set output is:

Quoted 6 lines
	output = input + 1;

I think this produces slightly better code because of not needing to reference the per-cpu variable hyperv_pcpu_input_arg a 2nd time.

Indeed! It's more elegant. :)

Quoted 20 lines
Quoted 20 lines
drivers/iommu/hyperv/Kconfig +20 -0
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	ret = hv_iommu_lookup_logical_dev_id(to_pci_dev(dev), &lid);
+	if (ret) {
+		local_irq_restore(flags);
+		return ret;
+	}
+	input->logical_device_id = lid;
+	input->code = code;
+	status = hv_do_hypercall(HVCALL_GET_LOGICAL_DEVICE_PROPERTY, input, output);
+	*property = *output;
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_GET_LOGICAL_DEVICE_PROPERTY failed, status %lld\n", status);
+
+	return hv_result_to_errno(status);
+}
+

[...]

Quoted 7 lines
Quoted 7 lines
drivers/iommu/hyperv/Kconfig +7 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
Quoted 9 lines

drivers/iommu/hyperv/Kconfig

Quoted 3 lines
drivers/iommu/hyperv/Kconfig +3 -0
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Sorry I forgot to mention this in the changelog.

[...]

Quoted 40 lines
Quoted 40 lines
drivers/iommu/hyperv/Kconfig +40 -0
+static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+	struct pt_iommu_x86_64_cfg cfg = {};
+
+	hv_domain = kzalloc_obj(*hv_domain, GFP_KERNEL);
+	if (!hv_domain)
+		return ERR_PTR(-ENOMEM);
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret) {
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->pt_iommu.nid = dev_to_node(dev);
+
+	cfg.common.hw_max_vasz_lg2 = hv_iommu_device->max_iova_width;
+	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.top_level = (hv_iommu_device->max_iova_width > 48) ? 4 : 3;
+
+	ret = pt_iommu_x86_64_init(&hv_domain->pt_iommu_x86_64, &cfg, GFP_KERNEL);
+	if (ret) {
+		hv_delete_device_domain(hv_domain);
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	/* Constrain to page sizes the hypervisor supports */
+	hv_domain->domain.pgsize_bitmap &= hv_iommu_device->pgsize_bitmap;
+
+	hv_domain->domain.ops = &hv_iommu_paging_domain_ops;
+
+	ret = hv_configure_device_domain(hv_domain, __IOMMU_DOMAIN_PAGING);
+	if (ret) {
+		pt_iommu_deinit(&hv_domain->pt_iommu);
+		hv_delete_device_domain(hv_domain);
+		kfree(hv_domain);
Quoted 9 lines

drivers/iommu/hyperv/Kconfig

Quoted 4 lines
drivers/iommu/hyperv/Kconfig +4 -0
+		return ERR_PTR(ret);
+	}
+
+	return &hv_domain->domain;

I think this function would be better if the error paths did "goto" a cascading set of error labels. That's the typical pattern, and it's what you use in hv_iommu_init(), for example.

Good point. Will restructure to use goto-based error labels

Quoted 20 lines
Quoted 20 lines
drivers/iommu/hyperv/Kconfig +20 -0
+}
+
+static struct iommu_ops hv_iommu_ops = {
+	.capable		  = hv_iommu_capable,
+	.domain_alloc_paging	  = hv_iommu_domain_alloc_paging,
+	.probe_device		  = hv_iommu_probe_device,
+	.release_device		  = hv_iommu_release_device,
+	.device_group		  = hv_iommu_device_group,
+	.get_resv_regions	  = hv_iommu_get_resv_regions,
+	.owner			  = THIS_MODULE,
+	.identity_domain	  = &hv_identity_domain.domain,
+	.blocked_domain		  = &hv_blocking_domain.domain,
+	.release_domain		  = &hv_blocking_domain.domain,
+};
+
+static int hv_iommu_detect(struct hv_output_get_iommu_capabilities *hv_iommu_cap)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_get_iommu_capabilities *input;
Quoted 9 lines

drivers/iommu/hyperv/Kconfig

Quoted 6 lines
drivers/iommu/hyperv/Kconfig +6 -0
+	struct hv_output_get_iommu_capabilities *output;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	output = *this_cpu_ptr(hyperv_pcpu_input_arg) + sizeof(*input);

Potentially use "output = input + 1" here as well.

Yes. Thanks!

[...]

Quoted 4 lines
Quoted 4 lines
drivers/iommu/hyperv/Kconfig +0 -0
@@ -3857,13 +3858,25 @@ static int hv_pci_probe(struct hv_device *hdev,
 
 	hbus->state = hv_pcibus_probed;
 
Quoted 14 lines

drivers/iommu/hyperv/Kconfig static int hv_pci_probe(struct hv_device *hdev, · line 3865

Quoted 6 lines
drivers/iommu/hyperv/Kconfig +5 -1
-	ret = create_root_hv_pci_bus(hbus);
+	/* Notify pvIOMMU before any device on the bus is scanned. */
+	prefix = (hdev->dev_instance.b[5] << 24) |
+		 (hdev->dev_instance.b[4] << 16) |
+		 (hdev->dev_instance.b[7] <<  8) |
+		 (hdev->dev_instance.b[6] & 0xf8);

This assembling of the logical device id prefix duplicates the code in hv_irq_retarget_interrupt(). Could this code save the prefix in struct hv_pcibus_device, and then have hv_irq_retarget_interrupt() use it? Then it would be clear that HVCALL_RETARGET_INTERRUPT is using exactly the same logical device id as the IOMMU hypercalls.

Good point. I think we can do it. :)

Quoted 24 lines
Quoted 24 lines
drivers/iommu/hyperv/Kconfig +9 -0
+
+	ret = hv_iommu_register_pci_bus(dom, prefix);
 	if (ret)
 		goto free_windows;
 
+	ret = create_root_hv_pci_bus(hbus);
+	if (ret)
+		goto unregister_pviommu;
+
 	mutex_unlock(&hbus->state_lock);
 	return 0;
 
+unregister_pviommu:
+	hv_iommu_unregister_pci_bus(dom);
 free_windows:
 	hv_pci_free_bridge_windows(hbus);
 exit_d0:
@@ -3974,8 +3987,10 @@ static int hv_pci_bus_exit(struct hv_device *hdev, bool
 keep_devs)
 static void hv_pci_remove(struct hv_device *hdev)
 {
 	struct hv_pcibus_device *hbus;
+	int dom;
 
Quoted 8 lines

drivers/iommu/hyperv/Kconfig static int hv_pci_bus_exit(struct hv_device *hdev, bool · line 3994

Quoted 2 lines
drivers/iommu/hyperv/Kconfig +1 -0
 	hbus = hv_get_drvdata(hdev);
+	dom = hbus->bridge->domain_nr;

Nit: Setting "dom" here feels a little weird because the value is only needed under the "if" statement. The value must be read before the root bus is removed, but even so moving it under the "if" statement would make more sense to me.

Sure. Thanks!

Quoted 11 lines
Quoted 11 lines
drivers/iommu/hyperv/Kconfig +0 -0
 	if (hbus->state == hv_pcibus_installed) {
 		tasklet_disable(&hdev->channel->callback_event);
drivers/iommu/hyperv/Kconfig +2 -0
 		hbus->state = hv_pcibus_removing;
@@ -3994,6 +4009,8 @@ static void hv_pci_remove(struct hv_device *hdev)
 		hv_pci_remove_slots(hbus);
 		pci_remove_root_bus(hbus->bridge->bus);
 		pci_unlock_rescan_remove();
+
+		hv_iommu_unregister_pci_bus(dom);
 	}
 
Quoted 1 line

drivers/iommu/hyperv/Kconfig static void hv_pci_remove(struct hv_device *hdev) · line 4016

Quoted 1 line
drivers/iommu/hyperv/Kconfig +0 -0
 	hv_pci_bus_exit(hdev, false);

B.R.
Yu

#13 lore raw

RE: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 7:00 AM

Quoted 42 lines · Michael Kelley
Quoted 28 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 21 lines

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Quoted 5 lines

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

Quoted 5 lines

As you are probably aware, Mukesh's patch series to support PCI pass-thru devices also needs to get the logical device ID. Maybe the registration mechanism needs to move somewhere that can be shared with his code.

Thank you so much for the review, Michael!

Yes, I looked at Mukesh's series and noticed his hv_pci_vmbus_device_id() in pci-hyperv.c has the same dev_instance byte manipulation. We do need a common registration mechanism.

Quoted 5 lines

Any suggestion on where to put it? drivers/hv/hv_common.c seems like a natural place, but the register/lookup functions are currently only meaningful when CONFIG_HYPERV_PVIOMMU is set. If Mukesh's pass-thru code also needs them, we might need a new shared Kconfig option that both can select. Open to better ideas.

Unfortunately, I have not looked at Mukesh's series in detail yet, so I don't have enough knowledge of the full situation to offer a good recommendation.

Quoted 20 lines

[...]

Quoted 7 lines
Quoted 7 lines
drivers/iommu/hyperv/iommu.c new file +7 -0
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 147

Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;

The previous version of this patch had code to set several other fields in the input. I wanted to confirm that not setting them in this version is intentional. Were they not needed?

Quoted 3 lines

Oh. The RFC v1 set partition_id, owner_vtl, domain_id.type, and domain_id.id individually. In this version, I just simplified it to a struct assignment. No functional change.

Of course! I should have looked more closely at the details before making this comment. :-(

[...]

Quoted 11 lines
Quoted 6 lines

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Got it. But after the IOMMU core attaches the device to the blocking domain, there's the possibility that the vPCI device is rescinded by Hyper-V and it goes away entirely. Or the device might be subjected to an "unbind/bind" cycle in Linux. Does the detach need to be done on the blocking domain in such cases? In this version of the patches, the Hyper-V "attach" and "detach" hypercalls still end up unbalanced. That seems a bit untidy at best, and I wonder if there are scenarios where Hyper-V will complain about the lack of balance.

Michael

author
#14 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Quoted 49 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 7:00 AM

Quoted 42 lines · Michael Kelley
Quoted 28 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 21 lines

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Quoted 5 lines

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

Quoted 5 lines

As you are probably aware, Mukesh's patch series to support PCI pass-thru devices also needs to get the logical device ID. Maybe the registration mechanism needs to move somewhere that can be shared with his code.

Thank you so much for the review, Michael!

Yes, I looked at Mukesh's series and noticed his hv_pci_vmbus_device_id() in pci-hyperv.c has the same dev_instance byte manipulation. We do need a common registration mechanism.

Quoted 5 lines

Any suggestion on where to put it? drivers/hv/hv_common.c seems like a natural place, but the register/lookup functions are currently only meaningful when CONFIG_HYPERV_PVIOMMU is set. If Mukesh's pass-thru code also needs them, we might need a new shared Kconfig option that both can select. Open to better ideas.

Quoted 4 lines

Unfortunately, I have not looked at Mukesh's series in detail yet, so I don't have enough knowledge of the full situation to offer a good recommendation.

Sorry I forgot to Cc Mukesh in the previous reply. :(
@Mukesh, any thoughts on sharing the logical device ID registration mechanism?

Quoted 41 lines
Quoted 20 lines

[...]

Quoted 7 lines
Quoted 7 lines
drivers/iommu/hyperv/iommu.c new file +7 -0
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 147

Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;

The previous version of this patch had code to set several other fields in the input. I wanted to confirm that not setting them in this version is intentional. Were they not needed?

Quoted 3 lines

Oh. The RFC v1 set partition_id, owner_vtl, domain_id.type, and domain_id.id individually. In this version, I just simplified it to a struct assignment. No functional change.

Of course! I should have looked more closely at the details before making this comment. :-(

[...]

Quoted 11 lines
Quoted 6 lines

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Quoted 9 lines

Got it. But after the IOMMU core attaches the device to the blocking domain, there's the possibility that the vPCI device is rescinded by Hyper-V and it goes away entirely. Or the device might be subjected to an "unbind/bind" cycle in Linux. Does the detach need to be done on the blocking domain in such cases? In this version of the patches, the Hyper-V "attach" and "detach" hypercalls still end up unbalanced. That seems a bit untidy at best, and I wonder if there are scenarios where Hyper-V will complain about the lack of balance.

Thank you, Michael. May I ask what "the vPCI device is rescinded by Hyper-V and it goes away entirely" mean?

I realized it's a bit untidy. But I want to understand this issue more clearly first. :)

B.R.
Yu

#15 lore raw

RE: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 9:54 AM

Quoted 6 lines · Michael Kelley
Quoted 4 lines

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 7:00 AM

Quoted 3 lines · Michael Kelley
Quoted 1 line

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

[....]

Quoted 22 lines
Quoted 12 lines
Quoted 11 lines
Quoted 6 lines

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Quoted 9 lines

Got it. But after the IOMMU core attaches the device to the blocking domain, there's the possibility that the vPCI device is rescinded by Hyper-V and it goes away entirely. Or the device might be subjected to an "unbind/bind" cycle in Linux. Does the detach need to be done on the blocking domain in such cases? In this version of the patches, the Hyper-V "attach" and "detach" hypercalls still end up unbalanced. That seems a bit untidy at best, and I wonder if there are scenarios where Hyper-V will complain about the lack of balance.

Quoted 3 lines

Thank you, Michael. May I ask what "the vPCI device is rescinded by Hyper-V and it goes away entirely" mean?

See the documentation at Documentation/virt/hyperv/vpci.rst in a kernel source code tree, and particularly the section entitled "PCI Device Removal". Such removals can and do happen in running Azure guest VMs. Start with that info and then I'll do my best to answer follow-up questions you may have.

The unbind/bind case is separate, but has some of the same effects in that Linux should be removing all setup of the PCI device. There's actually two unbind steps -- one to unbind the device-specific driver (e.g., the Mellanox MLX5 driver or the NMVe driver) driver from the device, and potentially a second to unbind the VMBus vPCI driver from the device. These unbind/bind sequences can be done in the Linux guest without the Hyper-V host rescinding the device.

Michael

author
#16 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Quoted 42 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 9:54 AM

Quoted 6 lines · Michael Kelley
Quoted 4 lines

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 7:00 AM

Quoted 3 lines · Michael Kelley
Quoted 1 line

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

[....]

Quoted 22 lines
Quoted 12 lines
Quoted 11 lines
Quoted 6 lines

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Quoted 9 lines

Got it. But after the IOMMU core attaches the device to the blocking domain, there's the possibility that the vPCI device is rescinded by Hyper-V and it goes away entirely. Or the device might be subjected to an "unbind/bind" cycle in Linux. Does the detach need to be done on the blocking domain in such cases? In this version of the patches, the Hyper-V "attach" and "detach" hypercalls still end up unbalanced. That seems a bit untidy at best, and I wonder if there are scenarios where Hyper-V will complain about the lack of balance.

Quoted 3 lines

Thank you, Michael. May I ask what "the vPCI device is rescinded by Hyper-V and it goes away entirely" mean?

See the documentation at Documentation/virt/hyperv/vpci.rst in a kernel source code tree, and particularly the section entitled "PCI Device Removal". Such removals can and do happen in running Azure guest VMs. Start with that info and then I'll do my best to answer follow-up questions you may have.

Quoted 7 lines

The unbind/bind case is separate, but has some of the same effects in that Linux should be removing all setup of the PCI device. There's actually two unbind steps -- one to unbind the device-specific driver (e.g., the Mellanox MLX5 driver or the NMVe driver) driver from the device, and potentially a second to unbind the VMBus vPCI driver from the device. These unbind/bind sequences can be done in the Linux guest without the Hyper-V host rescinding the device.

Thanks for pointing me to the vpci.rst doc, Michael!

IIUC, for the vPCI rescind case and the VMBus vPCI driver unbind case, both will trigger iommu_deinit_device(), in which IOMMU core attaches the device to our blocking domain. And hypervisor will handle such attaching to the blocking domain by essentially disable the DMA translation and IOPF for the device. Since the device is already in a safe state after that, I don't think an additional detach is necessary.

For the device-specific driver unbind (e.g., unbind nvme then bind back, or bind to vfio-pci), that is transparent to the IOMMU layer.

Also, while looking at Jason's comments on the detach/attach semantics, I'm now thinking that making the attach hypercall atomic (having the hypervisor handle the domain switch internally) might be a cleaner approach. That also eliminates the attach/detach imbalance issue entirely. I need to do some verification on the hypervisor side first, but will keep you posted. Thanks!

B.R.
Yu

Quoted 3 lines

Michael

#17 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

In reply to Yu Zhang
Quoted 50 lines · Yu Zhang
Quoted 49 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 7:00 AM

Quoted 47 lines · Michael Kelley
Quoted 28 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 21 lines

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Quoted 5 lines

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

Quoted 5 lines

As you are probably aware, Mukesh's patch series to support PCI pass-thru devices also needs to get the logical device ID. Maybe the registration mechanism needs to move somewhere that can be shared with his code.

Thank you so much for the review, Michael!

Yes, I looked at Mukesh's series and noticed his hv_pci_vmbus_device_id() in pci-hyperv.c has the same dev_instance byte manipulation. We do need a common registration mechanism.

Any suggestion on where to put it? drivers/hv/hv_common.c seems like a natural place, but the register/lookup functions are currently only meaningful when CONFIG_HYPERV_PVIOMMU is set. If Mukesh's pass-thru code also needs them, we might need a new shared Kconfig option that both can select. Open to better ideas.

Quoted 7 lines
Quoted 4 lines

Unfortunately, I have not looked at Mukesh's series in detail yet, so I don't have enough knowledge of the full situation to offer a good recommendation.

Sorry I forgot to Cc Mukesh in the previous reply. :(
@Mukesh, any thoughts on sharing the logical device ID registration mechanism?

Yeah, I went round and round trying to find the best place. I almost created virt/hyperv/hv_utils.c file. Maybe that is the best place?

Thanks,
-Mukesh

Quoted 59 lines
Quoted 41 lines
Quoted 20 lines

[...]

Quoted 7 lines
Quoted 7 lines
drivers/iommu/hyperv/iommu.c new file +7 -0
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 147

Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;

The previous version of this patch had code to set several other fields in the input. I wanted to confirm that not setting them in this version is intentional. Were they not needed?

Quoted 3 lines

Oh. The RFC v1 set partition_id, owner_vtl, domain_id.type, and domain_id.id individually. In this version, I just simplified it to a struct assignment. No functional change.

Of course! I should have looked more closely at the details before making this comment. :-(

[...]

Quoted 11 lines
Quoted 6 lines

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Quoted 9 lines

Got it. But after the IOMMU core attaches the device to the blocking domain, there's the possibility that the vPCI device is rescinded by Hyper-V and it goes away entirely. Or the device might be subjected to an "unbind/bind" cycle in Linux. Does the detach need to be done on the blocking domain in such cases? In this version of the patches, the Hyper-V "attach" and "detach" hypercalls still end up unbalanced. That seems a bit untidy at best, and I wonder if there are scenarios where Hyper-V will complain about the lack of balance.

Thank you, Michael. May I ask what "the vPCI device is rescinded by Hyper-V and it goes away entirely" mean?

I realized it's a bit untidy. But I want to understand this issue more clearly first. :)

B.R.
Yu

author
#18 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Quoted 56 lines · Mukesh R
Quoted 55 lines · Yu Zhang
Quoted 53 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 7:00 AM

Quoted 42 lines · Michael Kelley
Quoted 28 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 21 lines

Add a para-virtualized IOMMU driver for Linux guests running on Hyper-V. This driver implements stage-1 IO translation within the guest OS. It integrates with the Linux IOMMU core, utilizing Hyper-V hypercalls for:
- Capability discovery
- Domain allocation, configuration, and deallocation
- Device attachment and detachment
- IOTLB invalidation

The driver constructs x86-compatible stage-1 IO page tables in the guest memory using consolidated IO page table helpers. This allows the guest to manage stage-1 translations independently of vendor- specific drivers (like Intel VT-d or AMD IOMMU).

Hyper-V consumes this stage-1 IO page table when a device domain is created and configured, and nests it with the host's stage-2 IO page tables, therefore eliminating the VM exits for guest IOMMU mapping operations. For unmapping operations, VM exits to perform the IOTLB flush are still unavoidable.

Quoted 5 lines

Hyper-V identifies each PCI pass-thru device by a logical device ID in its hypercall interface. The vPCI driver (pci-hyperv) registers the per-bus portion of this ID with the pvIOMMU driver during bus probe. The pvIOMMU driver stores this mapping and combines it with the function number of the endpoint PCI device to form the complete ID for hypercalls.

Quoted 5 lines

As you are probably aware, Mukesh's patch series to support PCI pass-thru devices also needs to get the logical device ID. Maybe the registration mechanism needs to move somewhere that can be shared with his code.

Thank you so much for the review, Michael!

Yes, I looked at Mukesh's series and noticed his hv_pci_vmbus_device_id() in pci-hyperv.c has the same dev_instance byte manipulation. We do need a common registration mechanism.

Quoted 5 lines

Any suggestion on where to put it? drivers/hv/hv_common.c seems like a natural place, but the register/lookup functions are currently only meaningful when CONFIG_HYPERV_PVIOMMU is set. If Mukesh's pass-thru code also needs them, we might need a new shared Kconfig option that both can select. Open to better ideas.

Unfortunately, I have not looked at Mukesh's series in detail yet, so I don't have enough knowledge of the full situation to offer a good recommendation.

Quoted 5 lines
Quoted 2 lines

Sorry I forgot to Cc Mukesh in the previous reply. :(
@Mukesh, any thoughts on sharing the logical device ID registration mechanism?

Yeah, I went round and round trying to find the best place. I almost created virt/hyperv/hv_utils.c file. Maybe that is the best place?

Thanks for thinking about this, Mukesh!

I'm a bit hesitant about introducing virt/hyperv/. Currently virt/ only hosts KVM's architecture-neutral hypervisor core. And it feels like the wrong layer for driver-level utility code. And drivers/hv/ seems like a more natural fit?

I'm also thinking about the config to gating these new interfaces( register/lookup etc.), I am using CONFIG_HYPERV_PVIOMMU, and I guess you may propably propose another one for the host side change(or just CONFIG_MSHV_ROOT)?

B.R.
Yu

Quoted 65 lines

Thanks,
-Mukesh

Quoted 59 lines
Quoted 41 lines
Quoted 20 lines

[...]

Quoted 7 lines
Quoted 7 lines
drivers/iommu/hyperv/iommu.c new file +7 -0
+static void hv_flush_device_domain(struct hv_iommu_domain *hv_domain)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_flush_device_domain *input;
+
+	local_irq_save(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 147

Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->device_domain = hv_domain->device_domain;

The previous version of this patch had code to set several other fields in the input. I wanted to confirm that not setting them in this version is intentional. Were they not needed?

Quoted 3 lines

Oh. The RFC v1 set partition_id, owner_vtl, domain_id.type, and domain_id.id individually. In this version, I just simplified it to a struct assignment. No functional change.

Of course! I should have looked more closely at the details before making this comment. :-(

[...]

Quoted 11 lines
Quoted 6 lines

Previous versions of this function did hv_iommu_detach_dev(). With that call removed from here, hv_iommu_detach_dev() is only called when attaching a domain to a device that already has a domain attached. Is it the case that Hyper-V doesn't require the detach as a cleanup step?

The IOMMU core attaches the device to release_domain (our blocking domain) before calling release_device(), so I believe the explicit detach in the RFC was redundant. I simply didn't realize that at the time.

Quoted 9 lines

Got it. But after the IOMMU core attaches the device to the blocking domain, there's the possibility that the vPCI device is rescinded by Hyper-V and it goes away entirely. Or the device might be subjected to an "unbind/bind" cycle in Linux. Does the detach need to be done on the blocking domain in such cases? In this version of the patches, the Hyper-V "attach" and "detach" hypercalls still end up unbalanced. That seems a bit untidy at best, and I wonder if there are scenarios where Hyper-V will complain about the lack of balance.

Thank you, Michael. May I ask what "the vPCI device is rescinded by Hyper-V and it goes away entirely" mean?

I realized it's a bit untidy. But I want to understand this issue more clearly first. :)

B.R.
Yu

#19 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

In reply to Yu Zhang

drivers/iommu/hyperv/iommu.c line 35

Quoted 9 lines · Yu Zhang
drivers/iommu/hyperv/iommu.c new file +9 -0
+/*
+ * Identity and blocking domains are static singletons: identity is a 1:1
+ * passthrough with no page table, blocking rejects all DMA. Neither holds
+ * per-IOMMU state, so one instance suffices even with multiple vIOMMUs.
+ */
+static struct hv_iommu_domain hv_identity_domain;
+static struct hv_iommu_domain hv_blocking_domain;
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops;
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops;

Please follow the format of other drivers and statically initialize these here instead of in C code.

drivers/iommu/hyperv/iommu.c line 43

Quoted 8 lines
drivers/iommu/hyperv/iommu.c new file +8 -0
+static struct iommu_ops hv_iommu_ops;
+static LIST_HEAD(hv_iommu_pci_bus_list);
+static DEFINE_SPINLOCK(hv_iommu_pci_bus_lock);
+
+#define hv_iommu_present(iommu_cap) (iommu_cap & HV_IOMMU_CAP_PRESENT)
+#define hv_iommu_s1_domain_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1)
+#define hv_iommu_5lvl_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1_5LVL)
+#define hv_iommu_ats_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_ATS)

prefer to see static inlines

Quoted 18 lines
drivers/iommu/hyperv/iommu.c new file +18 -0
+static void hv_iommu_detach_dev(struct iommu_domain *domain, struct device *dev)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_detach_device_domain *input;
+	struct pci_dev *pdev;
+	struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain);
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+
+	/* See the attach function, only PCI devices for now */
+	if (!dev_is_pci(dev) || vdev->hv_domain != hv_domain)
+		return;
+
+	pdev = to_pci_dev(dev);
+
+	dev_dbg(dev, "detaching from domain %d\n", hv_domain->device_domain.domain_id.id);
+
+	local_irq_save(flags);

drivers/iommu/hyperv/iommu.c line 241

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	if (hv_iommu_lookup_logical_dev_id(pdev, &input->device_id.as_uint64)) {
+		local_irq_restore(flags);
+		dev_warn(&pdev->dev, "no IOMMU registration for vPCI bus on detach\n");
+		return;
+	}
+	status = hv_do_hypercall(HVCALL_DETACH_DEVICE_DOMAIN, input, NULL);

FWIW the hypervisor cannot implement the linux attach semantics if it has detach/attach. It must support simply 'attach' which atomically changes the translation. With detach you have a confusing problem if errors happen in the middle of the sequence the device is left in an unclear state. You should at least document what state the hypervisor is supposed to leaave the translation iin during these failures..

drivers/iommu/hyperv/iommu.c line 376

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

Does the driver really need to mess with set_dma_ops ? I'd rather not see that in new iommu drivers if at all possible :|

Quoted 11 lines
drivers/iommu/hyperv/iommu.c new file +11 -0
+static int __init hv_initialize_static_domains(void)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+
+	/* Default stage-1 identity domain */
+	hv_domain = &hv_identity_domain;
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret)
+		return ret;

drivers/iommu/hyperv/iommu.c line 440

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+
+	ret = hv_configure_device_domain(hv_domain, IOMMU_DOMAIN_IDENTITY);
+	if (ret)
+		goto delete_identity_domain;
+
+	hv_domain->domain.type = IOMMU_DOMAIN_IDENTITY;
+	hv_domain->domain.ops = &hv_iommu_identity_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap = hv_iommu_device->pgsize_bitmap;

identity doesn't use geometry or pgsize_bitmap

Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+	/* Default stage-1 blocked domain */
+	hv_domain = &hv_blocking_domain;
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret)
+		goto delete_identity_domain;

drivers/iommu/hyperv/iommu.c line 457

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+
+	ret = hv_configure_device_domain(hv_domain, IOMMU_DOMAIN_BLOCKED);
+	if (ret)
+		goto delete_blocked_domain;
+
+	hv_domain->domain.type = IOMMU_DOMAIN_BLOCKED;
+	hv_domain->domain.ops = &hv_iommu_blocking_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap = hv_iommu_device->pgsize_bitmap;

Nor does blocked

drivers/iommu/hyperv/iommu.c line 477

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+#define INTERRUPT_RANGE_START	(0xfee00000)
+#define INTERRUPT_RANGE_END	(0xfeefffff)
+static void hv_iommu_get_resv_regions(struct device *dev,
+		struct list_head *head)
+{
+	struct iommu_resv_region *region;
+
+	region = iommu_alloc_resv_region(INTERRUPT_RANGE_START,
+				      INTERRUPT_RANGE_END - INTERRUPT_RANGE_START + 1,
+				      0, IOMMU_RESV_MSI, GFP_KERNEL);

Surprised these constants are not discovered from the hv?

drivers/iommu/hyperv/iommu.c line 495

Quoted 12 lines
drivers/iommu/hyperv/iommu.c new file +12 -0
+static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+}
+
+static void hv_iommu_iotlb_sync(struct iommu_domain *domain,
+				struct iommu_iotlb_gather *iotlb_gather)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+
+	iommu_put_pages_list(&iotlb_gather->freelist);
+}

Full invalidation only huh?

drivers/iommu/hyperv/iommu.c line 515

Quoted 7 lines
drivers/iommu/hyperv/iommu.c new file +7 -0
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};

Usually I would expect these to have their own attach functions. blocking in particular must have an attach op that cannot fail. It is used to recover the device back to a known translation in case of cascading other errors.

Quoted 15 lines
drivers/iommu/hyperv/iommu.c new file +15 -0
+static const struct iommu_domain_ops hv_iommu_paging_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+	IOMMU_PT_DOMAIN_OPS(x86_64),
+	.flush_iotlb_all = hv_iommu_flush_iotlb_all,
+	.iotlb_sync = hv_iommu_iotlb_sync,
+	.free = hv_iommu_paging_domain_free,
+};
+
+static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+	struct pt_iommu_x86_64_cfg cfg = {};
+
+	hv_domain = kzalloc_obj(*hv_domain, GFP_KERNEL);

drivers/iommu/hyperv/iommu.c line 541

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+	if (!hv_domain)
+		return ERR_PTR(-ENOMEM);
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret) {
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	hv_domain->domain.geometry = hv_iommu_device->geometry;

geoemtry shouldn't be set here, it is overriden by pt_iommu_x86_64_init() with the exact page table configuration

Quoted 17 lines
drivers/iommu/hyperv/iommu.c new file +17 -0
+static void __init hv_init_iommu_device(struct hv_iommu_dev *hv_iommu,
+			struct hv_output_get_iommu_capabilities *hv_iommu_cap)
+{
+	ida_init(&hv_iommu->domain_ids);
+
+	hv_iommu->cap = hv_iommu_cap->iommu_cap;
+	hv_iommu->max_iova_width = hv_iommu_cap->max_iova_width;
+	if (!hv_iommu_5lvl_supported(hv_iommu->cap) &&
+	    hv_iommu->max_iova_width > 48) {
+		pr_info("5-level paging not supported, limiting iova width to 48.\n");
+		hv_iommu->max_iova_width = 48;
+	}
+
+	hv_iommu->geometry = (struct iommu_domain_geometry) {
+		.aperture_start = 0,
+		.aperture_end = (((u64)1) << hv_iommu->max_iova_width) - 1,
+		.force_aperture = true,

drivers/iommu/hyperv/iommu.c line 634

Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+	};
+
+	hv_iommu->first_domain = HV_DEVICE_DOMAIN_ID_DEFAULT + 1;
+	hv_iommu->last_domain = HV_DEVICE_DOMAIN_ID_NULL - 1;
+	/* Only x86 page sizes (4K/2M/1G) are supported */
+	hv_iommu->pgsize_bitmap = hv_iommu_cap->pgsize_bitmap &
+				  (SZ_4K | SZ_2M | SZ_1G);
+	if (hv_iommu->pgsize_bitmap != hv_iommu_cap->pgsize_bitmap)
+		pr_warn("unsupported page sizes masked: 0x%llx -> 0x%llx\n",
+			hv_iommu_cap->pgsize_bitmap, hv_iommu->pgsize_bitmap);

IKD if you need this logic, the way the page table code is used it just sort of falls out naturally that other page sizes are ignored.

drivers/iommu/hyperv/iommu.h line 33

Quoted 6 lines
drivers/iommu/hyperv/iommu.h new file +6 -0
+struct hv_iommu_domain {
+	union {
+		struct iommu_domain    domain;
+		struct pt_iommu        pt_iommu;
+		struct pt_iommu_x86_64 pt_iommu_x86_64;
+	};

You should retain the build assertions here

Jason

author
#20 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Quoted 14 lines · Jason Gunthorpe

drivers/iommu/hyperv/iommu.c line 35

Quoted 9 lines · Yu Zhang
drivers/iommu/hyperv/iommu.c new file +9 -0
+/*
+ * Identity and blocking domains are static singletons: identity is a 1:1
+ * passthrough with no page table, blocking rejects all DMA. Neither holds
+ * per-IOMMU state, so one instance suffices even with multiple vIOMMUs.
+ */
+static struct hv_iommu_domain hv_identity_domain;
+static struct hv_iommu_domain hv_blocking_domain;
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops;
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops;

Please follow the format of other drivers and statically initialize these here instead of in C code.

Thanks! Will do.

Quoted 11 lines

drivers/iommu/hyperv/iommu.c line 43

Quoted 8 lines
drivers/iommu/hyperv/iommu.c new file +8 -0
+static struct iommu_ops hv_iommu_ops;
+static LIST_HEAD(hv_iommu_pci_bus_list);
+static DEFINE_SPINLOCK(hv_iommu_pci_bus_lock);
+
+#define hv_iommu_present(iommu_cap) (iommu_cap & HV_IOMMU_CAP_PRESENT)
+#define hv_iommu_s1_domain_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1)
+#define hv_iommu_5lvl_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_S1_5LVL)
+#define hv_iommu_ats_supported(iommu_cap) (iommu_cap & HV_IOMMU_CAP_ATS)

prefer to see static inlines

Yes. Thanks.

Quoted 27 lines
Quoted 27 lines
drivers/iommu/hyperv/iommu.c new file +27 -0
+static void hv_iommu_detach_dev(struct iommu_domain *domain, struct device *dev)
+{
+	u64 status;
+	unsigned long flags;
+	struct hv_input_detach_device_domain *input;
+	struct pci_dev *pdev;
+	struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain);
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+
+	/* See the attach function, only PCI devices for now */
+	if (!dev_is_pci(dev) || vdev->hv_domain != hv_domain)
+		return;
+
+	pdev = to_pci_dev(dev);
+
+	dev_dbg(dev, "detaching from domain %d\n", hv_domain->device_domain.domain_id.id);
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+	input->partition_id = HV_PARTITION_ID_SELF;
+	if (hv_iommu_lookup_logical_dev_id(pdev, &input->device_id.as_uint64)) {
+		local_irq_restore(flags);
+		dev_warn(&pdev->dev, "no IOMMU registration for vPCI bus on detach\n");
+		return;
+	}
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 241

Quoted 1 line
drivers/iommu/hyperv/iommu.c new file +1 -0
+	status = hv_do_hypercall(HVCALL_DETACH_DEVICE_DOMAIN, input, NULL);

FWIW the hypervisor cannot implement the linux attach semantics if it has detach/attach. It must support simply 'attach' which atomically changes the translation. With detach you have a confusing problem if errors happen in the middle of the sequence the device is left in an unclear state. You should at least document what state the hypervisor is supposed to leaave the translation iin during these failures..

Thanks for raising this!

My understanding is that the detach hypercall just clears the HW IOMMU entry for the device (e.g., context table entry on VT-d, DTE on AMD IOMMU) and flushes the IOTLB. So after detach and before the subsequent attach, DMA from the device is blocked by the HW IOMMU
- the device is not in an unprotected state.

The detach shall not fail unless the pvIOMMU driver passes incorrect parameters or is otherwise in a buggy state, or Hyper-V itself has a bug.

But making attach atomic might be a cleaner approach (drop the explicit detach and let the hypervisor handle the domain switch internally)? I'll look into making that work, though it needs verification (and possibly changes) on the hypervisor side (these hypercalls are not exclusively for Linux guest). If that doesn't work out, I'll keep the two-step approach with comments documenting the intermediate translation state.

Quoted 5 lines
Quoted 5 lines
drivers/iommu/hyperv/iommu.c new file +5 -0
+static void hv_iommu_release_device(struct device *dev)
+{
+	struct hv_iommu_endpoint *vdev = dev_iommu_priv_get(dev);
+	struct pci_dev *pdev = to_pci_dev(dev);
+
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 376

Quoted 5 lines
drivers/iommu/hyperv/iommu.c new file +5 -0
+	if (pdev->ats_enabled)
+		pci_disable_ats(pdev);
+
+	dev_iommu_priv_set(dev, NULL);
+	set_dma_ops(dev, NULL);

Does the driver really need to mess with set_dma_ops ? I'd rather not see that in new iommu drivers if at all possible :|

No. I should have removed it. Thanks!

Quoted 15 lines
Quoted 15 lines
drivers/iommu/hyperv/iommu.c new file +15 -0
+static int __init hv_initialize_static_domains(void)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+
+	/* Default stage-1 identity domain */
+	hv_domain = &hv_identity_domain;
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret)
+		return ret;
+
+	ret = hv_configure_device_domain(hv_domain, IOMMU_DOMAIN_IDENTITY);
+	if (ret)
+		goto delete_identity_domain;
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 440

Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+
+	hv_domain->domain.type = IOMMU_DOMAIN_IDENTITY;
+	hv_domain->domain.ops = &hv_iommu_identity_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap = hv_iommu_device->pgsize_bitmap;

identity doesn't use geometry or pgsize_bitmap

Sure. Will remove it.

Quoted 10 lines
Quoted 10 lines
drivers/iommu/hyperv/iommu.c new file +10 -0
+	/* Default stage-1 blocked domain */
+	hv_domain = &hv_blocking_domain;
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret)
+		goto delete_identity_domain;
+
+	ret = hv_configure_device_domain(hv_domain, IOMMU_DOMAIN_BLOCKED);
+	if (ret)
+		goto delete_blocked_domain;
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 457

Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+
+	hv_domain->domain.type = IOMMU_DOMAIN_BLOCKED;
+	hv_domain->domain.ops = &hv_iommu_blocking_domain_ops;
+	hv_domain->domain.owner = &hv_iommu_ops;
+	hv_domain->domain.geometry = hv_iommu_device->geometry;
+	hv_domain->domain.pgsize_bitmap = hv_iommu_device->pgsize_bitmap;

Nor does blocked

Same. Will remove.

Quoted 4 lines
Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+#define INTERRUPT_RANGE_START	(0xfee00000)
+#define INTERRUPT_RANGE_END	(0xfeefffff)
+static void hv_iommu_get_resv_regions(struct device *dev,
+		struct list_head *head)
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 477

Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+{
+	struct iommu_resv_region *region;
+
+	region = iommu_alloc_resv_region(INTERRUPT_RANGE_START,
+				      INTERRUPT_RANGE_END - INTERRUPT_RANGE_START + 1,
+				      0, IOMMU_RESV_MSI, GFP_KERNEL);

Surprised these constants are not discovered from the hv?

Thanks. Since the pvIOMMU currently only targets x86, hardcoding the x86 architectural MSI range should be reasonable?

If in the future we need additional reserved regions (e.g., RMRR-style identity-mapped ranges), those would be discovered from the hypervisor.

Quoted 6 lines
Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+}
+
+static void hv_iommu_iotlb_sync(struct iommu_domain *domain,
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 495

Quoted 6 lines
drivers/iommu/hyperv/iommu.c new file +6 -0
+				struct iommu_iotlb_gather *iotlb_gather)
+{
+	hv_flush_device_domain(to_hv_iommu_domain(domain));
+
+	iommu_put_pages_list(&iotlb_gather->freelist);
+}

Full invalidation only huh?

Page-selective IOTLB flush is added in patch 4/4.

Quoted 4 lines
Quoted 4 lines
drivers/iommu/hyperv/iommu.c new file +4 -0
+static const struct iommu_domain_ops hv_iommu_identity_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 515

Quoted 3 lines
drivers/iommu/hyperv/iommu.c new file +3 -0
+static const struct iommu_domain_ops hv_iommu_blocking_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+};

Usually I would expect these to have their own attach functions. blocking in particular must have an attach op that cannot fail. It is used to recover the device back to a known translation in case of cascading other errors.

For blocking domain, the hypercall handler of such attach essentially disable the translation and IOPF for the device. It should not fail unless there is a bug in the driver or the hypervisor.
How about something like this?

	static int hv_blocking_attach_dev(domain, dev, old)
	{
		...
		status = hv_do_hypercall(HVCALL_ATTACH, blocking, dev);
		WARN_ON(!hv_result_success(status));
		vdev->hv_domain = blocking;
		return 0;
	}

For identity domain, would it be fine to keep sharing the same attach callback with paging domain?

Quoted 20 lines
Quoted 20 lines
drivers/iommu/hyperv/iommu.c new file +20 -0
+static const struct iommu_domain_ops hv_iommu_paging_domain_ops = {
+	.attach_dev	= hv_iommu_attach_dev,
+	IOMMU_PT_DOMAIN_OPS(x86_64),
+	.flush_iotlb_all = hv_iommu_flush_iotlb_all,
+	.iotlb_sync = hv_iommu_iotlb_sync,
+	.free = hv_iommu_paging_domain_free,
+};
+
+static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev)
+{
+	int ret;
+	struct hv_iommu_domain *hv_domain;
+	struct pt_iommu_x86_64_cfg cfg = {};
+
+	hv_domain = kzalloc_obj(*hv_domain, GFP_KERNEL);
+	if (!hv_domain)
+		return ERR_PTR(-ENOMEM);
+
+	ret = hv_create_device_domain(hv_domain, HV_DEVICE_DOMAIN_TYPE_S1);
+	if (ret) {
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 541

Quoted 5 lines
drivers/iommu/hyperv/iommu.c new file +5 -0
+		kfree(hv_domain);
+		return ERR_PTR(ret);
+	}
+
+	hv_domain->domain.geometry = hv_iommu_device->geometry;

geoemtry shouldn't be set here, it is overriden by pt_iommu_x86_64_init() with the exact page table configuration

Right. Will remove.

Quoted 22 lines
Quoted 22 lines
drivers/iommu/hyperv/iommu.c new file +22 -0
+static void __init hv_init_iommu_device(struct hv_iommu_dev *hv_iommu,
+			struct hv_output_get_iommu_capabilities *hv_iommu_cap)
+{
+	ida_init(&hv_iommu->domain_ids);
+
+	hv_iommu->cap = hv_iommu_cap->iommu_cap;
+	hv_iommu->max_iova_width = hv_iommu_cap->max_iova_width;
+	if (!hv_iommu_5lvl_supported(hv_iommu->cap) &&
+	    hv_iommu->max_iova_width > 48) {
+		pr_info("5-level paging not supported, limiting iova width to 48.\n");
+		hv_iommu->max_iova_width = 48;
+	}
+
+	hv_iommu->geometry = (struct iommu_domain_geometry) {
+		.aperture_start = 0,
+		.aperture_end = (((u64)1) << hv_iommu->max_iova_width) - 1,
+		.force_aperture = true,
+	};
+
+	hv_iommu->first_domain = HV_DEVICE_DOMAIN_ID_DEFAULT + 1;
+	hv_iommu->last_domain = HV_DEVICE_DOMAIN_ID_NULL - 1;
+	/* Only x86 page sizes (4K/2M/1G) are supported */
Quoted 9 lines

drivers/iommu/hyperv/iommu.c line 634

Quoted 5 lines
drivers/iommu/hyperv/iommu.c new file +5 -0
+	hv_iommu->pgsize_bitmap = hv_iommu_cap->pgsize_bitmap &
+				  (SZ_4K | SZ_2M | SZ_1G);
+	if (hv_iommu->pgsize_bitmap != hv_iommu_cap->pgsize_bitmap)
+		pr_warn("unsupported page sizes masked: 0x%llx -> 0x%llx\n",
+			hv_iommu_cap->pgsize_bitmap, hv_iommu->pgsize_bitmap);

IKD if you need this logic, the way the page table code is used it just sort of falls out naturally that other page sizes are ignored.

Right, the page table code can handle 4K/2M/1G naturally. We'd like hypervisor to be able to choose to support only a subset of {4K, 2M, 1G}. This masking filters out any unexpected page sizes and falls back to 4K if nothing valid remains.

The if statement may be a bit paranoid perhaps, but it felt safer to validate explicitly. Happy to drop it if you think it's unnecessary.

Quoted 9 lines

drivers/iommu/hyperv/iommu.h line 33

Quoted 6 lines
drivers/iommu/hyperv/iommu.h new file +6 -0
+struct hv_iommu_domain {
+	union {
+		struct iommu_domain    domain;
+		struct pt_iommu        pt_iommu;
+		struct pt_iommu_x86_64 pt_iommu_x86_64;
+	};

You should retain the build assertions here

Sure. Thanks!

B.R.
Yu

Quoted 2 lines

Jason

#21 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Hi Yu,

Quoted 16 lines · On Wed, 20 May 2026 23:25:43 +0800 Yu Zhang <[email protected]>…
Quoted 6 lines
Quoted 6 lines

+static const struct iommu_domain_ops
hv_iommu_identity_domain_ops = {

drivers/iommu/hyperv/iommu.c new file +4 -0
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops
Quoted 9 lines

Review

Quoted 3 lines

hv_iommu_blocking_domain_ops = {

(quoted diff) +2 -0
+	.attach_dev	= hv_iommu_attach_dev,
+};  

Usually I would expect these to have their own attach functions. blocking in particular must have an attach op that cannot fail. It is used to recover the device back to a known translation in case of cascading other errors.

Quoted 2 lines

For blocking domain, the hypercall handler of such attach essentially disable the translation and IOPF for the device.

I think this should disable all faults, including unrecoverable fault reporting. right?

author
#22 lore raw

Re: [PATCH v1 3/4] iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest

Quoted 21 lines · Jacob Pan

Hi Yu,

Quoted 16 lines · On Wed, 20 May 2026 23:25:43 +0800 Yu Zhang <[email protected]>…
Quoted 15 lines

Review

Quoted 9 lines

+static const struct iommu_domain_ops
hv_iommu_identity_domain_ops = {

drivers/iommu/hyperv/iommu.c new file +4 -0
+	.attach_dev	= hv_iommu_attach_dev,
+};
+
+static const struct iommu_domain_ops

hv_iommu_blocking_domain_ops = {

(quoted diff) +2 -0
+	.attach_dev	= hv_iommu_attach_dev,
+};  

Usually I would expect these to have their own attach functions. blocking in particular must have an attach op that cannot fail. It is used to recover the device back to a known translation in case of cascading other errors.

Quoted 4 lines
Quoted 2 lines

For blocking domain, the hypercall handler of such attach essentially disable the translation and IOPF for the device.

I think this should disable all faults, including unrecoverable fault reporting. right?

Yes, it should (e.g., my understanding is it shall set the FPD in scalable mode context entry). Will double confirm with hypervisor team and make sure it behaves so.

B.R.
Yu

author
#23 lore raw

PATCH 4/4 iommu/hyperv: Add page-selective IOTLB flush support

In reply to Yu Zhang

Add page-selective IOTLB flush using HVCALL_FLUSH_DEVICE_DOMAIN_LIST. This hypercall accepts a list of (page_number, page_mask_shift) entries, enabling finer-grained IOTLB invalidation compared to the domain-wide HVCALL_FLUSH_DEVICE_DOMAIN used by hv_iommu_flush_iotlb_all().

hv_iommu_fill_iova_list() decomposes a contiguous IOVA range into a minimal set of aligned power-of-two regions that fit in a single hypercall input page. When the range exceeds the page capacity, the code falls back to a full domain flush automatically.

---
 drivers/iommu/hyperv/iommu.c | 91 +++++++++++++++++++++++++++++++++++-
 include/hyperv/hvgdk_mini.h  |  1 +
 include/hyperv/hvhdk_mini.h  | 17 +++++++
 3 files changed, 108 insertions(+), 1 deletion(-)
drivers/iommu/hyperv/iommu.c +90 -1
index e5fc625314b5..3bca362b7815 100644
@@ -486,10 +486,98 @@ static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
 	hv_flush_device_domain(to_hv_iommu_domain(domain));
 }
 
+/* Max number of iova_list entries in a single hypercall input page. */
+#define HV_IOMMU_MAX_FLUSH_VA_COUNT \
+	((HV_HYP_PAGE_SIZE - sizeof(struct hv_input_flush_device_domain_list)) / \
+	 sizeof(union hv_iommu_flush_va))
+
+/* Returned by hv_iommu_fill_iova_list() when the range exceeds the capacity */
+#define HV_IOMMU_FLUSH_VA_OVERFLOW	U16_MAX
+
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}
+
+	return count;
+}
+
+static void hv_flush_device_domain_list(struct hv_iommu_domain *hv_domain,
+					struct iommu_iotlb_gather *iotlb_gather)
+{
+	u64 status;
+	u16 count;
+	unsigned long flags;
+	struct hv_input_flush_device_domain_list *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+
+	input->device_domain = hv_domain->device_domain;
+	input->flags |= HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT;
+	count = hv_iommu_fill_iova_list(input->iova_list,
+					iotlb_gather->start,
+					iotlb_gather->end);
+	if (count == HV_IOMMU_FLUSH_VA_OVERFLOW) {
+		/*
+		 * Range exceeds hypercall page capacity. Fall back to a full
+		 * domain flush.
+		 */
+		struct hv_input_flush_device_domain *flush_all = (void *)input;
+
+		memset(flush_all, 0, sizeof(*flush_all));
+		flush_all->device_domain = hv_domain->device_domain;
+		status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN,
+					flush_all, NULL);
+	} else {
+		status = hv_do_rep_hypercall(
+				HVCALL_FLUSH_DEVICE_DOMAIN_LIST,
+				count, 0, input, NULL);
+	}
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN_LIST failed, status %lld\n", status);
+}
+
 static void hv_iommu_iotlb_sync(struct iommu_domain *domain,
 				struct iommu_iotlb_gather *iotlb_gather)
 {
-	hv_flush_device_domain(to_hv_iommu_domain(domain));
+	hv_flush_device_domain_list(to_hv_iommu_domain(domain), iotlb_gather);
 
 	iommu_put_pages_list(&iotlb_gather->freelist);
 }
@@ -543,6 +631,7 @@ static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev)
 
 	cfg.common.hw_max_vasz_lg2 = hv_iommu_device->max_iova_width;
 	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE);
 	cfg.top_level = (hv_iommu_device->max_iova_width > 48) ? 4 : 3;
 
 	ret = pt_iommu_x86_64_init(&hv_domain->pt_iommu_x86_64, &cfg, GFP_KERNEL);
include/hyperv/hvgdk_mini.h +1 -0
index 5bdbb44da112..eaaf87171478 100644
@@ -496,6 +496,7 @@ union hv_vp_assist_msr_contents {	 /* HV_REGISTER_VP_ASSIST_PAGE */
 #define HVCALL_GET_GPA_PAGES_ACCESS_STATES		0x00c9
 #define HVCALL_CONFIGURE_DEVICE_DOMAIN			0x00ce
 #define HVCALL_FLUSH_DEVICE_DOMAIN			0x00d0
+#define HVCALL_FLUSH_DEVICE_DOMAIN_LIST			0x00d1
 #define HVCALL_ACQUIRE_SPARSE_SPA_PAGE_HOST_ACCESS	0x00d7
 #define HVCALL_RELEASE_SPARSE_SPA_PAGE_HOST_ACCESS	0x00d8
 #define HVCALL_MODIFY_SPARSE_GPA_PAGE_HOST_VISIBILITY	0x00db
include/hyperv/hvhdk_mini.h +17 -0
index 493608e791b4..f51d5d9467f1 100644
@@ -671,4 +671,21 @@ struct hv_input_flush_device_domain {
 	u32 reserved;
 } __packed;
 
+union hv_iommu_flush_va {
+	u64 iova;
+	struct {
+		u64 page_mask_shift : 12;
+		u64 page_number : 52;
+	};
+} __packed;
+
+
+struct hv_input_flush_device_domain_list {
+	struct hv_input_device_domain device_domain;
+#define HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT (1 << 0)
+	u32 flags;
+	u32 reserved;
+	union hv_iommu_flush_va iova_list[];
+} __packed;
+
 #endif /* _HV_HVHDK_MINI_H */
Signature · 1 line
2.52.0
#24 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Critical] hv_iommu_fill_iova_list() incorrectly uses guest PAGE_SHIFT instead of hypervisor…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Critical] hv_iommu_fill_iova_list() incorrectly uses guest PAGE_SHIFT instead of hypervisor HV_HYP_PAGE_SHIFT, causing incomplete and incorrect IOTLB flushes on architectures with non-4KB pages.
- [High] Unconditional use of the new HVCALL_FLUSH_DEVICE_DOMAIN_LIST hypercall without a capability check or fallback.
- [Medium] Bitfield assignment on uninitialized flexible array member causes KMSAN use-of-uninitialized-value warnings.
--

commit 5fd02fd07f9fbc4f1734f312b8a33dfd79a38961
Author: Yu Zhang <[email protected]>

iommu/hyperv: Add page-selective IOTLB flush support

This patch adds page-selective IOTLB flush support using the HVCALL_FLUSH_DEVICE_DOMAIN_LIST hypercall. It decomposes IOVA ranges into aligned power-of-two regions to fit in a single hypercall page, falling back to a full domain flush if the range exceeds page capacity.

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +0 -0
index e5fc625314b55..3bca362b78150 100644

[ ... ]

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 502

Quoted 6 lines
drivers/iommu/hyperv/iommu.c +6 -0
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;

Should this use HV_HYP_PAGE_SHIFT instead of PAGE_SHIFT?

If the kernel is compiled with a larger page size (like 64KB on ARM64), start >> PAGE_SHIFT produces a 64KB guest PFN.

Since Hyper-V hypercalls expect 4KB PFNs (HV_HYP_PAGE_SHIFT = 12), this could result in flushing the wrong pages and leaving stale DMA mappings active.

Quoted 13 lines
drivers/iommu/hyperv/iommu.c +13 -0
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 525

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;

Could this assignment trigger a KMSAN use-of-uninitialized-value warning?

The input buffer is from a per-CPU page and memset in hv_flush_device_domain_list() only zeroes the fixed-size header, leaving the flexible array uninitialized.

Assigning to bitfields forces a read-modify-write on the uninitialized 64-bit union hv_iommu_flush_va.

Quoted 39 lines
drivers/iommu/hyperv/iommu.c +39 -0
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}
+
+	return count;
+}
+
+static void hv_flush_device_domain_list(struct hv_iommu_domain *hv_domain,
+					struct iommu_iotlb_gather *iotlb_gather)
+{
+	u64 status;
+	u16 count;
+	unsigned long flags;
+	struct hv_input_flush_device_domain_list *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+
+	input->device_domain = hv_domain->device_domain;
+	input->flags |= HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT;
+	count = hv_iommu_fill_iova_list(input->iova_list,
+					iotlb_gather->start,
+					iotlb_gather->end);
+	if (count == HV_IOMMU_FLUSH_VA_OVERFLOW) {
+		/*
+		 * Range exceeds hypercall page capacity. Fall back to a full
+		 * domain flush.
+		 */
+		struct hv_input_flush_device_domain *flush_all = (void *)input;
+
+		memset(flush_all, 0, sizeof(*flush_all));
+		flush_all->device_domain = hv_domain->device_domain;
+		status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN,
+					flush_all, NULL);

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 574

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+	} else {
+		status = hv_do_rep_hypercall(
+				HVCALL_FLUSH_DEVICE_DOMAIN_LIST,
+				count, 0, input, NULL);
+	}
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN_LIST failed, status %lld\n", status);

Does this code need a capability check or fallback for older hosts?

If the hypervisor doesn't support the new HVCALL_FLUSH_DEVICE_DOMAIN_LIST hypercall, hv_do_rep_hypercall() might return an error status.

The code prints an error but doesn't fall back to HVCALL_FLUSH_DEVICE_DOMAIN, potentially leaving the IOTLB unflushed.

Quoted 1 line

+}

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

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

In reply to Yu Zhang

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 31 lines

Add page-selective IOTLB flush using HVCALL_FLUSH_DEVICE_DOMAIN_LIST. This hypercall accepts a list of (page_number, page_mask_shift) entries, enabling finer-grained IOTLB invalidation compared to the domain-wide HVCALL_FLUSH_DEVICE_DOMAIN used by hv_iommu_flush_iotlb_all().

hv_iommu_fill_iova_list() decomposes a contiguous IOVA range into a minimal set of aligned power-of-two regions that fit in a single hypercall input page. When the range exceeds the page capacity, the code falls back to a full domain flush automatically.

---
 drivers/iommu/hyperv/iommu.c | 91 +++++++++++++++++++++++++++++++++++-
 include/hyperv/hvgdk_mini.h  |  1 +
 include/hyperv/hvhdk_mini.h  | 17 +++++++
 3 files changed, 108 insertions(+), 1 deletion(-)
drivers/iommu/hyperv/iommu.c +4 -0
index e5fc625314b5..3bca362b7815 100644
@@ -486,10 +486,98 @@ static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
 	hv_flush_device_domain(to_hv_iommu_domain(domain));
 }
 
+/* Max number of iova_list entries in a single hypercall input page. */
+#define HV_IOMMU_MAX_FLUSH_VA_COUNT \
+	((HV_HYP_PAGE_SIZE - sizeof(struct hv_input_flush_device_domain_list)) / \
+	 sizeof(union hv_iommu_flush_va))

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 502

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+
+/* Returned by hv_iommu_fill_iova_list() when the range exceeds the capacity */
+#define HV_IOMMU_FLUSH_VA_OVERFLOW	U16_MAX
+
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;

"end" is an inclusive end address per comment in struct iommu_iotlb_gather. So a page aligned value would typically have 0xFFF as the low order 12 bits, and PAGE_ALIGN() will do the right thing. But I don't think the value is *required* to be page aligned. If the value of "end" had 0x000 as the low order 12 bits, the above calculation would fail to include the page that has the address ending in 0x000. I think it needs to be PAGE_ALIGN(end + 1) in order to work correctly for this corner case.

Quoted 6 lines
drivers/iommu/hyperv/iommu.c +6 -0
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 518

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);

I don't understand why __ffs() is correct here. I would expect __fls() so it is consistent with the calculation of size_align. But I can only surmise how the hypercall works since there's no documentation, so maybe my understanding of the hypercall is
wrong. If __ffs really is correct, a comment explaining why
would help. :-)

Quoted 22 lines
drivers/iommu/hyperv/iommu.c +22 -0
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}
+
+	return count;
+}
+
+static void hv_flush_device_domain_list(struct hv_iommu_domain *hv_domain,
+					struct iommu_iotlb_gather *iotlb_gather)
+{
+	u64 status;
+	u16 count;

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 550

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+	unsigned long flags;
+	struct hv_input_flush_device_domain_list *input;
+
+	local_irq_save(flags);
+
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+
+	input->device_domain = hv_domain->device_domain;
+	input->flags |= HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT;

I would suggest moving the memset() and setting the input fields down under the "else" below so that they are parallel with the flush all case.

Quoted 14 lines
drivers/iommu/hyperv/iommu.c +14 -0
+	count = hv_iommu_fill_iova_list(input->iova_list,
+					iotlb_gather->start,
+					iotlb_gather->end);
+	if (count == HV_IOMMU_FLUSH_VA_OVERFLOW) {
+		/*
+		 * Range exceeds hypercall page capacity. Fall back to a full
+		 * domain flush.
+		 */
+		struct hv_input_flush_device_domain *flush_all = (void *)input;
+
+		memset(flush_all, 0, sizeof(*flush_all));
+		flush_all->device_domain = hv_domain->device_domain;
+		status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN,
+					flush_all, NULL);

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 574

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+	} else {
+		status = hv_do_rep_hypercall(
+				HVCALL_FLUSH_DEVICE_DOMAIN_LIST,
+				count, 0, input, NULL);
+	}
+
+	local_irq_restore(flags);
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN_LIST failed, status %lld\n", status);

As Sashiko pointed out, a failure here can lead to all kinds of trouble because of leaving unflushed entries. Maybe a WARN() is more appropriate? Also, maybe a failure in the list flush should try a flush all as a fallback, with the WARN() only if the flush all fails.

Quoted 61 lines
drivers/iommu/hyperv/iommu.c +4 -1
+}
+
 static void hv_iommu_iotlb_sync(struct iommu_domain *domain,
 				struct iommu_iotlb_gather *iotlb_gather)
 {
-	hv_flush_device_domain(to_hv_iommu_domain(domain));
+	hv_flush_device_domain_list(to_hv_iommu_domain(domain), iotlb_gather);
 
 	iommu_put_pages_list(&iotlb_gather->freelist);
 }
@@ -543,6 +631,7 @@ static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev)
 
 	cfg.common.hw_max_vasz_lg2 = hv_iommu_device->max_iova_width;
 	cfg.common.hw_max_oasz_lg2 = 52;
+	cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE);
 	cfg.top_level = (hv_iommu_device->max_iova_width > 48) ? 4 : 3;
 
 	ret = pt_iommu_x86_64_init(&hv_domain->pt_iommu_x86_64, &cfg,

GFP_KERNEL);

include/hyperv/hvgdk_mini.h +0 -0
index 5bdbb44da112..eaaf87171478 100644
@@ -496,6 +496,7 @@ union hv_vp_assist_msr_contents {	 /*

HV_REGISTER_VP_ASSIST_PAGE */
#define HVCALL_GET_GPA_PAGES_ACCESS_STATES 0x00c9
#define HVCALL_CONFIGURE_DEVICE_DOMAIN 0x00ce
#define HVCALL_FLUSH_DEVICE_DOMAIN 0x00d0

include/hyperv/hvgdk_mini.h +1 -0
+#define HVCALL_FLUSH_DEVICE_DOMAIN_LIST			0x00d1
 #define HVCALL_ACQUIRE_SPARSE_SPA_PAGE_HOST_ACCESS	0x00d7
 #define HVCALL_RELEASE_SPARSE_SPA_PAGE_HOST_ACCESS	0x00d8
 #define HVCALL_MODIFY_SPARSE_GPA_PAGE_HOST_VISIBILITY	0x00db
include/hyperv/hvhdk_mini.h +17 -1
index 493608e791b4..f51d5d9467f1 100644
@@ -671,4 +671,21 @@ struct hv_input_flush_device_domain {
 	u32 reserved;
 } __packed;
 
+union hv_iommu_flush_va {
+	u64 iova;
+	struct {
+		u64 page_mask_shift : 12;
+		u64 page_number : 52;
+	};
+} __packed;
+
+
+struct hv_input_flush_device_domain_list {
+	struct hv_input_device_domain device_domain;
+#define HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT (1 << 0)
+	u32 flags;
+	u32 reserved;
+	union hv_iommu_flush_va iova_list[];
+} __packed;
+
 #endif /* _HV_HVHDK_MINI_H */
--

2.52.0

#26 lore raw

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

From: Michael Kelley <[email protected]> Sent: Thursday, May 14, 2026 11:14 AM

Quoted 44 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 31 lines

Add page-selective IOTLB flush using HVCALL_FLUSH_DEVICE_DOMAIN_LIST. This hypercall accepts a list of (page_number, page_mask_shift) entries, enabling finer-grained IOTLB invalidation compared to the domain-wide HVCALL_FLUSH_DEVICE_DOMAIN used by hv_iommu_flush_iotlb_all().

hv_iommu_fill_iova_list() decomposes a contiguous IOVA range into a minimal set of aligned power-of-two regions that fit in a single hypercall input page. When the range exceeds the page capacity, the code falls back to a full domain flush automatically.

---
 drivers/iommu/hyperv/iommu.c | 91 +++++++++++++++++++++++++++++++++++-
 include/hyperv/hvgdk_mini.h  |  1 +
 include/hyperv/hvhdk_mini.h  | 17 +++++++
 3 files changed, 108 insertions(+), 1 deletion(-)
drivers/iommu/hyperv/iommu.c +4 -0
index e5fc625314b5..3bca362b7815 100644
@@ -486,10 +486,98 @@ static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
 	hv_flush_device_domain(to_hv_iommu_domain(domain));
 }
 
+/* Max number of iova_list entries in a single hypercall input page. */
+#define HV_IOMMU_MAX_FLUSH_VA_COUNT \
+	((HV_HYP_PAGE_SIZE - sizeof(struct hv_input_flush_device_domain_list)) / \
+	 sizeof(union hv_iommu_flush_va))

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 502

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+
+/* Returned by hv_iommu_fill_iova_list() when the range exceeds the capacity */
+#define HV_IOMMU_FLUSH_VA_OVERFLOW	U16_MAX
+
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
Quoted 8 lines

"end" is an inclusive end address per comment in struct iommu_iotlb_gather. So a page aligned value would typically have 0xFFF as the low order 12 bits, and PAGE_ALIGN() will do the right thing. But I don't think the value is *required* to be page aligned. If the value of "end" had 0x000 as the low order 12 bits, the above calculation would fail to include the page that has the address ending in 0x000. I think it needs to be PAGE_ALIGN(end + 1) in order to work correctly for this corner case.

One follow-on comment: the macros HVPFN_UP() and HVPFN_DOWN() would likely be useful in setting start_pfn and end_pfn.

Michael

author
#27 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

In reply to Michael Kelley
Quoted 43 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 31 lines

Add page-selective IOTLB flush using HVCALL_FLUSH_DEVICE_DOMAIN_LIST. This hypercall accepts a list of (page_number, page_mask_shift) entries, enabling finer-grained IOTLB invalidation compared to the domain-wide HVCALL_FLUSH_DEVICE_DOMAIN used by hv_iommu_flush_iotlb_all().

hv_iommu_fill_iova_list() decomposes a contiguous IOVA range into a minimal set of aligned power-of-two regions that fit in a single hypercall input page. When the range exceeds the page capacity, the code falls back to a full domain flush automatically.

---
 drivers/iommu/hyperv/iommu.c | 91 +++++++++++++++++++++++++++++++++++-
 include/hyperv/hvgdk_mini.h  |  1 +
 include/hyperv/hvhdk_mini.h  | 17 +++++++
 3 files changed, 108 insertions(+), 1 deletion(-)
drivers/iommu/hyperv/iommu.c +4 -0
index e5fc625314b5..3bca362b7815 100644
@@ -486,10 +486,98 @@ static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain)
 	hv_flush_device_domain(to_hv_iommu_domain(domain));
 }
 
+/* Max number of iova_list entries in a single hypercall input page. */
+#define HV_IOMMU_MAX_FLUSH_VA_COUNT \
+	((HV_HYP_PAGE_SIZE - sizeof(struct hv_input_flush_device_domain_list)) / \
+	 sizeof(union hv_iommu_flush_va))

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 502

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+
+/* Returned by hv_iommu_fill_iova_list() when the range exceeds the capacity */
+#define HV_IOMMU_FLUSH_VA_OVERFLOW	U16_MAX
+
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
Quoted 8 lines

"end" is an inclusive end address per comment in struct iommu_iotlb_gather. So a page aligned value would typically have 0xFFF as the low order 12 bits, and PAGE_ALIGN() will do the right thing. But I don't think the value is *required* to be page aligned. If the value of "end" had 0x000 as the low order 12 bits, the above calculation would fail to include the page that has the address ending in 0x000. I think it needs to be PAGE_ALIGN(end + 1) in order to work correctly for this corner case.

Good catch! Will use HVPFN_DOWN(start) and HVPFN_UP(end + 1) as you suggested in your follow-up mail.

Quoted 15 lines
Quoted 15 lines
drivers/iommu/hyperv/iommu.c +15 -0
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 518

Quoted 1 line
drivers/iommu/hyperv/iommu.c +1 -0
+			pfn_align = __ffs(start_pfn);

I don't understand why __ffs() is correct here. I would expect __fls() so it is consistent with the calculation of size_align. But I can only surmise how the hypercall works since there's no documentation, so maybe my understanding of the hypercall is
wrong. If __ffs really is correct, a comment explaining why
would help. :-)

The use of __ffs() is intentional. Each flush entry invalidates a naturally aligned 2^N page block, and the hypervisor requires the page_number to be aligned to 2^page_mask_shift.

Here __ffs() and __fls() serve different purposes:
- __ffs(start_pfn) is about the alignment constraint, e.g., how large a block can this address support?
- __fls(nr_pages) is about the size constraint, e.g., how large a block can the remaining range hold?

Taking min() of both ensures each entry is both properly aligned and within bounds.

Thanks for raising this — it definitely deserves a comment. I had to stare at it for a while myself to remember why. :)

Quoted 27 lines
Quoted 27 lines
drivers/iommu/hyperv/iommu.c +27 -0
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}
+
+	return count;
+}
+
+static void hv_flush_device_domain_list(struct hv_iommu_domain *hv_domain,
+					struct iommu_iotlb_gather *iotlb_gather)
+{
+	u64 status;
+	u16 count;
+	unsigned long flags;
+	struct hv_input_flush_device_domain_list *input;
+
+	local_irq_save(flags);
+
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 550

Quoted 5 lines
drivers/iommu/hyperv/iommu.c +5 -0
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+
+	input->device_domain = hv_domain->device_domain;
+	input->flags |= HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT;

I would suggest moving the memset() and setting the input fields down under the "else" below so that they are parallel with the flush all case.

I agree the structure should be more symmetric. Yet I guess the memset and hv_iommu_fill_iova_list() need to stay before the branch since the fill writes directly into input->iova_list[]. :)

Quoted 21 lines
Quoted 21 lines
drivers/iommu/hyperv/iommu.c +21 -0
+	count = hv_iommu_fill_iova_list(input->iova_list,
+					iotlb_gather->start,
+					iotlb_gather->end);
+	if (count == HV_IOMMU_FLUSH_VA_OVERFLOW) {
+		/*
+		 * Range exceeds hypercall page capacity. Fall back to a full
+		 * domain flush.
+		 */
+		struct hv_input_flush_device_domain *flush_all = (void *)input;
+
+		memset(flush_all, 0, sizeof(*flush_all));
+		flush_all->device_domain = hv_domain->device_domain;
+		status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN,
+					flush_all, NULL);
+	} else {
+		status = hv_do_rep_hypercall(
+				HVCALL_FLUSH_DEVICE_DOMAIN_LIST,
+				count, 0, input, NULL);
+	}
+
+	local_irq_restore(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 574

Quoted 3 lines
drivers/iommu/hyperv/iommu.c +3 -0
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN_LIST failed, status %lld\n", status);

As Sashiko pointed out, a failure here can lead to all kinds of trouble because of leaving unflushed entries. Maybe a WARN() is more appropriate? Also, maybe a failure in the list flush should try a flush all as a fallback, with the WARN() only if the flush all fails.

Good idea. How about we restructure this routine to sth. like this:

	memset(input, 0, sizeof(*input));
	count = hv_iommu_fill_iova_list(...);
	
	if (count != HV_IOMMU_FLUSH_VA_OVERFLOW) {
		input->device_domain = ...;
		...
		status = hv_do_rep_hypercall(FLUSH_DEVICE_DOMAIN_LIST, ...);
		if (hv_result_success(status))
			goto out;
	}
	
	/* overflow or list flush failed: fallback to full domain flush */
	flush_all = (void *)input;
	memset(flush_all, 0, sizeof(*flush_all));
	flush_all->device_domain = ...;
	status = hv_do_hypercall(FLUSH_DEVICE_DOMAIN, ...);
	WARN(!hv_result_success(status), "IOTLB flush failed, status %lld\n", status);

	out:
		local_irq_restore(flags);

B.R.
Yu

#28 lore raw

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 9:24 AM

Quoted 4 lines · Michael Kelley
Quoted 2 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 1 line

[....]

Quoted 35 lines
Quoted 15 lines
Quoted 15 lines
drivers/iommu/hyperv/iommu.c +15 -0
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 518

Quoted 1 line
drivers/iommu/hyperv/iommu.c +1 -0
+			pfn_align = __ffs(start_pfn);

I don't understand why __ffs() is correct here. I would expect __fls() so it is consistent with the calculation of size_align. But I can only surmise how the hypercall works since there's no documentation, so maybe my understanding of the hypercall is
wrong. If __ffs really is correct, a comment explaining why
would help. :-)

The use of __ffs() is intentional. Each flush entry invalidates a naturally aligned 2^N page block, and the hypervisor requires the page_number to be aligned to 2^page_mask_shift.

Here __ffs() and __fls() serve different purposes:
- __ffs(start_pfn) is about the alignment constraint, e.g., how large a block can this address support?
- __fls(nr_pages) is about the size constraint, e.g., how large a block can the remaining range hold?

Quoted 5 lines

Taking min() of both ensures each entry is both properly aligned and within bounds.

Thanks for raising this - it definitely deserves a comment. I had to stare at it for a while myself to remember why. :)

Hmmm. Something about this still nags at me. I'll run some experiments to either convince myself that you are right, or to come up with a counterexample.

A related thought occurred to me. If each flush entry that is passed to Hyper-V describes a naturally aligned 2^N page block, I don't think the HV_IOMMU_MAX_FLUSH_VA_COUNT can ever
be reached. The number of entries is limited by the number of bits in a PFN and the pages count, both of which are 64. And with 52 bit physical addressing and 4KiB pages, the actual size of a PFN and pages count is even smaller than 64. HV_IOMMU_MAX_FLUSH_VA_COUNT is the number of 8 byte
union hv_iommu_flush_va entries that fit in a 4KiB page, so it's ~500.

My statement applies to a single flush range. If multiple flush ranges were strung together in a single hypercall, a larger count could be reached, but hv_flush_device_domain_list() only does a single range. So I don't think the overflow case in hv_flush_device_domain_list() can ever happen. But let me do my experiments, and I will also look at this aspect to confirm if it's right.

Quoted 38 lines
Quoted 28 lines
Quoted 28 lines
drivers/iommu/hyperv/iommu.c +27 -0
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}
+
+	return count;
+}
+
+static void hv_flush_device_domain_list(struct hv_iommu_domain *hv_domain,
+					struct iommu_iotlb_gather *iotlb_gather)
+{
+	u64 status;
+	u16 count;
+	unsigned long flags;
+	struct hv_input_flush_device_domain_list *input;
+
+	local_irq_save(flags);
+
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 550

Quoted 5 lines
drivers/iommu/hyperv/iommu.c +5 -0
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+
+	input->device_domain = hv_domain->device_domain;
+	input->flags |= HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT;

I would suggest moving the memset() and setting the input fields down under the "else" below so that they are parallel with the flush all case.

Quoted 3 lines

I agree the structure should be more symmetric. Yet I guess the memset and hv_iommu_fill_iova_list() need to stay before the branch since the fill writes directly into input->iova_list[]. :)

Agreed.

Quoted 47 lines
Quoted 22 lines
Quoted 22 lines
drivers/iommu/hyperv/iommu.c +21 -0
+	count = hv_iommu_fill_iova_list(input->iova_list,
+					iotlb_gather->start,
+					iotlb_gather->end);
+	if (count == HV_IOMMU_FLUSH_VA_OVERFLOW) {
+		/*
+		 * Range exceeds hypercall page capacity. Fall back to a full
+		 * domain flush.
+		 */
+		struct hv_input_flush_device_domain *flush_all = (void *)input;
+
+		memset(flush_all, 0, sizeof(*flush_all));
+		flush_all->device_domain = hv_domain->device_domain;
+		status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN,
+					flush_all, NULL);
+	} else {
+		status = hv_do_rep_hypercall(
+				HVCALL_FLUSH_DEVICE_DOMAIN_LIST,
+				count, 0, input, NULL);
+	}
+
+	local_irq_restore(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 574

Quoted 3 lines
drivers/iommu/hyperv/iommu.c +3 -0
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN_LIST failed, status %lld\n", status);

As Sashiko pointed out, a failure here can lead to all kinds of trouble because of leaving unflushed entries. Maybe a WARN() is more appropriate? Also, maybe a failure in the list flush should try a flush all as a fallback, with the WARN() only if the flush all fails.

Good idea. How about we restructure this routine to sth. like this:

	memset(input, 0, sizeof(*input));
	count = hv_iommu_fill_iova_list(...);

	if (count != HV_IOMMU_FLUSH_VA_OVERFLOW) {
		input->device_domain = ...;
		...
		status = hv_do_rep_hypercall(FLUSH_DEVICE_DOMAIN_LIST, ...);
		if (hv_result_success(status))
			goto out;
	}

	/* overflow or list flush failed: fallback to full domain flush */
Quoted 9 lines
	flush_all = (void *)input;
	memset(flush_all, 0, sizeof(*flush_all));
	flush_all->device_domain = ...;
	status = hv_do_hypercall(FLUSH_DEVICE_DOMAIN, ...);
	WARN(!hv_result_success(status), "IOTLB flush failed, status %lld\n", status);

	out:
		local_irq_restore(flags);

Yes, I think this works. But per my earlier comment, if I'm right that the overflow case never occurs, it could be simplified further to just do the list flush with the full flush as the error fallback. Then WARN if the full flush fails.

Michael

#29 lore raw

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

From: Michael Kelley <[email protected]> Sent: Friday, May 15, 2026 11:00 AM

Quoted 47 lines

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 9:24 AM

Quoted 4 lines · Michael Kelley
Quoted 2 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 1 line

[....]

Quoted 38 lines
Quoted 15 lines
Quoted 15 lines
drivers/iommu/hyperv/iommu.c +15 -0
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 518

Quoted 1 line
drivers/iommu/hyperv/iommu.c +1 -0
+			pfn_align = __ffs(start_pfn);

I don't understand why __ffs() is correct here. I would expect __fls() so it is consistent with the calculation of size_align. But I can only surmise how the hypercall works since there's no documentation, so maybe my understanding of the hypercall is
wrong. If __ffs really is correct, a comment explaining why
would help. :-)

The use of __ffs() is intentional. Each flush entry invalidates a naturally aligned 2^N page block, and the hypervisor requires the page_number to be aligned to 2^page_mask_shift.

Here __ffs() and __fls() serve different purposes:
- __ffs(start_pfn) is about the alignment constraint, e.g., how large a block can this address support?
- __fls(nr_pages) is about the size constraint, e.g., how large a block can the remaining range hold?

Taking min() of both ensures each entry is both properly aligned and within bounds.

Quoted 6 lines
Quoted 2 lines

Thanks for raising this - it definitely deserves a comment. I had to stare at it for a while myself to remember why. :)

Hmmm. Something about this still nags at me. I'll run some experiments to either convince myself that you are right, or to come up with a counterexample.

I have resolved what was nagging at me. My understanding of how _ffs() and __fls() work was wrong. :-( Your code is correct.

Quoted 12 lines

A related thought occurred to me. If each flush entry that is passed to Hyper-V describes a naturally aligned 2^N page block, I don't think the HV_IOMMU_MAX_FLUSH_VA_COUNT can ever
be reached. The number of entries is limited by the number of bits in a PFN and the pages count, both of which are 64. And with 52 bit physical addressing and 4KiB pages, the actual size of a PFN and pages count is even smaller than 64. HV_IOMMU_MAX_FLUSH_VA_COUNT is the number of 8 byte
union hv_iommu_flush_va entries that fit in a 4KiB page, so it's ~500.

Quoted 7 lines

My statement applies to a single flush range. If multiple flush ranges were strung together in a single hypercall, a larger count could be reached, but hv_flush_device_domain_list() only does a single range. So I don't think the overflow case in hv_flush_device_domain_list() can ever happen. But let me do my experiments, and I will also look at this aspect to confirm if it's right.

My experiments also convince me that the overflow case can't happen as long as the hypercall is being populated with entries derived from a single range.

Michael

Quoted 108 lines
Quoted 39 lines
Quoted 29 lines
Quoted 29 lines
drivers/iommu/hyperv/iommu.c +27 -0
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}
+
+	return count;
+}
+
+static void hv_flush_device_domain_list(struct hv_iommu_domain *hv_domain,
+					struct iommu_iotlb_gather *iotlb_gather)
+{
+	u64 status;
+	u16 count;
+	unsigned long flags;
+	struct hv_input_flush_device_domain_list *input;
+
+	local_irq_save(flags);
+
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 550

Quoted 5 lines
drivers/iommu/hyperv/iommu.c +5 -0
+	input = *this_cpu_ptr(hyperv_pcpu_input_arg);
+	memset(input, 0, sizeof(*input));
+
+	input->device_domain = hv_domain->device_domain;
+	input->flags |= HV_FLUSH_DEVICE_DOMAIN_LIST_IOMMU_FORMAT;

I would suggest moving the memset() and setting the input fields down under the "else" below so that they are parallel with the flush all case.

Quoted 3 lines

I agree the structure should be more symmetric. Yet I guess the memset and hv_iommu_fill_iova_list() need to stay before the branch since the fill writes directly into input->iova_list[]. :)

Agreed.

Quoted 47 lines
Quoted 22 lines
Quoted 22 lines
drivers/iommu/hyperv/iommu.c +21 -0
+	count = hv_iommu_fill_iova_list(input->iova_list,
+					iotlb_gather->start,
+					iotlb_gather->end);
+	if (count == HV_IOMMU_FLUSH_VA_OVERFLOW) {
+		/*
+		 * Range exceeds hypercall page capacity. Fall back to a full
+		 * domain flush.
+		 */
+		struct hv_input_flush_device_domain *flush_all = (void *)input;
+
+		memset(flush_all, 0, sizeof(*flush_all));
+		flush_all->device_domain = hv_domain->device_domain;
+		status = hv_do_hypercall(HVCALL_FLUSH_DEVICE_DOMAIN,
+					flush_all, NULL);
+	} else {
+		status = hv_do_rep_hypercall(
+				HVCALL_FLUSH_DEVICE_DOMAIN_LIST,
+				count, 0, input, NULL);
+	}
+
+	local_irq_restore(flags);
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 574

Quoted 3 lines
drivers/iommu/hyperv/iommu.c +3 -0
+
+	if (!hv_result_success(status))
+		pr_err("HVCALL_FLUSH_DEVICE_DOMAIN_LIST failed, status %lld\n", status);

As Sashiko pointed out, a failure here can lead to all kinds of trouble because of leaving unflushed entries. Maybe a WARN() is more appropriate? Also, maybe a failure in the list flush should try a flush all as a fallback, with the WARN() only if the flush all fails.

Good idea. How about we restructure this routine to sth. like this:

	memset(input, 0, sizeof(*input));
	count = hv_iommu_fill_iova_list(...);

	if (count != HV_IOMMU_FLUSH_VA_OVERFLOW) {
		input->device_domain = ...;
		...
		status = hv_do_rep_hypercall(FLUSH_DEVICE_DOMAIN_LIST, ...);
		if (hv_result_success(status))
			goto out;
	}

	/* overflow or list flush failed: fallback to full domain flush */
Quoted 9 lines
	flush_all = (void *)input;
	memset(flush_all, 0, sizeof(*flush_all));
	flush_all->device_domain = ...;
	status = hv_do_hypercall(FLUSH_DEVICE_DOMAIN, ...);
	WARN(!hv_result_success(status), "IOTLB flush failed, status %lld\n", status);

	out:
		local_irq_restore(flags);

Yes, I think this works. But per my earlier comment, if I'm right that the overflow case never occurs, it could be simplified further to just do the list flush with the full flush as the error fallback. Then WARN if the full flush fails.

Michael

author
#30 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

Quoted 78 lines · Michael Kelley

From: Michael Kelley <[email protected]> Sent: Friday, May 15, 2026 11:00 AM

Quoted 47 lines

From: Yu Zhang <[email protected]> Sent: Friday, May 15, 2026 9:24 AM

Quoted 4 lines · Michael Kelley
Quoted 2 lines

From: Yu Zhang <[email protected]> Sent: Monday, May 11, 2026 9:24 AM

Quoted 1 line

[....]

Quoted 38 lines
Quoted 15 lines
Quoted 15 lines
drivers/iommu/hyperv/iommu.c +15 -0
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
Quoted 9 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 518

Quoted 1 line
drivers/iommu/hyperv/iommu.c +1 -0
+			pfn_align = __ffs(start_pfn);

I don't understand why __ffs() is correct here. I would expect __fls() so it is consistent with the calculation of size_align. But I can only surmise how the hypercall works since there's no documentation, so maybe my understanding of the hypercall is
wrong. If __ffs really is correct, a comment explaining why
would help. :-)

The use of __ffs() is intentional. Each flush entry invalidates a naturally aligned 2^N page block, and the hypervisor requires the page_number to be aligned to 2^page_mask_shift.

Here __ffs() and __fls() serve different purposes:
- __ffs(start_pfn) is about the alignment constraint, e.g., how large a block can this address support?
- __fls(nr_pages) is about the size constraint, e.g., how large a block can the remaining range hold?

Taking min() of both ensures each entry is both properly aligned and within bounds.

Quoted 6 lines
Quoted 2 lines

Thanks for raising this - it definitely deserves a comment. I had to stare at it for a while myself to remember why. :)

Hmmm. Something about this still nags at me. I'll run some experiments to either convince myself that you are right, or to come up with a counterexample.

I have resolved what was nagging at me. My understanding of how _ffs() and __fls() work was wrong. :-( Your code is correct.

Quoted 12 lines

A related thought occurred to me. If each flush entry that is passed to Hyper-V describes a naturally aligned 2^N page block, I don't think the HV_IOMMU_MAX_FLUSH_VA_COUNT can ever
be reached. The number of entries is limited by the number of bits in a PFN and the pages count, both of which are 64. And with 52 bit physical addressing and 4KiB pages, the actual size of a PFN and pages count is even smaller than 64. HV_IOMMU_MAX_FLUSH_VA_COUNT is the number of 8 byte
union hv_iommu_flush_va entries that fit in a 4KiB page, so it's ~500.

Quoted 7 lines

My statement applies to a single flush range. If multiple flush ranges were strung together in a single hypercall, a larger count could be reached, but hv_flush_device_domain_list() only does a single range. So I don't think the overflow case in hv_flush_device_domain_list() can ever happen. But let me do my experiments, and I will also look at this aspect to confirm if it's right.

Quoted 3 lines

My experiments also convince me that the overflow case can't happen as long as the hypercall is being populated with entries derived from a single range.

Gosh. You're right. I think I've been overthinking this :(

So we can simplify this to just do the list flush and fall back to HVCALL_FLUSH_DEVICE_DOMAIN only if the list flush fails.

B.R.
Yu

#31 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

In reply to Yu Zhang
Quoted 25 lines · Yu Zhang
drivers/iommu/hyperv/iommu.c +25 -0
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 10 lines
drivers/iommu/hyperv/iommu.c +10 -0
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Jason

author
#32 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

Quoted 32 lines · Jason Gunthorpe
Quoted 31 lines · Yu Zhang
drivers/iommu/hyperv/iommu.c +31 -0
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
Quoted 8 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +4 -0
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Fair point. I'm not sure how much flexibility we have to change this hypercall interface at the moment - it predates the pvIOMMU work and may have other consumers beyond Linux guest. On the other hand, having the guest specify 2^N-aligned blocks does save the hypervisor from having to decompose ranges itself before issuing hardware invalidation commands - the guest-provided entries can be fed to the HW more or less directly.

That said, the way I'm currently using this interface may be more precise than necessary. Maybe we have 2 options:

1) Current approach: decompose the range into multiple exact 2^N-aligned blocks with no over-flush, but at the cost of more complex calculations and more entries.

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

Any preference?

@Michael, since you've also been reviewing this patch, I'd appreciate your thoughts on the above as well. :)

Yu

#33 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

Quoted 3 lines · Yu Zhang

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

If it is plugged straight into a HW invalidation I would do this..

Jason

#34 lore raw

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

In reply to Yu Zhang

From: Yu Zhang <[email protected]> Sent: Wednesday, May 20, 2026 10:15 AM

Quoted 58 lines · Jason Gunthorpe
Quoted 32 lines · Yu Zhang
Quoted 31 lines
drivers/iommu/hyperv/iommu.c +31 -0
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
Quoted 8 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +4 -0
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Fair point. I'm not sure how much flexibility we have to change this hypercall interface at the moment - it predates the pvIOMMU work and may have other consumers beyond Linux guest. On the other hand, having the guest specify 2^N-aligned blocks does save the hypervisor from having to decompose ranges itself before issuing hardware invalidation commands - the guest-provided entries can be fed to the HW more or less directly.

That said, the way I'm currently using this interface may be more precise than necessary. Maybe we have 2 options:

1) Current approach: decompose the range into multiple exact 2^N-aligned blocks with no over-flush, but at the cost of more complex calculations and more entries.

Quoted 9 lines

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

Any preference?

@Michael, since you've also been reviewing this patch, I'd appreciate your thoughts on the above as well. :)

I'm just guessing, but perhaps flushing an aligned power-of-2 range can be processed by the hypervisor at a relatively fixed cost, regardless of the size. Having the guest do the decomposing of an arbitrary range allows the hypervisor to make use of the existing "rep" hypercall mechanism if the hypercall is taking "too long". The hypervisor can pause its processing, return to the guest temporarily, and then continue the hypercall. If the arbitrary range were passed into the hypercall for the hypervisor to do the decomposing, that pause-and-restart mechanism wouldn't be available.

Of course, Linux doesn't really take advantage of the pause to reduce guest interrupt latency because the Hyper-V code in Linux typically disable interrupts around a hypercall due to the way the hypercall input page is allocated. But other guest operating systems might benefit from such a pause. And we could probably fix the Hyper-V code in Linux to allow interrupts during a hypercall pause/restart if long-running hypercalls turn out to be a problem.

Regarding proposal (1) vs. (2), perhaps you could confirm with the Hyper-V team that flushing an aligned power-of-2 range has relatively fixed cost, regardless of the size. And what do the flush requests coming from the generic IOMMU subsystem look like? Do they match dma_unmap() ranges, which are probably dominated by relatively small ranges of a few pages at most, with a few outliers for disk I/O requests of 1 MiB or some such? If the dominant flush request is for a few pages at most, then doing (2) seems reasonable.

Michael

#35 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

Hi Michael,

Quoted 107 lines · On Wed, 20 May 2026 19:26:24 +0000 Michael Kelley <[email protected]> wrote:

From: Michael Kelley <[email protected]>
To: Yu Zhang <[email protected]>, Jason Gunthorpe <[email protected]> CC: "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]>, "[email protected]" <[email protected]> Subject: RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support Date: Wed, 20 May 2026 19:26:24 +0000

From: Yu Zhang <[email protected]> Sent: Wednesday, May 20, 2026 10:15 AM

Quoted 59 lines · Jason Gunthorpe
Quoted 33 lines · Yu Zhang
Quoted 32 lines

+static inline u16 hv_iommu_fill_iova_list(union
hv_iommu_flush_va *iova_list,

drivers/iommu/hyperv/iommu.c +30 -0
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
Quoted 8 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +4 -0
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}  

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Fair point. I'm not sure how much flexibility we have to change this hypercall interface at the moment - it predates the pvIOMMU work and may have other consumers beyond Linux guest. On the other hand, having the guest specify 2^N-aligned blocks does save the hypervisor from having to decompose ranges itself before issuing hardware invalidation commands - the guest-provided entries can be fed to the HW more or less directly.

That said, the way I'm currently using this interface may be more precise than necessary. Maybe we have 2 options:

1) Current approach: decompose the range into multiple exact 2^N-aligned blocks with no over-flush, but at the cost of more complex calculations and more entries.

Quoted 9 lines

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

Any preference?

@Michael, since you've also been reviewing this patch, I'd appreciate your thoughts on the above as well. :)

I'm just guessing, but perhaps flushing an aligned power-of-2 range can be processed by the hypervisor at a relatively fixed cost, regardless of the size. Having the guest do the decomposing of an arbitrary range allows the hypervisor to make use of the existing "rep" hypercall mechanism if the hypercall is taking "too long". The hypervisor can pause its processing, return to the guest temporarily, and then continue the hypercall. If the arbitrary range were passed into the hypercall for the hypervisor to do the decomposing, that pause-and-restart mechanism wouldn't be available.

Quoted 8 lines

Of course, Linux doesn't really take advantage of the pause to reduce guest interrupt latency because the Hyper-V code in Linux typically disable interrupts around a hypercall due to the way the hypercall input page is allocated. But other guest operating systems might benefit from such a pause. And we could probably fix the Hyper-V code in Linux to allow interrupts during a hypercall pause/restart if long-running hypercalls turn out to be a problem.

I am not sure if this pause feature is suitable for IOTLB flush at all since it is inherently synchronous — the caller must block until all invalidations complete. Pausing mid-flush to return to the guest doesn't help if the guest can't make forward progress anyway.

#36 lore raw

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

From: Jacob Pan <[email protected]> Sent: Wednesday, May 20, 2026 1:40 PM

Quoted 98 lines

Hi Michael,

Quoted 83 lines · On Wed, 20 May 2026 19:26:24 +0000 Michael Kelley <[email protected]> wrote:

From: Michael Kelley <[email protected]> To: Yu Zhang <[email protected]>, Jason Gunthorpe

From: Yu Zhang <[email protected]> Sent: Wednesday, May 20, 2026 10:15 AM

Quoted 59 lines · Jason Gunthorpe
Quoted 33 lines · Yu Zhang
Quoted 32 lines

+static inline u16 hv_iommu_fill_iova_list(union
hv_iommu_flush_va *iova_list,

drivers/iommu/hyperv/iommu.c +30 -0
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
Quoted 8 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +4 -0
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Fair point. I'm not sure how much flexibility we have to change this hypercall interface at the moment - it predates the pvIOMMU work and may have other consumers beyond Linux guest. On the other hand, having the guest specify 2^N-aligned blocks does save the hypervisor from having to decompose ranges itself before issuing hardware invalidation commands - the guest-provided entries can be fed to the HW more or less directly.

That said, the way I'm currently using this interface may be more precise than necessary. Maybe we have 2 options:

1) Current approach: decompose the range into multiple exact 2^N-aligned blocks with no over-flush, but at the cost of more complex calculations and more entries.

Quoted 9 lines

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

Any preference?

@Michael, since you've also been reviewing this patch, I'd appreciate your thoughts on the above as well. :)

I'm just guessing, but perhaps flushing an aligned power-of-2 range can be processed by the hypervisor at a relatively fixed cost, regardless of the size. Having the guest do the decomposing of an arbitrary range allows the hypervisor to make use of the existing "rep" hypercall mechanism if the hypercall is taking "too long". The hypervisor can pause its processing, return to the guest temporarily, and then continue the hypercall. If the arbitrary range were passed into the hypercall for the hypervisor to do the decomposing, that pause-and-restart mechanism wouldn't be available.

Quoted 8 lines

Of course, Linux doesn't really take advantage of the pause to reduce guest interrupt latency because the Hyper-V code in Linux typically disable interrupts around a hypercall due to the way the hypercall input page is allocated. But other guest operating systems might benefit from such a pause. And we could probably fix the Hyper-V code in Linux to allow interrupts during a hypercall pause/restart if long-running hypercalls turn out to be a problem.

Quoted 4 lines

I am not sure if this pause feature is suitable for IOTLB flush at all since it is inherently synchronous — the caller must block until all invalidations complete. Pausing mid-flush to return to the guest doesn't help if the guest can't make forward progress anyway.

I agree that hypercall pause/resume doesn't help with forward progress. But it could help with interrupt latency in the guest if the hypercall executes with interrupts enabled in the guest. During the pause when control returns to the guest, the guest could take an interrupt, versus the interrupt having to wait until the entire hypercall completes. And if preemption is enabled in the guest thread executing the hypercall, the thread could be descheduled, potentially improving scheduling latency.

At least that's my understanding of why Hyper-V has this pause/ resume mechanism for "rep" hypercalls. :-)

Michael

author
#37 lore raw

Re: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

In reply to Michael Kelley
Quoted 89 lines · Michael Kelley

From: Yu Zhang <[email protected]> Sent: Wednesday, May 20, 2026 10:15 AM

Quoted 58 lines · Jason Gunthorpe
Quoted 32 lines · Yu Zhang
Quoted 31 lines
drivers/iommu/hyperv/iommu.c +31 -0
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
Quoted 8 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +4 -0
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Fair point. I'm not sure how much flexibility we have to change this hypercall interface at the moment - it predates the pvIOMMU work and may have other consumers beyond Linux guest. On the other hand, having the guest specify 2^N-aligned blocks does save the hypervisor from having to decompose ranges itself before issuing hardware invalidation commands - the guest-provided entries can be fed to the HW more or less directly.

That said, the way I'm currently using this interface may be more precise than necessary. Maybe we have 2 options:

1) Current approach: decompose the range into multiple exact 2^N-aligned blocks with no over-flush, but at the cost of more complex calculations and more entries.

Quoted 9 lines

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

Any preference?

@Michael, since you've also been reviewing this patch, I'd appreciate your thoughts on the above as well. :)

I'm just guessing, but perhaps flushing an aligned power-of-2 range can be processed by the hypervisor at a relatively fixed cost, regardless of the size. Having the guest do the decomposing of an arbitrary range allows the hypervisor to make use of the existing "rep" hypercall mechanism if the hypercall is taking "too long". The hypervisor can pause its processing, return to the guest temporarily, and then continue the hypercall. If the arbitrary range were passed into the hypercall for the hypervisor to do the decomposing, that pause-and-restart mechanism wouldn't be available.

Of course, Linux doesn't really take advantage of the pause to reduce guest interrupt latency because the Hyper-V code in Linux typically disable interrupts around a hypercall due to the way the hypercall input page is allocated. But other guest operating systems might benefit from such a pause. And we could probably fix the Hyper-V code in Linux to allow interrupts during a hypercall pause/restart if long-running hypercalls turn out to be a problem.

Quoted 9 lines

Regarding proposal (1) vs. (2), perhaps you could confirm with the Hyper-V team that flushing an aligned power-of-2 range has relatively fixed cost, regardless of the size. And what do the flush requests coming from the generic IOMMU subsystem look like? Do they match dma_unmap() ranges, which are probably dominated by relatively small ranges of a few pages at most, with a few outliers for disk I/O requests of 1 MiB or some such? If the dominant flush request is for a few pages at most, then doing (2) seems reasonable.

Thanks for the thoughtful suggestions, Michael!

I believe the time might be dominated by the number of descriptors, instead of the size of each range, especially when device TLB invalidations are involved.

Here's my understanding of what hypervisor does in its handler:

Hyper-V constructs one IOTLB invalidation descriptor (and possibly a Device TLB invalidation descriptor as well) per iova_list entry and submits them to the HW invalidation queue, then synchronously waits for completion. So multiple 2^N-aligned entries should be less efficient than a single larger 2^N aligned one.

Since both options submit 2^N-aligned entries to the hypervisor, either one single coarser-grained entry or a precise decomposition, I'm now also leaning towards option 2, which is also what Intel/AMD drivers do for page-selective IOTLB flush. Simpler guest code, faster flush, and the hypervisor can feed the single entry almost directly to HW.

Yu

#38 lore raw

RE: [PATCH v1 4/4] iommu/hyperv: Add page-selective IOTLB flush support

From: Yu Zhang <[email protected]> Sent: Thursday, May 21, 2026 7:34 AM

Quoted 107 lines · Michael Kelley
Quoted 89 lines

From: Yu Zhang <[email protected]> Sent: Wednesday, May 20, 2026 10:15 AM

Quoted 58 lines · Jason Gunthorpe
Quoted 32 lines · Yu Zhang
Quoted 31 lines
drivers/iommu/hyperv/iommu.c +31 -0
+static inline u16 hv_iommu_fill_iova_list(union hv_iommu_flush_va *iova_list,
+					  unsigned long start,
+					  unsigned long end)
+{
+	unsigned long start_pfn = start >> PAGE_SHIFT;
+	unsigned long end_pfn = PAGE_ALIGN(end) >> PAGE_SHIFT;
+	unsigned long nr_pages = end_pfn - start_pfn;
+	u16 count = 0;
+
+	while (nr_pages > 0) {
+		unsigned long flush_pages;
+		int order;
+		unsigned long pfn_align;
+		unsigned long size_align;
+
+		if (count >= HV_IOMMU_MAX_FLUSH_VA_COUNT) {
+			count = HV_IOMMU_FLUSH_VA_OVERFLOW;
+			break;
+		}
+
+		if (start_pfn)
+			pfn_align = __ffs(start_pfn);
+		else
+			pfn_align = BITS_PER_LONG - 1;
+
+		size_align = __fls(nr_pages);
+		order = min(pfn_align, size_align);
+		iova_list[count].page_mask_shift = order;
+		iova_list[count].page_number = start_pfn;
+
+		flush_pages = 1UL << order;
Quoted 8 lines

drivers/iommu/hyperv/iommu.c static void hv_iommu_flush_iotlb_all(struct iommu_domain *domain) · line 531

Quoted 4 lines
drivers/iommu/hyperv/iommu.c +4 -0
+		start_pfn += flush_pages;
+		nr_pages -= flush_pages;
+		count++;
+	}

This seems like a really silly hypervisor interface. Why doesn't it just accept a normal range? Splitting it into power of two aligned ranges is very inefficient.

Fair point. I'm not sure how much flexibility we have to change this hypercall interface at the moment - it predates the pvIOMMU work and may have other consumers beyond Linux guest. On the other hand, having the guest specify 2^N-aligned blocks does save the hypervisor from having to decompose ranges itself before issuing hardware invalidation commands - the guest-provided entries can be fed to the HW more or less directly.

That said, the way I'm currently using this interface may be more precise than necessary. Maybe we have 2 options:

1) Current approach: decompose the range into multiple exact 2^N-aligned blocks with no over-flush, but at the cost of more complex calculations and more entries.

Quoted 9 lines

2) Follow what Intel/AMD drivers do: find a single minimal 2^N-aligned block that covers the entire range, but may over-flush.

Any preference?

@Michael, since you've also been reviewing this patch, I'd appreciate your thoughts on the above as well. :)

I'm just guessing, but perhaps flushing an aligned power-of-2 range can be processed by the hypervisor at a relatively fixed cost, regardless of the size. Having the guest do the decomposing of an arbitrary range allows the hypervisor to make use of the existing "rep" hypercall mechanism if the hypercall is taking "too long". The hypervisor can pause its processing, return to the guest temporarily, and then continue the hypercall. If the arbitrary range were passed into the hypercall for the hypervisor to do the decomposing, that pause-and-restart mechanism wouldn't be available.

Of course, Linux doesn't really take advantage of the pause to reduce guest interrupt latency because the Hyper-V code in Linux typically disable interrupts around a hypercall due to the way the hypercall input page is allocated. But other guest operating systems might benefit from such a pause. And we could probably fix the Hyper-V code in Linux to allow interrupts during a hypercall pause/restart if long-running hypercalls turn out to be a problem.

Quoted 9 lines

Regarding proposal (1) vs. (2), perhaps you could confirm with the Hyper-V team that flushing an aligned power-of-2 range has relatively fixed cost, regardless of the size. And what do the flush requests coming from the generic IOMMU subsystem look like? Do they match dma_unmap() ranges, which are probably dominated by relatively small ranges of a few pages at most, with a few outliers for disk I/O requests of 1 MiB or some such? If the dominant flush request is for a few pages at most, then doing (2) seems reasonable.

Thanks for the thoughtful suggestions, Michael!

I believe the time might be dominated by the number of descriptors, instead of the size of each range, especially when device TLB invalidations are involved.

Quoted 7 lines

Here's my understanding of what hypervisor does in its handler:

Hyper-V constructs one IOTLB invalidation descriptor (and possibly a Device TLB invalidation descriptor as well) per iova_list entry and submits them to the HW invalidation queue, then synchronously waits for completion. So multiple 2^N-aligned entries should be less efficient than a single larger 2^N aligned one.

Agreed. The hypercall time should be roughly linear in the number of descriptors.

If the approach is to do a precise flush, my argument is that it is better for the guest to construct the 2^N aligned descriptors instead of having the host do it. In the former case, the hypercall can do the pause/resume thing, which provides the opportunity to reduce interrupt latency in the guest. In the latter case, it cannot.

But my argument is moot if you do Option 2. And I'm fine with Option 2 if the assumptions about it are true.

Michael

Quoted 9 lines

Since both options submit 2^N-aligned entries to the hypervisor, either one single coarser-grained entry or a precise decomposition, I'm now also leaning towards option 2, which is also what Intel/AMD drivers do for page-selective IOTLB flush. Simpler guest code, faster flush, and the hypervisor can feed the single entry almost directly to HW.

Yu