AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/08 06:59 flow patch-triage
11m Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "VFIO",
    "VFIO_GROUP",
    "VFIO_DEVICE_CDEV",
    "IOMMUFD",
    "IOMMUFD_TEST",
    "PCI_TSM",
    "AMD_IOMMU_IOMMUFD"
  ],
  "FocusSymbols": [
    "iommufd_vdevice_tsm_req_ioctl",
    "iommufd_viommu_alloc_ioctl",
    "iommufd_vdevice_alloc_ioctl",
    "iommufd_viommu_alloc_hwpt_nested",
    "kvm_vfio_file_add",
    "vfio_file_set_kvm",
    "file_to_kvm_x86",
    "pci_tsm_context_get",
    "pci_tsm_context_put",
    "disconnect_store",
    "sev_vm_move_enc_context_from",
    "kvm_page_track_register_notifier"
  ],
  "KMSANReasoning": "The patch series makes architectural changes across KVM, VFIO, PCI/TSM, and IOMMUFD:\n1. Replaces direct 'struct kvm *' pointers in VFIO and architecture hooks with 'struct file *' back-references (via get_file_active() / fput()) to manage VM file lifetimes without circular pinning.\n2. Refactors vIOMMU driver ops lookup by introducing get_viommu_ops returning 'const struct iommufd_viommu_ops *'.\n3. Adds PCI TSM context lifecycle management and refcounting (pci_tsm_context, context_users, contexts_drained completion) to prevent premature link disconnection.\n4. Implements the IOMMU_VDEVICE_TSM_REQ ioctl (iommufd_vdevice_tsm_req_ioctl) to forward guest TSM requests to vdevices.\n\nMemory initialization and KMSAN applicability analysis:\n- Kernel-to-userspace data copying: The only new structure copied to userspace is 'struct iommu_vdevice_tsm_req' in iommufd_vdevice_tsm_req_ioctl() via iommufd_ucmd_respond(). The structure contains six 32-bit fields (24 bytes) followed by three 64-bit fields (24 bytes), totalling 48 bytes with zero padding holes. The command buffer is initialized by copy_struct_from_user() (which zeroes any remaining bytes in the kernel buffer if userspace provides fewer bytes), and 'out_tsm_code' is explicitly zero-initialized prior to execution. There is no risk of info-leaks or uninitialized byte exposures.\n- Heap structures: All newly allocated heap structures (struct pci_tsm_context via kzalloc_obj, struct iommufd_viommu and struct iommufd_device via _iommufd_object_alloc/kzalloc) are zero-initialized upon allocation.\n- Stack structures: 'struct tsm_guest_req_info info' is fully populated using a designated initializer.\n- Flow and bounds: Control flow, operations masks, and buffer lengths (req_len, resp_len \u003c= INT_MAX; op \u003c TSM_REQ_MAX) are explicitly validated.\n\nKASAN vs KMSAN applicability:\nThe primary risks introduced by these changes are reference counting mismatches (file references, module refcounts), synchronization deadlocks (completion wait loops and mutex/rwsem locks), and use-after-free conditions during object cleanup. All of these failure modes are covered by standard KASAN, LOCKDEP, and refcount tracking. Because no uninitialized memory usage or padding leaks are introduced, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "This patch series refactors reference counting and lifecycle management between KVM, VFIO, and IOMMUFD by replacing raw 'struct kvm *' pointers with 'struct file *' references. It introduces a new userspace ioctl (IOMMU_VDEVICE_TSM_REQ) handled by iommufd_vdevice_tsm_req_ioctl(), refactors virtual IOMMU (viommu) allocation and vDevice handling in IOMMUFD, refactors PCI TSM context lifecycle and sysfs disconnection handling, and updates KVM SEV context migration. These code paths are directly reachable and exercisable from userspace via /dev/kvm, /dev/iommu, VFIO file descriptors, and sysfs.",
  "WorthFuzzing": true
}

1/1 2026/10/08 06:59 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit bf97d08b5c6e71cd454dbf6a948982dac7a9d1d3\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Thu Oct 8 06:59:51 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/ABI/testing/sysfs-bus-pci b/Documentation/ABI/testing/sysfs-bus-pci\nindex 55ea1db749a18..4c64b30544cdc 100644\n--- a/Documentation/ABI/testing/sysfs-bus-pci\n+++ b/Documentation/ABI/testing/sysfs-bus-pci\n@@ -654,6 +654,9 @@ Contact:\tlinux-coco@lists.linux.dev\n Description:\n \t\t(WO) Write the name of the TSM device that was specified\n \t\tto 'connect' to teardown the connection.\n+\t\tThe write fails with EBUSY while any vdevice depends on the\n+\t\tconnection. Userspace must destroy those vdevices before\n+\t\tdisconnecting the link.\n \n What:\t\t/sys/bus/pci/devices/.../tsm/dsm\n Contact:\tlinux-coco@lists.linux.dev\n@@ -671,20 +674,6 @@ Description:\t(RO) Return PCI device name of this device's DSM (Device\n \t\tPCIe switch port. This is a \"link\" TSM attribute, see\n \t\tDocumentation/ABI/testing/sysfs-class-tsm.\n \n-What:\t\t/sys/bus/pci/devices/.../tsm/bound\n-Contact:\tlinux-coco@lists.linux.dev\n-Description:\t(RO) Return the device name of the TSM when the device is in a\n-\t\tTDISP (TEE Device Interface Security Protocol) operational state\n-\t\t(LOCKED, RUN, or ERROR, not UNLOCKED). Bound devices consume\n-\t\tplatform TSM resources and depend on the device's configuration\n-\t\t(e.g. BME (Bus Master Enable) and MSE (Memory Space Enable)\n-\t\tamong other settings) to remain stable for the duration of the\n-\t\tbound state. This attribute is only visible for devices that\n-\t\tsupport TDISP operation, and it is only populated after\n-\t\tsuccessful connect and TSM bind. The TSM bind operation is\n-\t\tinitiated by VFIO/IOMMUFD. This is a \"link\" TSM attribute, see\n-\t\tDocumentation/ABI/testing/sysfs-class-tsm.\n-\n What:\t\t/sys/bus/pci/devices/.../authenticated\n Contact:\tlinux-pci@vger.kernel.org\n Description:\ndiff --git a/Documentation/userspace-api/iommufd.rst b/Documentation/userspace-api/iommufd.rst\nindex f1c4d21e5c5ee..8e2fa3a524f0c 100644\n--- a/Documentation/userspace-api/iommufd.rst\n+++ b/Documentation/userspace-api/iommufd.rst\n@@ -82,11 +82,10 @@ Following IOMMUFD objects are exposed to userspace:\n   * Direct assigned invalidation queues\n   * Direct assigned interrupts\n \n-  Such a vIOMMU object generally has the access to a nesting parent pagetable\n-  to support some HW-accelerated virtualization features. So, a vIOMMU object\n-  must be created given a nesting parent HWPT_PAGING object, and then it would\n-  encapsulate that HWPT_PAGING object. Therefore, a vIOMMU object can be used\n-  to allocate an HWPT_NESTED object in place of the encapsulated HWPT_PAGING.\n+  A vIOMMU object may encapsulate a nesting parent HWPT_PAGING object to\n+  support HW-accelerated virtualization features. Whether a parent is required\n+  is determined by the selected vIOMMU implementation. Only a parent-backed\n+  vIOMMU can be used to allocate an HWPT_NESTED object.\n \n   .. note::\n \n@@ -226,9 +225,9 @@ creating the objects and links::\n      flag is set.\n \n 4. IOMMUFD_OBJ_HWPT_NESTED can be only manually created via the IOMMU_HWPT_ALLOC\n-   uAPI, provided an hwpt_id or a viommu_id of a vIOMMU object encapsulating a\n-   nesting parent HWPT_PAGING via @pt_id to associate the new HWPT_NESTED object\n-   to the corresponding HWPT_PAGING object. The associating HWPT_PAGING object\n+   uAPI, provided an hwpt_id or a viommu_id of a parent-backed vIOMMU object\n+   via @pt_id to associate the new HWPT_NESTED object to the corresponding\n+   HWPT_PAGING object. The associating HWPT_PAGING object\n    must be a nesting parent manually allocated via the same uAPI previously with\n    an IOMMU_HWPT_ALLOC_NEST_PARENT flag, otherwise the allocation will fail. The\n    allocation will be further validated by the IOMMU driver to ensure that the\n@@ -245,25 +244,28 @@ creating the objects and links::\n       of the object passed in via the @pt_id field of struct iommufd_hwpt_alloc.\n \n 5. IOMMUFD_OBJ_VIOMMU can be only manually created via the IOMMU_VIOMMU_ALLOC\n-   uAPI, provided a dev_id (for the device's physical IOMMU to back the vIOMMU)\n-   and an hwpt_id (to associate the vIOMMU to a nesting parent HWPT_PAGING). The\n-   iommufd core will link the vIOMMU object to the struct iommu_device that the\n-   struct device is behind. And an IOMMU driver can implement a viommu_alloc op\n-   to allocate its own vIOMMU data structure embedding the core-level structure\n-   iommufd_viommu and some driver-specific data. If necessary, the driver can\n-   also configure its HW virtualization feature for that vIOMMU (and thus for\n-   the VM). Successful completion of this operation sets up the linkages between\n-   the vIOMMU object and the HWPT_PAGING, then this vIOMMU object can be used\n-   as a nesting parent object to allocate an HWPT_NESTED object described above.\n+   uAPI, provided a dev_id identifying the device used to select the vIOMMU\n+   implementation and, if the selected implementation requires a nesting\n+   parent HWPT_PAGING, an hwpt_id. The hwpt_id must be zero for an\n+   implementation that does not use a parent. A physical-IOMMU implementation\n+   links the vIOMMU object to the struct iommu_device behind the device. Other\n+   implementations, such as a TSM associated with the device, can provide their\n+   own backing and device association. An implementation can allocate its own\n+   vIOMMU data structure embedding the core-level structure iommufd_viommu and\n+   some implementation-specific data. If necessary, it can also configure its\n+   virtualization resources for that vIOMMU (and thus for the VM). A\n+   parent-backed vIOMMU can be used as a nesting parent object to allocate an\n+   HWPT_NESTED object described above.\n \n 6. IOMMUFD_OBJ_VDEVICE can be only manually created via the IOMMU_VDEVICE_ALLOC\n    uAPI, provided a viommu_id for an iommufd_viommu object and a dev_id for an\n    iommufd_device object. The vDEVICE object will be the binding between these\n    two parent objects. Another @virt_id will be also set via the uAPI providing\n    the iommufd core an index to store the vDEVICE object to a vDEVICE array per\n-   vIOMMU. If necessary, the IOMMU driver may choose to implement a vdevce_alloc\n-   op to init its HW for virtualization feature related to a vDEVICE. Successful\n-   completion of this operation sets up the linkages between vIOMMU and device.\n+   vIOMMU. A physical-IOMMU implementation requires the device to be behind the\n+   same iommu_device as the vIOMMU. Other implementations validate the device\n+   association while initializing the vDEVICE. Successful initialization sets\n+   up the linkage between the vIOMMU and device.\n \n A device can only bind to an iommufd due to DMA ownership claim and attach to at\n most one IOAS object (no support of PASID yet).\ndiff --git a/arch/s390/include/asm/kvm_host_s390.h b/arch/s390/include/asm/kvm_host_s390.h\nindex cd692f8fb7643..9519b8028b104 100644\n--- a/arch/s390/include/asm/kvm_host_s390.h\n+++ b/arch/s390/include/asm/kvm_host_s390.h\n@@ -27,6 +27,8 @@\n #include \u003casm/isc.h\u003e\n #include \u003casm/guarded_storage.h\u003e\n \n+#define kvm_file_to_kvm_arch s390\n+\n #define KVM_HAVE_MMU_RWLOCK\n #define KVM_MAX_VCPUS 255\n \n@@ -720,7 +722,7 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {}\n void kvm_arch_free_vm(struct kvm *kvm);\n \n struct zpci_kvm_hook {\n-\tint (*kvm_register)(void *opaque, struct kvm *kvm);\n+\tint (*kvm_register)(void *opaque, struct file *kvm_file);\n \tvoid (*kvm_unregister)(void *opaque);\n };\n \ndiff --git a/arch/s390/kvm/s390/pci.c b/arch/s390/kvm/s390/pci.c\nindex 82892e1e03d94..d79bd3bdc68e9 100644\n--- a/arch/s390/kvm/s390/pci.c\n+++ b/arch/s390/kvm/s390/pci.c\n@@ -498,17 +498,22 @@ static void kvm_s390_pci_dev_release(struct zpci_dev *zdev)\n  * available, enable them and let userspace indicate whether or not they will\n  * be used (specify SHM bit to disable).\n  */\n-static int kvm_s390_pci_register_kvm(void *opaque, struct kvm *kvm)\n+static int kvm_s390_pci_register_kvm(void *opaque, struct file *kvm_file)\n {\n \tstruct zpci_dev *zdev = opaque;\n+\tstruct kvm *kvm;\n \tint rc;\n \n \tif (!zdev)\n \t\treturn -EINVAL;\n \n+\tkvm = file_to_kvm_s390(kvm_file);\n+\tif (!kvm)\n+\t\treturn -ENOENT;\n+\n \tmutex_lock(\u0026zdev-\u003ekzdev_lock);\n \n-\tif (zdev-\u003ekzdev || zdev-\u003egisa != 0 || !kvm) {\n+\tif (zdev-\u003ekzdev || zdev-\u003egisa != 0) {\n \t\tmutex_unlock(\u0026zdev-\u003ekzdev_lock);\n \t\treturn -EINVAL;\n \t}\ndiff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h\nindex 683bb8bf43a94..e460073ff176d 100644\n--- a/arch/x86/include/asm/kvm_host.h\n+++ b/arch/x86/include/asm/kvm_host.h\n@@ -44,6 +44,8 @@\n \n #include \u003chyperv/hvhdk.h\u003e\n \n+#define kvm_file_to_kvm_arch x86\n+\n #define __KVM_HAVE_ARCH_VCPU_DEBUGFS\n \n /*\ndiff --git a/arch/x86/include/asm/kvm_page_track.h b/arch/x86/include/asm/kvm_page_track.h\nindex 3d040741044b4..ea885dd5c9aff 100644\n--- a/arch/x86/include/asm/kvm_page_track.h\n+++ b/arch/x86/include/asm/kvm_page_track.h\n@@ -44,13 +44,15 @@ struct kvm_page_track_notifier_node {\n \t\t\t\t    struct kvm_page_track_notifier_node *node);\n };\n \n-int kvm_page_track_register_notifier(struct kvm *kvm,\n+struct file;\n+\n+int kvm_page_track_register_notifier(struct file *file,\n \t\t\t\t     struct kvm_page_track_notifier_node *n);\n-void kvm_page_track_unregister_notifier(struct kvm *kvm,\n+void kvm_page_track_unregister_notifier(struct file *file,\n \t\t\t\t\tstruct kvm_page_track_notifier_node *n);\n \n-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn);\n-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn);\n+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn);\n+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn);\n #else\n /*\n  * Allow defining a node in a structure even if page tracking is disabled, e.g.\ndiff --git a/arch/x86/kvm/Makefile b/arch/x86/kvm/Makefile\nindex 0474604ab8a14..c6bf463f50327 100644\n--- a/arch/x86/kvm/Makefile\n+++ b/arch/x86/kvm/Makefile\n@@ -61,9 +61,7 @@ exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/a\n \t\t\t\t-e kvm_page_track_unregister_notifier \\\n \t\t\t\t-e kvm_write_track_add_gfn \\\n \t\t\t\t-e kvm_write_track_remove_gfn \\\n-\t\t\t\t-e kvm_get_kvm \\\n-\t\t\t\t-e kvm_get_kvm_safe \\\n-\t\t\t\t-e kvm_put_kvm\n+\t\t\t\t-e kvm_file_to_kvm_fn\n \n # Force grep to emit a goofy group separator that can in turn be replaced with\n # the above newline macro (newlines in Make are a nightmare).  Note, grep only\ndiff --git a/arch/x86/kvm/mmu/page_track.c b/arch/x86/kvm/mmu/page_track.c\nindex 7e8195a311bb0..f12558dfcd812 100644\n--- a/arch/x86/kvm/mmu/page_track.c\n+++ b/arch/x86/kvm/mmu/page_track.c\n@@ -16,6 +16,8 @@\n #include \u003clinux/kvm_host.h\u003e\n #include \u003clinux/rculist.h\u003e\n \n+#include \u003casm/kvm_page_track.h\u003e\n+\n #include \"mmu.h\"\n #include \"mmu_internal.h\"\n #include \"page_track.h\"\n@@ -237,10 +239,11 @@ static int kvm_enable_external_write_tracking(struct kvm *kvm)\n  * register the notifier so that event interception for the tracked guest\n  * pages can be received.\n  */\n-int kvm_page_track_register_notifier(struct kvm *kvm,\n+int kvm_page_track_register_notifier(struct file *file,\n \t\t\t\t     struct kvm_page_track_notifier_node *n)\n {\n \tstruct kvm_page_track_notifier_head *head;\n+\tstruct kvm *kvm = file_to_kvm_x86(file);\n \tint r;\n \n \tif (!kvm || kvm-\u003emm != current-\u003emm)\n@@ -252,7 +255,7 @@ int kvm_page_track_register_notifier(struct kvm *kvm,\n \t\t\treturn r;\n \t}\n \n-\tkvm_get_kvm(kvm);\n+\tget_file(file);\n \n \thead = \u0026kvm-\u003earch.track_notifier_head;\n \n@@ -267,10 +270,11 @@ EXPORT_SYMBOL_GPL(kvm_page_track_register_notifier);\n  * stop receiving the event interception. It is the opposed operation of\n  * kvm_page_track_register_notifier().\n  */\n-void kvm_page_track_unregister_notifier(struct kvm *kvm,\n+void kvm_page_track_unregister_notifier(struct file *file,\n \t\t\t\t\tstruct kvm_page_track_notifier_node *n)\n {\n \tstruct kvm_page_track_notifier_head *head;\n+\tstruct kvm *kvm = file_to_kvm_x86(file);\n \n \thead = \u0026kvm-\u003earch.track_notifier_head;\n \n@@ -279,7 +283,7 @@ void kvm_page_track_unregister_notifier(struct kvm *kvm,\n \twrite_unlock(\u0026kvm-\u003emmu_lock);\n \tsynchronize_srcu(\u0026head-\u003etrack_srcu);\n \n-\tkvm_put_kvm(kvm);\n+\tfput(file);\n }\n EXPORT_SYMBOL_GPL(kvm_page_track_unregister_notifier);\n \n@@ -336,11 +340,12 @@ void kvm_page_track_delete_slot(struct kvm *kvm, struct kvm_memory_slot *slot)\n  * add guest page to the tracking pool so that corresponding access on that\n  * page will be intercepted.\n  *\n- * @kvm: the guest instance we are interested in.\n+ * @file: the VM file of the guest instance we are interested in.\n  * @gfn: the guest page.\n  */\n-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn)\n+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn)\n {\n+\tstruct kvm *kvm = file_to_kvm_x86(file);\n \tstruct kvm_memory_slot *slot;\n \tint idx;\n \n@@ -366,11 +371,12 @@ EXPORT_SYMBOL_GPL(kvm_write_track_add_gfn);\n  * remove the guest page from the tracking pool which stops the interception\n  * of corresponding access on that page.\n  *\n- * @kvm: the guest instance we are interested in.\n+ * @file: the VM file of the guest instance we are interested in.\n  * @gfn: the guest page.\n  */\n-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn)\n+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn)\n {\n+\tstruct kvm *kvm = file_to_kvm_x86(file);\n \tstruct kvm_memory_slot *slot;\n \tint idx;\n \ndiff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c\nindex 63eb2155a7749..db7ed11e9056f 100644\n--- a/arch/x86/kvm/svm/sev.c\n+++ b/arch/x86/kvm/svm/sev.c\n@@ -2151,10 +2151,10 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)\n \tif (fd_empty(f))\n \t\treturn -EBADF;\n \n-\tif (!file_is_kvm(fd_file(f)))\n+\tsource_kvm = file_to_kvm_x86(fd_file(f));\n+\tif (!source_kvm)\n \t\treturn -EBADF;\n \n-\tsource_kvm = fd_file(f)-\u003eprivate_data;\n \tret = sev_lock_two_vms(kvm, source_kvm);\n \tif (ret)\n \t\treturn ret;\n@@ -2876,10 +2876,10 @@ int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)\n \tif (fd_empty(f))\n \t\treturn -EBADF;\n \n-\tif (!file_is_kvm(fd_file(f)))\n+\tsource_kvm = file_to_kvm_x86(fd_file(f));\n+\tif (!source_kvm)\n \t\treturn -EBADF;\n \n-\tsource_kvm = fd_file(f)-\u003eprivate_data;\n \tret = sev_lock_two_vms(kvm, source_kvm);\n \tif (ret)\n \t\treturn ret;\ndiff --git a/drivers/iommu/amd/iommu.c b/drivers/iommu/amd/iommu.c\nindex 56262f6b1f700..a3c58dd39549b 100644\n--- a/drivers/iommu/amd/iommu.c\n+++ b/drivers/iommu/amd/iommu.c\n@@ -3211,8 +3211,7 @@ const struct iommu_ops amd_iommu_ops = {\n \t.is_attach_deferred = amd_iommu_is_attach_deferred,\n \t.def_domain_type = amd_iommu_def_domain_type,\n \t.page_response = amd_iommu_page_response,\n-\t.get_viommu_size = amd_iommufd_get_viommu_size,\n-\t.viommu_init = amd_iommufd_viommu_init,\n+\t.get_viommu_ops = amd_iommufd_get_viommu_ops,\n };\n \n #ifdef CONFIG_IRQ_REMAP\ndiff --git a/drivers/iommu/amd/iommufd.c b/drivers/iommu/amd/iommufd.c\nindex 52300b867c1f2..c1e132382adc7 100644\n--- a/drivers/iommu/amd/iommufd.c\n+++ b/drivers/iommu/amd/iommufd.c\n@@ -32,13 +32,21 @@ void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_ty\n \treturn hwinfo;\n }\n \n-size_t amd_iommufd_get_viommu_size(struct device *dev, enum iommu_viommu_type viommu_type)\n+static size_t amd_iommufd_get_viommu_size(struct device *dev,\n+\t\tenum iommu_viommu_type viommu_type)\n {\n \treturn VIOMMU_STRUCT_SIZE(struct amd_iommu_viommu, core);\n }\n \n-int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *parent,\n-\t\t\t    const struct iommu_user_data *user_data)\n+const struct iommufd_viommu_ops *\n+amd_iommufd_get_viommu_ops(struct device *dev, enum iommu_viommu_type viommu_type)\n+{\n+\treturn \u0026amd_viommu_ops;\n+}\n+\n+int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,\n+\t\tstruct device *dev, struct iommu_domain *parent,\n+\t\tconst struct iommu_user_data *user_data)\n {\n \tunsigned long flags;\n \tstruct protection_domain *pdom = to_pdomain(parent);\n@@ -47,8 +55,6 @@ int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *\n \txa_init_flags(\u0026aviommu-\u003egdomid_array, XA_FLAGS_ALLOC1);\n \taviommu-\u003eparent = pdom;\n \n-\tviommu-\u003eops = \u0026amd_viommu_ops;\n-\n \tspin_lock_irqsave(\u0026pdom-\u003elock, flags);\n \tlist_add(\u0026aviommu-\u003epdom_list, \u0026pdom-\u003eviommu_list);\n \tspin_unlock_irqrestore(\u0026pdom-\u003elock, flags);\n@@ -73,5 +79,7 @@ static void amd_iommufd_viommu_destroy(struct iommufd_viommu *viommu)\n  * struct iommufd_viommu_ops - vIOMMU specific operations\n  */\n static const struct iommufd_viommu_ops amd_viommu_ops = {\n+\t.get_viommu_size = amd_iommufd_get_viommu_size,\n+\t.viommu_init = amd_iommufd_viommu_init,\n \t.destroy = amd_iommufd_viommu_destroy,\n };\ndiff --git a/drivers/iommu/amd/iommufd.h b/drivers/iommu/amd/iommufd.h\nindex 62e9e1bebfbe5..0d8e7c0902cff 100644\n--- a/drivers/iommu/amd/iommufd.h\n+++ b/drivers/iommu/amd/iommufd.h\n@@ -8,13 +8,16 @@\n \n #if IS_ENABLED(CONFIG_AMD_IOMMU_IOMMUFD)\n void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_type *type);\n-size_t amd_iommufd_get_viommu_size(struct device *dev, enum iommu_viommu_type viommu_type);\n-int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *parent,\n-\t\t\t    const struct iommu_user_data *user_data);\n+const struct iommufd_viommu_ops *\n+amd_iommufd_get_viommu_ops(struct device *dev,\n+\t\tenum iommu_viommu_type viommu_type);\n+int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,\n+\t\tstruct device *dev, struct iommu_domain *parent,\n+\t\tconst struct iommu_user_data *user_data);\n #else\n #define amd_iommufd_hw_info NULL\n #define amd_iommufd_viommu_init NULL\n-#define amd_iommufd_get_viommu_size NULL\n+#define amd_iommufd_get_viommu_ops NULL\n #endif /* CONFIG_AMD_IOMMU_IOMMUFD */\n \n #endif /* AMD_IOMMUFD_H */\ndiff --git a/drivers/iommu/amd/nested.c b/drivers/iommu/amd/nested.c\nindex f1c7987fc5859..5b07136e7cd92 100644\n--- a/drivers/iommu/amd/nested.c\n+++ b/drivers/iommu/amd/nested.c\n@@ -90,7 +90,7 @@ static void *gdom_info_load_or_alloc_locked(struct xarray *xa,\n \n /*\n  * This function is assigned to struct iommufd_viommu_ops.alloc_domain_nested()\n- * during the call to struct iommu_ops.viommu_init().\n+ * when the vIOMMU operations are selected.\n  */\n struct iommu_domain *\n amd_iommu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,\n@@ -198,7 +198,7 @@ static void set_dte_nested(struct amd_iommu *iommu, struct iommu_domain *dom,\n \n \t/*\n \t * The nest parent domain is attached during the call to the\n-\t * struct iommu_ops.viommu_init(), which will be stored as part\n+\t * struct iommufd_viommu_ops.viommu_init(), which will be stored as part\n \t * of the struct amd_iommu_viommu.parent.\n \t */\n \tif (WARN_ON(!ndom-\u003eviommu || !ndom-\u003eviommu-\u003eparent))\ndiff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c\nindex 25982bdbcbd9a..1dd1031963534 100644\n--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c\n+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c\n@@ -417,20 +417,29 @@ int arm_vsmmu_cache_invalidate(struct iommufd_viommu *viommu,\n \treturn ret;\n }\n \n+static size_t arm_vsmmu_get_size(struct device *dev,\n+\t\t\t\t enum iommu_viommu_type viommu_type)\n+{\n+\treturn VIOMMU_STRUCT_SIZE(struct arm_vsmmu, core);\n+}\n+\n static const struct iommufd_viommu_ops arm_vsmmu_ops = {\n+\t.get_viommu_size = arm_vsmmu_get_size,\n+\t.viommu_init = arm_vsmmu_init,\n \t.alloc_domain_nested = arm_vsmmu_alloc_domain_nested,\n \t.cache_invalidate = arm_vsmmu_cache_invalidate,\n \t.vdevice_init = arm_vsmmu_vdevice_init,\n };\n \n-size_t arm_smmu_get_viommu_size(struct device *dev,\n-\t\t\t\tenum iommu_viommu_type viommu_type)\n+const struct iommufd_viommu_ops *\n+arm_smmu_get_viommu_ops(struct device *dev,\n+\t\tenum iommu_viommu_type viommu_type)\n {\n \tstruct arm_smmu_master *master = dev_iommu_priv_get(dev);\n \tstruct arm_smmu_device *smmu = master-\u003esmmu;\n \n \tif (!(smmu-\u003efeatures \u0026 ARM_SMMU_FEAT_NESTING))\n-\t\treturn 0;\n+\t\treturn NULL;\n \n \t/*\n \t * FORCE_SYNC is not set with FEAT_NESTING. Some study of the exact HW\n@@ -438,7 +447,7 @@ size_t arm_smmu_get_viommu_size(struct device *dev,\n \t * any change to remove this.\n \t */\n \tif (WARN_ON(smmu-\u003eoptions \u0026 ARM_SMMU_OPT_CMDQ_FORCE_SYNC))\n-\t\treturn 0;\n+\t\treturn NULL;\n \n \t/*\n \t * Must support some way to prevent the VM from bypassing the cache\n@@ -450,19 +459,19 @@ size_t arm_smmu_get_viommu_size(struct device *dev,\n \t */\n \tif (!arm_smmu_master_canwbs(master) \u0026\u0026\n \t    !(smmu-\u003efeatures \u0026 ARM_SMMU_FEAT_S2FWB))\n-\t\treturn 0;\n+\t\treturn NULL;\n \n \tif (viommu_type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3)\n-\t\treturn VIOMMU_STRUCT_SIZE(struct arm_vsmmu, core);\n+\t\treturn \u0026arm_vsmmu_ops;\n \n-\tif (!smmu-\u003eimpl_ops || !smmu-\u003eimpl_ops-\u003eget_viommu_size)\n-\t\treturn 0;\n-\treturn smmu-\u003eimpl_ops-\u003eget_viommu_size(viommu_type);\n+\tif (!smmu-\u003eimpl_ops || !smmu-\u003eimpl_ops-\u003eget_viommu_ops)\n+\t\treturn NULL;\n+\treturn smmu-\u003eimpl_ops-\u003eget_viommu_ops(viommu_type);\n }\n \n-int arm_vsmmu_init(struct iommufd_viommu *viommu,\n-\t\t   struct iommu_domain *parent_domain,\n-\t\t   const struct iommu_user_data *user_data)\n+int arm_vsmmu_init(struct iommufd_viommu *viommu, struct device *dev,\n+\t\tstruct iommu_domain *parent_domain,\n+\t\tconst struct iommu_user_data *user_data)\n {\n \tstruct arm_vsmmu *vsmmu = container_of(viommu, struct arm_vsmmu, core);\n \tstruct arm_smmu_device *smmu =\n@@ -477,10 +486,8 @@ int arm_vsmmu_init(struct iommufd_viommu *viommu,\n \t/* FIXME Move VMID allocation from the S2 domain allocation to here */\n \tvsmmu-\u003evmid = s2_parent-\u003es2_cfg.vmid;\n \n-\tif (viommu-\u003etype == IOMMU_VIOMMU_TYPE_ARM_SMMUV3) {\n-\t\tviommu-\u003eops = \u0026arm_vsmmu_ops;\n+\tif (viommu-\u003etype == IOMMU_VIOMMU_TYPE_ARM_SMMUV3)\n \t\treturn 0;\n-\t}\n \n \treturn smmu-\u003eimpl_ops-\u003evsmmu_init(vsmmu, user_data);\n }\ndiff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c\nindex 5732f3ba0122d..97dfaec6dc589 100644\n--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c\n+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c\n@@ -4389,8 +4389,7 @@ static const struct iommu_ops arm_smmu_ops = {\n \t.get_resv_regions\t= arm_smmu_get_resv_regions,\n \t.page_response\t\t= arm_smmu_page_response,\n \t.def_domain_type\t= arm_smmu_def_domain_type,\n-\t.get_viommu_size\t= arm_smmu_get_viommu_size,\n-\t.viommu_init\t\t= arm_vsmmu_init,\n+\t.get_viommu_ops\t= arm_smmu_get_viommu_ops,\n \t.user_pasid_table\t= 1,\n \t.owner\t\t\t= THIS_MODULE,\n \t.default_domain_ops = \u0026(const struct iommu_domain_ops) {\n@@ -5489,8 +5488,8 @@ static struct arm_smmu_device *arm_smmu_impl_probe(struct arm_smmu_device *smmu)\n \n \tops = new_smmu-\u003eimpl_ops;\n \tif (ops) {\n-\t\t/* get_viommu_size and vsmmu_init ops must be paired */\n-\t\tif (WARN_ON(!ops-\u003eget_viommu_size != !ops-\u003evsmmu_init)) {\n+\t\t/* get_viommu_ops and vsmmu_init ops must be paired */\n+\t\tif (WARN_ON(!ops-\u003eget_viommu_ops != !ops-\u003evsmmu_init)) {\n \t\t\tret = -EINVAL;\n \t\t\tgoto err_remove;\n \t\t}\ndiff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h\nindex dd2fee2f560e6..79f2adf7a1f51 100644\n--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h\n+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h\n@@ -886,7 +886,8 @@ struct arm_smmu_impl_ops {\n \t */\n \tvoid *(*hw_info)(struct arm_smmu_device *smmu, u32 *length,\n \t\t\t enum iommu_hw_info_type *type);\n-\tsize_t (*get_viommu_size)(enum iommu_viommu_type viommu_type);\n+\tconst struct iommufd_viommu_ops *(*get_viommu_ops)(\n+\t\tenum iommu_viommu_type viommu_type);\n \tint (*vsmmu_init)(struct arm_vsmmu *vsmmu,\n \t\t\t  const struct iommu_user_data *user_data);\n };\n@@ -1260,11 +1261,12 @@ struct arm_vsmmu {\n #if IS_ENABLED(CONFIG_ARM_SMMU_V3_IOMMUFD)\n void *arm_smmu_hw_info(struct device *dev, u32 *length,\n \t\t       enum iommu_hw_info_type *type);\n-size_t arm_smmu_get_viommu_size(struct device *dev,\n-\t\t\t\tenum iommu_viommu_type viommu_type);\n-int arm_vsmmu_init(struct iommufd_viommu *viommu,\n-\t\t   struct iommu_domain *parent_domain,\n-\t\t   const struct iommu_user_data *user_data);\n+const struct iommufd_viommu_ops *\n+arm_smmu_get_viommu_ops(struct device *dev,\n+\t\tenum iommu_viommu_type viommu_type);\n+int arm_vsmmu_init(struct iommufd_viommu *viommu, struct device *dev,\n+\t\tstruct iommu_domain *parent_domain,\n+\t\tconst struct iommu_user_data *user_data);\n int arm_smmu_attach_prepare_vmaster(struct arm_smmu_attach_state *state,\n \t\t\t\t    struct arm_smmu_nested_domain *nested_domain);\n void arm_smmu_attach_commit_vmaster(struct arm_smmu_attach_state *state);\n@@ -1276,7 +1278,7 @@ arm_vsmmu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,\n int arm_vsmmu_cache_invalidate(struct iommufd_viommu *viommu,\n \t\t\t       struct iommu_user_data_array *array);\n #else\n-#define arm_smmu_get_viommu_size NULL\n+#define arm_smmu_get_viommu_ops NULL\n #define arm_smmu_hw_info NULL\n #define arm_vsmmu_init NULL\n #define arm_vsmmu_alloc_domain_nested NULL\ndiff --git a/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c b/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c\nindex 6644075c1431e..1c8a7939fc1c0 100644\n--- a/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c\n+++ b/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c\n@@ -892,11 +892,14 @@ static void *tegra241_cmdqv_hw_info(struct arm_smmu_device *smmu, u32 *length,\n \treturn info;\n }\n \n-static size_t tegra241_cmdqv_get_vintf_size(enum iommu_viommu_type viommu_type)\n+static const struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops;\n+\n+static const struct iommufd_viommu_ops *\n+tegra241_cmdqv_get_viommu_ops(enum iommu_viommu_type viommu_type)\n {\n \tif (viommu_type != IOMMU_VIOMMU_TYPE_TEGRA241_CMDQV)\n-\t\treturn 0;\n-\treturn VIOMMU_STRUCT_SIZE(struct tegra241_vintf, vsmmu.core);\n+\t\treturn NULL;\n+\treturn \u0026tegra241_cmdqv_viommu_ops;\n }\n \n static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {\n@@ -907,7 +910,7 @@ static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {\n \t.device_remove = tegra241_cmdqv_remove,\n \t/* For user-space use */\n \t.hw_info = tegra241_cmdqv_hw_info,\n-\t.get_viommu_size = tegra241_cmdqv_get_vintf_size,\n+\t.get_viommu_ops = tegra241_cmdqv_get_viommu_ops,\n \t.vsmmu_init = tegra241_cmdqv_init_vintf_user,\n };\n \n@@ -1289,7 +1292,15 @@ static int tegra241_vintf_init_vsid(struct iommufd_vdevice *vdev)\n \treturn 0;\n }\n \n-static struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops = {\n+static size_t tegra241_cmdqv_get_vintf_size(struct device *dev,\n+\t\t\t\t\t    enum iommu_viommu_type viommu_type)\n+{\n+\treturn VIOMMU_STRUCT_SIZE(struct tegra241_vintf, vsmmu.core);\n+}\n+\n+static const struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops = {\n+\t.get_viommu_size = tegra241_cmdqv_get_vintf_size,\n+\t.viommu_init = arm_vsmmu_init,\n \t.destroy = tegra241_cmdqv_destroy_vintf_user,\n \t.alloc_domain_nested = arm_vsmmu_alloc_domain_nested,\n \t/* Non-accelerated commands will be still handled by the kernel */\n@@ -1312,7 +1323,7 @@ tegra241_cmdqv_init_vintf_user(struct arm_vsmmu *vsmmu,\n \tint ret;\n \n \t/*\n-\t * Unsupported type should be rejected by tegra241_cmdqv_get_vintf_size.\n+\t * Unsupported type should be rejected by tegra241_cmdqv_get_viommu_ops.\n \t * Seeing one here indicates a kernel bug or some data corruption.\n \t */\n \tif (WARN_ON(vsmmu-\u003ecore.type != IOMMU_VIOMMU_TYPE_TEGRA241_CMDQV))\n@@ -1364,7 +1375,6 @@ tegra241_cmdqv_init_vintf_user(struct arm_vsmmu *vsmmu,\n \tdev_dbg(cmdqv-\u003edev, \"VINTF%u: allocated with vmid (%d)\\n\", vintf-\u003eidx,\n \t\tvintf-\u003evsmmu.vmid);\n \n-\tvsmmu-\u003ecore.ops = \u0026tegra241_cmdqv_viommu_ops;\n \treturn 0;\n \n free_mmap:\ndiff --git a/drivers/iommu/iommufd/Makefile b/drivers/iommu/iommufd/Makefile\nindex 67207914bb6e0..f90efe2f9d106 100644\n--- a/drivers/iommu/iommufd/Makefile\n+++ b/drivers/iommu/iommufd/Makefile\n@@ -11,6 +11,8 @@ iommufd-y := \\\n \tviommu.o\n \n iommufd-$(CONFIG_IOMMUFD_NOIOMMU) += hwpt_noiommu.o\n+iommufd-$(CONFIG_TSM) += tsm.o\n+\n iommufd-$(CONFIG_IOMMUFD_TEST) += selftest.o\n \n obj-$(CONFIG_IOMMUFD) += iommufd.o\ndiff --git a/drivers/iommu/iommufd/device.c b/drivers/iommu/iommufd/device.c\nindex a664c70a6fe73..f99f7bee2e774 100644\n--- a/drivers/iommu/iommufd/device.c\n+++ b/drivers/iommu/iommufd/device.c\n@@ -295,6 +295,7 @@ static int iommufd_bind_noiommu(struct iommufd_device *idev)\n  * iommufd_device_bind - Bind a physical device to an iommu fd\n  * @ictx: iommufd file descriptor\n  * @dev: Pointer to a physical device struct\n+ * @kvm_file: VM file if device belongs to a KVM VM\n  * @id: Output ID number to return to userspace for this device\n  *\n  * A successful bind establishes an ownership over the device and returns\n@@ -308,7 +309,9 @@ static int iommufd_bind_noiommu(struct iommufd_device *idev)\n  * The caller must undo this with iommufd_device_unbind()\n  */\n struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,\n-\t\t\t\t\t   struct device *dev, u32 *id)\n+\t\t\t\t\t   struct device *dev,\n+\t\t\t\t\t   struct file *kvm_file,\n+\t\t\t\t\t   u32 *id)\n {\n \tstruct iommufd_device *idev;\n \tint rc;\n@@ -319,6 +322,8 @@ struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,\n \n \tidev-\u003eictx = ictx;\n \tidev-\u003edev = dev;\n+\t/* VFIO holds the file reference while the device is open. */\n+\tidev-\u003ekvm_file = kvm_file;\n \n \tif (!iommufd_device_is_noiommu(idev))\n \t\trc = iommufd_bind_iommu(idev);\ndiff --git a/drivers/iommu/iommufd/hw_pagetable.c b/drivers/iommu/iommufd/hw_pagetable.c\nindex ef6e119c2a752..bd562bc2db487 100644\n--- a/drivers/iommu/iommufd/hw_pagetable.c\n+++ b/drivers/iommu/iommufd/hw_pagetable.c\n@@ -306,6 +306,10 @@ iommufd_viommu_alloc_hwpt_nested(struct iommufd_viommu *viommu, u32 flags,\n \t\treturn ERR_PTR(-EOPNOTSUPP);\n \tif (!user_data-\u003elen)\n \t\treturn ERR_PTR(-EOPNOTSUPP);\n+\tif (!viommu-\u003ehwpt)\n+\t\treturn ERR_PTR(-EOPNOTSUPP);\n+\tif (!viommu-\u003eiommu_dev)\n+\t\treturn ERR_PTR(-EOPNOTSUPP);\n \tif (!viommu-\u003eops || !viommu-\u003eops-\u003ealloc_domain_nested)\n \t\treturn ERR_PTR(-EOPNOTSUPP);\n \n@@ -404,10 +408,12 @@ int iommufd_hwpt_alloc(struct iommufd_ucmd *ucmd)\n \t\tstruct iommufd_viommu *viommu;\n \n \t\tviommu = container_of(pt_obj, struct iommufd_viommu, obj);\n-\t\tiommu_dev = iommufd_device_get_iommu_dev(idev);\n-\t\tif (!iommu_dev || viommu-\u003eiommu_dev != iommu_dev) {\n-\t\t\trc = -EINVAL;\n-\t\t\tgoto out_unlock;\n+\t\tif (viommu-\u003eiommu_dev) {\n+\t\t\tiommu_dev = iommufd_device_get_iommu_dev(idev);\n+\t\t\tif (!iommu_dev || viommu-\u003eiommu_dev != iommu_dev) {\n+\t\t\t\trc = -EINVAL;\n+\t\t\t\tgoto out_unlock;\n+\t\t\t}\n \t\t}\n \t\thwpt_nested = iommufd_viommu_alloc_hwpt_nested(\n \t\t\tviommu, cmd-\u003eflags, \u0026user_data);\ndiff --git a/drivers/iommu/iommufd/iommufd_private.h b/drivers/iommu/iommufd/iommufd_private.h\nindex eb2e85b27e429..64e0d9e4da168 100644\n--- a/drivers/iommu/iommufd/iommufd_private.h\n+++ b/drivers/iommu/iommufd/iommufd_private.h\n@@ -509,6 +509,8 @@ struct iommufd_device {\n \tstruct list_head group_item;\n \t/* always the physical device */\n \tstruct device *dev;\n+\t/* ..and the VM file if available */\n+\tstruct file *kvm_file;\n \tbool enforce_cache_coherency;\n \tstruct iommufd_vdevice *vdev;\n \tbool destroying;\n@@ -728,6 +730,14 @@ void iommufd_vdevice_destroy(struct iommufd_object *obj);\n void iommufd_vdevice_abort(struct iommufd_object *obj);\n int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd);\n void iommufd_hw_queue_destroy(struct iommufd_object *obj);\n+#ifdef CONFIG_TSM\n+int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd);\n+#else\n+static inline int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)\n+{\n+\treturn -EOPNOTSUPP;\n+}\n+#endif\n \n #ifdef CONFIG_IOMMUFD_TEST\n int iommufd_test(struct iommufd_ucmd *ucmd);\ndiff --git a/drivers/iommu/iommufd/main.c b/drivers/iommu/iommufd/main.c\nindex 9a921b1531620..577eef2760a35 100644\n--- a/drivers/iommu/iommufd/main.c\n+++ b/drivers/iommu/iommufd/main.c\n@@ -453,6 +453,7 @@ union ucmd_buffer {\n \tstruct iommu_veventq_alloc veventq;\n \tstruct iommu_vfio_ioas vfio_ioas;\n \tstruct iommu_viommu_alloc viommu;\n+\tstruct iommu_vdevice_tsm_req tsm_req;\n #ifdef CONFIG_IOMMUFD_TEST\n \tstruct iommu_test_cmd test;\n #endif\n@@ -516,6 +517,8 @@ static const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {\n \t\t __reserved),\n \tIOCTL_OP(IOMMU_VIOMMU_ALLOC, iommufd_viommu_alloc_ioctl,\n \t\t struct iommu_viommu_alloc, out_viommu_id),\n+\tIOCTL_OP(IOMMU_VDEVICE_TSM_REQ, iommufd_vdevice_tsm_req_ioctl,\n+\t\t struct iommu_vdevice_tsm_req, out_tsm_code),\n #ifdef CONFIG_IOMMUFD_TEST\n \tIOCTL_OP(IOMMU_TEST_CMD, iommufd_test, struct iommu_test_cmd, last),\n #endif\ndiff --git a/drivers/iommu/iommufd/selftest.c b/drivers/iommu/iommufd/selftest.c\nindex ee706f18f7e91..426ea94467ffe 100644\n--- a/drivers/iommu/iommufd/selftest.c\n+++ b/drivers/iommu/iommufd/selftest.c\n@@ -774,7 +774,19 @@ static int mock_hw_queue_init_phys(struct iommufd_hw_queue *hw_queue, u32 index,\n \treturn rc;\n }\n \n-static struct iommufd_viommu_ops mock_viommu_ops = {\n+static int mock_viommu_init(struct iommufd_viommu *viommu, struct device *dev,\n+\t\tstruct iommu_domain *parent_domain,\n+\t\tconst struct iommu_user_data *user_data);\n+\n+static size_t mock_get_viommu_size(struct device *dev,\n+\t\t\t\t   enum iommu_viommu_type viommu_type)\n+{\n+\treturn VIOMMU_STRUCT_SIZE(struct mock_viommu, core);\n+}\n+\n+static const struct iommufd_viommu_ops mock_viommu_ops = {\n+\t.get_viommu_size = mock_get_viommu_size,\n+\t.viommu_init = mock_viommu_init,\n \t.destroy = mock_viommu_destroy,\n \t.alloc_domain_nested = mock_viommu_alloc_domain_nested,\n \t.cache_invalidate = mock_viommu_cache_invalidate,\n@@ -782,17 +794,18 @@ static struct iommufd_viommu_ops mock_viommu_ops = {\n \t.hw_queue_init_phys = mock_hw_queue_init_phys,\n };\n \n-static size_t mock_get_viommu_size(struct device *dev,\n-\t\t\t\t   enum iommu_viommu_type viommu_type)\n+static const struct iommufd_viommu_ops *\n+mock_get_viommu_ops(struct device *dev,\n+\t\tenum iommu_viommu_type viommu_type)\n {\n \tif (viommu_type != IOMMU_VIOMMU_TYPE_SELFTEST)\n-\t\treturn 0;\n-\treturn VIOMMU_STRUCT_SIZE(struct mock_viommu, core);\n+\t\treturn NULL;\n+\treturn \u0026mock_viommu_ops;\n }\n \n static int mock_viommu_init(struct iommufd_viommu *viommu,\n-\t\t\t    struct iommu_domain *parent_domain,\n-\t\t\t    const struct iommu_user_data *user_data)\n+\t\tstruct device *dev, struct iommu_domain *parent_domain,\n+\t\tconst struct iommu_user_data *user_data)\n {\n \tstruct mock_iommu_device *mock_iommu = container_of(\n \t\tviommu-\u003eiommu_dev, struct mock_iommu_device, iommu_dev);\n@@ -834,7 +847,6 @@ static int mock_viommu_init(struct iommufd_viommu *viommu,\n \tmutex_init(\u0026mock_viommu-\u003equeue_mutex);\n \tmock_viommu-\u003es2_parent = to_mock_domain(parent_domain);\n \n-\tviommu-\u003eops = \u0026mock_viommu_ops;\n \treturn 0;\n \n err_destroy_mmap:\n@@ -861,8 +873,7 @@ static const struct iommu_ops mock_ops = {\n \t.probe_device = mock_probe_device,\n \t.page_response = mock_domain_page_response,\n \t.user_pasid_table = true,\n-\t.get_viommu_size = mock_get_viommu_size,\n-\t.viommu_init = mock_viommu_init,\n+\t.get_viommu_ops = mock_get_viommu_ops,\n };\n \n static void mock_domain_free_nested(struct iommu_domain *domain)\n@@ -1074,7 +1085,7 @@ static int iommufd_test_mock_domain(struct iommufd_ucmd *ucmd,\n \t\tgoto out_sobj;\n \t}\n \n-\tidev = iommufd_device_bind(ucmd-\u003eictx, \u0026sobj-\u003eidev.mock_dev-\u003edev,\n+\tidev = iommufd_device_bind(ucmd-\u003eictx, \u0026sobj-\u003eidev.mock_dev-\u003edev, NULL,\n \t\t\t\t   \u0026idev_id);\n \tif (IS_ERR(idev)) {\n \t\trc = PTR_ERR(idev);\ndiff --git a/drivers/iommu/iommufd/tsm.c b/drivers/iommu/iommufd/tsm.c\nnew file mode 100644\nindex 0000000000000..b28ff86403456\n--- /dev/null\n+++ b/drivers/iommu/iommufd/tsm.c\n@@ -0,0 +1,80 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (C) 2026 ARM Ltd.\n+ */\n+\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/build_bug.h\u003e\n+#include \u003clinux/limits.h\u003e\n+#include \u003clinux/tsm.h\u003e\n+#include \"iommufd_private.h\"\n+\n+/**\n+ * iommufd_vdevice_tsm_req_ioctl - Forward TSM requests\n+ * @ucmd: user command data for IOMMU_VDEVICE_TSM_REQ\n+ *\n+ * Resolve @iommu_vdevice_tsm_req::vdevice_id to a vdevice and pass the\n+ * request/response buffers to its vIOMMU implementation.\n+ *\n+ * Return:\n+ *  -errno on error.\n+ *  positive residue if response/request bytes were left unconsumed.\n+ *    if response buffer is provided, residue indicates the number of bytes\n+ *    not used in response buffer\n+ *    if there is no response buffer, residue indicates the number of bytes\n+ *    not consumed in req buffer\n+ *  0 otherwise.\n+ */\n+int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)\n+{\n+\tint ret;\n+\tstruct iommufd_object *obj;\n+\tstruct iommufd_vdevice *vdev;\n+\tstruct iommu_vdevice_tsm_req *cmd = ucmd-\u003ecmd;\n+\tstruct tsm_guest_req_info info = {\n+\t\t.op = cmd-\u003eop,\n+\t\t.tvm_arch = cmd-\u003etvm_arch,\n+\t\t.req = u64_to_user_ptr(cmd-\u003ereq_uptr),\n+\t\t.req_len = cmd-\u003ereq_len,\n+\t\t.resp = u64_to_user_ptr(cmd-\u003eresp_uptr),\n+\t\t.resp_len = cmd-\u003eresp_len,\n+\t};\n+\n+\t/* Every defined operation must fit in the vdevice's u64 mask. */\n+\tBUILD_BUG_ON(BITS_PER_TYPE(u64) \u003c TSM_REQ_MAX);\n+\n+\t/* Successful residues must fit in the ioctl's int return value. */\n+\tif (cmd-\u003ereq_len \u003e INT_MAX || cmd-\u003eresp_len \u003e INT_MAX)\n+\t\treturn -EINVAL;\n+\n+\tobj = iommufd_get_object(ucmd-\u003eictx, cmd-\u003evdevice_id,\n+\t\t\t\t IOMMUFD_OBJ_VDEVICE);\n+\tif (IS_ERR(obj))\n+\t\treturn PTR_ERR(obj);\n+\tvdev = container_of(obj, struct iommufd_vdevice, obj);\n+\n+\tcmd-\u003eout_tsm_code = 0;\n+\tif (!vdev-\u003eviommu-\u003eops || !vdev-\u003eviommu-\u003eops-\u003evdevice_tsm_req ||\n+\t    !vdev-\u003etsm_req_op_mask) {\n+\t\tret = -EOPNOTSUPP;\n+\t\tgoto out_respond;\n+\t}\n+\t/* Bounds-check the user-supplied shift before BIT_ULL(). */\n+\tif (cmd-\u003etvm_arch != vdev-\u003etsm_tvm_arch ||\n+\t    cmd-\u003eop \u003e= TSM_REQ_MAX ||\n+\t    !(vdev-\u003etsm_req_op_mask \u0026 BIT_ULL(cmd-\u003eop))) {\n+\t\tret = -EINVAL;\n+\t\tgoto out_put_object;\n+\t}\n+\tret = vdev-\u003eviommu-\u003eops-\u003evdevice_tsm_req(vdev, \u0026info,\n+\t\t\t\t\t\t \u0026cmd-\u003eout_tsm_code);\n+\n+out_respond:\n+\t/* Always copy the tsm_code as response */\n+\tif (iommufd_ucmd_respond(ucmd, sizeof(*cmd)))\n+\t\tret = -EFAULT;\n+\n+out_put_object:\n+\tiommufd_put_object(ucmd-\u003eictx, obj);\n+\treturn ret;\n+}\ndiff --git a/drivers/iommu/iommufd/viommu.c b/drivers/iommu/iommufd/viommu.c\nindex f7951057a1e56..9155d0dcb4b40 100644\n--- a/drivers/iommu/iommufd/viommu.c\n+++ b/drivers/iommu/iommufd/viommu.c\n@@ -1,6 +1,10 @@\n // SPDX-License-Identifier: GPL-2.0-only\n /* Copyright (c) 2024, NVIDIA CORPORATION \u0026 AFFILIATES\n  */\n+#include \u003clinux/file.h\u003e\n+#include \u003clinux/cleanup.h\u003e\n+#include \u003clinux/tsm.h\u003e\n+\n #include \"iommufd_private.h\"\n \n void iommufd_viommu_destroy(struct iommufd_object *obj)\n@@ -10,7 +14,12 @@ void iommufd_viommu_destroy(struct iommufd_object *obj)\n \n \tif (viommu-\u003eops \u0026\u0026 viommu-\u003eops-\u003edestroy)\n \t\tviommu-\u003eops-\u003edestroy(viommu);\n-\trefcount_dec(\u0026viommu-\u003ehwpt-\u003ecommon.obj.users);\n+\tif (viommu-\u003etsm_dev)\n+\t\ttsm_put_device(viommu-\u003etsm_dev);\n+\tif (viommu-\u003ehwpt)\n+\t\trefcount_dec(\u0026viommu-\u003ehwpt-\u003ecommon.obj.users);\n+\tif (viommu-\u003ekvm_file)\n+\t\tfput(viommu-\u003ekvm_file);\n \txa_destroy(\u0026viommu-\u003evdevs);\n }\n \n@@ -22,11 +31,12 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n \t\t.uptr = u64_to_user_ptr(cmd-\u003edata_uptr),\n \t\t.len = cmd-\u003edata_len,\n \t};\n-\tstruct iommufd_hwpt_paging *hwpt_paging;\n+\tstruct iommufd_hwpt_paging *hwpt_paging = NULL;\n+\tstruct tsm_dev *tsm_dev = NULL;\n \tstruct iommufd_viommu *viommu;\n \tstruct iommufd_device *idev;\n-\tstruct iommu_device *iommu_dev;\n-\tconst struct iommu_ops *ops;\n+\tstruct iommu_device *iommu_dev = NULL;\n+\tconst struct iommufd_viommu_ops *ops;\n \tsize_t viommu_size;\n \tint rc;\n \n@@ -37,41 +47,66 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n \tif (IS_ERR(idev))\n \t\treturn PTR_ERR(idev);\n \n-\tiommu_dev = iommufd_device_get_iommu_dev(idev);\n-\tif (!iommu_dev) {\n-\t\trc = -EOPNOTSUPP;\n+\ttsm_dev = tsm_get_device(idev-\u003edev);\n+\tif (IS_ERR(tsm_dev)) {\n+\t\trc = PTR_ERR(tsm_dev);\n+\t\ttsm_dev = NULL;\n \t\tgoto out_put_idev;\n \t}\n-\tops = iommu_dev-\u003eops;\n-\tif (!ops-\u003eget_viommu_size || !ops-\u003eviommu_init) {\n-\t\trc = -EOPNOTSUPP;\n+\tops = tsm_dev ? tsm_viommu_get_ops(tsm_dev, idev-\u003edev, cmd-\u003etype) : NULL;\n+\tif (IS_ERR(ops)) {\n+\t\trc = PTR_ERR(ops);\n \t\tgoto out_put_idev;\n \t}\n-\n-\tviommu_size = ops-\u003eget_viommu_size(idev-\u003edev, cmd-\u003etype);\n-\tif (!viommu_size) {\n-\t\trc = -EOPNOTSUPP;\n-\t\tgoto out_put_idev;\n+\tif (!ops) {\n+\t\tif (tsm_dev) {\n+\t\t\ttsm_put_device(tsm_dev);\n+\t\t\ttsm_dev = NULL;\n+\t\t}\n+\t\tiommu_dev = iommufd_device_get_iommu_dev(idev);\n+\t\tif (!iommu_dev) {\n+\t\t\trc = -EOPNOTSUPP;\n+\t\t\tgoto out_put_idev;\n+\t\t}\n+\t\tif (!iommu_dev-\u003eops-\u003eget_viommu_ops) {\n+\t\t\trc = -EOPNOTSUPP;\n+\t\t\tgoto out_put_idev;\n+\t\t}\n+\t\tops = iommu_dev-\u003eops-\u003eget_viommu_ops(idev-\u003edev, cmd-\u003etype);\n+\t\tif (!ops) {\n+\t\t\trc = -EOPNOTSUPP;\n+\t\t\tgoto out_put_idev;\n+\t\t}\n \t}\n \n \t/*\n-\t * It is a driver bug for providing a viommu_size smaller than the core\n-\t * vIOMMU structure size\n+\t * It is a driver bug to omit the required operations or provide a size\n+\t * smaller than the core vIOMMU structure.\n \t */\n-\tif (WARN_ON_ONCE(viommu_size \u003c sizeof(*viommu))) {\n+\tif (WARN_ON_ONCE(!ops-\u003eget_viommu_size || !ops-\u003eviommu_init)) {\n \t\trc = -EOPNOTSUPP;\n \t\tgoto out_put_idev;\n \t}\n-\n-\thwpt_paging = iommufd_get_hwpt_paging(ucmd, cmd-\u003ehwpt_id);\n-\tif (IS_ERR(hwpt_paging)) {\n-\t\trc = PTR_ERR(hwpt_paging);\n+\tviommu_size = ops-\u003eget_viommu_size(idev-\u003edev, cmd-\u003etype);\n+\tif (!viommu_size || WARN_ON_ONCE(viommu_size \u003c sizeof(*viommu))) {\n+\t\trc = -EOPNOTSUPP;\n \t\tgoto out_put_idev;\n \t}\n \n-\tif (!hwpt_paging-\u003enest_parent) {\n+\tif ((ops-\u003eflags \u0026 IOMMUFD_VIOMMU_NO_HWPT) \u0026\u0026 cmd-\u003ehwpt_id) {\n \t\trc = -EINVAL;\n-\t\tgoto out_put_hwpt;\n+\t\tgoto out_put_idev;\n+\t}\n+\tif (!(ops-\u003eflags \u0026 IOMMUFD_VIOMMU_NO_HWPT)) {\n+\t\thwpt_paging = iommufd_get_hwpt_paging(ucmd, cmd-\u003ehwpt_id);\n+\t\tif (IS_ERR(hwpt_paging)) {\n+\t\t\trc = PTR_ERR(hwpt_paging);\n+\t\t\tgoto out_put_idev;\n+\t\t}\n+\t\tif (!hwpt_paging-\u003enest_parent) {\n+\t\t\trc = -EINVAL;\n+\t\t\tgoto out_put_hwpt;\n+\t\t}\n \t}\n \n \tviommu = (struct iommufd_viommu *)_iommufd_object_alloc_ucmd(\n@@ -82,10 +117,15 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n \t}\n \n \txa_init(\u0026viommu-\u003evdevs);\n+\tif (idev-\u003ekvm_file)\n+\t\tviommu-\u003ekvm_file = get_file(idev-\u003ekvm_file);\n \tviommu-\u003etype = cmd-\u003etype;\n \tviommu-\u003eictx = ucmd-\u003eictx;\n+\tviommu-\u003etsm_dev = tsm_dev;\n+\ttsm_dev = NULL;\n \tviommu-\u003ehwpt = hwpt_paging;\n-\trefcount_inc(\u0026viommu-\u003ehwpt-\u003ecommon.obj.users);\n+\tif (viommu-\u003ehwpt)\n+\t\trefcount_inc(\u0026viommu-\u003ehwpt-\u003ecommon.obj.users);\n \tINIT_LIST_HEAD(\u0026viommu-\u003eveventqs);\n \tinit_rwsem(\u0026viommu-\u003eveventqs_rwsem);\n \t/*\n@@ -95,23 +135,22 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n \t */\n \tviommu-\u003eiommu_dev = iommu_dev;\n \n-\trc = ops-\u003eviommu_init(viommu, hwpt_paging-\u003ecommon.domain,\n+\trc = ops-\u003eviommu_init(viommu, idev-\u003edev,\n+\t\t\t      hwpt_paging ? hwpt_paging-\u003ecommon.domain : NULL,\n \t\t\t      user_data.len ? \u0026user_data : NULL);\n \tif (rc)\n \t\tgoto out_put_hwpt;\n-\n-\t/* It is a driver bug that viommu-\u003eops isn't filled */\n-\tif (WARN_ON_ONCE(!viommu-\u003eops)) {\n-\t\trc = -EOPNOTSUPP;\n-\t\tgoto out_put_hwpt;\n-\t}\n+\tviommu-\u003eops = ops;\n \n \tcmd-\u003eout_viommu_id = viommu-\u003eobj.id;\n \trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\n \n out_put_hwpt:\n-\tiommufd_put_object(ucmd-\u003eictx, \u0026hwpt_paging-\u003ecommon.obj);\n+\tif (hwpt_paging)\n+\t\tiommufd_put_object(ucmd-\u003eictx, \u0026hwpt_paging-\u003ecommon.obj);\n out_put_idev:\n+\tif (tsm_dev)\n+\t\ttsm_put_device(tsm_dev);\n \tiommufd_put_object(ucmd-\u003eictx, \u0026idev-\u003eobj);\n \treturn rc;\n }\n@@ -171,10 +210,12 @@ int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd)\n \t\tgoto out_put_viommu;\n \t}\n \n-\tiommu_dev = iommufd_device_get_iommu_dev(idev);\n-\tif (!iommu_dev || viommu-\u003eiommu_dev != iommu_dev) {\n-\t\trc = -EINVAL;\n-\t\tgoto out_put_idev;\n+\tif (viommu-\u003eiommu_dev) {\n+\t\tiommu_dev = iommufd_device_get_iommu_dev(idev);\n+\t\tif (!iommu_dev || viommu-\u003eiommu_dev != iommu_dev) {\n+\t\t\trc = -EINVAL;\n+\t\t\tgoto out_put_idev;\n+\t\t}\n \t}\n \n \tmutex_lock(\u0026idev-\u003eigroup-\u003elock);\n@@ -394,7 +435,7 @@ int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)\n \tif (IS_ERR(viommu))\n \t\treturn PTR_ERR(viommu);\n \n-\tif (!viommu-\u003eops || !viommu-\u003eops-\u003eget_hw_queue_size ||\n+\tif (!viommu-\u003ehwpt || !viommu-\u003eops || !viommu-\u003eops-\u003eget_hw_queue_size ||\n \t    !viommu-\u003eops-\u003ehw_queue_init_phys) {\n \t\trc = -EOPNOTSUPP;\n \t\tgoto out_put_viommu;\ndiff --git a/drivers/pci/tsm.c b/drivers/pci/tsm.c\nindex 5fdcd7f2e8207..8aa74ba31932b 100644\n--- a/drivers/pci/tsm.c\n+++ b/drivers/pci/tsm.c\n@@ -9,9 +9,15 @@\n #define dev_fmt(fmt) \"PCI/TSM: \" fmt\n \n #include \u003clinux/bitfield.h\u003e\n+#include \u003clinux/iommufd.h\u003e\n+#include \u003clinux/jiffies.h\u003e\n+#include \u003clinux/module.h\u003e\n #include \u003clinux/pci.h\u003e\n #include \u003clinux/pci-doe.h\u003e\n #include \u003clinux/pci-tsm.h\u003e\n+#include \u003clinux/pid.h\u003e\n+#include \u003clinux/sched.h\u003e\n+#include \u003clinux/slab.h\u003e\n #include \u003clinux/sysfs.h\u003e\n #include \u003clinux/tsm.h\u003e\n #include \u003clinux/xarray.h\u003e\n@@ -35,6 +41,25 @@ static const struct pci_tsm_ops *to_pci_tsm_ops(struct pci_tsm *tsm)\n \treturn tsm-\u003etsm_dev-\u003epci_ops;\n }\n \n+struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)\n+{\n+\tconst struct pci_tsm_ops *ops;\n+\tstruct tsm_dev *tsm_dev;\n+\n+\tguard(rwsem_read)(\u0026pci_tsm_rwsem);\n+\tif (!pdev-\u003etsm)\n+\t\treturn NULL;\n+\n+\ttsm_dev = pdev-\u003etsm-\u003etsm_dev;\n+\tops = tsm_dev-\u003epci_ops;\n+\tif (!ops-\u003eviommu_get_ops)\n+\t\treturn NULL;\n+\tif (!try_module_get(ops-\u003eowner))\n+\t\treturn ERR_PTR(-ENODEV);\n+\treturn tsm_dev;\n+}\n+EXPORT_SYMBOL_GPL(pci_tsm_get_device);\n+\n static inline bool is_dsm(struct pci_dev *pdev)\n {\n \treturn pdev-\u003etsm \u0026\u0026 pdev-\u003etsm-\u003edsm_dev == pdev;\n@@ -292,156 +317,103 @@ static int remove_fn(struct pci_dev *pdev, void *data)\n \treturn 0;\n }\n \n-/*\n- * Note, this helper only returns an error code and takes an argument for\n- * compatibility with the pci_walk_bus() callback prototype. pci_tsm_unbind()\n- * always succeeds.\n- */\n-static int __pci_tsm_unbind(struct pci_dev *pdev, void *data)\n+bool pci_tsm_is_configured(struct pci_dev *pdev)\n {\n-\tstruct pci_tdi *tdi;\n-\tstruct pci_tsm_pf0 *tsm_pf0;\n-\n-\tlockdep_assert_held(\u0026pci_tsm_rwsem);\n-\n-\tif (!pdev-\u003etsm)\n-\t\treturn 0;\n-\n-\ttsm_pf0 = to_pci_tsm_pf0(pdev-\u003etsm);\n-\tguard(mutex)(\u0026tsm_pf0-\u003elock);\n-\n-\ttdi = pdev-\u003etsm-\u003etdi;\n-\tif (!tdi)\n-\t\treturn 0;\n-\n-\tto_pci_tsm_ops(pdev-\u003etsm)-\u003eunbind(tdi);\n-\tpdev-\u003etsm-\u003etdi = NULL;\n+\tguard(rwsem_read)(\u0026pci_tsm_rwsem);\n \n-\treturn 0;\n+\treturn !!pdev-\u003etsm;\n }\n+EXPORT_SYMBOL_GPL(pci_tsm_is_configured);\n \n-void pci_tsm_unbind(struct pci_dev *pdev)\n-{\n-\tguard(rwsem_read)(\u0026pci_tsm_rwsem);\n-\t__pci_tsm_unbind(pdev, NULL);\n-}\n-EXPORT_SYMBOL_GPL(pci_tsm_unbind);\n+struct pci_tsm_context {\n+\tstruct pci_tsm_pf0 *pf0;\n+\tstruct pci_dev *pdev;\n+\tstruct pci_dev *dsm_dev;\n+};\n \n-/**\n- * pci_tsm_bind() - Bind @pdev as a TDI for @kvm\n- * @pdev: PCI device function to bind\n- * @kvm: Private memory attach context\n- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM\n- *\n- * Returns 0 on success, or a negative error code on failure.\n- *\n- * Context: Caller is responsible for constraining the bind lifetime to the\n- * registered state of the device. For example, pci_tsm_bind() /\n- * pci_tsm_unbind() limited to the VFIO driver bound state of the device.\n- */\n-int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id)\n+struct pci_tsm_context *pci_tsm_context_get(struct pci_dev *pdev,\n+\t\t\t\t\t    struct tsm_dev *viommu_tsm_dev)\n {\n-\tstruct pci_tsm_pf0 *tsm_pf0;\n-\tstruct pci_tdi *tdi;\n-\n-\tif (!kvm)\n-\t\treturn -EINVAL;\n+\tstruct pci_tsm_context *context;\n+\tstruct pci_tsm_pf0 *pf0;\n \n \tguard(rwsem_read)(\u0026pci_tsm_rwsem);\n+\tif (!pdev-\u003etsm || !is_link_tsm(pdev-\u003etsm-\u003etsm_dev))\n+\t\treturn ERR_PTR(-EOPNOTSUPP);\n+\t/*\n+\t * The vdevice can use a different PCI function from VIOMMU_ALLOC. The\n+\t * module pin keeps the vIOMMU's TSM registered, but does not freeze this\n+\t * function's link. Match its current TSM before pinning the link below.\n+\t */\n+\tif (pdev-\u003etsm-\u003etsm_dev != viommu_tsm_dev)\n+\t\treturn ERR_PTR(-EXDEV);\n \n-\tif (!pdev-\u003etsm)\n-\t\treturn -EINVAL;\n-\n-\tif (!is_link_tsm(pdev-\u003etsm-\u003etsm_dev))\n-\t\treturn -ENXIO;\n+\tpf0 = to_pci_tsm_pf0(pdev-\u003etsm);\n+\tif (!pf0)\n+\t\treturn ERR_PTR(-ENXIO);\n \n-\ttsm_pf0 = to_pci_tsm_pf0(pdev-\u003etsm);\n-\tguard(mutex)(\u0026tsm_pf0-\u003elock);\n+\tcontext = kzalloc_obj(*context);\n+\tif (!context)\n+\t\treturn ERR_PTR(-ENOMEM);\n \n-\t/* Resolve races to bind a TDI */\n-\tif (pdev-\u003etsm-\u003etdi) {\n-\t\tif (pdev-\u003etsm-\u003etdi-\u003ekvm != kvm)\n-\t\t\treturn -EBUSY;\n-\t\treturn 0;\n+\tguard(mutex)(\u0026pf0-\u003elock);\n+\tif (pf0-\u003eremoving) {\n+\t\tkfree(context);\n+\t\treturn ERR_PTR(-ENODEV);\n \t}\n-\n-\ttdi = to_pci_tsm_ops(pdev-\u003etsm)-\u003ebind(pdev, kvm, tdi_id);\n-\tif (IS_ERR(tdi))\n-\t\treturn PTR_ERR(tdi);\n-\n-\tpdev-\u003etsm-\u003etdi = tdi;\n-\n-\treturn 0;\n+\tif (!pf0-\u003econtext_users)\n+\t\treinit_completion(\u0026pf0-\u003econtexts_drained);\n+\tpf0-\u003econtext_users++;\n+\tcontext-\u003epf0 = pf0;\n+\tcontext-\u003epdev = pci_dev_get(pdev);\n+\tcontext-\u003edsm_dev = pci_dev_get(pf0-\u003ebase_tsm.pdev);\n+\treturn context;\n }\n-EXPORT_SYMBOL_GPL(pci_tsm_bind);\n+EXPORT_SYMBOL_GPL(pci_tsm_context_get);\n \n-/**\n- * pci_tsm_guest_req() - helper to marshal guest requests to the TSM driver\n- * @pdev: @pdev representing a bound tdi\n- * @scope: caller asserts this passthrough request is limited to TDISP operations\n- * @req_in: Input payload forwarded from the guest\n- * @in_len: Length of @req_in\n- * @req_out: Output payload buffer response to the guest\n- * @out_len: Length of @req_out on input, bytes filled in @req_out on output\n- * @tsm_code: Optional TSM arch specific result code for the guest TSM\n- *\n- * This is a common entry point for requests triggered by userspace KVM-exit\n- * service handlers responding to TDI information or state change requests. The\n- * scope parameter limits requests to TDISP state management, or limited debug.\n- * This path is only suitable for commands and results that are the host kernel\n- * has no use, the host is only facilitating guest to TSM communication.\n- *\n- * Returns 0 on success and -error on failure and positive \"residue\" on success\n- * but @req_out is filled with less then @out_len, or @req_out is NULL and a\n- * residue number of bytes were not consumed from @req_in.  On success or\n- * failure @tsm_code may be populated with a TSM implementation specific result\n- * code for the guest to consume.\n- *\n- * Context: Caller is responsible for calling this within the pci_tsm_bind()\n- * state of the TDI.\n- */\n-ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope,\n-\t\t\t  sockptr_t req_in, size_t in_len, sockptr_t req_out,\n-\t\t\t  size_t out_len, u64 *tsm_code)\n+void pci_tsm_context_put(struct pci_tsm_context *context)\n {\n-\tstruct pci_tsm_pf0 *tsm_pf0;\n-\tstruct pci_tdi *tdi;\n-\tint rc;\n-\n-\t/* Forbid requests that are not directly related to TDISP operations */\n-\tif (scope \u003e PCI_TSM_REQ_STATE_CHANGE)\n-\t\treturn -EINVAL;\n+\tstruct pci_tsm_pf0 *pf0 = context-\u003epf0;\n \n-\tACQUIRE(rwsem_read_intr, lock)(\u0026pci_tsm_rwsem);\n-\tif ((rc = ACQUIRE_ERR(rwsem_read_intr, \u0026lock)))\n-\t\treturn rc;\n+\tdown_read(\u0026pci_tsm_rwsem);\n+\tmutex_lock(\u0026pf0-\u003elock);\n+\tif (WARN_ON(!pf0-\u003econtext_users))\n+\t\tgoto out_unlock;\n+\tif (!--pf0-\u003econtext_users)\n+\t\tcomplete_all(\u0026pf0-\u003econtexts_drained);\n+out_unlock:\n+\tmutex_unlock(\u0026pf0-\u003elock);\n+\tup_read(\u0026pci_tsm_rwsem);\n \n-\tif (!pdev-\u003etsm)\n-\t\treturn -ENXIO;\n-\n-\tif (!is_link_tsm(pdev-\u003etsm-\u003etsm_dev))\n-\t\treturn -ENXIO;\n+\tpci_dev_put(context-\u003epdev);\n+\tpci_dev_put(context-\u003edsm_dev);\n+\tkfree(context);\n+}\n+EXPORT_SYMBOL_GPL(pci_tsm_context_put);\n \n-\ttsm_pf0 = to_pci_tsm_pf0(pdev-\u003etsm);\n-\tACQUIRE(mutex_intr, ops_lock)(\u0026tsm_pf0-\u003elock);\n-\tif ((rc = ACQUIRE_ERR(mutex_intr, \u0026ops_lock)))\n-\t\treturn rc;\n+struct pci_tsm_pf0 *pci_tsm_context_pf0(struct pci_tsm_context *context)\n+{\n+\treturn context-\u003epf0;\n+}\n+EXPORT_SYMBOL_GPL(pci_tsm_context_pf0);\n \n-\ttdi = pdev-\u003etsm-\u003etdi;\n-\tif (!tdi)\n-\t\treturn -ENXIO;\n-\treturn to_pci_tsm_ops(pdev-\u003etsm)-\u003eguest_req(tdi, scope, req_in, in_len,\n-\t\t\t\t\t\t    req_out, out_len, tsm_code);\n+struct pci_dev *pci_tsm_context_dsm_dev(struct pci_tsm_context *context)\n+{\n+\treturn context-\u003edsm_dev;\n }\n-EXPORT_SYMBOL_GPL(pci_tsm_guest_req);\n+EXPORT_SYMBOL_GPL(pci_tsm_context_dsm_dev);\n \n-static void pci_tsm_unbind_all(struct pci_dev *pdev)\n+bool pci_tsm_context_match_device(struct pci_tsm_context *context,\n+\t\t\t\t  struct pci_dev *pdev)\n {\n-\tpci_tsm_walk_fns_reverse(pdev, __pci_tsm_unbind, NULL);\n-\t__pci_tsm_unbind(pdev, NULL);\n+\tguard(rwsem_read)(\u0026pci_tsm_rwsem);\n+\n+\treturn pdev-\u003etsm \u0026\u0026 is_link_tsm(pdev-\u003etsm-\u003etsm_dev) \u0026\u0026\n+\t       to_pci_tsm_pf0(pdev-\u003etsm) == context-\u003epf0;\n }\n+EXPORT_SYMBOL_GPL(pci_tsm_context_match_device);\n \n-static void __pci_tsm_disconnect(struct pci_dev *pdev)\n+static int __pci_tsm_disconnect(struct pci_dev *pdev)\n {\n \tstruct pci_tsm_pf0 *tsm_pf0 = to_pci_tsm_pf0(pdev-\u003etsm);\n \tconst struct pci_tsm_ops *ops = to_pci_tsm_ops(pdev-\u003etsm);\n@@ -449,21 +421,29 @@ static void __pci_tsm_disconnect(struct pci_dev *pdev)\n \t/* disconnect() mutually exclusive with subfunction pci_tsm_init() */\n \tlockdep_assert_held_write(\u0026pci_tsm_rwsem);\n \n-\tpci_tsm_unbind_all(pdev);\n-\n \t/*\n-\t * disconnect() is uninterruptible as it may be called for device\n-\t * teardown\n+\t * A vdevice holds a context for its lifetime. Refuse to tear down the\n+\t * link until userspace destroys all dependent vdevices.\n+\t *\n+\t * disconnect() is uninterruptible as it may also be called for device\n+\t * teardown.\n \t */\n \tguard(mutex)(\u0026tsm_pf0-\u003elock);\n+\tif (tsm_pf0-\u003econtext_users)\n+\t\treturn -EBUSY;\n \tpci_tsm_walk_fns_reverse(pdev, remove_fn, NULL);\n \tops-\u003edisconnect(pdev);\n+\treturn 0;\n }\n \n-static void pci_tsm_disconnect(struct pci_dev *pdev)\n+static int pci_tsm_disconnect(struct pci_dev *pdev)\n {\n-\t__pci_tsm_disconnect(pdev);\n+\tint ret = __pci_tsm_disconnect(pdev);\n+\n+\tif (ret)\n+\t\treturn ret;\n \ttsm_remove(pdev-\u003etsm);\n+\treturn 0;\n }\n \n static ssize_t disconnect_store(struct device *dev,\n@@ -484,39 +464,17 @@ static ssize_t disconnect_store(struct device *dev,\n \ttsm_dev = pdev-\u003etsm-\u003etsm_dev;\n \tif (!sysfs_streq(buf, dev_name(\u0026tsm_dev-\u003edev)))\n \t\treturn -EINVAL;\n+\tif (is_link_tsm(tsm_dev) \u0026\u0026 is_pci_tsm_pf0(pdev) \u0026\u0026\n+\t    to_pci_tsm_pf0(pdev-\u003etsm)-\u003eremoving)\n+\t\treturn -ENODEV;\n \n-\tpci_tsm_disconnect(pdev);\n+\trc = pci_tsm_disconnect(pdev);\n+\tif (rc)\n+\t\treturn rc;\n \treturn len;\n }\n static DEVICE_ATTR_WO(disconnect);\n \n-static ssize_t bound_show(struct device *dev,\n-\t\t\t  struct device_attribute *attr, char *buf)\n-{\n-\tstruct pci_dev *pdev = to_pci_dev(dev);\n-\tstruct pci_tsm_pf0 *tsm_pf0;\n-\tstruct pci_tsm *tsm;\n-\tint rc;\n-\n-\tACQUIRE(rwsem_read_intr, lock)(\u0026pci_tsm_rwsem);\n-\tif ((rc = ACQUIRE_ERR(rwsem_read_intr, \u0026lock)))\n-\t\treturn rc;\n-\n-\ttsm = pdev-\u003etsm;\n-\tif (!tsm)\n-\t\treturn sysfs_emit(buf, \"\\n\");\n-\ttsm_pf0 = to_pci_tsm_pf0(tsm);\n-\n-\tACQUIRE(mutex_intr, ops_lock)(\u0026tsm_pf0-\u003elock);\n-\tif ((rc = ACQUIRE_ERR(mutex_intr, \u0026ops_lock)))\n-\t\treturn rc;\n-\n-\tif (!tsm-\u003etdi)\n-\t\treturn sysfs_emit(buf, \"\\n\");\n-\treturn sysfs_emit(buf, \"%s\\n\", dev_name(\u0026tsm-\u003etsm_dev-\u003edev));\n-}\n-static DEVICE_ATTR_RO(bound);\n-\n static ssize_t dsm_show(struct device *dev, struct device_attribute *attr,\n \t\t\tchar *buf)\n {\n@@ -571,13 +529,6 @@ static umode_t pci_tsm_attr_visible(struct kobject *kobj,\n \tif (pci_tsm_link_group_visible(kobj)) {\n \t\tstruct pci_dev *pdev = to_pci_dev(kobj_to_dev(kobj));\n \n-\t\tif (attr == \u0026dev_attr_bound.attr) {\n-\t\t\tif (is_pci_tsm_pf0(pdev) \u0026\u0026 has_tee(pdev))\n-\t\t\t\treturn attr-\u003emode;\n-\t\t\tif (pdev-\u003etsm \u0026\u0026 has_tee(pdev-\u003etsm-\u003edsm_dev))\n-\t\t\t\treturn attr-\u003emode;\n-\t\t}\n-\n \t\tif (attr == \u0026dev_attr_dsm.attr) {\n \t\t\tif (is_pci_tsm_pf0(pdev))\n \t\t\t\treturn attr-\u003emode;\n@@ -604,7 +555,6 @@ DEFINE_SYSFS_GROUP_VISIBLE(pci_tsm);\n static struct attribute *pci_tsm_attrs[] = {\n \t\u0026dev_attr_connect.attr,\n \t\u0026dev_attr_disconnect.attr,\n-\t\u0026dev_attr_bound.attr,\n \t\u0026dev_attr_dsm.attr,\n \tNULL\n };\n@@ -694,22 +644,6 @@ static struct pci_dev *find_dsm_dev(struct pci_dev *pdev)\n \treturn NULL;\n }\n \n-/**\n- * pci_tsm_tdi_constructor() - base 'struct pci_tdi' initialization for link TSMs\n- * @pdev: PCI device function representing the TDI\n- * @tdi: context to initialize\n- * @kvm: Private memory attach context\n- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM\n- */\n-void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi,\n-\t\t\t     struct kvm *kvm, u32 tdi_id)\n-{\n-\ttdi-\u003epdev = pdev;\n-\ttdi-\u003ekvm = kvm;\n-\ttdi-\u003etdi_id = tdi_id;\n-}\n-EXPORT_SYMBOL_GPL(pci_tsm_tdi_constructor);\n-\n /**\n  * pci_tsm_link_constructor() - base 'struct pci_tsm' initialization for link TSMs\n  * @pdev: The PCI device\n@@ -744,6 +678,9 @@ int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm,\n \t\t\t    struct tsm_dev *tsm_dev)\n {\n \tmutex_init(\u0026tsm-\u003elock);\n+\tinit_completion(\u0026tsm-\u003econtexts_drained);\n+\ttsm-\u003econtext_users = 0;\n+\ttsm-\u003eremoving = false;\n \ttsm-\u003edoe_mb = pci_find_doe_mailbox(pdev, PCI_VENDOR_ID_PCI_SIG,\n \t\t\t\t\t   PCI_DOE_FEATURE_CMA);\n \tif (!tsm-\u003edoe_mb) {\n@@ -789,12 +726,6 @@ int pci_tsm_register(struct tsm_dev *tsm_dev)\n \treturn 0;\n }\n \n-static void pci_tsm_fn_exit(struct pci_dev *pdev)\n-{\n-\t__pci_tsm_unbind(pdev, NULL);\n-\ttsm_remove(pdev-\u003etsm);\n-}\n-\n /**\n  * __pci_tsm_destroy() - destroy the TSM context for @pdev\n  * @pdev: device to cleanup\n@@ -828,16 +759,54 @@ static void __pci_tsm_destroy(struct pci_dev *pdev, struct tsm_dev *tsm_dev)\n \telse if (tsm_dev != tsm-\u003etsm_dev)\n \t\treturn;\n \n-\tif (is_link_tsm(tsm_dev) \u0026\u0026 is_pci_tsm_pf0(pdev))\n-\t\tpci_tsm_disconnect(pdev);\n-\telse\n-\t\tpci_tsm_fn_exit(pdev);\n+\tif (is_link_tsm(tsm_dev) \u0026\u0026 is_pci_tsm_pf0(pdev)) {\n+\t\tif (pci_tsm_disconnect(pdev))\n+\t\t\tpci_warn(pdev, \"TSM connection is still in use\\n\");\n+\t} else {\n+\t\ttsm_remove(pdev-\u003etsm);\n+\t}\n }\n \n void pci_tsm_destroy(struct pci_dev *pdev)\n {\n-\tguard(rwsem_write)(\u0026pci_tsm_rwsem);\n+\tstruct pci_tsm_pf0 *pf0 = NULL;\n+\tstruct completion *drained;\n+\tbool interrupted = false;\n+\tlong rc;\n+\n+\tdown_write(\u0026pci_tsm_rwsem);\n+\tif (pdev-\u003etsm \u0026\u0026 is_link_tsm(pdev-\u003etsm-\u003etsm_dev) \u0026\u0026\n+\t    is_pci_tsm_pf0(pdev)) {\n+\t\tpf0 = to_pci_tsm_pf0(pdev-\u003etsm);\n+\t\tdrained = \u0026pf0-\u003econtexts_drained;\n+\t\tmutex_lock(\u0026pf0-\u003elock);\n+\t\tpf0-\u003eremoving = true;\n+\t\tmutex_unlock(\u0026pf0-\u003elock);\n+\n+\t\t/* An unused DSM may never have completed contexts_drained. */\n+\t\trc = pf0-\u003econtext_users ?\n+\t\t\ttry_wait_for_completion(drained) : 1;\n+\t\t/* Context release needs the read side of pci_tsm_rwsem. */\n+\t\tup_write(\u0026pci_tsm_rwsem);\n+\t\twhile (rc \u003c= 0) {\n+\t\t\tif (interrupted) {\n+\t\t\t\trc = wait_for_completion_timeout(drained, HZ * 10);\n+\t\t\t} else {\n+\t\t\t\trc = wait_for_completion_interruptible_timeout(drained,\n+\t\t\t\t\t\t\t\t\t       HZ * 10);\n+\t\t\t\tif (rc \u003c 0) {\n+\t\t\t\t\tinterrupted = true;\n+\t\t\t\t\tpci_warn(pdev, \"Task \\\"%s\\\" (%d) blocked until vdevices are released\\n\",\n+\t\t\t\t\t\t current-\u003ecomm, task_pid_nr(current));\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (!rc)\n+\t\t\t\tpci_warn(pdev, \"TSM connection is in use, waiting for vdevices\\n\");\n+\t\t}\n+\t\tdown_write(\u0026pci_tsm_rwsem);\n+\t}\n \t__pci_tsm_destroy(pdev, NULL);\n+\tup_write(\u0026pci_tsm_rwsem);\n }\n \n void pci_tsm_init(struct pci_dev *pdev)\n@@ -864,6 +833,9 @@ void pci_tsm_init(struct pci_dev *pdev)\n \t\t */\n \t\tif (!dsm-\u003etsm)\n \t\t\treturn;\n+\t\tif (is_link_tsm(dsm-\u003etsm-\u003etsm_dev) \u0026\u0026\n+\t\t    to_pci_tsm_pf0(dsm-\u003etsm)-\u003eremoving)\n+\t\t\treturn;\n \n \t\tprobe_fn(pdev, dsm);\n \t}\ndiff --git a/drivers/s390/crypto/vfio_ap_ops.c b/drivers/s390/crypto/vfio_ap_ops.c\nindex 4db878c18f41c..373ce574c4319 100644\n--- a/drivers/s390/crypto/vfio_ap_ops.c\n+++ b/drivers/s390/crypto/vfio_ap_ops.c\n@@ -1822,17 +1822,27 @@ static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {\n \n /**\n  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed\n- * to manage AP resources for the guest whose state is represented by @kvm\n+ * to manage AP resources for the guest whose state is represented by\n+ * @kvm_file\n  *\n  * @matrix_mdev: a mediated matrix device\n- * @kvm: reference to KVM instance\n+ * @kvm_file: the KVM VM file this vfio device is associated with\n  *\n- * Return: 0 if no other mediated matrix device has a reference to @kvm;\n+ * Return: 0 if no other mediated matrix device has a reference to the VM;\n  * otherwise, returns an -EPERM.\n  */\n static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,\n-\t\t\t\tstruct kvm *kvm)\n+\t\t\t\tstruct file *kvm_file)\n {\n+\tstruct kvm *kvm;\n+\n+\tif (!kvm_file)\n+\t\treturn -ENOENT;\n+\n+\tkvm = file_to_kvm_s390(kvm_file);\n+\tif (!kvm)\n+\t\treturn -ENOENT;\n+\n \tif (kvm-\u003earch.crypto.crycbd) {\n \t\tget_update_locks_for_kvm(kvm);\n \t\tif (kvm-\u003earch.crypto.pqap_hook) {\n@@ -1841,7 +1851,6 @@ static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,\n \t\t}\n \t\tkvm-\u003earch.crypto.pqap_hook = \u0026matrix_mdev-\u003epqap_hook;\n \n-\t\tkvm_get_kvm(kvm);\n \t\tmatrix_mdev-\u003ekvm = kvm;\n \t\tvfio_ap_mdev_update_guest_apcb(matrix_mdev);\n \t\trelease_update_locks_for_kvm(kvm);\n@@ -1894,7 +1903,6 @@ static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)\n \t\tmatrix_mdev-\u003ekvm = NULL;\n \n \t\trelease_update_locks_for_kvm(kvm);\n-\t\tkvm_put_kvm(kvm);\n \t}\n }\n \ndiff --git a/drivers/vfio/group.c b/drivers/vfio/group.c\nindex b2299e5bc6df3..5bf8cbdff377c 100644\n--- a/drivers/vfio/group.c\n+++ b/drivers/vfio/group.c\n@@ -860,11 +860,20 @@ bool vfio_group_enforced_coherent(struct vfio_group *group)\n \treturn ret;\n }\n \n-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)\n+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)\n {\n+\tstruct file *old;\n+\n+\tif (kvm)\n+\t\tget_file(kvm);\n+\n \tspin_lock(\u0026group-\u003ekvm_ref_lock);\n+\told = group-\u003ekvm;\n \tgroup-\u003ekvm = kvm;\n \tspin_unlock(\u0026group-\u003ekvm_ref_lock);\n+\n+\tif (old)\n+\t\tfput(old);\n }\n \n /**\ndiff --git a/drivers/vfio/iommufd.c b/drivers/vfio/iommufd.c\nindex e9893d34d07be..3beb1b1bae368 100644\n--- a/drivers/vfio/iommufd.c\n+++ b/drivers/vfio/iommufd.c\n@@ -123,7 +123,8 @@ int vfio_iommufd_physical_bind(struct vfio_device *vdev,\n {\n \tstruct iommufd_device *idev;\n \n-\tidev = iommufd_device_bind(ictx, vdev-\u003edev, out_device_id);\n+\tidev = iommufd_device_bind(ictx, vdev-\u003edev, vdev-\u003ekvm,\n+\t\t\t\t   out_device_id);\n \tif (IS_ERR(idev))\n \t\treturn PTR_ERR(idev);\n \tvdev-\u003eiommufd_device = idev;\ndiff --git a/drivers/vfio/vfio.h b/drivers/vfio/vfio.h\nindex 7728bc99b63d1..9b619951a5d0c 100644\n--- a/drivers/vfio/vfio.h\n+++ b/drivers/vfio/vfio.h\n@@ -23,7 +23,7 @@ struct vfio_device_file {\n \tu8 access_granted;\n \tu32 devid; /* only valid when iommufd is valid */\n \tspinlock_t kvm_ref_lock; /* protect kvm field */\n-\tstruct kvm *kvm;\n+\tstruct file *kvm;\n \tstruct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */\n };\n \n@@ -88,7 +88,7 @@ struct vfio_group {\n #endif\n \tenum vfio_group_type\t\ttype;\n \tstruct mutex\t\t\tgroup_lock;\n-\tstruct kvm\t\t\t*kvm;\n+\tstruct file\t\t\t*kvm;\n \tstruct file\t\t\t*opened_file;\n \tstruct iommufd_ctx\t\t*iommufd;\n \tspinlock_t\t\t\tkvm_ref_lock;\n@@ -107,7 +107,7 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device);\n void vfio_df_group_close(struct vfio_device_file *df);\n struct vfio_group *vfio_group_from_file(struct file *file);\n bool vfio_group_enforced_coherent(struct vfio_group *group);\n-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm);\n+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm);\n bool vfio_device_has_container(struct vfio_device *device);\n int __init vfio_group_init(void);\n void vfio_group_cleanup(void);\n@@ -165,7 +165,7 @@ static inline bool vfio_group_enforced_coherent(struct vfio_group *group)\n \treturn true;\n }\n \n-static inline void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)\n+static inline void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)\n {\n }\n \n@@ -429,11 +429,11 @@ static inline void vfio_virqfd_exit(void)\n #endif\n \n #if IS_ENABLED(CONFIG_KVM)\n-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm);\n+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm);\n void vfio_device_put_kvm(struct vfio_device *device);\n #else\n static inline void vfio_device_get_kvm_safe(struct vfio_device *device,\n-\t\t\t\t\t    struct kvm *kvm)\n+\t\t\t\t\t    struct file *kvm)\n {\n }\n \ndiff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c\nindex 423ead48aafe3..ed96acfa86358 100644\n--- a/drivers/vfio/vfio_main.c\n+++ b/drivers/vfio/vfio_main.c\n@@ -472,36 +472,14 @@ void vfio_unregister_group_dev(struct vfio_device *device)\n EXPORT_SYMBOL_GPL(vfio_unregister_group_dev);\n \n #if IS_ENABLED(CONFIG_KVM)\n-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm)\n+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm)\n {\n-\tvoid (*pfn)(struct kvm *kvm);\n-\tbool (*fn)(struct kvm *kvm);\n-\tbool ret;\n-\n \tlockdep_assert_held(\u0026device-\u003edev_set-\u003elock);\n \n \tif (!kvm)\n \t\treturn;\n \n-\tpfn = symbol_get(kvm_put_kvm);\n-\tif (WARN_ON(!pfn))\n-\t\treturn;\n-\n-\tfn = symbol_get(kvm_get_kvm_safe);\n-\tif (WARN_ON(!fn)) {\n-\t\tsymbol_put(kvm_put_kvm);\n-\t\treturn;\n-\t}\n-\n-\tret = fn(kvm);\n-\tsymbol_put(kvm_get_kvm_safe);\n-\tif (!ret) {\n-\t\tsymbol_put(kvm_put_kvm);\n-\t\treturn;\n-\t}\n-\n-\tdevice-\u003eput_kvm = pfn;\n-\tdevice-\u003ekvm = kvm;\n+\tdevice-\u003ekvm = get_file(kvm);\n }\n \n void vfio_device_put_kvm(struct vfio_device *device)\n@@ -511,14 +489,7 @@ void vfio_device_put_kvm(struct vfio_device *device)\n \tif (!device-\u003ekvm)\n \t\treturn;\n \n-\tif (WARN_ON(!device-\u003eput_kvm))\n-\t\tgoto clear;\n-\n-\tdevice-\u003eput_kvm(device-\u003ekvm);\n-\tdevice-\u003eput_kvm = NULL;\n-\tsymbol_put(kvm_put_kvm);\n-\n-clear:\n+\tfput(device-\u003ekvm);\n \tdevice-\u003ekvm = NULL;\n }\n #endif\n@@ -1544,9 +1515,13 @@ bool vfio_file_enforced_coherent(struct file *file)\n }\n EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);\n \n-static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)\n+static void vfio_device_file_set_kvm(struct file *file, struct file *kvm)\n {\n \tstruct vfio_device_file *df = file-\u003eprivate_data;\n+\tstruct file *old;\n+\n+\tif (kvm)\n+\t\tget_file(kvm);\n \n \t/*\n \t * The kvm is first recorded in the vfio_device_file, and will\n@@ -1554,28 +1529,32 @@ static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)\n \t * iommufd successfully in the vfio device cdev path.\n \t */\n \tspin_lock(\u0026df-\u003ekvm_ref_lock);\n+\told = df-\u003ekvm;\n \tdf-\u003ekvm = kvm;\n \tspin_unlock(\u0026df-\u003ekvm_ref_lock);\n+\n+\tif (old)\n+\t\tfput(old);\n }\n \n /**\n  * vfio_file_set_kvm - Link a kvm with VFIO drivers\n- * @file: VFIO group file or VFIO device file\n- * @kvm: KVM to link\n+ * @vfio_file: VFIO group file or VFIO device file\n+ * @kvm: KVM file to link\n  *\n  * When a VFIO device is first opened the KVM will be available in\n  * device-\u003ekvm if one was associated with the file.\n  */\n-void vfio_file_set_kvm(struct file *file, struct kvm *kvm)\n+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)\n {\n \tstruct vfio_group *group;\n \n-\tgroup = vfio_group_from_file(file);\n+\tgroup = vfio_group_from_file(vfio_file);\n \tif (group)\n \t\tvfio_group_set_kvm(group, kvm);\n \n-\tif (vfio_device_from_file(file))\n-\t\tvfio_device_file_set_kvm(file, kvm);\n+\tif (vfio_device_from_file(vfio_file))\n+\t\tvfio_device_file_set_kvm(vfio_file, kvm);\n }\n EXPORT_SYMBOL_GPL(vfio_file_set_kvm);\n \ndiff --git a/drivers/virt/coco/tsm-core.c b/drivers/virt/coco/tsm-core.c\nindex e784993353d8f..2fce341ff9231 100644\n--- a/drivers/virt/coco/tsm-core.c\n+++ b/drivers/virt/coco/tsm-core.c\n@@ -9,6 +9,16 @@\n #include \u003clinux/cleanup.h\u003e\n #include \u003clinux/pci-tsm.h\u003e\n \n+/* The caller must hold a tsm_get_device() reference for the entire use. */\n+const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,\n+\t\tstruct device *dev, enum iommu_viommu_type type)\n+{\n+\tif (!tsm_dev-\u003epci_ops-\u003eviommu_get_ops)\n+\t\treturn NULL;\n+\treturn tsm_dev-\u003epci_ops-\u003eviommu_get_ops(dev, type);\n+}\n+EXPORT_SYMBOL_GPL(tsm_viommu_get_ops);\n+\n static void tsm_release(struct device *);\n static const struct class tsm_class = {\n \t.name\t\t= \"tsm\",\n@@ -16,6 +26,29 @@ static const struct class tsm_class = {\n };\n static DEFINE_IDA(tsm_ida);\n \n+/**\n+ * tsm_get_device() - Pin the TSM attached to a device\n+ * @dev: device whose TSM is to be pinned\n+ *\n+ * A successful lookup pins the backend module. Backends providing vIOMMU\n+ * operations must not unregister their TSM independently of module unload.\n+ * Return: NULL if no vIOMMU-capable TSM is attached, an error if the module\n+ * cannot be pinned, or the TSM device associated with the pinned backend.\n+ */\n+struct tsm_dev *tsm_get_device(struct device *dev)\n+{\n+\tif (!dev_is_pci(dev))\n+\t\treturn NULL;\n+\treturn pci_tsm_get_device(to_pci_dev(dev));\n+}\n+EXPORT_SYMBOL_GPL(tsm_get_device);\n+\n+void tsm_put_device(struct tsm_dev *tsm_dev)\n+{\n+\tmodule_put(tsm_dev-\u003epci_ops-\u003eowner);\n+}\n+EXPORT_SYMBOL_GPL(tsm_put_device);\n+\n static int match_id(struct device *dev, const void *data)\n {\n \tstruct tsm_dev *tsm_dev = container_of(dev, struct tsm_dev, dev);\n@@ -56,26 +89,25 @@ static struct tsm_dev *alloc_tsm_dev(struct device *parent)\n \treturn no_free_ptr(tsm_dev);\n }\n \n-static struct tsm_dev *tsm_register_pci_or_reset(struct tsm_dev *tsm_dev,\n-\t\t\t\t\t\t struct pci_tsm_ops *pci_ops)\n+static int tsm_register_pci(struct tsm_dev *tsm_dev, struct pci_tsm_ops *pci_ops)\n {\n \tint rc;\n \n \tif (!pci_ops)\n-\t\treturn tsm_dev;\n+\t\treturn 0;\n \n \ttsm_dev-\u003epci_ops = pci_ops;\n \trc = pci_tsm_register(tsm_dev);\n \tif (rc) {\n+\t\ttsm_dev-\u003epci_ops = NULL;\n \t\tdev_err(tsm_dev-\u003edev.parent,\n \t\t\t\"PCI/TSM registration failure: %d\\n\", rc);\n-\t\tdevice_unregister(\u0026tsm_dev-\u003edev);\n-\t\treturn ERR_PTR(rc);\n+\t\treturn rc;\n \t}\n \n \t/* Notify TSM userspace that PCI/TSM operations are now possible */\n \tkobject_uevent(\u0026tsm_dev-\u003edev.kobj, KOBJ_CHANGE);\n-\treturn tsm_dev;\n+\treturn 0;\n }\n \n struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *pci_ops)\n@@ -96,15 +128,22 @@ struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *pci_ops)\n \tif (rc)\n \t\treturn ERR_PTR(rc);\n \n-\treturn tsm_register_pci_or_reset(no_free_ptr(tsm_dev), pci_ops);\n+\trc = tsm_register_pci(tsm_dev, pci_ops);\n+\tif (rc) {\n+\t\tdevice_del(dev);\n+\t\treturn ERR_PTR(rc);\n+\t}\n+\treturn no_free_ptr(tsm_dev);\n }\n EXPORT_SYMBOL_GPL(tsm_register);\n \n void tsm_unregister(struct tsm_dev *tsm_dev)\n {\n+\t/* Remove the class lookup first. */\n+\tdevice_del(\u0026tsm_dev-\u003edev);\n \tif (tsm_dev-\u003epci_ops)\n \t\tpci_tsm_unregister(tsm_dev);\n-\tdevice_unregister(\u0026tsm_dev-\u003edev);\n+\tput_device(\u0026tsm_dev-\u003edev);\n }\n EXPORT_SYMBOL_GPL(tsm_unregister);\n \ndiff --git a/include/linux/iommu.h b/include/linux/iommu.h\nindex ac43b8b93f14a..9931c96e5dd33 100644\n--- a/include/linux/iommu.h\n+++ b/include/linux/iommu.h\n@@ -46,6 +46,7 @@ struct iommu_dma_msi_cookie;\n struct iommu_fault_param;\n struct iommufd_ctx;\n struct iommufd_viommu;\n+struct iommufd_viommu_ops;\n struct msi_desc;\n struct msi_msg;\n \n@@ -669,16 +670,8 @@ __iommu_copy_struct_to_user(const struct iommu_user_data *dst_data,\n  *\t\t- IOMMU_DOMAIN_DMA: must use a dma domain\n  *\t\t- 0: use the default setting\n  * @default_domain_ops: the default ops for domains\n- * @get_viommu_size: Get the size of a driver-level vIOMMU structure for a given\n- *                   @dev corresponding to @viommu_type. Driver should return 0\n- *                   if vIOMMU isn't supported accordingly. It is required for\n- *                   driver to use the VIOMMU_STRUCT_SIZE macro to sanitize the\n- *                   driver-level vIOMMU structure related to the core one\n- * @viommu_init: Init the driver-level struct of an iommufd_viommu on a physical\n- *               IOMMU instance @viommu-\u003eiommu_dev, as the set of virtualization\n- *               resources shared/passed to user space IOMMU instance. Associate\n- *               it with a nesting @parent_domain. It is required for driver to\n- *               set @viommu-\u003eops pointing to its own viommu_ops\n+ * @get_viommu_ops: Return the vIOMMU operations supported by @dev for a type.\n+ *                  Return NULL if the type is unsupported.\n  * @owner: Driver module providing these ops\n  * @identity_domain: An always available, always attachable identity\n  *                   translation.\n@@ -729,11 +722,8 @@ struct iommu_ops {\n \n \tint (*def_domain_type)(struct device *dev);\n \n-\tsize_t (*get_viommu_size)(struct device *dev,\n-\t\t\t\t  enum iommu_viommu_type viommu_type);\n-\tint (*viommu_init)(struct iommufd_viommu *viommu,\n-\t\t\t   struct iommu_domain *parent_domain,\n-\t\t\t   const struct iommu_user_data *user_data);\n+\tconst struct iommufd_viommu_ops *(*get_viommu_ops)(\n+\t\tstruct device *dev, enum iommu_viommu_type viommu_type);\n \n \tconst struct iommu_domain_ops *default_domain_ops;\n \tstruct module *owner;\ndiff --git a/include/linux/iommufd.h b/include/linux/iommufd.h\nindex 6e7efe83bc5d8..2e67846d6f35a 100644\n--- a/include/linux/iommufd.h\n+++ b/include/linux/iommufd.h\n@@ -6,6 +6,7 @@\n #ifndef __LINUX_IOMMUFD_H\n #define __LINUX_IOMMUFD_H\n \n+#include \u003clinux/bits.h\u003e\n #include \u003clinux/err.h\u003e\n #include \u003clinux/errno.h\u003e\n #include \u003clinux/iommu.h\u003e\n@@ -23,7 +24,9 @@ struct iommufd_access;\n struct iommufd_ctx;\n struct iommufd_device;\n struct iommufd_viommu_ops;\n+struct tsm_dev;\n struct page;\n+struct tsm_guest_req_info;\n \n enum iommufd_object_type {\n \tIOMMUFD_OBJ_NONE,\n@@ -59,7 +62,9 @@ struct iommufd_object {\n };\n \n struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,\n-\t\t\t\t\t   struct device *dev, u32 *id);\n+\t\t\t\t\t   struct device *dev,\n+\t\t\t\t\t   struct file *kvm_file,\n+\t\t\t\t\t   u32 *id);\n void iommufd_device_unbind(struct iommufd_device *idev);\n \n int iommufd_device_attach(struct iommufd_device *idev, ioasid_t pasid,\n@@ -99,8 +104,11 @@ void iommufd_ctx_get(struct iommufd_ctx *ictx);\n struct iommufd_viommu {\n \tstruct iommufd_object obj;\n \tstruct iommufd_ctx *ictx;\n+\t/* Physical IOMMU backing, or NULL. */\n \tstruct iommu_device *iommu_dev;\n \tstruct iommufd_hwpt_paging *hwpt;\n+\tstruct file *kvm_file;\n+\tstruct tsm_dev *tsm_dev;\n \n \tconst struct iommufd_viommu_ops *ops;\n \n@@ -122,6 +130,10 @@ struct iommufd_vdevice {\n \t */\n \tu64 virt_id;\n \n+\t/* Guest TSM requests accepted by this vdevice; set by vdevice_init(). */\n+\tu64 tsm_req_op_mask;\n+\tu32 tsm_tvm_arch;\n+\n \t/* Clean up all driver-specific parts of an iommufd_vdevice */\n \tvoid (*destroy)(struct iommufd_vdevice *vdev);\n };\n@@ -140,8 +152,19 @@ struct iommufd_hw_queue {\n \tvoid (*destroy)(struct iommufd_hw_queue *hw_queue);\n };\n \n+#define IOMMUFD_VIOMMU_NO_HWPT\tBIT(0)\n+\n /**\n  * struct iommufd_viommu_ops - vIOMMU specific operations\n+ * @flags: Properties needed by the core before vIOMMU initialization\n+ * @get_viommu_size: Get the size of a driver-level vIOMMU structure for a given\n+ *                   @dev corresponding to @viommu_type. Driver should return 0\n+ *                   if vIOMMU isn't supported accordingly. It is required for\n+ *                   driver to use the VIOMMU_STRUCT_SIZE macro to sanitize the\n+ *                   driver-level vIOMMU structure related to the core one\n+ * @viommu_init: Initialize the selected driver-level iommufd_viommu for @dev.\n+ *               @parent_domain is the nesting parent, or NULL for an\n+ *               implementation that does not use a parent HWPT.\n  * @destroy: Clean up all driver-specific parts of an iommufd_viommu. The memory\n  *           of the vIOMMU will be free-ed by iommufd core after calling this op\n  * @alloc_domain_nested: Allocate a IOMMU_DOMAIN_NESTED on a vIOMMU that holds a\n@@ -164,6 +187,7 @@ struct iommufd_hw_queue {\n  *                include/uapi/linux/iommufd.h)\n  *                If driver has a deinit function to revert what vdevice_init op\n  *                does, it should set it to the @vdev-\u003edestroy function pointer\n+ * @vdevice_tsm_req: Forward a guest TSM request to a driver-owned vDEVICE\n  * @get_hw_queue_size: Get the size of a driver-defined HW queue structure for a\n  *                     given @viommu corresponding to @queue_type. Driver should\n  *                     return 0 if HW queue aren't supported accordingly. It is\n@@ -182,6 +206,12 @@ struct iommufd_hw_queue {\n  *                      does, it should set it to the @hw_queue-\u003edestroy pointer\n  */\n struct iommufd_viommu_ops {\n+\tunsigned long flags;\n+\tsize_t (*get_viommu_size)(struct device *dev,\n+\t\tenum iommu_viommu_type type);\n+\tint (*viommu_init)(struct iommufd_viommu *viommu, struct device *dev,\n+\t\tstruct iommu_domain *parent_domain,\n+\t\tconst struct iommu_user_data *user_data);\n \tvoid (*destroy)(struct iommufd_viommu *viommu);\n \tstruct iommu_domain *(*alloc_domain_nested)(\n \t\tstruct iommufd_viommu *viommu, u32 flags,\n@@ -190,6 +220,9 @@ struct iommufd_viommu_ops {\n \t\t\t\tstruct iommu_user_data_array *array);\n \tconst size_t vdevice_size;\n \tint (*vdevice_init)(struct iommufd_vdevice *vdev);\n+\tssize_t (*vdevice_tsm_req)(struct iommufd_vdevice *vdev,\n+\t\t\t\t   struct tsm_guest_req_info *info,\n+\t\t\t\t   u64 *tsm_code);\n \tsize_t (*get_hw_queue_size)(struct iommufd_viommu *viommu,\n \t\t\t\t    enum iommu_hw_queue_type queue_type);\n \t/* AMD's HW will add hw_queue_init simply using @hw_queue-\u003ebase_addr */\ndiff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h\nindex cf7fe835c4ad2..586f6e8bb81b3 100644\n--- a/include/linux/kvm_host.h\n+++ b/include/linux/kvm_host.h\n@@ -784,6 +784,12 @@ struct kvm {\n \t * kvm_swap_active_memslots().\n \t */\n \tstruct mutex slots_arch_lock;\n+\t/*\n+\t * Back-reference to the VM file for subsystems (e.g., VFIO). Holds no\n+\t * reference to avoid pinning the VM. Callers storing the file must\n+\t * take their own reference.\n+\t */\n+\tstruct file *file;\n \tstruct mm_struct *mm; /* userspace tied to this vm */\n \tunsigned long nr_memslot_pages;\n \t/* The two memslot sets - active and inactive (per address space) */\n@@ -1081,7 +1087,18 @@ void kvm_exit(void);\n void kvm_get_kvm(struct kvm *kvm);\n bool kvm_get_kvm_safe(struct kvm *kvm);\n void kvm_put_kvm(struct kvm *kvm);\n-bool file_is_kvm(struct file *file);\n+\n+/*\n+ * Architectures define kvm_file_to_kvm_arch to \u003carch\u003e\n+ * to get a typed, arch-namespaced helper:\n+ *\n+ *   struct kvm *file_to_kvm_\u003carch\u003e(struct file *file)\n+ */\n+#ifdef kvm_file_to_kvm_arch\n+#define kvm_file_to_kvm_fn CONCATENATE(file_to_kvm_, kvm_file_to_kvm_arch)\n+struct kvm *kvm_file_to_kvm_fn(struct file *file);\n+#endif /* kvm_file_to_kvm_arch */\n+\n void kvm_put_kvm_no_destroy(struct kvm *kvm);\n \n static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id)\ndiff --git a/include/linux/pci-tsm.h b/include/linux/pci-tsm.h\nindex a6435aba03f9b..3adc317d0f9bc 100644\n--- a/include/linux/pci-tsm.h\n+++ b/include/linux/pci-tsm.h\n@@ -1,14 +1,15 @@\n /* SPDX-License-Identifier: GPL-2.0 */\n #ifndef __PCI_TSM_H\n #define __PCI_TSM_H\n+#include \u003clinux/completion.h\u003e\n #include \u003clinux/mutex.h\u003e\n #include \u003clinux/pci.h\u003e\n-#include \u003clinux/sockptr.h\u003e\n \n+struct iommufd_viommu_ops;\n+struct module;\n struct pci_tsm;\n+struct pci_tsm_context;\n struct tsm_dev;\n-struct kvm;\n-enum pci_tsm_req_scope;\n \n /*\n  * struct pci_tsm_ops - manage confidential links and security state\n@@ -18,12 +19,26 @@ enum pci_tsm_req_scope;\n  * @devsec_ops: Lock, unlock, and interrogate the security state of the\n  *\t\tfunction via the platform TSM (typically virtual function\n  *\t\toperations).\n+ * @viommu_get_ops: Return operations for a supported TSM-owned vIOMMU type,\n+ *\t\t  or NULL if unsupported\n+ * @owner: Module providing the vIOMMU operations, if built as a module\n+ *\n+ * The vIOMMU owner pins the backend module before querying @viommu_get_ops\n+ * and releases it after vIOMMU destruction. A backend providing this callback\n+ * must not unregister its TSM while the module is pinned.\n  *\n  * This operations are mutually exclusive either a tsm_dev instance\n  * manages physical link properties or it manages function security\n  * states like TDISP lock/unlock.\n+ *\n+ * @viommu_get_ops runs with the backend module pinned. The PCI/TSM\n+ * association is checked during acquisition under pci_tsm_rwsem.\n  */\n struct pci_tsm_ops {\n+\tstruct module *owner;\n+\tconst struct iommufd_viommu_ops *(*viommu_get_ops)(\n+\t\tstruct device *dev, enum iommu_viommu_type type);\n+\n \t/*\n \t * struct pci_tsm_link_ops - Manage physical link and the TSM/DSM session\n \t * @probe: establish context with the TSM (allocate / wrap 'struct\n@@ -32,17 +47,12 @@ struct pci_tsm_ops {\n \t * @connect: establish / validate a secure connection (e.g. IDE)\n \t *\t     with the device\n \t * @disconnect: teardown the secure link\n-\t * @bind: bind a TDI in preparation for it to be accepted by a TVM\n-\t * @unbind: remove a TDI from secure operation with a TVM\n-\t * @guest_req: marshal TVM information and state change requests\n \t *\n \t * Context: @probe, @remove, @connect, and @disconnect run under\n \t * pci_tsm_rwsem held for write to sync with TSM unregistration and\n \t * mutual exclusion of @connect and @disconnect. @connect and\n \t * @disconnect additionally run under the DSM lock (struct\n \t * pci_tsm_pf0::lock) as well as @probe and @remove of the subfunctions.\n-\t * @bind, @unbind, and @guest_req run under pci_tsm_rwsem held for read\n-\t * and the DSM lock.\n \t */\n \tstruct_group_tagged(pci_tsm_link_ops, link_ops,\n \t\tstruct pci_tsm *(*probe)(struct tsm_dev *tsm_dev,\n@@ -50,14 +60,6 @@ struct pci_tsm_ops {\n \t\tvoid (*remove)(struct pci_tsm *tsm);\n \t\tint (*connect)(struct pci_dev *pdev);\n \t\tvoid (*disconnect)(struct pci_dev *pdev);\n-\t\tstruct pci_tdi *(*bind)(struct pci_dev *pdev,\n-\t\t\t\t\tstruct kvm *kvm, u32 tdi_id);\n-\t\tvoid (*unbind)(struct pci_tdi *tdi);\n-\t\tssize_t (*guest_req)(struct pci_tdi *tdi,\n-\t\t\t\t     enum pci_tsm_req_scope scope,\n-\t\t\t\t     sockptr_t req_in, size_t in_len,\n-\t\t\t\t     sockptr_t req_out, size_t out_len,\n-\t\t\t\t     u64 *tsm_code);\n \t);\n \n \t/*\n@@ -77,25 +79,12 @@ struct pci_tsm_ops {\n \t);\n };\n \n-/**\n- * struct pci_tdi - Core TEE I/O Device Interface (TDI) context\n- * @pdev: host side representation of guest-side TDI\n- * @kvm: TEE VM context of bound TDI\n- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM\n- */\n-struct pci_tdi {\n-\tstruct pci_dev *pdev;\n-\tstruct kvm *kvm;\n-\tu32 tdi_id;\n-};\n-\n /**\n  * struct pci_tsm - Core TSM context for a given PCIe endpoint\n  * @pdev: Back ref to device function, distinguishes type of pci_tsm context\n  * @dsm_dev: PCI Device Security Manager for link operations on @pdev\n  * @tsm_dev: PCI TEE Security Manager device for Link Confidentiality or Device\n  *\t     Function Security operations\n- * @tdi: TDI context established by the @bind link operation\n  *\n  * This structure is wrapped by low level TSM driver data and returned by\n  * probe()/lock(), it is freed by the corresponding remove()/unlock().\n@@ -111,18 +100,24 @@ struct pci_tsm {\n \tstruct pci_dev *pdev;\n \tstruct pci_dev *dsm_dev;\n \tstruct tsm_dev *tsm_dev;\n-\tstruct pci_tdi *tdi;\n };\n \n /**\n  * struct pci_tsm_pf0 - Physical Function 0 TDISP link context\n  * @base_tsm: generic core \"tsm\" context\n  * @lock: mutual exclustion for pci_tsm_ops invocation\n+ * @context_users: live per-function contexts on this PF0; a nonzero count\n+ *\tblocks link disconnect\n+ * @contexts_drained: completed when the last context is released\n+ * @removing: reject new contexts while the DSM is being removed\n  * @doe_mb: PCIe Data Object Exchange mailbox\n  */\n struct pci_tsm_pf0 {\n \tstruct pci_tsm base_tsm;\n \tstruct mutex lock;\n+\tunsigned int context_users;\n+\tstruct completion contexts_drained;\n+\tbool removing;\n \tstruct pci_doe_mb *doe_mb;\n };\n \n@@ -159,46 +154,6 @@ static inline bool is_pci_tsm_pf0(struct pci_dev *pdev)\n \treturn PCI_FUNC(pdev-\u003edevfn) == 0;\n }\n \n-/**\n- * enum pci_tsm_req_scope - Scope of guest requests to be validated by TSM\n- *\n- * Guest requests are a transport for a TVM to communicate with a TSM + DSM for\n- * a given TDI. A TSM driver is responsible for maintaining the kernel security\n- * model and limit commands that may affect the host, or are otherwise outside\n- * the typical TDISP operational model.\n- */\n-enum pci_tsm_req_scope {\n-\t/**\n-\t * @PCI_TSM_REQ_INFO: Read-only, without side effects, request for\n-\t * typical TDISP collateral information like Device Interface Reports.\n-\t * No device secrets are permitted, and no device state is changed.\n-\t */\n-\tPCI_TSM_REQ_INFO = 0,\n-\t/**\n-\t * @PCI_TSM_REQ_STATE_CHANGE: Request to change the TDISP state from\n-\t * UNLOCKED-\u003eLOCKED, LOCKED-\u003eRUN, or other architecture specific state\n-\t * changes to support those transitions for a TDI. No other (unrelated\n-\t * to TDISP) device / host state, configuration, or data change is\n-\t * permitted.\n-\t */\n-\tPCI_TSM_REQ_STATE_CHANGE = 1,\n-\t/**\n-\t * @PCI_TSM_REQ_DEBUG_READ: Read-only request for debug information\n-\t *\n-\t * A method to facilitate TVM information retrieval outside of typical\n-\t * TDISP operational requirements. No device secrets are permitted.\n-\t */\n-\tPCI_TSM_REQ_DEBUG_READ = 2,\n-\t/**\n-\t * @PCI_TSM_REQ_DEBUG_WRITE: Device state changes for debug purposes\n-\t *\n-\t * The request may affect the operational state of the device outside of\n-\t * the TDISP operational model. If allowed, requires CAP_SYS_RAW_IO, and\n-\t * will taint the kernel.\n-\t */\n-\tPCI_TSM_REQ_DEBUG_WRITE = 3,\n-};\n-\n #ifdef CONFIG_PCI_TSM\n int pci_tsm_register(struct tsm_dev *tsm_dev);\n void pci_tsm_unregister(struct tsm_dev *tsm_dev);\n@@ -209,13 +164,15 @@ int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm,\n void pci_tsm_pf0_destructor(struct pci_tsm_pf0 *tsm);\n int pci_tsm_doe_transfer(struct pci_dev *pdev, u8 type, const void *req,\n \t\t\t size_t req_sz, void *resp, size_t resp_sz);\n-int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id);\n-void pci_tsm_unbind(struct pci_dev *pdev);\n-void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi,\n-\t\t\t     struct kvm *kvm, u32 tdi_id);\n-ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope,\n-\t\t\t  sockptr_t req_in, size_t in_len, sockptr_t req_out,\n-\t\t\t  size_t out_len, u64 *tsm_code);\n+bool pci_tsm_is_configured(struct pci_dev *pdev);\n+struct pci_tsm_context *pci_tsm_context_get(struct pci_dev *pdev,\n+\t\t\t\t\t    struct tsm_dev *viommu_tsm_dev);\n+void pci_tsm_context_put(struct pci_tsm_context *context);\n+struct pci_tsm_pf0 *pci_tsm_context_pf0(struct pci_tsm_context *context);\n+struct pci_dev *pci_tsm_context_dsm_dev(struct pci_tsm_context *context);\n+bool pci_tsm_context_match_device(struct pci_tsm_context *context,\n+\t\t\t\t  struct pci_dev *pdev);\n+struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev);\n #else\n static inline int pci_tsm_register(struct tsm_dev *tsm_dev)\n {\n@@ -224,20 +181,44 @@ static inline int pci_tsm_register(struct tsm_dev *tsm_dev)\n static inline void pci_tsm_unregister(struct tsm_dev *tsm_dev)\n {\n }\n-static inline int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u64 tdi_id)\n+\n+static inline bool pci_tsm_is_configured(struct pci_dev *pdev)\n {\n-\treturn -ENXIO;\n+\treturn false;\n }\n-static inline void pci_tsm_unbind(struct pci_dev *pdev)\n+\n+static inline struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)\n {\n+\treturn NULL;\n }\n-static inline ssize_t pci_tsm_guest_req(struct pci_dev *pdev,\n-\t\t\t\t\tenum pci_tsm_req_scope scope,\n-\t\t\t\t\tsockptr_t req_in, size_t in_len,\n-\t\t\t\t\tsockptr_t req_out, size_t out_len,\n-\t\t\t\t\tu64 *tsm_code)\n+\n+static inline struct pci_tsm_context *\n+pci_tsm_context_get(struct pci_dev *pdev, struct tsm_dev *viommu_tsm_dev)\n+{\n+\treturn ERR_PTR(-EOPNOTSUPP);\n+}\n+\n+static inline void pci_tsm_context_put(struct pci_tsm_context *context)\n+{\n+}\n+\n+static inline struct pci_tsm_pf0 *\n+pci_tsm_context_pf0(struct pci_tsm_context *context)\n+{\n+\treturn NULL;\n+}\n+\n+static inline struct pci_dev *\n+pci_tsm_context_dsm_dev(struct pci_tsm_context *context)\n+{\n+\treturn NULL;\n+}\n+\n+static inline bool\n+pci_tsm_context_match_device(struct pci_tsm_context *context,\n+\t\t\t     struct pci_dev *pdev)\n {\n-\treturn -ENXIO;\n+\treturn false;\n }\n #endif\n #endif /*__PCI_TSM_H */\ndiff --git a/include/linux/tsm.h b/include/linux/tsm.h\nindex 381c53244c835..e5d14f9a23e9f 100644\n--- a/include/linux/tsm.h\n+++ b/include/linux/tsm.h\n@@ -6,6 +6,7 @@\n #include \u003clinux/types.h\u003e\n #include \u003clinux/uuid.h\u003e\n #include \u003clinux/device.h\u003e\n+#include \u003cuapi/linux/iommufd.h\u003e\n \n #define TSM_REPORT_INBLOB_MAX 64\n #define TSM_REPORT_OUTBLOB_MAX SZ_16M\n@@ -109,6 +110,8 @@ struct tsm_report_ops {\n };\n \n struct pci_tsm_ops;\n+struct iommufd_viommu_ops;\n+\n struct tsm_dev {\n \tstruct device dev;\n \tint id;\n@@ -123,4 +126,47 @@ int tsm_report_unregister(const struct tsm_report_ops *ops);\n struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *ops);\n void tsm_unregister(struct tsm_dev *tsm_dev);\n struct tsm_dev *find_tsm_dev(int id);\n+\n+#ifdef CONFIG_TSM\n+struct tsm_dev *tsm_get_device(struct device *dev);\n+void tsm_put_device(struct tsm_dev *tsm_dev);\n+const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,\n+\t\tstruct device *dev, enum iommu_viommu_type type);\n+\n+/**\n+ * struct tsm_guest_req_info - parameters for a guest-initiated TSM request\n+ * @op: operation for the guest-initiated request\n+ * @tvm_arch: guest TVM architecture\n+ * @req: userspace buffer containing the guest request\n+ * @req_len: request size in bytes, at most INT_MAX\n+ * @resp: userspace buffer for the response\n+ * @resp_len: response buffer capacity in bytes, at most INT_MAX\n+ */\n+struct tsm_guest_req_info {\n+\tenum iommu_vdevice_tsm_guest_req_op op;\n+\tenum iommu_vdevice_tsm_guest_tvm_arch tvm_arch;\n+\tconst void __user *req;\n+\tu32 req_len;\n+\tvoid __user *resp;\n+\tu32 resp_len;\n+};\n+#else\n+static inline struct tsm_dev *tsm_get_device(struct device *dev)\n+{\n+\treturn NULL;\n+}\n+\n+static inline void tsm_put_device(struct tsm_dev *tsm_dev)\n+{\n+}\n+\n+static inline const struct iommufd_viommu_ops *\n+tsm_viommu_get_ops(struct tsm_dev *tsm_dev, struct device *dev,\n+\t\tenum iommu_viommu_type type)\n+{\n+\treturn NULL;\n+}\n+\n+struct tsm_guest_req_info;\n+#endif\n #endif /* __TSM_H */\ndiff --git a/include/linux/vfio.h b/include/linux/vfio.h\nindex 45f08986359e4..0cc91c6f96d2b 100644\n--- a/include/linux/vfio.h\n+++ b/include/linux/vfio.h\n@@ -54,7 +54,7 @@ struct vfio_device {\n \tstruct list_head dev_set_list;\n \tunsigned int migration_flags;\n \tu8 precopy_info_v2;\n-\tstruct kvm *kvm;\n+\tstruct file *kvm;\n \n \t/* Members below here are private, not for driver use */\n \tunsigned int index;\n@@ -66,7 +66,6 @@ struct vfio_device {\n \tunsigned int open_count;\n \tstruct completion comp;\n \tstruct iommufd_access *iommufd_access;\n-\tvoid (*put_kvm)(struct kvm *kvm);\n \tstruct inode *inode;\n #if IS_ENABLED(CONFIG_IOMMUFD)\n \tstruct iommufd_device *iommufd_device;\n@@ -378,7 +377,7 @@ static inline bool vfio_file_has_dev(struct file *file, struct vfio_device *devi\n #endif\n bool vfio_file_is_valid(struct file *file);\n bool vfio_file_enforced_coherent(struct file *file);\n-void vfio_file_set_kvm(struct file *file, struct kvm *kvm);\n+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm);\n \n #define VFIO_PIN_PAGES_MAX_ENTRIES\t(PAGE_SIZE/sizeof(unsigned long))\n \ndiff --git a/include/uapi/linux/iommufd.h b/include/uapi/linux/iommufd.h\nindex 206fa667c7828..3d1ebbdf39488 100644\n--- a/include/uapi/linux/iommufd.h\n+++ b/include/uapi/linux/iommufd.h\n@@ -58,6 +58,7 @@ enum {\n \tIOMMUFD_CMD_VEVENTQ_ALLOC = 0x93,\n \tIOMMUFD_CMD_HW_QUEUE_ALLOC = 0x94,\n \tIOMMUFD_CMD_IOAS_NOIOMMU_GET_PA = 0x95,\n+\tIOMMUFD_CMD_VDEVICE_TSM_REQ = 0x96,\n };\n \n /**\n@@ -1129,7 +1130,8 @@ struct iommu_viommu_tegra241_cmdqv {\n  * @flags: Must be 0\n  * @type: Type of the virtual IOMMU. Must be defined in enum iommu_viommu_type\n  * @dev_id: The device's physical IOMMU will be used to back the virtual IOMMU\n- * @hwpt_id: ID of a nesting parent HWPT to associate to\n+ * @hwpt_id: ID of a nesting parent HWPT to associate to. Must be zero when the\n+ *           selected vIOMMU implementation does not use a parent HWPT\n  * @out_viommu_id: Output virtual IOMMU ID for the allocated object\n  * @data_len: Length of the type specific data\n  * @__reserved: Must be 0\n@@ -1390,4 +1392,85 @@ struct iommu_hw_queue_alloc {\n \t__aligned_u64 length;\n };\n #define IOMMU_HW_QUEUE_ALLOC _IO(IOMMUFD_TYPE, IOMMUFD_CMD_HW_QUEUE_ALLOC)\n+\n+/**\n+ * enum iommu_vdevice_tsm_guest_tvm_arch - guest TVM architecture\n+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_CCA: Arm CCA TVM\n+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_SEV: AMD SEV TVM\n+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_TDX: Intel TDX TVM\n+ */\n+enum iommu_vdevice_tsm_guest_tvm_arch {\n+\tIOMMU_VDEVICE_TSM_TVM_ARCH_CCA = 1,\n+\tIOMMU_VDEVICE_TSM_TVM_ARCH_SEV,\n+\tIOMMU_VDEVICE_TSM_TVM_ARCH_TDX,\n+};\n+\n+/**\n+ * enum iommu_vdevice_tsm_guest_req_op - Guest TSM request operations\n+ * @TSM_REQ_VALIDATE_MMIO: Validate and map a guest MMIO range for the trusted\n+ *                         device.\n+ * @TSM_REQ_SET_TDI_STATE: Transition the trusted device to the unlocked,\n+ *                         locked, or running state.\n+ * @TSM_REQ_SEV_ENABLE_DMA: Enable DMA for an SEV device.\n+ * @TSM_REQ_SEV_DISABLE_DMA: Disable DMA for an SEV device.\n+ * @TSM_REQ_READ_OBJECT: Read bytes from a device object, such as a certificate,\n+ *                       measurement, or interface report.\n+ * @TSM_REQ_REGEN_OBJECT: Regenerate a device object, such as a measurement or\n+ *                        interface report.\n+ * @TSM_REQ_OBJECT_INFO: Query the size of a device object.\n+ * @TSM_REQ_MAX: One past the last request operation; not a command.\n+ *\n+ * The request payload and response format depend on the TVM architecture.\n+ */\n+enum iommu_vdevice_tsm_guest_req_op {\n+\tTSM_REQ_VALIDATE_MMIO = 1,\n+\tTSM_REQ_SET_TDI_STATE,\n+\tTSM_REQ_SEV_ENABLE_DMA,\n+\tTSM_REQ_SEV_DISABLE_DMA,\n+\tTSM_REQ_READ_OBJECT,\n+\tTSM_REQ_REGEN_OBJECT,\n+\tTSM_REQ_OBJECT_INFO,\n+\tTSM_REQ_MAX,\n+};\n+\n+/**\n+ * struct iommu_vdevice_tsm_req - ioctl(IOMMU_VDEVICE_TSM_REQ)\n+ * @size: sizeof(struct iommu_vdevice_tsm_req)\n+ * @vdevice_id: vDevice ID the guest request is for\n+ * @op: One of enum iommu_vdevice_tsm_guest_req_op, excluding TSM_REQ_MAX\n+ * @tvm_arch: One of enum iommu_vdevice_tsm_guest_tvm_arch\n+ * @req_len: Size in bytes of the input payload at @req_uptr, at most INT_MAX\n+ * @resp_len: Size in bytes of the output buffer at @resp_uptr, at most INT_MAX\n+ * @req_uptr: Userspace pointer to the guest-provided request payload\n+ * @resp_uptr: Userspace pointer to the guest response buffer\n+ * @out_tsm_code: TSM-specific result code returned by the TSM implementation\n+ *\n+ * Forward a TSM request to the TSM bound vDevice. This is intended for\n+ * guest TSM/TDISP message transport where the host kernel only marshals\n+ * bytes between userspace and the TSM implementation.\n+ *\n+ * The request operation is guest initiated. The vDEVICE implementation\n+ * declares the TVM architecture and operations it accepts; iommufd checks\n+ * both before forwarding the request.\n+ *\n+ * The request payload is read from @req_uptr/@req_len. If a response is\n+ * expected, userspace provides @resp_uptr/@resp_len as writable storage for\n+ * response bytes returned by the TSM path.\n+ *\n+ * The ioctl is only suitable for commands and results that the host kernel\n+ * has no use, the host is only facilitating guest to TSM communication.\n+ */\n+struct iommu_vdevice_tsm_req {\n+\t__u32 size;\n+\t__u32 vdevice_id;\n+\t__u32 op;\n+\t__u32 tvm_arch;\n+\t__u32 req_len;\n+\t__u32 resp_len;\n+\t__aligned_u64 req_uptr;\n+\t__aligned_u64 resp_uptr;\n+\t__aligned_u64 out_tsm_code;\n+};\n+\n+#define IOMMU_VDEVICE_TSM_REQ _IO(IOMMUFD_TYPE, IOMMUFD_CMD_VDEVICE_TSM_REQ)\n #endif\ndiff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c\nindex 85f42289748dc..60e614795a36c 100644\n--- a/virt/kvm/kvm_main.c\n+++ b/virt/kvm/kvm_main.c\n@@ -1314,7 +1314,7 @@ void kvm_get_kvm(struct kvm *kvm)\n {\n \trefcount_inc(\u0026kvm-\u003eusers_count);\n }\n-EXPORT_SYMBOL_GPL(kvm_get_kvm);\n+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm);\n \n /*\n  * Make sure the vm is not during destruction, which is a safe version of\n@@ -1324,14 +1324,14 @@ bool kvm_get_kvm_safe(struct kvm *kvm)\n {\n \treturn refcount_inc_not_zero(\u0026kvm-\u003eusers_count);\n }\n-EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);\n+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm_safe);\n \n void kvm_put_kvm(struct kvm *kvm)\n {\n \tif (refcount_dec_and_test(\u0026kvm-\u003eusers_count))\n \t\tkvm_destroy_vm(kvm);\n }\n-EXPORT_SYMBOL_GPL(kvm_put_kvm);\n+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_put_kvm);\n \n /*\n  * Used to put a reference that was taken on behalf of an object associated\n@@ -1352,6 +1352,8 @@ static int kvm_vm_release(struct inode *inode, struct file *filp)\n \n \tkvm_irqfd_release(kvm);\n \n+\tWRITE_ONCE(kvm-\u003efile, NULL);\n+\n \tkvm_put_kvm(kvm);\n \treturn 0;\n }\n@@ -5513,11 +5515,16 @@ static struct file_operations kvm_vm_fops = {\n \tKVM_COMPAT(kvm_vm_compat_ioctl),\n };\n \n-bool file_is_kvm(struct file *file)\n+#ifdef kvm_file_to_kvm_arch\n+struct kvm *kvm_file_to_kvm_fn(struct file *file)\n {\n-\treturn file \u0026\u0026 file-\u003ef_op == \u0026kvm_vm_fops;\n+\tif (!file || file-\u003ef_op != \u0026kvm_vm_fops)\n+\t\treturn NULL;\n+\n+\treturn file-\u003eprivate_data;\n }\n-EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_is_kvm);\n+EXPORT_SYMBOL_GPL(kvm_file_to_kvm_fn);\n+#endif\n \n static int kvm_dev_ioctl_create_vm(unsigned long type)\n {\n@@ -5544,6 +5551,8 @@ static int kvm_dev_ioctl_create_vm(unsigned long type)\n \t\tgoto put_kvm;\n \t}\n \n+\tkvm-\u003efile = file;\n+\n \t/*\n \t * Don't call kvm_put_kvm anymore at this point; file-\u003ef_op is\n \t * already set, with -\u003erelease() being kvm_vm_release().  In error\ndiff --git a/virt/kvm/vfio.c b/virt/kvm/vfio.c\nindex 6cdc4e9a333a3..19548a4309426 100644\n--- a/virt/kvm/vfio.c\n+++ b/virt/kvm/vfio.c\n@@ -35,15 +35,15 @@ struct kvm_vfio {\n \tbool noncoherent;\n };\n \n-static void kvm_vfio_file_set_kvm(struct file *file, struct kvm *kvm)\n+static void kvm_vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)\n {\n-\tvoid (*fn)(struct file *file, struct kvm *kvm);\n+\tvoid (*fn)(struct file *vfio_file, struct file *kvm);\n \n \tfn = symbol_get(vfio_file_set_kvm);\n \tif (!fn)\n \t\treturn;\n \n-\tfn(file, kvm);\n+\tfn(vfio_file, kvm);\n \n \tsymbol_put(vfio_file_set_kvm);\n }\n@@ -144,6 +144,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)\n {\n \tstruct kvm_vfio *kv = dev-\u003eprivate;\n \tstruct kvm_vfio_file *kvf;\n+\tstruct file *kvm_file __free(fput) = NULL;\n \tstruct file *filp __free(fput) = NULL;\n \n \tfilp = fget(fd);\n@@ -154,6 +155,10 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)\n \tif (!kvm_vfio_file_is_valid(filp))\n \t\treturn -EINVAL;\n \n+\tkvm_file = get_file_active(\u0026dev-\u003ekvm-\u003efile);\n+\tif (!kvm_file)\n+\t\treturn -ENOENT;\n+\n \tguard(mutex)(\u0026kv-\u003elock);\n \n \tlist_for_each_entry(kvf, \u0026kv-\u003efile_list, node) {\n@@ -168,7 +173,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)\n \tkvf-\u003efile = get_file(filp);\n \tlist_add_tail(\u0026kvf-\u003enode, \u0026kv-\u003efile_list);\n \n-\tkvm_vfio_file_set_kvm(kvf-\u003efile, dev-\u003ekvm);\n+\tkvm_vfio_file_set_kvm(kvf-\u003efile, kvm_file);\n \tkvm_vfio_update_coherency(dev);\n \n \treturn 0;\n"
}

2/1 2026/10/08 06:59 agent patch-evaluator
4m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "VFIO",
    "VFIO_GROUP",
    "VFIO_DEVICE_CDEV",
    "IOMMUFD",
    "IOMMUFD_TEST",
    "PCI_TSM",
    "AMD_IOMMU_IOMMUFD"
  ],
  "FocusSymbols": [
    "iommufd_vdevice_tsm_req_ioctl",
    "iommufd_viommu_alloc_ioctl",
    "iommufd_vdevice_alloc_ioctl",
    "iommufd_viommu_alloc_hwpt_nested",
    "kvm_vfio_file_add",
    "vfio_file_set_kvm",
    "file_to_kvm_x86",
    "pci_tsm_context_get",
    "pci_tsm_context_put",
    "disconnect_store",
    "sev_vm_move_enc_context_from",
    "kvm_page_track_register_notifier"
  ],
  "Reasoning": "This patch series refactors reference counting and lifecycle management between KVM, VFIO, and IOMMUFD by replacing raw 'struct kvm *' pointers with 'struct file *' references. It introduces a new userspace ioctl (IOMMU_VDEVICE_TSM_REQ) handled by iommufd_vdevice_tsm_req_ioctl(), refactors virtual IOMMU (viommu) allocation and vDevice handling in IOMMUFD, refactors PCI TSM context lifecycle and sysfs disconnection handling, and updates KVM SEV context migration. These code paths are directly reachable and exercisable from userspace via /dev/kvm, /dev/iommu, VFIO file descriptors, and sysfs.",
  "WorthFuzzing": true
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit bf97d08b5c6e71cd454dbf6a948982dac7a9d1d3
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 8 06:59:51 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/ABI/testing/sysfs-bus-pci b/Documentation/ABI/testing/sysfs-bus-pci
index 55ea1db749a18..4c64b30544cdc 100644
--- a/Documentation/ABI/testing/sysfs-bus-pci
+++ b/Documentation/ABI/testing/sysfs-bus-pci
@@ -654,6 +654,9 @@ Contact:	linux-coco@lists.linux.dev
 Description:
 		(WO) Write the name of the TSM device that was specified
 		to 'connect' to teardown the connection.
+		The write fails with EBUSY while any vdevice depends on the
+		connection. Userspace must destroy those vdevices before
+		disconnecting the link.
 
 What:		/sys/bus/pci/devices/.../tsm/dsm
 Contact:	linux-coco@lists.linux.dev
@@ -671,20 +674,6 @@ Description:	(RO) Return PCI device name of this device's DSM (Device
 		PCIe switch port. This is a "link" TSM attribute, see
 		Documentation/ABI/testing/sysfs-class-tsm.
 
-What:		/sys/bus/pci/devices/.../tsm/bound
-Contact:	linux-coco@lists.linux.dev
-Description:	(RO) Return the device name of the TSM when the device is in a
-		TDISP (TEE Device Interface Security Protocol) operational state
-		(LOCKED, RUN, or ERROR, not UNLOCKED). Bound devices consume
-		platform TSM resources and depend on the device's configuration
-		(e.g. BME (Bus Master Enable) and MSE (Memory Space Enable)
-		among other settings) to remain stable for the duration of the
-		bound state. This attribute is only visible for devices that
-		support TDISP operation, and it is only populated after
-		successful connect and TSM bind. The TSM bind operation is
-		initiated by VFIO/IOMMUFD. This is a "link" TSM attribute, see
-		Documentation/ABI/testing/sysfs-class-tsm.
-
 What:		/sys/bus/pci/devices/.../authenticated
 Contact:	linux-pci@vger.kernel.org
 Description:
diff --git a/Documentation/userspace-api/iommufd.rst b/Documentation/userspace-api/iommufd.rst
index f1c4d21e5c5ee..8e2fa3a524f0c 100644
--- a/Documentation/userspace-api/iommufd.rst
+++ b/Documentation/userspace-api/iommufd.rst
@@ -82,11 +82,10 @@ Following IOMMUFD objects are exposed to userspace:
   * Direct assigned invalidation queues
   * Direct assigned interrupts
 
-  Such a vIOMMU object generally has the access to a nesting parent pagetable
-  to support some HW-accelerated virtualization features. So, a vIOMMU object
-  must be created given a nesting parent HWPT_PAGING object, and then it would
-  encapsulate that HWPT_PAGING object. Therefore, a vIOMMU object can be used
-  to allocate an HWPT_NESTED object in place of the encapsulated HWPT_PAGING.
+  A vIOMMU object may encapsulate a nesting parent HWPT_PAGING object to
+  support HW-accelerated virtualization features. Whether a parent is required
+  is determined by the selected vIOMMU implementation. Only a parent-backed
+  vIOMMU can be used to allocate an HWPT_NESTED object.
 
   .. note::
 
@@ -226,9 +225,9 @@ creating the objects and links::
      flag is set.
 
 4. IOMMUFD_OBJ_HWPT_NESTED can be only manually created via the IOMMU_HWPT_ALLOC
-   uAPI, provided an hwpt_id or a viommu_id of a vIOMMU object encapsulating a
-   nesting parent HWPT_PAGING via @pt_id to associate the new HWPT_NESTED object
-   to the corresponding HWPT_PAGING object. The associating HWPT_PAGING object
+   uAPI, provided an hwpt_id or a viommu_id of a parent-backed vIOMMU object
+   via @pt_id to associate the new HWPT_NESTED object to the corresponding
+   HWPT_PAGING object. The associating HWPT_PAGING object
    must be a nesting parent manually allocated via the same uAPI previously with
    an IOMMU_HWPT_ALLOC_NEST_PARENT flag, otherwise the allocation will fail. The
    allocation will be further validated by the IOMMU driver to ensure that the
@@ -245,25 +244,28 @@ creating the objects and links::
       of the object passed in via the @pt_id field of struct iommufd_hwpt_alloc.
 
 5. IOMMUFD_OBJ_VIOMMU can be only manually created via the IOMMU_VIOMMU_ALLOC
-   uAPI, provided a dev_id (for the device's physical IOMMU to back the vIOMMU)
-   and an hwpt_id (to associate the vIOMMU to a nesting parent HWPT_PAGING). The
-   iommufd core will link the vIOMMU object to the struct iommu_device that the
-   struct device is behind. And an IOMMU driver can implement a viommu_alloc op
-   to allocate its own vIOMMU data structure embedding the core-level structure
-   iommufd_viommu and some driver-specific data. If necessary, the driver can
-   also configure its HW virtualization feature for that vIOMMU (and thus for
-   the VM). Successful completion of this operation sets up the linkages between
-   the vIOMMU object and the HWPT_PAGING, then this vIOMMU object can be used
-   as a nesting parent object to allocate an HWPT_NESTED object described above.
+   uAPI, provided a dev_id identifying the device used to select the vIOMMU
+   implementation and, if the selected implementation requires a nesting
+   parent HWPT_PAGING, an hwpt_id. The hwpt_id must be zero for an
+   implementation that does not use a parent. A physical-IOMMU implementation
+   links the vIOMMU object to the struct iommu_device behind the device. Other
+   implementations, such as a TSM associated with the device, can provide their
+   own backing and device association. An implementation can allocate its own
+   vIOMMU data structure embedding the core-level structure iommufd_viommu and
+   some implementation-specific data. If necessary, it can also configure its
+   virtualization resources for that vIOMMU (and thus for the VM). A
+   parent-backed vIOMMU can be used as a nesting parent object to allocate an
+   HWPT_NESTED object described above.
 
 6. IOMMUFD_OBJ_VDEVICE can be only manually created via the IOMMU_VDEVICE_ALLOC
    uAPI, provided a viommu_id for an iommufd_viommu object and a dev_id for an
    iommufd_device object. The vDEVICE object will be the binding between these
    two parent objects. Another @virt_id will be also set via the uAPI providing
    the iommufd core an index to store the vDEVICE object to a vDEVICE array per
-   vIOMMU. If necessary, the IOMMU driver may choose to implement a vdevce_alloc
-   op to init its HW for virtualization feature related to a vDEVICE. Successful
-   completion of this operation sets up the linkages between vIOMMU and device.
+   vIOMMU. A physical-IOMMU implementation requires the device to be behind the
+   same iommu_device as the vIOMMU. Other implementations validate the device
+   association while initializing the vDEVICE. Successful initialization sets
+   up the linkage between the vIOMMU and device.
 
 A device can only bind to an iommufd due to DMA ownership claim and attach to at
 most one IOAS object (no support of PASID yet).
diff --git a/arch/s390/include/asm/kvm_host_s390.h b/arch/s390/include/asm/kvm_host_s390.h
index cd692f8fb7643..9519b8028b104 100644
--- a/arch/s390/include/asm/kvm_host_s390.h
+++ b/arch/s390/include/asm/kvm_host_s390.h
@@ -27,6 +27,8 @@
 #include <asm/isc.h>
 #include <asm/guarded_storage.h>
 
+#define kvm_file_to_kvm_arch s390
+
 #define KVM_HAVE_MMU_RWLOCK
 #define KVM_MAX_VCPUS 255
 
@@ -720,7 +722,7 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {}
 void kvm_arch_free_vm(struct kvm *kvm);
 
 struct zpci_kvm_hook {
-	int (*kvm_register)(void *opaque, struct kvm *kvm);
+	int (*kvm_register)(void *opaque, struct file *kvm_file);
 	void (*kvm_unregister)(void *opaque);
 };
 
diff --git a/arch/s390/kvm/s390/pci.c b/arch/s390/kvm/s390/pci.c
index 82892e1e03d94..d79bd3bdc68e9 100644
--- a/arch/s390/kvm/s390/pci.c
+++ b/arch/s390/kvm/s390/pci.c
@@ -498,17 +498,22 @@ static void kvm_s390_pci_dev_release(struct zpci_dev *zdev)
  * available, enable them and let userspace indicate whether or not they will
  * be used (specify SHM bit to disable).
  */
-static int kvm_s390_pci_register_kvm(void *opaque, struct kvm *kvm)
+static int kvm_s390_pci_register_kvm(void *opaque, struct file *kvm_file)
 {
 	struct zpci_dev *zdev = opaque;
+	struct kvm *kvm;
 	int rc;
 
 	if (!zdev)
 		return -EINVAL;
 
+	kvm = file_to_kvm_s390(kvm_file);
+	if (!kvm)
+		return -ENOENT;
+
 	mutex_lock(&zdev->kzdev_lock);
 
-	if (zdev->kzdev || zdev->gisa != 0 || !kvm) {
+	if (zdev->kzdev || zdev->gisa != 0) {
 		mutex_unlock(&zdev->kzdev_lock);
 		return -EINVAL;
 	}
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 683bb8bf43a94..e460073ff176d 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -44,6 +44,8 @@
 
 #include <hyperv/hvhdk.h>
 
+#define kvm_file_to_kvm_arch x86
+
 #define __KVM_HAVE_ARCH_VCPU_DEBUGFS
 
 /*
diff --git a/arch/x86/include/asm/kvm_page_track.h b/arch/x86/include/asm/kvm_page_track.h
index 3d040741044b4..ea885dd5c9aff 100644
--- a/arch/x86/include/asm/kvm_page_track.h
+++ b/arch/x86/include/asm/kvm_page_track.h
@@ -44,13 +44,15 @@ struct kvm_page_track_notifier_node {
 				    struct kvm_page_track_notifier_node *node);
 };
 
-int kvm_page_track_register_notifier(struct kvm *kvm,
+struct file;
+
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n);
-void kvm_page_track_unregister_notifier(struct kvm *kvm,
+void kvm_page_track_unregister_notifier(struct file *file,
 					struct kvm_page_track_notifier_node *n);
 
-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn);
-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn);
+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn);
+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn);
 #else
 /*
  * Allow defining a node in a structure even if page tracking is disabled, e.g.
diff --git a/arch/x86/kvm/Makefile b/arch/x86/kvm/Makefile
index 0474604ab8a14..c6bf463f50327 100644
--- a/arch/x86/kvm/Makefile
+++ b/arch/x86/kvm/Makefile
@@ -61,9 +61,7 @@ exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/a
 				-e kvm_page_track_unregister_notifier \
 				-e kvm_write_track_add_gfn \
 				-e kvm_write_track_remove_gfn \
-				-e kvm_get_kvm \
-				-e kvm_get_kvm_safe \
-				-e kvm_put_kvm
+				-e kvm_file_to_kvm_fn
 
 # Force grep to emit a goofy group separator that can in turn be replaced with
 # the above newline macro (newlines in Make are a nightmare).  Note, grep only
diff --git a/arch/x86/kvm/mmu/page_track.c b/arch/x86/kvm/mmu/page_track.c
index 7e8195a311bb0..f12558dfcd812 100644
--- a/arch/x86/kvm/mmu/page_track.c
+++ b/arch/x86/kvm/mmu/page_track.c
@@ -16,6 +16,8 @@
 #include <linux/kvm_host.h>
 #include <linux/rculist.h>
 
+#include <asm/kvm_page_track.h>
+
 #include "mmu.h"
 #include "mmu_internal.h"
 #include "page_track.h"
@@ -237,10 +239,11 @@ static int kvm_enable_external_write_tracking(struct kvm *kvm)
  * register the notifier so that event interception for the tracked guest
  * pages can be received.
  */
-int kvm_page_track_register_notifier(struct kvm *kvm,
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n)
 {
 	struct kvm_page_track_notifier_head *head;
+	struct kvm *kvm = file_to_kvm_x86(file);
 	int r;
 
 	if (!kvm || kvm->mm != current->mm)
@@ -252,7 +255,7 @@ int kvm_page_track_register_notifier(struct kvm *kvm,
 			return r;
 	}
 
-	kvm_get_kvm(kvm);
+	get_file(file);
 
 	head = &kvm->arch.track_notifier_head;
 
@@ -267,10 +270,11 @@ EXPORT_SYMBOL_GPL(kvm_page_track_register_notifier);
  * stop receiving the event interception. It is the opposed operation of
  * kvm_page_track_register_notifier().
  */
-void kvm_page_track_unregister_notifier(struct kvm *kvm,
+void kvm_page_track_unregister_notifier(struct file *file,
 					struct kvm_page_track_notifier_node *n)
 {
 	struct kvm_page_track_notifier_head *head;
+	struct kvm *kvm = file_to_kvm_x86(file);
 
 	head = &kvm->arch.track_notifier_head;
 
@@ -279,7 +283,7 @@ void kvm_page_track_unregister_notifier(struct kvm *kvm,
 	write_unlock(&kvm->mmu_lock);
 	synchronize_srcu(&head->track_srcu);
 
-	kvm_put_kvm(kvm);
+	fput(file);
 }
 EXPORT_SYMBOL_GPL(kvm_page_track_unregister_notifier);
 
@@ -336,11 +340,12 @@ void kvm_page_track_delete_slot(struct kvm *kvm, struct kvm_memory_slot *slot)
  * add guest page to the tracking pool so that corresponding access on that
  * page will be intercepted.
  *
- * @kvm: the guest instance we are interested in.
+ * @file: the VM file of the guest instance we are interested in.
  * @gfn: the guest page.
  */
-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn)
+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn)
 {
+	struct kvm *kvm = file_to_kvm_x86(file);
 	struct kvm_memory_slot *slot;
 	int idx;
 
@@ -366,11 +371,12 @@ EXPORT_SYMBOL_GPL(kvm_write_track_add_gfn);
  * remove the guest page from the tracking pool which stops the interception
  * of corresponding access on that page.
  *
- * @kvm: the guest instance we are interested in.
+ * @file: the VM file of the guest instance we are interested in.
  * @gfn: the guest page.
  */
-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn)
+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn)
 {
+	struct kvm *kvm = file_to_kvm_x86(file);
 	struct kvm_memory_slot *slot;
 	int idx;
 
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index 63eb2155a7749..db7ed11e9056f 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -2151,10 +2151,10 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
 	if (fd_empty(f))
 		return -EBADF;
 
-	if (!file_is_kvm(fd_file(f)))
+	source_kvm = file_to_kvm_x86(fd_file(f));
+	if (!source_kvm)
 		return -EBADF;
 
-	source_kvm = fd_file(f)->private_data;
 	ret = sev_lock_two_vms(kvm, source_kvm);
 	if (ret)
 		return ret;
@@ -2876,10 +2876,10 @@ int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
 	if (fd_empty(f))
 		return -EBADF;
 
-	if (!file_is_kvm(fd_file(f)))
+	source_kvm = file_to_kvm_x86(fd_file(f));
+	if (!source_kvm)
 		return -EBADF;
 
-	source_kvm = fd_file(f)->private_data;
 	ret = sev_lock_two_vms(kvm, source_kvm);
 	if (ret)
 		return ret;
diff --git a/drivers/iommu/amd/iommu.c b/drivers/iommu/amd/iommu.c
index 56262f6b1f700..a3c58dd39549b 100644
--- a/drivers/iommu/amd/iommu.c
+++ b/drivers/iommu/amd/iommu.c
@@ -3211,8 +3211,7 @@ const struct iommu_ops amd_iommu_ops = {
 	.is_attach_deferred = amd_iommu_is_attach_deferred,
 	.def_domain_type = amd_iommu_def_domain_type,
 	.page_response = amd_iommu_page_response,
-	.get_viommu_size = amd_iommufd_get_viommu_size,
-	.viommu_init = amd_iommufd_viommu_init,
+	.get_viommu_ops = amd_iommufd_get_viommu_ops,
 };
 
 #ifdef CONFIG_IRQ_REMAP
diff --git a/drivers/iommu/amd/iommufd.c b/drivers/iommu/amd/iommufd.c
index 52300b867c1f2..c1e132382adc7 100644
--- a/drivers/iommu/amd/iommufd.c
+++ b/drivers/iommu/amd/iommufd.c
@@ -32,13 +32,21 @@ void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_ty
 	return hwinfo;
 }
 
-size_t amd_iommufd_get_viommu_size(struct device *dev, enum iommu_viommu_type viommu_type)
+static size_t amd_iommufd_get_viommu_size(struct device *dev,
+		enum iommu_viommu_type viommu_type)
 {
 	return VIOMMU_STRUCT_SIZE(struct amd_iommu_viommu, core);
 }
 
-int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *parent,
-			    const struct iommu_user_data *user_data)
+const struct iommufd_viommu_ops *
+amd_iommufd_get_viommu_ops(struct device *dev, enum iommu_viommu_type viommu_type)
+{
+	return &amd_viommu_ops;
+}
+
+int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,
+		struct device *dev, struct iommu_domain *parent,
+		const struct iommu_user_data *user_data)
 {
 	unsigned long flags;
 	struct protection_domain *pdom = to_pdomain(parent);
@@ -47,8 +55,6 @@ int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *
 	xa_init_flags(&aviommu->gdomid_array, XA_FLAGS_ALLOC1);
 	aviommu->parent = pdom;
 
-	viommu->ops = &amd_viommu_ops;
-
 	spin_lock_irqsave(&pdom->lock, flags);
 	list_add(&aviommu->pdom_list, &pdom->viommu_list);
 	spin_unlock_irqrestore(&pdom->lock, flags);
@@ -73,5 +79,7 @@ static void amd_iommufd_viommu_destroy(struct iommufd_viommu *viommu)
  * struct iommufd_viommu_ops - vIOMMU specific operations
  */
 static const struct iommufd_viommu_ops amd_viommu_ops = {
+	.get_viommu_size = amd_iommufd_get_viommu_size,
+	.viommu_init = amd_iommufd_viommu_init,
 	.destroy = amd_iommufd_viommu_destroy,
 };
diff --git a/drivers/iommu/amd/iommufd.h b/drivers/iommu/amd/iommufd.h
index 62e9e1bebfbe5..0d8e7c0902cff 100644
--- a/drivers/iommu/amd/iommufd.h
+++ b/drivers/iommu/amd/iommufd.h
@@ -8,13 +8,16 @@
 
 #if IS_ENABLED(CONFIG_AMD_IOMMU_IOMMUFD)
 void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_type *type);
-size_t amd_iommufd_get_viommu_size(struct device *dev, enum iommu_viommu_type viommu_type);
-int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *parent,
-			    const struct iommu_user_data *user_data);
+const struct iommufd_viommu_ops *
+amd_iommufd_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type);
+int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,
+		struct device *dev, struct iommu_domain *parent,
+		const struct iommu_user_data *user_data);
 #else
 #define amd_iommufd_hw_info NULL
 #define amd_iommufd_viommu_init NULL
-#define amd_iommufd_get_viommu_size NULL
+#define amd_iommufd_get_viommu_ops NULL
 #endif /* CONFIG_AMD_IOMMU_IOMMUFD */
 
 #endif /* AMD_IOMMUFD_H */
diff --git a/drivers/iommu/amd/nested.c b/drivers/iommu/amd/nested.c
index f1c7987fc5859..5b07136e7cd92 100644
--- a/drivers/iommu/amd/nested.c
+++ b/drivers/iommu/amd/nested.c
@@ -90,7 +90,7 @@ static void *gdom_info_load_or_alloc_locked(struct xarray *xa,
 
 /*
  * This function is assigned to struct iommufd_viommu_ops.alloc_domain_nested()
- * during the call to struct iommu_ops.viommu_init().
+ * when the vIOMMU operations are selected.
  */
 struct iommu_domain *
 amd_iommu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,
@@ -198,7 +198,7 @@ static void set_dte_nested(struct amd_iommu *iommu, struct iommu_domain *dom,
 
 	/*
 	 * The nest parent domain is attached during the call to the
-	 * struct iommu_ops.viommu_init(), which will be stored as part
+	 * struct iommufd_viommu_ops.viommu_init(), which will be stored as part
 	 * of the struct amd_iommu_viommu.parent.
 	 */
 	if (WARN_ON(!ndom->viommu || !ndom->viommu->parent))
diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c
index 25982bdbcbd9a..1dd1031963534 100644
--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c
+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c
@@ -417,20 +417,29 @@ int arm_vsmmu_cache_invalidate(struct iommufd_viommu *viommu,
 	return ret;
 }
 
+static size_t arm_vsmmu_get_size(struct device *dev,
+				 enum iommu_viommu_type viommu_type)
+{
+	return VIOMMU_STRUCT_SIZE(struct arm_vsmmu, core);
+}
+
 static const struct iommufd_viommu_ops arm_vsmmu_ops = {
+	.get_viommu_size = arm_vsmmu_get_size,
+	.viommu_init = arm_vsmmu_init,
 	.alloc_domain_nested = arm_vsmmu_alloc_domain_nested,
 	.cache_invalidate = arm_vsmmu_cache_invalidate,
 	.vdevice_init = arm_vsmmu_vdevice_init,
 };
 
-size_t arm_smmu_get_viommu_size(struct device *dev,
-				enum iommu_viommu_type viommu_type)
+const struct iommufd_viommu_ops *
+arm_smmu_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type)
 {
 	struct arm_smmu_master *master = dev_iommu_priv_get(dev);
 	struct arm_smmu_device *smmu = master->smmu;
 
 	if (!(smmu->features & ARM_SMMU_FEAT_NESTING))
-		return 0;
+		return NULL;
 
 	/*
 	 * FORCE_SYNC is not set with FEAT_NESTING. Some study of the exact HW
@@ -438,7 +447,7 @@ size_t arm_smmu_get_viommu_size(struct device *dev,
 	 * any change to remove this.
 	 */
 	if (WARN_ON(smmu->options & ARM_SMMU_OPT_CMDQ_FORCE_SYNC))
-		return 0;
+		return NULL;
 
 	/*
 	 * Must support some way to prevent the VM from bypassing the cache
@@ -450,19 +459,19 @@ size_t arm_smmu_get_viommu_size(struct device *dev,
 	 */
 	if (!arm_smmu_master_canwbs(master) &&
 	    !(smmu->features & ARM_SMMU_FEAT_S2FWB))
-		return 0;
+		return NULL;
 
 	if (viommu_type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3)
-		return VIOMMU_STRUCT_SIZE(struct arm_vsmmu, core);
+		return &arm_vsmmu_ops;
 
-	if (!smmu->impl_ops || !smmu->impl_ops->get_viommu_size)
-		return 0;
-	return smmu->impl_ops->get_viommu_size(viommu_type);
+	if (!smmu->impl_ops || !smmu->impl_ops->get_viommu_ops)
+		return NULL;
+	return smmu->impl_ops->get_viommu_ops(viommu_type);
 }
 
-int arm_vsmmu_init(struct iommufd_viommu *viommu,
-		   struct iommu_domain *parent_domain,
-		   const struct iommu_user_data *user_data)
+int arm_vsmmu_init(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data)
 {
 	struct arm_vsmmu *vsmmu = container_of(viommu, struct arm_vsmmu, core);
 	struct arm_smmu_device *smmu =
@@ -477,10 +486,8 @@ int arm_vsmmu_init(struct iommufd_viommu *viommu,
 	/* FIXME Move VMID allocation from the S2 domain allocation to here */
 	vsmmu->vmid = s2_parent->s2_cfg.vmid;
 
-	if (viommu->type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3) {
-		viommu->ops = &arm_vsmmu_ops;
+	if (viommu->type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3)
 		return 0;
-	}
 
 	return smmu->impl_ops->vsmmu_init(vsmmu, user_data);
 }
diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c
index 5732f3ba0122d..97dfaec6dc589 100644
--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c
+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c
@@ -4389,8 +4389,7 @@ static const struct iommu_ops arm_smmu_ops = {
 	.get_resv_regions	= arm_smmu_get_resv_regions,
 	.page_response		= arm_smmu_page_response,
 	.def_domain_type	= arm_smmu_def_domain_type,
-	.get_viommu_size	= arm_smmu_get_viommu_size,
-	.viommu_init		= arm_vsmmu_init,
+	.get_viommu_ops	= arm_smmu_get_viommu_ops,
 	.user_pasid_table	= 1,
 	.owner			= THIS_MODULE,
 	.default_domain_ops = &(const struct iommu_domain_ops) {
@@ -5489,8 +5488,8 @@ static struct arm_smmu_device *arm_smmu_impl_probe(struct arm_smmu_device *smmu)
 
 	ops = new_smmu->impl_ops;
 	if (ops) {
-		/* get_viommu_size and vsmmu_init ops must be paired */
-		if (WARN_ON(!ops->get_viommu_size != !ops->vsmmu_init)) {
+		/* get_viommu_ops and vsmmu_init ops must be paired */
+		if (WARN_ON(!ops->get_viommu_ops != !ops->vsmmu_init)) {
 			ret = -EINVAL;
 			goto err_remove;
 		}
diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h
index dd2fee2f560e6..79f2adf7a1f51 100644
--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h
+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h
@@ -886,7 +886,8 @@ struct arm_smmu_impl_ops {
 	 */
 	void *(*hw_info)(struct arm_smmu_device *smmu, u32 *length,
 			 enum iommu_hw_info_type *type);
-	size_t (*get_viommu_size)(enum iommu_viommu_type viommu_type);
+	const struct iommufd_viommu_ops *(*get_viommu_ops)(
+		enum iommu_viommu_type viommu_type);
 	int (*vsmmu_init)(struct arm_vsmmu *vsmmu,
 			  const struct iommu_user_data *user_data);
 };
@@ -1260,11 +1261,12 @@ struct arm_vsmmu {
 #if IS_ENABLED(CONFIG_ARM_SMMU_V3_IOMMUFD)
 void *arm_smmu_hw_info(struct device *dev, u32 *length,
 		       enum iommu_hw_info_type *type);
-size_t arm_smmu_get_viommu_size(struct device *dev,
-				enum iommu_viommu_type viommu_type);
-int arm_vsmmu_init(struct iommufd_viommu *viommu,
-		   struct iommu_domain *parent_domain,
-		   const struct iommu_user_data *user_data);
+const struct iommufd_viommu_ops *
+arm_smmu_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type);
+int arm_vsmmu_init(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data);
 int arm_smmu_attach_prepare_vmaster(struct arm_smmu_attach_state *state,
 				    struct arm_smmu_nested_domain *nested_domain);
 void arm_smmu_attach_commit_vmaster(struct arm_smmu_attach_state *state);
@@ -1276,7 +1278,7 @@ arm_vsmmu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,
 int arm_vsmmu_cache_invalidate(struct iommufd_viommu *viommu,
 			       struct iommu_user_data_array *array);
 #else
-#define arm_smmu_get_viommu_size NULL
+#define arm_smmu_get_viommu_ops NULL
 #define arm_smmu_hw_info NULL
 #define arm_vsmmu_init NULL
 #define arm_vsmmu_alloc_domain_nested NULL
diff --git a/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c b/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c
index 6644075c1431e..1c8a7939fc1c0 100644
--- a/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c
+++ b/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c
@@ -892,11 +892,14 @@ static void *tegra241_cmdqv_hw_info(struct arm_smmu_device *smmu, u32 *length,
 	return info;
 }
 
-static size_t tegra241_cmdqv_get_vintf_size(enum iommu_viommu_type viommu_type)
+static const struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops;
+
+static const struct iommufd_viommu_ops *
+tegra241_cmdqv_get_viommu_ops(enum iommu_viommu_type viommu_type)
 {
 	if (viommu_type != IOMMU_VIOMMU_TYPE_TEGRA241_CMDQV)
-		return 0;
-	return VIOMMU_STRUCT_SIZE(struct tegra241_vintf, vsmmu.core);
+		return NULL;
+	return &tegra241_cmdqv_viommu_ops;
 }
 
 static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {
@@ -907,7 +910,7 @@ static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {
 	.device_remove = tegra241_cmdqv_remove,
 	/* For user-space use */
 	.hw_info = tegra241_cmdqv_hw_info,
-	.get_viommu_size = tegra241_cmdqv_get_vintf_size,
+	.get_viommu_ops = tegra241_cmdqv_get_viommu_ops,
 	.vsmmu_init = tegra241_cmdqv_init_vintf_user,
 };
 
@@ -1289,7 +1292,15 @@ static int tegra241_vintf_init_vsid(struct iommufd_vdevice *vdev)
 	return 0;
 }
 
-static struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops = {
+static size_t tegra241_cmdqv_get_vintf_size(struct device *dev,
+					    enum iommu_viommu_type viommu_type)
+{
+	return VIOMMU_STRUCT_SIZE(struct tegra241_vintf, vsmmu.core);
+}
+
+static const struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops = {
+	.get_viommu_size = tegra241_cmdqv_get_vintf_size,
+	.viommu_init = arm_vsmmu_init,
 	.destroy = tegra241_cmdqv_destroy_vintf_user,
 	.alloc_domain_nested = arm_vsmmu_alloc_domain_nested,
 	/* Non-accelerated commands will be still handled by the kernel */
@@ -1312,7 +1323,7 @@ tegra241_cmdqv_init_vintf_user(struct arm_vsmmu *vsmmu,
 	int ret;
 
 	/*
-	 * Unsupported type should be rejected by tegra241_cmdqv_get_vintf_size.
+	 * Unsupported type should be rejected by tegra241_cmdqv_get_viommu_ops.
 	 * Seeing one here indicates a kernel bug or some data corruption.
 	 */
 	if (WARN_ON(vsmmu->core.type != IOMMU_VIOMMU_TYPE_TEGRA241_CMDQV))
@@ -1364,7 +1375,6 @@ tegra241_cmdqv_init_vintf_user(struct arm_vsmmu *vsmmu,
 	dev_dbg(cmdqv->dev, "VINTF%u: allocated with vmid (%d)\n", vintf->idx,
 		vintf->vsmmu.vmid);
 
-	vsmmu->core.ops = &tegra241_cmdqv_viommu_ops;
 	return 0;
 
 free_mmap:
diff --git a/drivers/iommu/iommufd/Makefile b/drivers/iommu/iommufd/Makefile
index 67207914bb6e0..f90efe2f9d106 100644
--- a/drivers/iommu/iommufd/Makefile
+++ b/drivers/iommu/iommufd/Makefile
@@ -11,6 +11,8 @@ iommufd-y := \
 	viommu.o
 
 iommufd-$(CONFIG_IOMMUFD_NOIOMMU) += hwpt_noiommu.o
+iommufd-$(CONFIG_TSM) += tsm.o
+
 iommufd-$(CONFIG_IOMMUFD_TEST) += selftest.o
 
 obj-$(CONFIG_IOMMUFD) += iommufd.o
diff --git a/drivers/iommu/iommufd/device.c b/drivers/iommu/iommufd/device.c
index a664c70a6fe73..f99f7bee2e774 100644
--- a/drivers/iommu/iommufd/device.c
+++ b/drivers/iommu/iommufd/device.c
@@ -295,6 +295,7 @@ static int iommufd_bind_noiommu(struct iommufd_device *idev)
  * iommufd_device_bind - Bind a physical device to an iommu fd
  * @ictx: iommufd file descriptor
  * @dev: Pointer to a physical device struct
+ * @kvm_file: VM file if device belongs to a KVM VM
  * @id: Output ID number to return to userspace for this device
  *
  * A successful bind establishes an ownership over the device and returns
@@ -308,7 +309,9 @@ static int iommufd_bind_noiommu(struct iommufd_device *idev)
  * The caller must undo this with iommufd_device_unbind()
  */
 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
-					   struct device *dev, u32 *id)
+					   struct device *dev,
+					   struct file *kvm_file,
+					   u32 *id)
 {
 	struct iommufd_device *idev;
 	int rc;
@@ -319,6 +322,8 @@ struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
 
 	idev->ictx = ictx;
 	idev->dev = dev;
+	/* VFIO holds the file reference while the device is open. */
+	idev->kvm_file = kvm_file;
 
 	if (!iommufd_device_is_noiommu(idev))
 		rc = iommufd_bind_iommu(idev);
diff --git a/drivers/iommu/iommufd/hw_pagetable.c b/drivers/iommu/iommufd/hw_pagetable.c
index ef6e119c2a752..bd562bc2db487 100644
--- a/drivers/iommu/iommufd/hw_pagetable.c
+++ b/drivers/iommu/iommufd/hw_pagetable.c
@@ -306,6 +306,10 @@ iommufd_viommu_alloc_hwpt_nested(struct iommufd_viommu *viommu, u32 flags,
 		return ERR_PTR(-EOPNOTSUPP);
 	if (!user_data->len)
 		return ERR_PTR(-EOPNOTSUPP);
+	if (!viommu->hwpt)
+		return ERR_PTR(-EOPNOTSUPP);
+	if (!viommu->iommu_dev)
+		return ERR_PTR(-EOPNOTSUPP);
 	if (!viommu->ops || !viommu->ops->alloc_domain_nested)
 		return ERR_PTR(-EOPNOTSUPP);
 
@@ -404,10 +408,12 @@ int iommufd_hwpt_alloc(struct iommufd_ucmd *ucmd)
 		struct iommufd_viommu *viommu;
 
 		viommu = container_of(pt_obj, struct iommufd_viommu, obj);
-		iommu_dev = iommufd_device_get_iommu_dev(idev);
-		if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
-			rc = -EINVAL;
-			goto out_unlock;
+		if (viommu->iommu_dev) {
+			iommu_dev = iommufd_device_get_iommu_dev(idev);
+			if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
+				rc = -EINVAL;
+				goto out_unlock;
+			}
 		}
 		hwpt_nested = iommufd_viommu_alloc_hwpt_nested(
 			viommu, cmd->flags, &user_data);
diff --git a/drivers/iommu/iommufd/iommufd_private.h b/drivers/iommu/iommufd/iommufd_private.h
index eb2e85b27e429..64e0d9e4da168 100644
--- a/drivers/iommu/iommufd/iommufd_private.h
+++ b/drivers/iommu/iommufd/iommufd_private.h
@@ -509,6 +509,8 @@ struct iommufd_device {
 	struct list_head group_item;
 	/* always the physical device */
 	struct device *dev;
+	/* ..and the VM file if available */
+	struct file *kvm_file;
 	bool enforce_cache_coherency;
 	struct iommufd_vdevice *vdev;
 	bool destroying;
@@ -728,6 +730,14 @@ void iommufd_vdevice_destroy(struct iommufd_object *obj);
 void iommufd_vdevice_abort(struct iommufd_object *obj);
 int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd);
 void iommufd_hw_queue_destroy(struct iommufd_object *obj);
+#ifdef CONFIG_TSM
+int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd);
+#else
+static inline int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)
+{
+	return -EOPNOTSUPP;
+}
+#endif
 
 #ifdef CONFIG_IOMMUFD_TEST
 int iommufd_test(struct iommufd_ucmd *ucmd);
diff --git a/drivers/iommu/iommufd/main.c b/drivers/iommu/iommufd/main.c
index 9a921b1531620..577eef2760a35 100644
--- a/drivers/iommu/iommufd/main.c
+++ b/drivers/iommu/iommufd/main.c
@@ -453,6 +453,7 @@ union ucmd_buffer {
 	struct iommu_veventq_alloc veventq;
 	struct iommu_vfio_ioas vfio_ioas;
 	struct iommu_viommu_alloc viommu;
+	struct iommu_vdevice_tsm_req tsm_req;
 #ifdef CONFIG_IOMMUFD_TEST
 	struct iommu_test_cmd test;
 #endif
@@ -516,6 +517,8 @@ static const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {
 		 __reserved),
 	IOCTL_OP(IOMMU_VIOMMU_ALLOC, iommufd_viommu_alloc_ioctl,
 		 struct iommu_viommu_alloc, out_viommu_id),
+	IOCTL_OP(IOMMU_VDEVICE_TSM_REQ, iommufd_vdevice_tsm_req_ioctl,
+		 struct iommu_vdevice_tsm_req, out_tsm_code),
 #ifdef CONFIG_IOMMUFD_TEST
 	IOCTL_OP(IOMMU_TEST_CMD, iommufd_test, struct iommu_test_cmd, last),
 #endif
diff --git a/drivers/iommu/iommufd/selftest.c b/drivers/iommu/iommufd/selftest.c
index ee706f18f7e91..426ea94467ffe 100644
--- a/drivers/iommu/iommufd/selftest.c
+++ b/drivers/iommu/iommufd/selftest.c
@@ -774,7 +774,19 @@ static int mock_hw_queue_init_phys(struct iommufd_hw_queue *hw_queue, u32 index,
 	return rc;
 }
 
-static struct iommufd_viommu_ops mock_viommu_ops = {
+static int mock_viommu_init(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data);
+
+static size_t mock_get_viommu_size(struct device *dev,
+				   enum iommu_viommu_type viommu_type)
+{
+	return VIOMMU_STRUCT_SIZE(struct mock_viommu, core);
+}
+
+static const struct iommufd_viommu_ops mock_viommu_ops = {
+	.get_viommu_size = mock_get_viommu_size,
+	.viommu_init = mock_viommu_init,
 	.destroy = mock_viommu_destroy,
 	.alloc_domain_nested = mock_viommu_alloc_domain_nested,
 	.cache_invalidate = mock_viommu_cache_invalidate,
@@ -782,17 +794,18 @@ static struct iommufd_viommu_ops mock_viommu_ops = {
 	.hw_queue_init_phys = mock_hw_queue_init_phys,
 };
 
-static size_t mock_get_viommu_size(struct device *dev,
-				   enum iommu_viommu_type viommu_type)
+static const struct iommufd_viommu_ops *
+mock_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type)
 {
 	if (viommu_type != IOMMU_VIOMMU_TYPE_SELFTEST)
-		return 0;
-	return VIOMMU_STRUCT_SIZE(struct mock_viommu, core);
+		return NULL;
+	return &mock_viommu_ops;
 }
 
 static int mock_viommu_init(struct iommufd_viommu *viommu,
-			    struct iommu_domain *parent_domain,
-			    const struct iommu_user_data *user_data)
+		struct device *dev, struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data)
 {
 	struct mock_iommu_device *mock_iommu = container_of(
 		viommu->iommu_dev, struct mock_iommu_device, iommu_dev);
@@ -834,7 +847,6 @@ static int mock_viommu_init(struct iommufd_viommu *viommu,
 	mutex_init(&mock_viommu->queue_mutex);
 	mock_viommu->s2_parent = to_mock_domain(parent_domain);
 
-	viommu->ops = &mock_viommu_ops;
 	return 0;
 
 err_destroy_mmap:
@@ -861,8 +873,7 @@ static const struct iommu_ops mock_ops = {
 	.probe_device = mock_probe_device,
 	.page_response = mock_domain_page_response,
 	.user_pasid_table = true,
-	.get_viommu_size = mock_get_viommu_size,
-	.viommu_init = mock_viommu_init,
+	.get_viommu_ops = mock_get_viommu_ops,
 };
 
 static void mock_domain_free_nested(struct iommu_domain *domain)
@@ -1074,7 +1085,7 @@ static int iommufd_test_mock_domain(struct iommufd_ucmd *ucmd,
 		goto out_sobj;
 	}
 
-	idev = iommufd_device_bind(ucmd->ictx, &sobj->idev.mock_dev->dev,
+	idev = iommufd_device_bind(ucmd->ictx, &sobj->idev.mock_dev->dev, NULL,
 				   &idev_id);
 	if (IS_ERR(idev)) {
 		rc = PTR_ERR(idev);
diff --git a/drivers/iommu/iommufd/tsm.c b/drivers/iommu/iommufd/tsm.c
new file mode 100644
index 0000000000000..b28ff86403456
--- /dev/null
+++ b/drivers/iommu/iommufd/tsm.c
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2026 ARM Ltd.
+ */
+
+#include <linux/bits.h>
+#include <linux/build_bug.h>
+#include <linux/limits.h>
+#include <linux/tsm.h>
+#include "iommufd_private.h"
+
+/**
+ * iommufd_vdevice_tsm_req_ioctl - Forward TSM requests
+ * @ucmd: user command data for IOMMU_VDEVICE_TSM_REQ
+ *
+ * Resolve @iommu_vdevice_tsm_req::vdevice_id to a vdevice and pass the
+ * request/response buffers to its vIOMMU implementation.
+ *
+ * Return:
+ *  -errno on error.
+ *  positive residue if response/request bytes were left unconsumed.
+ *    if response buffer is provided, residue indicates the number of bytes
+ *    not used in response buffer
+ *    if there is no response buffer, residue indicates the number of bytes
+ *    not consumed in req buffer
+ *  0 otherwise.
+ */
+int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)
+{
+	int ret;
+	struct iommufd_object *obj;
+	struct iommufd_vdevice *vdev;
+	struct iommu_vdevice_tsm_req *cmd = ucmd->cmd;
+	struct tsm_guest_req_info info = {
+		.op = cmd->op,
+		.tvm_arch = cmd->tvm_arch,
+		.req = u64_to_user_ptr(cmd->req_uptr),
+		.req_len = cmd->req_len,
+		.resp = u64_to_user_ptr(cmd->resp_uptr),
+		.resp_len = cmd->resp_len,
+	};
+
+	/* Every defined operation must fit in the vdevice's u64 mask. */
+	BUILD_BUG_ON(BITS_PER_TYPE(u64) < TSM_REQ_MAX);
+
+	/* Successful residues must fit in the ioctl's int return value. */
+	if (cmd->req_len > INT_MAX || cmd->resp_len > INT_MAX)
+		return -EINVAL;
+
+	obj = iommufd_get_object(ucmd->ictx, cmd->vdevice_id,
+				 IOMMUFD_OBJ_VDEVICE);
+	if (IS_ERR(obj))
+		return PTR_ERR(obj);
+	vdev = container_of(obj, struct iommufd_vdevice, obj);
+
+	cmd->out_tsm_code = 0;
+	if (!vdev->viommu->ops || !vdev->viommu->ops->vdevice_tsm_req ||
+	    !vdev->tsm_req_op_mask) {
+		ret = -EOPNOTSUPP;
+		goto out_respond;
+	}
+	/* Bounds-check the user-supplied shift before BIT_ULL(). */
+	if (cmd->tvm_arch != vdev->tsm_tvm_arch ||
+	    cmd->op >= TSM_REQ_MAX ||
+	    !(vdev->tsm_req_op_mask & BIT_ULL(cmd->op))) {
+		ret = -EINVAL;
+		goto out_put_object;
+	}
+	ret = vdev->viommu->ops->vdevice_tsm_req(vdev, &info,
+						 &cmd->out_tsm_code);
+
+out_respond:
+	/* Always copy the tsm_code as response */
+	if (iommufd_ucmd_respond(ucmd, sizeof(*cmd)))
+		ret = -EFAULT;
+
+out_put_object:
+	iommufd_put_object(ucmd->ictx, obj);
+	return ret;
+}
diff --git a/drivers/iommu/iommufd/viommu.c b/drivers/iommu/iommufd/viommu.c
index f7951057a1e56..9155d0dcb4b40 100644
--- a/drivers/iommu/iommufd/viommu.c
+++ b/drivers/iommu/iommufd/viommu.c
@@ -1,6 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES
  */
+#include <linux/file.h>
+#include <linux/cleanup.h>
+#include <linux/tsm.h>
+
 #include "iommufd_private.h"
 
 void iommufd_viommu_destroy(struct iommufd_object *obj)
@@ -10,7 +14,12 @@ void iommufd_viommu_destroy(struct iommufd_object *obj)
 
 	if (viommu->ops && viommu->ops->destroy)
 		viommu->ops->destroy(viommu);
-	refcount_dec(&viommu->hwpt->common.obj.users);
+	if (viommu->tsm_dev)
+		tsm_put_device(viommu->tsm_dev);
+	if (viommu->hwpt)
+		refcount_dec(&viommu->hwpt->common.obj.users);
+	if (viommu->kvm_file)
+		fput(viommu->kvm_file);
 	xa_destroy(&viommu->vdevs);
 }
 
@@ -22,11 +31,12 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 		.uptr = u64_to_user_ptr(cmd->data_uptr),
 		.len = cmd->data_len,
 	};
-	struct iommufd_hwpt_paging *hwpt_paging;
+	struct iommufd_hwpt_paging *hwpt_paging = NULL;
+	struct tsm_dev *tsm_dev = NULL;
 	struct iommufd_viommu *viommu;
 	struct iommufd_device *idev;
-	struct iommu_device *iommu_dev;
-	const struct iommu_ops *ops;
+	struct iommu_device *iommu_dev = NULL;
+	const struct iommufd_viommu_ops *ops;
 	size_t viommu_size;
 	int rc;
 
@@ -37,41 +47,66 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	if (IS_ERR(idev))
 		return PTR_ERR(idev);
 
-	iommu_dev = iommufd_device_get_iommu_dev(idev);
-	if (!iommu_dev) {
-		rc = -EOPNOTSUPP;
+	tsm_dev = tsm_get_device(idev->dev);
+	if (IS_ERR(tsm_dev)) {
+		rc = PTR_ERR(tsm_dev);
+		tsm_dev = NULL;
 		goto out_put_idev;
 	}
-	ops = iommu_dev->ops;
-	if (!ops->get_viommu_size || !ops->viommu_init) {
-		rc = -EOPNOTSUPP;
+	ops = tsm_dev ? tsm_viommu_get_ops(tsm_dev, idev->dev, cmd->type) : NULL;
+	if (IS_ERR(ops)) {
+		rc = PTR_ERR(ops);
 		goto out_put_idev;
 	}
-
-	viommu_size = ops->get_viommu_size(idev->dev, cmd->type);
-	if (!viommu_size) {
-		rc = -EOPNOTSUPP;
-		goto out_put_idev;
+	if (!ops) {
+		if (tsm_dev) {
+			tsm_put_device(tsm_dev);
+			tsm_dev = NULL;
+		}
+		iommu_dev = iommufd_device_get_iommu_dev(idev);
+		if (!iommu_dev) {
+			rc = -EOPNOTSUPP;
+			goto out_put_idev;
+		}
+		if (!iommu_dev->ops->get_viommu_ops) {
+			rc = -EOPNOTSUPP;
+			goto out_put_idev;
+		}
+		ops = iommu_dev->ops->get_viommu_ops(idev->dev, cmd->type);
+		if (!ops) {
+			rc = -EOPNOTSUPP;
+			goto out_put_idev;
+		}
 	}
 
 	/*
-	 * It is a driver bug for providing a viommu_size smaller than the core
-	 * vIOMMU structure size
+	 * It is a driver bug to omit the required operations or provide a size
+	 * smaller than the core vIOMMU structure.
 	 */
-	if (WARN_ON_ONCE(viommu_size < sizeof(*viommu))) {
+	if (WARN_ON_ONCE(!ops->get_viommu_size || !ops->viommu_init)) {
 		rc = -EOPNOTSUPP;
 		goto out_put_idev;
 	}
-
-	hwpt_paging = iommufd_get_hwpt_paging(ucmd, cmd->hwpt_id);
-	if (IS_ERR(hwpt_paging)) {
-		rc = PTR_ERR(hwpt_paging);
+	viommu_size = ops->get_viommu_size(idev->dev, cmd->type);
+	if (!viommu_size || WARN_ON_ONCE(viommu_size < sizeof(*viommu))) {
+		rc = -EOPNOTSUPP;
 		goto out_put_idev;
 	}
 
-	if (!hwpt_paging->nest_parent) {
+	if ((ops->flags & IOMMUFD_VIOMMU_NO_HWPT) && cmd->hwpt_id) {
 		rc = -EINVAL;
-		goto out_put_hwpt;
+		goto out_put_idev;
+	}
+	if (!(ops->flags & IOMMUFD_VIOMMU_NO_HWPT)) {
+		hwpt_paging = iommufd_get_hwpt_paging(ucmd, cmd->hwpt_id);
+		if (IS_ERR(hwpt_paging)) {
+			rc = PTR_ERR(hwpt_paging);
+			goto out_put_idev;
+		}
+		if (!hwpt_paging->nest_parent) {
+			rc = -EINVAL;
+			goto out_put_hwpt;
+		}
 	}
 
 	viommu = (struct iommufd_viommu *)_iommufd_object_alloc_ucmd(
@@ -82,10 +117,15 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	}
 
 	xa_init(&viommu->vdevs);
+	if (idev->kvm_file)
+		viommu->kvm_file = get_file(idev->kvm_file);
 	viommu->type = cmd->type;
 	viommu->ictx = ucmd->ictx;
+	viommu->tsm_dev = tsm_dev;
+	tsm_dev = NULL;
 	viommu->hwpt = hwpt_paging;
-	refcount_inc(&viommu->hwpt->common.obj.users);
+	if (viommu->hwpt)
+		refcount_inc(&viommu->hwpt->common.obj.users);
 	INIT_LIST_HEAD(&viommu->veventqs);
 	init_rwsem(&viommu->veventqs_rwsem);
 	/*
@@ -95,23 +135,22 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	 */
 	viommu->iommu_dev = iommu_dev;
 
-	rc = ops->viommu_init(viommu, hwpt_paging->common.domain,
+	rc = ops->viommu_init(viommu, idev->dev,
+			      hwpt_paging ? hwpt_paging->common.domain : NULL,
 			      user_data.len ? &user_data : NULL);
 	if (rc)
 		goto out_put_hwpt;
-
-	/* It is a driver bug that viommu->ops isn't filled */
-	if (WARN_ON_ONCE(!viommu->ops)) {
-		rc = -EOPNOTSUPP;
-		goto out_put_hwpt;
-	}
+	viommu->ops = ops;
 
 	cmd->out_viommu_id = viommu->obj.id;
 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
 
 out_put_hwpt:
-	iommufd_put_object(ucmd->ictx, &hwpt_paging->common.obj);
+	if (hwpt_paging)
+		iommufd_put_object(ucmd->ictx, &hwpt_paging->common.obj);
 out_put_idev:
+	if (tsm_dev)
+		tsm_put_device(tsm_dev);
 	iommufd_put_object(ucmd->ictx, &idev->obj);
 	return rc;
 }
@@ -171,10 +210,12 @@ int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd)
 		goto out_put_viommu;
 	}
 
-	iommu_dev = iommufd_device_get_iommu_dev(idev);
-	if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
-		rc = -EINVAL;
-		goto out_put_idev;
+	if (viommu->iommu_dev) {
+		iommu_dev = iommufd_device_get_iommu_dev(idev);
+		if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
+			rc = -EINVAL;
+			goto out_put_idev;
+		}
 	}
 
 	mutex_lock(&idev->igroup->lock);
@@ -394,7 +435,7 @@ int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	if (IS_ERR(viommu))
 		return PTR_ERR(viommu);
 
-	if (!viommu->ops || !viommu->ops->get_hw_queue_size ||
+	if (!viommu->hwpt || !viommu->ops || !viommu->ops->get_hw_queue_size ||
 	    !viommu->ops->hw_queue_init_phys) {
 		rc = -EOPNOTSUPP;
 		goto out_put_viommu;
diff --git a/drivers/pci/tsm.c b/drivers/pci/tsm.c
index 5fdcd7f2e8207..8aa74ba31932b 100644
--- a/drivers/pci/tsm.c
+++ b/drivers/pci/tsm.c
@@ -9,9 +9,15 @@
 #define dev_fmt(fmt) "PCI/TSM: " fmt
 
 #include <linux/bitfield.h>
+#include <linux/iommufd.h>
+#include <linux/jiffies.h>
+#include <linux/module.h>
 #include <linux/pci.h>
 #include <linux/pci-doe.h>
 #include <linux/pci-tsm.h>
+#include <linux/pid.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
 #include <linux/sysfs.h>
 #include <linux/tsm.h>
 #include <linux/xarray.h>
@@ -35,6 +41,25 @@ static const struct pci_tsm_ops *to_pci_tsm_ops(struct pci_tsm *tsm)
 	return tsm->tsm_dev->pci_ops;
 }
 
+struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)
+{
+	const struct pci_tsm_ops *ops;
+	struct tsm_dev *tsm_dev;
+
+	guard(rwsem_read)(&pci_tsm_rwsem);
+	if (!pdev->tsm)
+		return NULL;
+
+	tsm_dev = pdev->tsm->tsm_dev;
+	ops = tsm_dev->pci_ops;
+	if (!ops->viommu_get_ops)
+		return NULL;
+	if (!try_module_get(ops->owner))
+		return ERR_PTR(-ENODEV);
+	return tsm_dev;
+}
+EXPORT_SYMBOL_GPL(pci_tsm_get_device);
+
 static inline bool is_dsm(struct pci_dev *pdev)
 {
 	return pdev->tsm && pdev->tsm->dsm_dev == pdev;
@@ -292,156 +317,103 @@ static int remove_fn(struct pci_dev *pdev, void *data)
 	return 0;
 }
 
-/*
- * Note, this helper only returns an error code and takes an argument for
- * compatibility with the pci_walk_bus() callback prototype. pci_tsm_unbind()
- * always succeeds.
- */
-static int __pci_tsm_unbind(struct pci_dev *pdev, void *data)
+bool pci_tsm_is_configured(struct pci_dev *pdev)
 {
-	struct pci_tdi *tdi;
-	struct pci_tsm_pf0 *tsm_pf0;
-
-	lockdep_assert_held(&pci_tsm_rwsem);
-
-	if (!pdev->tsm)
-		return 0;
-
-	tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
-	guard(mutex)(&tsm_pf0->lock);
-
-	tdi = pdev->tsm->tdi;
-	if (!tdi)
-		return 0;
-
-	to_pci_tsm_ops(pdev->tsm)->unbind(tdi);
-	pdev->tsm->tdi = NULL;
+	guard(rwsem_read)(&pci_tsm_rwsem);
 
-	return 0;
+	return !!pdev->tsm;
 }
+EXPORT_SYMBOL_GPL(pci_tsm_is_configured);
 
-void pci_tsm_unbind(struct pci_dev *pdev)
-{
-	guard(rwsem_read)(&pci_tsm_rwsem);
-	__pci_tsm_unbind(pdev, NULL);
-}
-EXPORT_SYMBOL_GPL(pci_tsm_unbind);
+struct pci_tsm_context {
+	struct pci_tsm_pf0 *pf0;
+	struct pci_dev *pdev;
+	struct pci_dev *dsm_dev;
+};
 
-/**
- * pci_tsm_bind() - Bind @pdev as a TDI for @kvm
- * @pdev: PCI device function to bind
- * @kvm: Private memory attach context
- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM
- *
- * Returns 0 on success, or a negative error code on failure.
- *
- * Context: Caller is responsible for constraining the bind lifetime to the
- * registered state of the device. For example, pci_tsm_bind() /
- * pci_tsm_unbind() limited to the VFIO driver bound state of the device.
- */
-int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id)
+struct pci_tsm_context *pci_tsm_context_get(struct pci_dev *pdev,
+					    struct tsm_dev *viommu_tsm_dev)
 {
-	struct pci_tsm_pf0 *tsm_pf0;
-	struct pci_tdi *tdi;
-
-	if (!kvm)
-		return -EINVAL;
+	struct pci_tsm_context *context;
+	struct pci_tsm_pf0 *pf0;
 
 	guard(rwsem_read)(&pci_tsm_rwsem);
+	if (!pdev->tsm || !is_link_tsm(pdev->tsm->tsm_dev))
+		return ERR_PTR(-EOPNOTSUPP);
+	/*
+	 * The vdevice can use a different PCI function from VIOMMU_ALLOC. The
+	 * module pin keeps the vIOMMU's TSM registered, but does not freeze this
+	 * function's link. Match its current TSM before pinning the link below.
+	 */
+	if (pdev->tsm->tsm_dev != viommu_tsm_dev)
+		return ERR_PTR(-EXDEV);
 
-	if (!pdev->tsm)
-		return -EINVAL;
-
-	if (!is_link_tsm(pdev->tsm->tsm_dev))
-		return -ENXIO;
+	pf0 = to_pci_tsm_pf0(pdev->tsm);
+	if (!pf0)
+		return ERR_PTR(-ENXIO);
 
-	tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
-	guard(mutex)(&tsm_pf0->lock);
+	context = kzalloc_obj(*context);
+	if (!context)
+		return ERR_PTR(-ENOMEM);
 
-	/* Resolve races to bind a TDI */
-	if (pdev->tsm->tdi) {
-		if (pdev->tsm->tdi->kvm != kvm)
-			return -EBUSY;
-		return 0;
+	guard(mutex)(&pf0->lock);
+	if (pf0->removing) {
+		kfree(context);
+		return ERR_PTR(-ENODEV);
 	}
-
-	tdi = to_pci_tsm_ops(pdev->tsm)->bind(pdev, kvm, tdi_id);
-	if (IS_ERR(tdi))
-		return PTR_ERR(tdi);
-
-	pdev->tsm->tdi = tdi;
-
-	return 0;
+	if (!pf0->context_users)
+		reinit_completion(&pf0->contexts_drained);
+	pf0->context_users++;
+	context->pf0 = pf0;
+	context->pdev = pci_dev_get(pdev);
+	context->dsm_dev = pci_dev_get(pf0->base_tsm.pdev);
+	return context;
 }
-EXPORT_SYMBOL_GPL(pci_tsm_bind);
+EXPORT_SYMBOL_GPL(pci_tsm_context_get);
 
-/**
- * pci_tsm_guest_req() - helper to marshal guest requests to the TSM driver
- * @pdev: @pdev representing a bound tdi
- * @scope: caller asserts this passthrough request is limited to TDISP operations
- * @req_in: Input payload forwarded from the guest
- * @in_len: Length of @req_in
- * @req_out: Output payload buffer response to the guest
- * @out_len: Length of @req_out on input, bytes filled in @req_out on output
- * @tsm_code: Optional TSM arch specific result code for the guest TSM
- *
- * This is a common entry point for requests triggered by userspace KVM-exit
- * service handlers responding to TDI information or state change requests. The
- * scope parameter limits requests to TDISP state management, or limited debug.
- * This path is only suitable for commands and results that are the host kernel
- * has no use, the host is only facilitating guest to TSM communication.
- *
- * Returns 0 on success and -error on failure and positive "residue" on success
- * but @req_out is filled with less then @out_len, or @req_out is NULL and a
- * residue number of bytes were not consumed from @req_in.  On success or
- * failure @tsm_code may be populated with a TSM implementation specific result
- * code for the guest to consume.
- *
- * Context: Caller is responsible for calling this within the pci_tsm_bind()
- * state of the TDI.
- */
-ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope,
-			  sockptr_t req_in, size_t in_len, sockptr_t req_out,
-			  size_t out_len, u64 *tsm_code)
+void pci_tsm_context_put(struct pci_tsm_context *context)
 {
-	struct pci_tsm_pf0 *tsm_pf0;
-	struct pci_tdi *tdi;
-	int rc;
-
-	/* Forbid requests that are not directly related to TDISP operations */
-	if (scope > PCI_TSM_REQ_STATE_CHANGE)
-		return -EINVAL;
+	struct pci_tsm_pf0 *pf0 = context->pf0;
 
-	ACQUIRE(rwsem_read_intr, lock)(&pci_tsm_rwsem);
-	if ((rc = ACQUIRE_ERR(rwsem_read_intr, &lock)))
-		return rc;
+	down_read(&pci_tsm_rwsem);
+	mutex_lock(&pf0->lock);
+	if (WARN_ON(!pf0->context_users))
+		goto out_unlock;
+	if (!--pf0->context_users)
+		complete_all(&pf0->contexts_drained);
+out_unlock:
+	mutex_unlock(&pf0->lock);
+	up_read(&pci_tsm_rwsem);
 
-	if (!pdev->tsm)
-		return -ENXIO;
-
-	if (!is_link_tsm(pdev->tsm->tsm_dev))
-		return -ENXIO;
+	pci_dev_put(context->pdev);
+	pci_dev_put(context->dsm_dev);
+	kfree(context);
+}
+EXPORT_SYMBOL_GPL(pci_tsm_context_put);
 
-	tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
-	ACQUIRE(mutex_intr, ops_lock)(&tsm_pf0->lock);
-	if ((rc = ACQUIRE_ERR(mutex_intr, &ops_lock)))
-		return rc;
+struct pci_tsm_pf0 *pci_tsm_context_pf0(struct pci_tsm_context *context)
+{
+	return context->pf0;
+}
+EXPORT_SYMBOL_GPL(pci_tsm_context_pf0);
 
-	tdi = pdev->tsm->tdi;
-	if (!tdi)
-		return -ENXIO;
-	return to_pci_tsm_ops(pdev->tsm)->guest_req(tdi, scope, req_in, in_len,
-						    req_out, out_len, tsm_code);
+struct pci_dev *pci_tsm_context_dsm_dev(struct pci_tsm_context *context)
+{
+	return context->dsm_dev;
 }
-EXPORT_SYMBOL_GPL(pci_tsm_guest_req);
+EXPORT_SYMBOL_GPL(pci_tsm_context_dsm_dev);
 
-static void pci_tsm_unbind_all(struct pci_dev *pdev)
+bool pci_tsm_context_match_device(struct pci_tsm_context *context,
+				  struct pci_dev *pdev)
 {
-	pci_tsm_walk_fns_reverse(pdev, __pci_tsm_unbind, NULL);
-	__pci_tsm_unbind(pdev, NULL);
+	guard(rwsem_read)(&pci_tsm_rwsem);
+
+	return pdev->tsm && is_link_tsm(pdev->tsm->tsm_dev) &&
+	       to_pci_tsm_pf0(pdev->tsm) == context->pf0;
 }
+EXPORT_SYMBOL_GPL(pci_tsm_context_match_device);
 
-static void __pci_tsm_disconnect(struct pci_dev *pdev)
+static int __pci_tsm_disconnect(struct pci_dev *pdev)
 {
 	struct pci_tsm_pf0 *tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
 	const struct pci_tsm_ops *ops = to_pci_tsm_ops(pdev->tsm);
@@ -449,21 +421,29 @@ static void __pci_tsm_disconnect(struct pci_dev *pdev)
 	/* disconnect() mutually exclusive with subfunction pci_tsm_init() */
 	lockdep_assert_held_write(&pci_tsm_rwsem);
 
-	pci_tsm_unbind_all(pdev);
-
 	/*
-	 * disconnect() is uninterruptible as it may be called for device
-	 * teardown
+	 * A vdevice holds a context for its lifetime. Refuse to tear down the
+	 * link until userspace destroys all dependent vdevices.
+	 *
+	 * disconnect() is uninterruptible as it may also be called for device
+	 * teardown.
 	 */
 	guard(mutex)(&tsm_pf0->lock);
+	if (tsm_pf0->context_users)
+		return -EBUSY;
 	pci_tsm_walk_fns_reverse(pdev, remove_fn, NULL);
 	ops->disconnect(pdev);
+	return 0;
 }
 
-static void pci_tsm_disconnect(struct pci_dev *pdev)
+static int pci_tsm_disconnect(struct pci_dev *pdev)
 {
-	__pci_tsm_disconnect(pdev);
+	int ret = __pci_tsm_disconnect(pdev);
+
+	if (ret)
+		return ret;
 	tsm_remove(pdev->tsm);
+	return 0;
 }
 
 static ssize_t disconnect_store(struct device *dev,
@@ -484,39 +464,17 @@ static ssize_t disconnect_store(struct device *dev,
 	tsm_dev = pdev->tsm->tsm_dev;
 	if (!sysfs_streq(buf, dev_name(&tsm_dev->dev)))
 		return -EINVAL;
+	if (is_link_tsm(tsm_dev) && is_pci_tsm_pf0(pdev) &&
+	    to_pci_tsm_pf0(pdev->tsm)->removing)
+		return -ENODEV;
 
-	pci_tsm_disconnect(pdev);
+	rc = pci_tsm_disconnect(pdev);
+	if (rc)
+		return rc;
 	return len;
 }
 static DEVICE_ATTR_WO(disconnect);
 
-static ssize_t bound_show(struct device *dev,
-			  struct device_attribute *attr, char *buf)
-{
-	struct pci_dev *pdev = to_pci_dev(dev);
-	struct pci_tsm_pf0 *tsm_pf0;
-	struct pci_tsm *tsm;
-	int rc;
-
-	ACQUIRE(rwsem_read_intr, lock)(&pci_tsm_rwsem);
-	if ((rc = ACQUIRE_ERR(rwsem_read_intr, &lock)))
-		return rc;
-
-	tsm = pdev->tsm;
-	if (!tsm)
-		return sysfs_emit(buf, "\n");
-	tsm_pf0 = to_pci_tsm_pf0(tsm);
-
-	ACQUIRE(mutex_intr, ops_lock)(&tsm_pf0->lock);
-	if ((rc = ACQUIRE_ERR(mutex_intr, &ops_lock)))
-		return rc;
-
-	if (!tsm->tdi)
-		return sysfs_emit(buf, "\n");
-	return sysfs_emit(buf, "%s\n", dev_name(&tsm->tsm_dev->dev));
-}
-static DEVICE_ATTR_RO(bound);
-
 static ssize_t dsm_show(struct device *dev, struct device_attribute *attr,
 			char *buf)
 {
@@ -571,13 +529,6 @@ static umode_t pci_tsm_attr_visible(struct kobject *kobj,
 	if (pci_tsm_link_group_visible(kobj)) {
 		struct pci_dev *pdev = to_pci_dev(kobj_to_dev(kobj));
 
-		if (attr == &dev_attr_bound.attr) {
-			if (is_pci_tsm_pf0(pdev) && has_tee(pdev))
-				return attr->mode;
-			if (pdev->tsm && has_tee(pdev->tsm->dsm_dev))
-				return attr->mode;
-		}
-
 		if (attr == &dev_attr_dsm.attr) {
 			if (is_pci_tsm_pf0(pdev))
 				return attr->mode;
@@ -604,7 +555,6 @@ DEFINE_SYSFS_GROUP_VISIBLE(pci_tsm);
 static struct attribute *pci_tsm_attrs[] = {
 	&dev_attr_connect.attr,
 	&dev_attr_disconnect.attr,
-	&dev_attr_bound.attr,
 	&dev_attr_dsm.attr,
 	NULL
 };
@@ -694,22 +644,6 @@ static struct pci_dev *find_dsm_dev(struct pci_dev *pdev)
 	return NULL;
 }
 
-/**
- * pci_tsm_tdi_constructor() - base 'struct pci_tdi' initialization for link TSMs
- * @pdev: PCI device function representing the TDI
- * @tdi: context to initialize
- * @kvm: Private memory attach context
- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM
- */
-void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi,
-			     struct kvm *kvm, u32 tdi_id)
-{
-	tdi->pdev = pdev;
-	tdi->kvm = kvm;
-	tdi->tdi_id = tdi_id;
-}
-EXPORT_SYMBOL_GPL(pci_tsm_tdi_constructor);
-
 /**
  * pci_tsm_link_constructor() - base 'struct pci_tsm' initialization for link TSMs
  * @pdev: The PCI device
@@ -744,6 +678,9 @@ int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm,
 			    struct tsm_dev *tsm_dev)
 {
 	mutex_init(&tsm->lock);
+	init_completion(&tsm->contexts_drained);
+	tsm->context_users = 0;
+	tsm->removing = false;
 	tsm->doe_mb = pci_find_doe_mailbox(pdev, PCI_VENDOR_ID_PCI_SIG,
 					   PCI_DOE_FEATURE_CMA);
 	if (!tsm->doe_mb) {
@@ -789,12 +726,6 @@ int pci_tsm_register(struct tsm_dev *tsm_dev)
 	return 0;
 }
 
-static void pci_tsm_fn_exit(struct pci_dev *pdev)
-{
-	__pci_tsm_unbind(pdev, NULL);
-	tsm_remove(pdev->tsm);
-}
-
 /**
  * __pci_tsm_destroy() - destroy the TSM context for @pdev
  * @pdev: device to cleanup
@@ -828,16 +759,54 @@ static void __pci_tsm_destroy(struct pci_dev *pdev, struct tsm_dev *tsm_dev)
 	else if (tsm_dev != tsm->tsm_dev)
 		return;
 
-	if (is_link_tsm(tsm_dev) && is_pci_tsm_pf0(pdev))
-		pci_tsm_disconnect(pdev);
-	else
-		pci_tsm_fn_exit(pdev);
+	if (is_link_tsm(tsm_dev) && is_pci_tsm_pf0(pdev)) {
+		if (pci_tsm_disconnect(pdev))
+			pci_warn(pdev, "TSM connection is still in use\n");
+	} else {
+		tsm_remove(pdev->tsm);
+	}
 }
 
 void pci_tsm_destroy(struct pci_dev *pdev)
 {
-	guard(rwsem_write)(&pci_tsm_rwsem);
+	struct pci_tsm_pf0 *pf0 = NULL;
+	struct completion *drained;
+	bool interrupted = false;
+	long rc;
+
+	down_write(&pci_tsm_rwsem);
+	if (pdev->tsm && is_link_tsm(pdev->tsm->tsm_dev) &&
+	    is_pci_tsm_pf0(pdev)) {
+		pf0 = to_pci_tsm_pf0(pdev->tsm);
+		drained = &pf0->contexts_drained;
+		mutex_lock(&pf0->lock);
+		pf0->removing = true;
+		mutex_unlock(&pf0->lock);
+
+		/* An unused DSM may never have completed contexts_drained. */
+		rc = pf0->context_users ?
+			try_wait_for_completion(drained) : 1;
+		/* Context release needs the read side of pci_tsm_rwsem. */
+		up_write(&pci_tsm_rwsem);
+		while (rc <= 0) {
+			if (interrupted) {
+				rc = wait_for_completion_timeout(drained, HZ * 10);
+			} else {
+				rc = wait_for_completion_interruptible_timeout(drained,
+									       HZ * 10);
+				if (rc < 0) {
+					interrupted = true;
+					pci_warn(pdev, "Task \"%s\" (%d) blocked until vdevices are released\n",
+						 current->comm, task_pid_nr(current));
+				}
+			}
+			if (!rc)
+				pci_warn(pdev, "TSM connection is in use, waiting for vdevices\n");
+		}
+		down_write(&pci_tsm_rwsem);
+	}
 	__pci_tsm_destroy(pdev, NULL);
+	up_write(&pci_tsm_rwsem);
 }
 
 void pci_tsm_init(struct pci_dev *pdev)
@@ -864,6 +833,9 @@ void pci_tsm_init(struct pci_dev *pdev)
 		 */
 		if (!dsm->tsm)
 			return;
+		if (is_link_tsm(dsm->tsm->tsm_dev) &&
+		    to_pci_tsm_pf0(dsm->tsm)->removing)
+			return;
 
 		probe_fn(pdev, dsm);
 	}
diff --git a/drivers/s390/crypto/vfio_ap_ops.c b/drivers/s390/crypto/vfio_ap_ops.c
index 4db878c18f41c..373ce574c4319 100644
--- a/drivers/s390/crypto/vfio_ap_ops.c
+++ b/drivers/s390/crypto/vfio_ap_ops.c
@@ -1822,17 +1822,27 @@ static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
 
 /**
  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
- * to manage AP resources for the guest whose state is represented by @kvm
+ * to manage AP resources for the guest whose state is represented by
+ * @kvm_file
  *
  * @matrix_mdev: a mediated matrix device
- * @kvm: reference to KVM instance
+ * @kvm_file: the KVM VM file this vfio device is associated with
  *
- * Return: 0 if no other mediated matrix device has a reference to @kvm;
+ * Return: 0 if no other mediated matrix device has a reference to the VM;
  * otherwise, returns an -EPERM.
  */
 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
-				struct kvm *kvm)
+				struct file *kvm_file)
 {
+	struct kvm *kvm;
+
+	if (!kvm_file)
+		return -ENOENT;
+
+	kvm = file_to_kvm_s390(kvm_file);
+	if (!kvm)
+		return -ENOENT;
+
 	if (kvm->arch.crypto.crycbd) {
 		get_update_locks_for_kvm(kvm);
 		if (kvm->arch.crypto.pqap_hook) {
@@ -1841,7 +1851,6 @@ static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
 		}
 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
 
-		kvm_get_kvm(kvm);
 		matrix_mdev->kvm = kvm;
 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
 		release_update_locks_for_kvm(kvm);
@@ -1894,7 +1903,6 @@ static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
 		matrix_mdev->kvm = NULL;
 
 		release_update_locks_for_kvm(kvm);
-		kvm_put_kvm(kvm);
 	}
 }
 
diff --git a/drivers/vfio/group.c b/drivers/vfio/group.c
index b2299e5bc6df3..5bf8cbdff377c 100644
--- a/drivers/vfio/group.c
+++ b/drivers/vfio/group.c
@@ -860,11 +860,20 @@ bool vfio_group_enforced_coherent(struct vfio_group *group)
 	return ret;
 }
 
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)
 {
+	struct file *old;
+
+	if (kvm)
+		get_file(kvm);
+
 	spin_lock(&group->kvm_ref_lock);
+	old = group->kvm;
 	group->kvm = kvm;
 	spin_unlock(&group->kvm_ref_lock);
+
+	if (old)
+		fput(old);
 }
 
 /**
diff --git a/drivers/vfio/iommufd.c b/drivers/vfio/iommufd.c
index e9893d34d07be..3beb1b1bae368 100644
--- a/drivers/vfio/iommufd.c
+++ b/drivers/vfio/iommufd.c
@@ -123,7 +123,8 @@ int vfio_iommufd_physical_bind(struct vfio_device *vdev,
 {
 	struct iommufd_device *idev;
 
-	idev = iommufd_device_bind(ictx, vdev->dev, out_device_id);
+	idev = iommufd_device_bind(ictx, vdev->dev, vdev->kvm,
+				   out_device_id);
 	if (IS_ERR(idev))
 		return PTR_ERR(idev);
 	vdev->iommufd_device = idev;
diff --git a/drivers/vfio/vfio.h b/drivers/vfio/vfio.h
index 7728bc99b63d1..9b619951a5d0c 100644
--- a/drivers/vfio/vfio.h
+++ b/drivers/vfio/vfio.h
@@ -23,7 +23,7 @@ struct vfio_device_file {
 	u8 access_granted;
 	u32 devid; /* only valid when iommufd is valid */
 	spinlock_t kvm_ref_lock; /* protect kvm field */
-	struct kvm *kvm;
+	struct file *kvm;
 	struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */
 };
 
@@ -88,7 +88,7 @@ struct vfio_group {
 #endif
 	enum vfio_group_type		type;
 	struct mutex			group_lock;
-	struct kvm			*kvm;
+	struct file			*kvm;
 	struct file			*opened_file;
 	struct iommufd_ctx		*iommufd;
 	spinlock_t			kvm_ref_lock;
@@ -107,7 +107,7 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device);
 void vfio_df_group_close(struct vfio_device_file *df);
 struct vfio_group *vfio_group_from_file(struct file *file);
 bool vfio_group_enforced_coherent(struct vfio_group *group);
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm);
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm);
 bool vfio_device_has_container(struct vfio_device *device);
 int __init vfio_group_init(void);
 void vfio_group_cleanup(void);
@@ -165,7 +165,7 @@ static inline bool vfio_group_enforced_coherent(struct vfio_group *group)
 	return true;
 }
 
-static inline void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)
+static inline void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)
 {
 }
 
@@ -429,11 +429,11 @@ static inline void vfio_virqfd_exit(void)
 #endif
 
 #if IS_ENABLED(CONFIG_KVM)
-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm);
+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm);
 void vfio_device_put_kvm(struct vfio_device *device);
 #else
 static inline void vfio_device_get_kvm_safe(struct vfio_device *device,
-					    struct kvm *kvm)
+					    struct file *kvm)
 {
 }
 
diff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c
index 423ead48aafe3..ed96acfa86358 100644
--- a/drivers/vfio/vfio_main.c
+++ b/drivers/vfio/vfio_main.c
@@ -472,36 +472,14 @@ void vfio_unregister_group_dev(struct vfio_device *device)
 EXPORT_SYMBOL_GPL(vfio_unregister_group_dev);
 
 #if IS_ENABLED(CONFIG_KVM)
-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm)
+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm)
 {
-	void (*pfn)(struct kvm *kvm);
-	bool (*fn)(struct kvm *kvm);
-	bool ret;
-
 	lockdep_assert_held(&device->dev_set->lock);
 
 	if (!kvm)
 		return;
 
-	pfn = symbol_get(kvm_put_kvm);
-	if (WARN_ON(!pfn))
-		return;
-
-	fn = symbol_get(kvm_get_kvm_safe);
-	if (WARN_ON(!fn)) {
-		symbol_put(kvm_put_kvm);
-		return;
-	}
-
-	ret = fn(kvm);
-	symbol_put(kvm_get_kvm_safe);
-	if (!ret) {
-		symbol_put(kvm_put_kvm);
-		return;
-	}
-
-	device->put_kvm = pfn;
-	device->kvm = kvm;
+	device->kvm = get_file(kvm);
 }
 
 void vfio_device_put_kvm(struct vfio_device *device)
@@ -511,14 +489,7 @@ void vfio_device_put_kvm(struct vfio_device *device)
 	if (!device->kvm)
 		return;
 
-	if (WARN_ON(!device->put_kvm))
-		goto clear;
-
-	device->put_kvm(device->kvm);
-	device->put_kvm = NULL;
-	symbol_put(kvm_put_kvm);
-
-clear:
+	fput(device->kvm);
 	device->kvm = NULL;
 }
 #endif
@@ -1544,9 +1515,13 @@ bool vfio_file_enforced_coherent(struct file *file)
 }
 EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);
 
-static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)
+static void vfio_device_file_set_kvm(struct file *file, struct file *kvm)
 {
 	struct vfio_device_file *df = file->private_data;
+	struct file *old;
+
+	if (kvm)
+		get_file(kvm);
 
 	/*
 	 * The kvm is first recorded in the vfio_device_file, and will
@@ -1554,28 +1529,32 @@ static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)
 	 * iommufd successfully in the vfio device cdev path.
 	 */
 	spin_lock(&df->kvm_ref_lock);
+	old = df->kvm;
 	df->kvm = kvm;
 	spin_unlock(&df->kvm_ref_lock);
+
+	if (old)
+		fput(old);
 }
 
 /**
  * vfio_file_set_kvm - Link a kvm with VFIO drivers
- * @file: VFIO group file or VFIO device file
- * @kvm: KVM to link
+ * @vfio_file: VFIO group file or VFIO device file
+ * @kvm: KVM file to link
  *
  * When a VFIO device is first opened the KVM will be available in
  * device->kvm if one was associated with the file.
  */
-void vfio_file_set_kvm(struct file *file, struct kvm *kvm)
+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)
 {
 	struct vfio_group *group;
 
-	group = vfio_group_from_file(file);
+	group = vfio_group_from_file(vfio_file);
 	if (group)
 		vfio_group_set_kvm(group, kvm);
 
-	if (vfio_device_from_file(file))
-		vfio_device_file_set_kvm(file, kvm);
+	if (vfio_device_from_file(vfio_file))
+		vfio_device_file_set_kvm(vfio_file, kvm);
 }
 EXPORT_SYMBOL_GPL(vfio_file_set_kvm);
 
diff --git a/drivers/virt/coco/tsm-core.c b/drivers/virt/coco/tsm-core.c
index e784993353d8f..2fce341ff9231 100644
--- a/drivers/virt/coco/tsm-core.c
+++ b/drivers/virt/coco/tsm-core.c
@@ -9,6 +9,16 @@
 #include <linux/cleanup.h>
 #include <linux/pci-tsm.h>
 
+/* The caller must hold a tsm_get_device() reference for the entire use. */
+const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,
+		struct device *dev, enum iommu_viommu_type type)
+{
+	if (!tsm_dev->pci_ops->viommu_get_ops)
+		return NULL;
+	return tsm_dev->pci_ops->viommu_get_ops(dev, type);
+}
+EXPORT_SYMBOL_GPL(tsm_viommu_get_ops);
+
 static void tsm_release(struct device *);
 static const struct class tsm_class = {
 	.name		= "tsm",
@@ -16,6 +26,29 @@ static const struct class tsm_class = {
 };
 static DEFINE_IDA(tsm_ida);
 
+/**
+ * tsm_get_device() - Pin the TSM attached to a device
+ * @dev: device whose TSM is to be pinned
+ *
+ * A successful lookup pins the backend module. Backends providing vIOMMU
+ * operations must not unregister their TSM independently of module unload.
+ * Return: NULL if no vIOMMU-capable TSM is attached, an error if the module
+ * cannot be pinned, or the TSM device associated with the pinned backend.
+ */
+struct tsm_dev *tsm_get_device(struct device *dev)
+{
+	if (!dev_is_pci(dev))
+		return NULL;
+	return pci_tsm_get_device(to_pci_dev(dev));
+}
+EXPORT_SYMBOL_GPL(tsm_get_device);
+
+void tsm_put_device(struct tsm_dev *tsm_dev)
+{
+	module_put(tsm_dev->pci_ops->owner);
+}
+EXPORT_SYMBOL_GPL(tsm_put_device);
+
 static int match_id(struct device *dev, const void *data)
 {
 	struct tsm_dev *tsm_dev = container_of(dev, struct tsm_dev, dev);
@@ -56,26 +89,25 @@ static struct tsm_dev *alloc_tsm_dev(struct device *parent)
 	return no_free_ptr(tsm_dev);
 }
 
-static struct tsm_dev *tsm_register_pci_or_reset(struct tsm_dev *tsm_dev,
-						 struct pci_tsm_ops *pci_ops)
+static int tsm_register_pci(struct tsm_dev *tsm_dev, struct pci_tsm_ops *pci_ops)
 {
 	int rc;
 
 	if (!pci_ops)
-		return tsm_dev;
+		return 0;
 
 	tsm_dev->pci_ops = pci_ops;
 	rc = pci_tsm_register(tsm_dev);
 	if (rc) {
+		tsm_dev->pci_ops = NULL;
 		dev_err(tsm_dev->dev.parent,
 			"PCI/TSM registration failure: %d\n", rc);
-		device_unregister(&tsm_dev->dev);
-		return ERR_PTR(rc);
+		return rc;
 	}
 
 	/* Notify TSM userspace that PCI/TSM operations are now possible */
 	kobject_uevent(&tsm_dev->dev.kobj, KOBJ_CHANGE);
-	return tsm_dev;
+	return 0;
 }
 
 struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *pci_ops)
@@ -96,15 +128,22 @@ struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *pci_ops)
 	if (rc)
 		return ERR_PTR(rc);
 
-	return tsm_register_pci_or_reset(no_free_ptr(tsm_dev), pci_ops);
+	rc = tsm_register_pci(tsm_dev, pci_ops);
+	if (rc) {
+		device_del(dev);
+		return ERR_PTR(rc);
+	}
+	return no_free_ptr(tsm_dev);
 }
 EXPORT_SYMBOL_GPL(tsm_register);
 
 void tsm_unregister(struct tsm_dev *tsm_dev)
 {
+	/* Remove the class lookup first. */
+	device_del(&tsm_dev->dev);
 	if (tsm_dev->pci_ops)
 		pci_tsm_unregister(tsm_dev);
-	device_unregister(&tsm_dev->dev);
+	put_device(&tsm_dev->dev);
 }
 EXPORT_SYMBOL_GPL(tsm_unregister);
 
diff --git a/include/linux/iommu.h b/include/linux/iommu.h
index ac43b8b93f14a..9931c96e5dd33 100644
--- a/include/linux/iommu.h
+++ b/include/linux/iommu.h
@@ -46,6 +46,7 @@ struct iommu_dma_msi_cookie;
 struct iommu_fault_param;
 struct iommufd_ctx;
 struct iommufd_viommu;
+struct iommufd_viommu_ops;
 struct msi_desc;
 struct msi_msg;
 
@@ -669,16 +670,8 @@ __iommu_copy_struct_to_user(const struct iommu_user_data *dst_data,
  *		- IOMMU_DOMAIN_DMA: must use a dma domain
  *		- 0: use the default setting
  * @default_domain_ops: the default ops for domains
- * @get_viommu_size: Get the size of a driver-level vIOMMU structure for a given
- *                   @dev corresponding to @viommu_type. Driver should return 0
- *                   if vIOMMU isn't supported accordingly. It is required for
- *                   driver to use the VIOMMU_STRUCT_SIZE macro to sanitize the
- *                   driver-level vIOMMU structure related to the core one
- * @viommu_init: Init the driver-level struct of an iommufd_viommu on a physical
- *               IOMMU instance @viommu->iommu_dev, as the set of virtualization
- *               resources shared/passed to user space IOMMU instance. Associate
- *               it with a nesting @parent_domain. It is required for driver to
- *               set @viommu->ops pointing to its own viommu_ops
+ * @get_viommu_ops: Return the vIOMMU operations supported by @dev for a type.
+ *                  Return NULL if the type is unsupported.
  * @owner: Driver module providing these ops
  * @identity_domain: An always available, always attachable identity
  *                   translation.
@@ -729,11 +722,8 @@ struct iommu_ops {
 
 	int (*def_domain_type)(struct device *dev);
 
-	size_t (*get_viommu_size)(struct device *dev,
-				  enum iommu_viommu_type viommu_type);
-	int (*viommu_init)(struct iommufd_viommu *viommu,
-			   struct iommu_domain *parent_domain,
-			   const struct iommu_user_data *user_data);
+	const struct iommufd_viommu_ops *(*get_viommu_ops)(
+		struct device *dev, enum iommu_viommu_type viommu_type);
 
 	const struct iommu_domain_ops *default_domain_ops;
 	struct module *owner;
diff --git a/include/linux/iommufd.h b/include/linux/iommufd.h
index 6e7efe83bc5d8..2e67846d6f35a 100644
--- a/include/linux/iommufd.h
+++ b/include/linux/iommufd.h
@@ -6,6 +6,7 @@
 #ifndef __LINUX_IOMMUFD_H
 #define __LINUX_IOMMUFD_H
 
+#include <linux/bits.h>
 #include <linux/err.h>
 #include <linux/errno.h>
 #include <linux/iommu.h>
@@ -23,7 +24,9 @@ struct iommufd_access;
 struct iommufd_ctx;
 struct iommufd_device;
 struct iommufd_viommu_ops;
+struct tsm_dev;
 struct page;
+struct tsm_guest_req_info;
 
 enum iommufd_object_type {
 	IOMMUFD_OBJ_NONE,
@@ -59,7 +62,9 @@ struct iommufd_object {
 };
 
 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
-					   struct device *dev, u32 *id);
+					   struct device *dev,
+					   struct file *kvm_file,
+					   u32 *id);
 void iommufd_device_unbind(struct iommufd_device *idev);
 
 int iommufd_device_attach(struct iommufd_device *idev, ioasid_t pasid,
@@ -99,8 +104,11 @@ void iommufd_ctx_get(struct iommufd_ctx *ictx);
 struct iommufd_viommu {
 	struct iommufd_object obj;
 	struct iommufd_ctx *ictx;
+	/* Physical IOMMU backing, or NULL. */
 	struct iommu_device *iommu_dev;
 	struct iommufd_hwpt_paging *hwpt;
+	struct file *kvm_file;
+	struct tsm_dev *tsm_dev;
 
 	const struct iommufd_viommu_ops *ops;
 
@@ -122,6 +130,10 @@ struct iommufd_vdevice {
 	 */
 	u64 virt_id;
 
+	/* Guest TSM requests accepted by this vdevice; set by vdevice_init(). */
+	u64 tsm_req_op_mask;
+	u32 tsm_tvm_arch;
+
 	/* Clean up all driver-specific parts of an iommufd_vdevice */
 	void (*destroy)(struct iommufd_vdevice *vdev);
 };
@@ -140,8 +152,19 @@ struct iommufd_hw_queue {
 	void (*destroy)(struct iommufd_hw_queue *hw_queue);
 };
 
+#define IOMMUFD_VIOMMU_NO_HWPT	BIT(0)
+
 /**
  * struct iommufd_viommu_ops - vIOMMU specific operations
+ * @flags: Properties needed by the core before vIOMMU initialization
+ * @get_viommu_size: Get the size of a driver-level vIOMMU structure for a given
+ *                   @dev corresponding to @viommu_type. Driver should return 0
+ *                   if vIOMMU isn't supported accordingly. It is required for
+ *                   driver to use the VIOMMU_STRUCT_SIZE macro to sanitize the
+ *                   driver-level vIOMMU structure related to the core one
+ * @viommu_init: Initialize the selected driver-level iommufd_viommu for @dev.
+ *               @parent_domain is the nesting parent, or NULL for an
+ *               implementation that does not use a parent HWPT.
  * @destroy: Clean up all driver-specific parts of an iommufd_viommu. The memory
  *           of the vIOMMU will be free-ed by iommufd core after calling this op
  * @alloc_domain_nested: Allocate a IOMMU_DOMAIN_NESTED on a vIOMMU that holds a
@@ -164,6 +187,7 @@ struct iommufd_hw_queue {
  *                include/uapi/linux/iommufd.h)
  *                If driver has a deinit function to revert what vdevice_init op
  *                does, it should set it to the @vdev->destroy function pointer
+ * @vdevice_tsm_req: Forward a guest TSM request to a driver-owned vDEVICE
  * @get_hw_queue_size: Get the size of a driver-defined HW queue structure for a
  *                     given @viommu corresponding to @queue_type. Driver should
  *                     return 0 if HW queue aren't supported accordingly. It is
@@ -182,6 +206,12 @@ struct iommufd_hw_queue {
  *                      does, it should set it to the @hw_queue->destroy pointer
  */
 struct iommufd_viommu_ops {
+	unsigned long flags;
+	size_t (*get_viommu_size)(struct device *dev,
+		enum iommu_viommu_type type);
+	int (*viommu_init)(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data);
 	void (*destroy)(struct iommufd_viommu *viommu);
 	struct iommu_domain *(*alloc_domain_nested)(
 		struct iommufd_viommu *viommu, u32 flags,
@@ -190,6 +220,9 @@ struct iommufd_viommu_ops {
 				struct iommu_user_data_array *array);
 	const size_t vdevice_size;
 	int (*vdevice_init)(struct iommufd_vdevice *vdev);
+	ssize_t (*vdevice_tsm_req)(struct iommufd_vdevice *vdev,
+				   struct tsm_guest_req_info *info,
+				   u64 *tsm_code);
 	size_t (*get_hw_queue_size)(struct iommufd_viommu *viommu,
 				    enum iommu_hw_queue_type queue_type);
 	/* AMD's HW will add hw_queue_init simply using @hw_queue->base_addr */
diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
index cf7fe835c4ad2..586f6e8bb81b3 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -784,6 +784,12 @@ struct kvm {
 	 * kvm_swap_active_memslots().
 	 */
 	struct mutex slots_arch_lock;
+	/*
+	 * Back-reference to the VM file for subsystems (e.g., VFIO). Holds no
+	 * reference to avoid pinning the VM. Callers storing the file must
+	 * take their own reference.
+	 */
+	struct file *file;
 	struct mm_struct *mm; /* userspace tied to this vm */
 	unsigned long nr_memslot_pages;
 	/* The two memslot sets - active and inactive (per address space) */
@@ -1081,7 +1087,18 @@ void kvm_exit(void);
 void kvm_get_kvm(struct kvm *kvm);
 bool kvm_get_kvm_safe(struct kvm *kvm);
 void kvm_put_kvm(struct kvm *kvm);
-bool file_is_kvm(struct file *file);
+
+/*
+ * Architectures define kvm_file_to_kvm_arch to <arch>
+ * to get a typed, arch-namespaced helper:
+ *
+ *   struct kvm *file_to_kvm_<arch>(struct file *file)
+ */
+#ifdef kvm_file_to_kvm_arch
+#define kvm_file_to_kvm_fn CONCATENATE(file_to_kvm_, kvm_file_to_kvm_arch)
+struct kvm *kvm_file_to_kvm_fn(struct file *file);
+#endif /* kvm_file_to_kvm_arch */
+
 void kvm_put_kvm_no_destroy(struct kvm *kvm);
 
 static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id)
diff --git a/include/linux/pci-tsm.h b/include/linux/pci-tsm.h
index a6435aba03f9b..3adc317d0f9bc 100644
--- a/include/linux/pci-tsm.h
+++ b/include/linux/pci-tsm.h
@@ -1,14 +1,15 @@
 /* SPDX-License-Identifier: GPL-2.0 */
 #ifndef __PCI_TSM_H
 #define __PCI_TSM_H
+#include <linux/completion.h>
 #include <linux/mutex.h>
 #include <linux/pci.h>
-#include <linux/sockptr.h>
 
+struct iommufd_viommu_ops;
+struct module;
 struct pci_tsm;
+struct pci_tsm_context;
 struct tsm_dev;
-struct kvm;
-enum pci_tsm_req_scope;
 
 /*
  * struct pci_tsm_ops - manage confidential links and security state
@@ -18,12 +19,26 @@ enum pci_tsm_req_scope;
  * @devsec_ops: Lock, unlock, and interrogate the security state of the
  *		function via the platform TSM (typically virtual function
  *		operations).
+ * @viommu_get_ops: Return operations for a supported TSM-owned vIOMMU type,
+ *		  or NULL if unsupported
+ * @owner: Module providing the vIOMMU operations, if built as a module
+ *
+ * The vIOMMU owner pins the backend module before querying @viommu_get_ops
+ * and releases it after vIOMMU destruction. A backend providing this callback
+ * must not unregister its TSM while the module is pinned.
  *
  * This operations are mutually exclusive either a tsm_dev instance
  * manages physical link properties or it manages function security
  * states like TDISP lock/unlock.
+ *
+ * @viommu_get_ops runs with the backend module pinned. The PCI/TSM
+ * association is checked during acquisition under pci_tsm_rwsem.
  */
 struct pci_tsm_ops {
+	struct module *owner;
+	const struct iommufd_viommu_ops *(*viommu_get_ops)(
+		struct device *dev, enum iommu_viommu_type type);
+
 	/*
 	 * struct pci_tsm_link_ops - Manage physical link and the TSM/DSM session
 	 * @probe: establish context with the TSM (allocate / wrap 'struct
@@ -32,17 +47,12 @@ struct pci_tsm_ops {
 	 * @connect: establish / validate a secure connection (e.g. IDE)
 	 *	     with the device
 	 * @disconnect: teardown the secure link
-	 * @bind: bind a TDI in preparation for it to be accepted by a TVM
-	 * @unbind: remove a TDI from secure operation with a TVM
-	 * @guest_req: marshal TVM information and state change requests
 	 *
 	 * Context: @probe, @remove, @connect, and @disconnect run under
 	 * pci_tsm_rwsem held for write to sync with TSM unregistration and
 	 * mutual exclusion of @connect and @disconnect. @connect and
 	 * @disconnect additionally run under the DSM lock (struct
 	 * pci_tsm_pf0::lock) as well as @probe and @remove of the subfunctions.
-	 * @bind, @unbind, and @guest_req run under pci_tsm_rwsem held for read
-	 * and the DSM lock.
 	 */
 	struct_group_tagged(pci_tsm_link_ops, link_ops,
 		struct pci_tsm *(*probe)(struct tsm_dev *tsm_dev,
@@ -50,14 +60,6 @@ struct pci_tsm_ops {
 		void (*remove)(struct pci_tsm *tsm);
 		int (*connect)(struct pci_dev *pdev);
 		void (*disconnect)(struct pci_dev *pdev);
-		struct pci_tdi *(*bind)(struct pci_dev *pdev,
-					struct kvm *kvm, u32 tdi_id);
-		void (*unbind)(struct pci_tdi *tdi);
-		ssize_t (*guest_req)(struct pci_tdi *tdi,
-				     enum pci_tsm_req_scope scope,
-				     sockptr_t req_in, size_t in_len,
-				     sockptr_t req_out, size_t out_len,
-				     u64 *tsm_code);
 	);
 
 	/*
@@ -77,25 +79,12 @@ struct pci_tsm_ops {
 	);
 };
 
-/**
- * struct pci_tdi - Core TEE I/O Device Interface (TDI) context
- * @pdev: host side representation of guest-side TDI
- * @kvm: TEE VM context of bound TDI
- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM
- */
-struct pci_tdi {
-	struct pci_dev *pdev;
-	struct kvm *kvm;
-	u32 tdi_id;
-};
-
 /**
  * struct pci_tsm - Core TSM context for a given PCIe endpoint
  * @pdev: Back ref to device function, distinguishes type of pci_tsm context
  * @dsm_dev: PCI Device Security Manager for link operations on @pdev
  * @tsm_dev: PCI TEE Security Manager device for Link Confidentiality or Device
  *	     Function Security operations
- * @tdi: TDI context established by the @bind link operation
  *
  * This structure is wrapped by low level TSM driver data and returned by
  * probe()/lock(), it is freed by the corresponding remove()/unlock().
@@ -111,18 +100,24 @@ struct pci_tsm {
 	struct pci_dev *pdev;
 	struct pci_dev *dsm_dev;
 	struct tsm_dev *tsm_dev;
-	struct pci_tdi *tdi;
 };
 
 /**
  * struct pci_tsm_pf0 - Physical Function 0 TDISP link context
  * @base_tsm: generic core "tsm" context
  * @lock: mutual exclustion for pci_tsm_ops invocation
+ * @context_users: live per-function contexts on this PF0; a nonzero count
+ *	blocks link disconnect
+ * @contexts_drained: completed when the last context is released
+ * @removing: reject new contexts while the DSM is being removed
  * @doe_mb: PCIe Data Object Exchange mailbox
  */
 struct pci_tsm_pf0 {
 	struct pci_tsm base_tsm;
 	struct mutex lock;
+	unsigned int context_users;
+	struct completion contexts_drained;
+	bool removing;
 	struct pci_doe_mb *doe_mb;
 };
 
@@ -159,46 +154,6 @@ static inline bool is_pci_tsm_pf0(struct pci_dev *pdev)
 	return PCI_FUNC(pdev->devfn) == 0;
 }
 
-/**
- * enum pci_tsm_req_scope - Scope of guest requests to be validated by TSM
- *
- * Guest requests are a transport for a TVM to communicate with a TSM + DSM for
- * a given TDI. A TSM driver is responsible for maintaining the kernel security
- * model and limit commands that may affect the host, or are otherwise outside
- * the typical TDISP operational model.
- */
-enum pci_tsm_req_scope {
-	/**
-	 * @PCI_TSM_REQ_INFO: Read-only, without side effects, request for
-	 * typical TDISP collateral information like Device Interface Reports.
-	 * No device secrets are permitted, and no device state is changed.
-	 */
-	PCI_TSM_REQ_INFO = 0,
-	/**
-	 * @PCI_TSM_REQ_STATE_CHANGE: Request to change the TDISP state from
-	 * UNLOCKED->LOCKED, LOCKED->RUN, or other architecture specific state
-	 * changes to support those transitions for a TDI. No other (unrelated
-	 * to TDISP) device / host state, configuration, or data change is
-	 * permitted.
-	 */
-	PCI_TSM_REQ_STATE_CHANGE = 1,
-	/**
-	 * @PCI_TSM_REQ_DEBUG_READ: Read-only request for debug information
-	 *
-	 * A method to facilitate TVM information retrieval outside of typical
-	 * TDISP operational requirements. No device secrets are permitted.
-	 */
-	PCI_TSM_REQ_DEBUG_READ = 2,
-	/**
-	 * @PCI_TSM_REQ_DEBUG_WRITE: Device state changes for debug purposes
-	 *
-	 * The request may affect the operational state of the device outside of
-	 * the TDISP operational model. If allowed, requires CAP_SYS_RAW_IO, and
-	 * will taint the kernel.
-	 */
-	PCI_TSM_REQ_DEBUG_WRITE = 3,
-};
-
 #ifdef CONFIG_PCI_TSM
 int pci_tsm_register(struct tsm_dev *tsm_dev);
 void pci_tsm_unregister(struct tsm_dev *tsm_dev);
@@ -209,13 +164,15 @@ int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm,
 void pci_tsm_pf0_destructor(struct pci_tsm_pf0 *tsm);
 int pci_tsm_doe_transfer(struct pci_dev *pdev, u8 type, const void *req,
 			 size_t req_sz, void *resp, size_t resp_sz);
-int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id);
-void pci_tsm_unbind(struct pci_dev *pdev);
-void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi,
-			     struct kvm *kvm, u32 tdi_id);
-ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope,
-			  sockptr_t req_in, size_t in_len, sockptr_t req_out,
-			  size_t out_len, u64 *tsm_code);
+bool pci_tsm_is_configured(struct pci_dev *pdev);
+struct pci_tsm_context *pci_tsm_context_get(struct pci_dev *pdev,
+					    struct tsm_dev *viommu_tsm_dev);
+void pci_tsm_context_put(struct pci_tsm_context *context);
+struct pci_tsm_pf0 *pci_tsm_context_pf0(struct pci_tsm_context *context);
+struct pci_dev *pci_tsm_context_dsm_dev(struct pci_tsm_context *context);
+bool pci_tsm_context_match_device(struct pci_tsm_context *context,
+				  struct pci_dev *pdev);
+struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev);
 #else
 static inline int pci_tsm_register(struct tsm_dev *tsm_dev)
 {
@@ -224,20 +181,44 @@ static inline int pci_tsm_register(struct tsm_dev *tsm_dev)
 static inline void pci_tsm_unregister(struct tsm_dev *tsm_dev)
 {
 }
-static inline int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u64 tdi_id)
+
+static inline bool pci_tsm_is_configured(struct pci_dev *pdev)
 {
-	return -ENXIO;
+	return false;
 }
-static inline void pci_tsm_unbind(struct pci_dev *pdev)
+
+static inline struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)
 {
+	return NULL;
 }
-static inline ssize_t pci_tsm_guest_req(struct pci_dev *pdev,
-					enum pci_tsm_req_scope scope,
-					sockptr_t req_in, size_t in_len,
-					sockptr_t req_out, size_t out_len,
-					u64 *tsm_code)
+
+static inline struct pci_tsm_context *
+pci_tsm_context_get(struct pci_dev *pdev, struct tsm_dev *viommu_tsm_dev)
+{
+	return ERR_PTR(-EOPNOTSUPP);
+}
+
+static inline void pci_tsm_context_put(struct pci_tsm_context *context)
+{
+}
+
+static inline struct pci_tsm_pf0 *
+pci_tsm_context_pf0(struct pci_tsm_context *context)
+{
+	return NULL;
+}
+
+static inline struct pci_dev *
+pci_tsm_context_dsm_dev(struct pci_tsm_context *context)
+{
+	return NULL;
+}
+
+static inline bool
+pci_tsm_context_match_device(struct pci_tsm_context *context,
+			     struct pci_dev *pdev)
 {
-	return -ENXIO;
+	return false;
 }
 #endif
 #endif /*__PCI_TSM_H */
diff --git a/include/linux/tsm.h b/include/linux/tsm.h
index 381c53244c835..e5d14f9a23e9f 100644
--- a/include/linux/tsm.h
+++ b/include/linux/tsm.h
@@ -6,6 +6,7 @@
 #include <linux/types.h>
 #include <linux/uuid.h>
 #include <linux/device.h>
+#include <uapi/linux/iommufd.h>
 
 #define TSM_REPORT_INBLOB_MAX 64
 #define TSM_REPORT_OUTBLOB_MAX SZ_16M
@@ -109,6 +110,8 @@ struct tsm_report_ops {
 };
 
 struct pci_tsm_ops;
+struct iommufd_viommu_ops;
+
 struct tsm_dev {
 	struct device dev;
 	int id;
@@ -123,4 +126,47 @@ int tsm_report_unregister(const struct tsm_report_ops *ops);
 struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *ops);
 void tsm_unregister(struct tsm_dev *tsm_dev);
 struct tsm_dev *find_tsm_dev(int id);
+
+#ifdef CONFIG_TSM
+struct tsm_dev *tsm_get_device(struct device *dev);
+void tsm_put_device(struct tsm_dev *tsm_dev);
+const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,
+		struct device *dev, enum iommu_viommu_type type);
+
+/**
+ * struct tsm_guest_req_info - parameters for a guest-initiated TSM request
+ * @op: operation for the guest-initiated request
+ * @tvm_arch: guest TVM architecture
+ * @req: userspace buffer containing the guest request
+ * @req_len: request size in bytes, at most INT_MAX
+ * @resp: userspace buffer for the response
+ * @resp_len: response buffer capacity in bytes, at most INT_MAX
+ */
+struct tsm_guest_req_info {
+	enum iommu_vdevice_tsm_guest_req_op op;
+	enum iommu_vdevice_tsm_guest_tvm_arch tvm_arch;
+	const void __user *req;
+	u32 req_len;
+	void __user *resp;
+	u32 resp_len;
+};
+#else
+static inline struct tsm_dev *tsm_get_device(struct device *dev)
+{
+	return NULL;
+}
+
+static inline void tsm_put_device(struct tsm_dev *tsm_dev)
+{
+}
+
+static inline const struct iommufd_viommu_ops *
+tsm_viommu_get_ops(struct tsm_dev *tsm_dev, struct device *dev,
+		enum iommu_viommu_type type)
+{
+	return NULL;
+}
+
+struct tsm_guest_req_info;
+#endif
 #endif /* __TSM_H */
diff --git a/include/linux/vfio.h b/include/linux/vfio.h
index 45f08986359e4..0cc91c6f96d2b 100644
--- a/include/linux/vfio.h
+++ b/include/linux/vfio.h
@@ -54,7 +54,7 @@ struct vfio_device {
 	struct list_head dev_set_list;
 	unsigned int migration_flags;
 	u8 precopy_info_v2;
-	struct kvm *kvm;
+	struct file *kvm;
 
 	/* Members below here are private, not for driver use */
 	unsigned int index;
@@ -66,7 +66,6 @@ struct vfio_device {
 	unsigned int open_count;
 	struct completion comp;
 	struct iommufd_access *iommufd_access;
-	void (*put_kvm)(struct kvm *kvm);
 	struct inode *inode;
 #if IS_ENABLED(CONFIG_IOMMUFD)
 	struct iommufd_device *iommufd_device;
@@ -378,7 +377,7 @@ static inline bool vfio_file_has_dev(struct file *file, struct vfio_device *devi
 #endif
 bool vfio_file_is_valid(struct file *file);
 bool vfio_file_enforced_coherent(struct file *file);
-void vfio_file_set_kvm(struct file *file, struct kvm *kvm);
+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm);
 
 #define VFIO_PIN_PAGES_MAX_ENTRIES	(PAGE_SIZE/sizeof(unsigned long))
 
diff --git a/include/uapi/linux/iommufd.h b/include/uapi/linux/iommufd.h
index 206fa667c7828..3d1ebbdf39488 100644
--- a/include/uapi/linux/iommufd.h
+++ b/include/uapi/linux/iommufd.h
@@ -58,6 +58,7 @@ enum {
 	IOMMUFD_CMD_VEVENTQ_ALLOC = 0x93,
 	IOMMUFD_CMD_HW_QUEUE_ALLOC = 0x94,
 	IOMMUFD_CMD_IOAS_NOIOMMU_GET_PA = 0x95,
+	IOMMUFD_CMD_VDEVICE_TSM_REQ = 0x96,
 };
 
 /**
@@ -1129,7 +1130,8 @@ struct iommu_viommu_tegra241_cmdqv {
  * @flags: Must be 0
  * @type: Type of the virtual IOMMU. Must be defined in enum iommu_viommu_type
  * @dev_id: The device's physical IOMMU will be used to back the virtual IOMMU
- * @hwpt_id: ID of a nesting parent HWPT to associate to
+ * @hwpt_id: ID of a nesting parent HWPT to associate to. Must be zero when the
+ *           selected vIOMMU implementation does not use a parent HWPT
  * @out_viommu_id: Output virtual IOMMU ID for the allocated object
  * @data_len: Length of the type specific data
  * @__reserved: Must be 0
@@ -1390,4 +1392,85 @@ struct iommu_hw_queue_alloc {
 	__aligned_u64 length;
 };
 #define IOMMU_HW_QUEUE_ALLOC _IO(IOMMUFD_TYPE, IOMMUFD_CMD_HW_QUEUE_ALLOC)
+
+/**
+ * enum iommu_vdevice_tsm_guest_tvm_arch - guest TVM architecture
+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_CCA: Arm CCA TVM
+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_SEV: AMD SEV TVM
+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_TDX: Intel TDX TVM
+ */
+enum iommu_vdevice_tsm_guest_tvm_arch {
+	IOMMU_VDEVICE_TSM_TVM_ARCH_CCA = 1,
+	IOMMU_VDEVICE_TSM_TVM_ARCH_SEV,
+	IOMMU_VDEVICE_TSM_TVM_ARCH_TDX,
+};
+
+/**
+ * enum iommu_vdevice_tsm_guest_req_op - Guest TSM request operations
+ * @TSM_REQ_VALIDATE_MMIO: Validate and map a guest MMIO range for the trusted
+ *                         device.
+ * @TSM_REQ_SET_TDI_STATE: Transition the trusted device to the unlocked,
+ *                         locked, or running state.
+ * @TSM_REQ_SEV_ENABLE_DMA: Enable DMA for an SEV device.
+ * @TSM_REQ_SEV_DISABLE_DMA: Disable DMA for an SEV device.
+ * @TSM_REQ_READ_OBJECT: Read bytes from a device object, such as a certificate,
+ *                       measurement, or interface report.
+ * @TSM_REQ_REGEN_OBJECT: Regenerate a device object, such as a measurement or
+ *                        interface report.
+ * @TSM_REQ_OBJECT_INFO: Query the size of a device object.
+ * @TSM_REQ_MAX: One past the last request operation; not a command.
+ *
+ * The request payload and response format depend on the TVM architecture.
+ */
+enum iommu_vdevice_tsm_guest_req_op {
+	TSM_REQ_VALIDATE_MMIO = 1,
+	TSM_REQ_SET_TDI_STATE,
+	TSM_REQ_SEV_ENABLE_DMA,
+	TSM_REQ_SEV_DISABLE_DMA,
+	TSM_REQ_READ_OBJECT,
+	TSM_REQ_REGEN_OBJECT,
+	TSM_REQ_OBJECT_INFO,
+	TSM_REQ_MAX,
+};
+
+/**
+ * struct iommu_vdevice_tsm_req - ioctl(IOMMU_VDEVICE_TSM_REQ)
+ * @size: sizeof(struct iommu_vdevice_tsm_req)
+ * @vdevice_id: vDevice ID the guest request is for
+ * @op: One of enum iommu_vdevice_tsm_guest_req_op, excluding TSM_REQ_MAX
+ * @tvm_arch: One of enum iommu_vdevice_tsm_guest_tvm_arch
+ * @req_len: Size in bytes of the input payload at @req_uptr, at most INT_MAX
+ * @resp_len: Size in bytes of the output buffer at @resp_uptr, at most INT_MAX
+ * @req_uptr: Userspace pointer to the guest-provided request payload
+ * @resp_uptr: Userspace pointer to the guest response buffer
+ * @out_tsm_code: TSM-specific result code returned by the TSM implementation
+ *
+ * Forward a TSM request to the TSM bound vDevice. This is intended for
+ * guest TSM/TDISP message transport where the host kernel only marshals
+ * bytes between userspace and the TSM implementation.
+ *
+ * The request operation is guest initiated. The vDEVICE implementation
+ * declares the TVM architecture and operations it accepts; iommufd checks
+ * both before forwarding the request.
+ *
+ * The request payload is read from @req_uptr/@req_len. If a response is
+ * expected, userspace provides @resp_uptr/@resp_len as writable storage for
+ * response bytes returned by the TSM path.
+ *
+ * The ioctl is only suitable for commands and results that the host kernel
+ * has no use, the host is only facilitating guest to TSM communication.
+ */
+struct iommu_vdevice_tsm_req {
+	__u32 size;
+	__u32 vdevice_id;
+	__u32 op;
+	__u32 tvm_arch;
+	__u32 req_len;
+	__u32 resp_len;
+	__aligned_u64 req_uptr;
+	__aligned_u64 resp_uptr;
+	__aligned_u64 out_tsm_code;
+};
+
+#define IOMMU_VDEVICE_TSM_REQ _IO(IOMMUFD_TYPE, IOMMUFD_CMD_VDEVICE_TSM_REQ)
 #endif
diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index 85f42289748dc..60e614795a36c 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -1314,7 +1314,7 @@ void kvm_get_kvm(struct kvm *kvm)
 {
 	refcount_inc(&kvm->users_count);
 }
-EXPORT_SYMBOL_GPL(kvm_get_kvm);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm);
 
 /*
  * Make sure the vm is not during destruction, which is a safe version of
@@ -1324,14 +1324,14 @@ bool kvm_get_kvm_safe(struct kvm *kvm)
 {
 	return refcount_inc_not_zero(&kvm->users_count);
 }
-EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm_safe);
 
 void kvm_put_kvm(struct kvm *kvm)
 {
 	if (refcount_dec_and_test(&kvm->users_count))
 		kvm_destroy_vm(kvm);
 }
-EXPORT_SYMBOL_GPL(kvm_put_kvm);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_put_kvm);
 
 /*
  * Used to put a reference that was taken on behalf of an object associated
@@ -1352,6 +1352,8 @@ static int kvm_vm_release(struct inode *inode, struct file *filp)
 
 	kvm_irqfd_release(kvm);
 
+	WRITE_ONCE(kvm->file, NULL);
+
 	kvm_put_kvm(kvm);
 	return 0;
 }
@@ -5513,11 +5515,16 @@ static struct file_operations kvm_vm_fops = {
 	KVM_COMPAT(kvm_vm_compat_ioctl),
 };
 
-bool file_is_kvm(struct file *file)
+#ifdef kvm_file_to_kvm_arch
+struct kvm *kvm_file_to_kvm_fn(struct file *file)
 {
-	return file && file->f_op == &kvm_vm_fops;
+	if (!file || file->f_op != &kvm_vm_fops)
+		return NULL;
+
+	return file->private_data;
 }
-EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_is_kvm);
+EXPORT_SYMBOL_GPL(kvm_file_to_kvm_fn);
+#endif
 
 static int kvm_dev_ioctl_create_vm(unsigned long type)
 {
@@ -5544,6 +5551,8 @@ static int kvm_dev_ioctl_create_vm(unsigned long type)
 		goto put_kvm;
 	}
 
+	kvm->file = file;
+
 	/*
 	 * Don't call kvm_put_kvm anymore at this point; file->f_op is
 	 * already set, with ->release() being kvm_vm_release().  In error
diff --git a/virt/kvm/vfio.c b/virt/kvm/vfio.c
index 6cdc4e9a333a3..19548a4309426 100644
--- a/virt/kvm/vfio.c
+++ b/virt/kvm/vfio.c
@@ -35,15 +35,15 @@ struct kvm_vfio {
 	bool noncoherent;
 };
 
-static void kvm_vfio_file_set_kvm(struct file *file, struct kvm *kvm)
+static void kvm_vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)
 {
-	void (*fn)(struct file *file, struct kvm *kvm);
+	void (*fn)(struct file *vfio_file, struct file *kvm);
 
 	fn = symbol_get(vfio_file_set_kvm);
 	if (!fn)
 		return;
 
-	fn(file, kvm);
+	fn(vfio_file, kvm);
 
 	symbol_put(vfio_file_set_kvm);
 }
@@ -144,6 +144,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 {
 	struct kvm_vfio *kv = dev->private;
 	struct kvm_vfio_file *kvf;
+	struct file *kvm_file __free(fput) = NULL;
 	struct file *filp __free(fput) = NULL;
 
 	filp = fget(fd);
@@ -154,6 +155,10 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 	if (!kvm_vfio_file_is_valid(filp))
 		return -EINVAL;
 
+	kvm_file = get_file_active(&dev->kvm->file);
+	if (!kvm_file)
+		return -ENOENT;
+
 	guard(mutex)(&kv->lock);
 
 	list_for_each_entry(kvf, &kv->file_list, node) {
@@ -168,7 +173,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 	kvf->file = get_file(filp);
 	list_add_tail(&kvf->node, &kv->file_list);
 
-	kvm_vfio_file_set_kvm(kvf->file, dev->kvm);
+	kvm_vfio_file_set_kvm(kvf->file, kvm_file);
 	kvm_vfio_update_coherency(dev);
 
 	return 0;

3/2 2026/10/08 06:59 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44374
							output: 38
							thoughts: 1611
						

Thoughts:
**Fuzzing Recommendation: A Definite Yes**

Alright, let's dive into this patch series. My initial thought is that we should definitely consider it for fuzzing with syzkaller. The target architecture is amd64, which is great.

First, I need to inspect the diff to understand the scope of the changes. The patch touches a broad area, but the keywords are KVM, VFIO, and IOMMUFD. That's a strong indicator. Specifically, the patch touches:

*   **Documentation:** Updates to ABI and user-space API documentation related to PCI, iommufd.
*   **Architecture-Specific KVM:** Changes in `arch/s390` and significant updates to `arch/x86`, which includes changes to file-to-kvm handling and page tracking, critical for hypervisor functionality. Especially the addition of functions that take `struct file *file` instead of `struct kvm *kvm` and x86 SEV enc context ioctls.
*   **IOMMU Drivers:** Modification of AMD IOMMU, ARM SMMU, and Tegra241 IOMMU drivers, along with a new file `tsm.c` within `iommufd`, which seems to involve Transactional Memory (TSM). The core of IOMMUFD is heavily modified, including ioctls for viommu allocation, vdevice allocation, and hardware queue allocation, and hardware page table allocation, plus selftests.
*   **PCI Drivers:** Updates to the TSM driver.
*   **VFIO Drivers:** Significant changes to VFIO and IOMMUFD integration.
*   **Kernel Core:** Includes updates to core KVM and VFIO code within `virt/kvm/` and `virt/vfio/`.

Now, the crucial question is, are these modified components reachable in a fuzzable environment? Absolutely. KVM is already extensively fuzzed through `/dev/kvm`. IOMMUFD, and VFIO, are also reachable, via `/dev/iommu` and mock devices or test devices, plus the selftests are a big plus. The presence of `drivers/iommu/iommufd/selftest.c` confirms this, with the mock viommu ops and core iommufd ioctls like `iommufd_viommu_alloc_ioctl`, `iommufd_vdevice_alloc_ioctl`, and more. KVM's side of things exposes ioctls like `kvm_dev_ioctl_create_vm`, `kvm_vm_release` that can be targeted. VFIO also exposes  `KVM_SET_DEVICE_ATTR` which supports vfio.

This patch changes the core of KVM, VFIO, and IOMMUFD functionality. The introduction of TSM and the integration between these components warrants thorough fuzzing.

My next step is to examine the specific changes in detail. I need to understand exactly what was modified, how these code paths are reached, the required kernel configurations, and what key symbols or ioctls to focus on for syzkaller. I'll need to do some code archaeology using grepper or `read-file` to get a precise understanding of the attack surface.



4/2 2026/10/08 07:00 tool grepper
0m Args:
{
  "Expression": "CONFIG_IOMMUFD",
  "PathPrefixes": [
    "drivers/iommu/iommufd/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 244 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (9 files in total):\ndrivers/iommu/iommufd/Makefile:5\ndrivers/iommu/iommufd/device.c:2\ndrivers/iommu/iommufd/hw_pagetable.c:1\ndrivers/iommu/iommufd/io_pagetable.c:6\ndrivers/iommu/iommufd/io_pagetable.h:1\ndrivers/iommu/iommufd/ioas.c:1\ndrivers/iommu/iommufd/iommufd_private.h:4\ndrivers/iommu/iommufd/main.c:8\ndrivers/iommu/iommufd/pages.c:18\n\ndrivers/iommu/iommufd/Makefile=2=iommufd-y := \\\n--\ndrivers/iommu/iommufd/Makefile-12-\ndrivers/iommu/iommufd/Makefile:13:iommufd-$(CONFIG_IOMMUFD_NOIOMMU) += hwpt_noiommu.o\ndrivers/iommu/iommufd/Makefile-14-iommufd-$(CONFIG_TSM) += tsm.o\ndrivers/iommu/iommufd/Makefile-15-\ndrivers/iommu/iommufd/Makefile:16:iommufd-$(CONFIG_IOMMUFD_TEST) += selftest.o\ndrivers/iommu/iommufd/Makefile-17-\ndrivers/iommu/iommufd/Makefile:18:obj-$(CONFIG_IOMMUFD) += iommufd.o\ndrivers/iommu/iommufd/Makefile:19:obj-$(CONFIG_IOMMUFD_DRIVER) += iova_bitmap.o\ndrivers/iommu/iommufd/Makefile-20-\ndrivers/iommu/iommufd/Makefile=21=iommufd_driver-y := driver.o\ndrivers/iommu/iommufd/Makefile:22:obj-$(CONFIG_IOMMUFD_DRIVER_CORE) += iommufd_driver.o\n--\ndrivers/iommu/iommufd/device.c=34=static bool iommufd_device_is_noiommu(struct iommufd_device *idev)\ndrivers/iommu/iommufd/device.c-35-{\ndrivers/iommu/iommufd/device.c:36:\treturn IS_ENABLED(CONFIG_IOMMUFD_NOIOMMU) \u0026\u0026 !idev-\u003edev-\u003eiommu;\ndrivers/iommu/iommufd/device.c-37-}\n--\ndrivers/iommu/iommufd/device.c=1490=int iommufd_access_pin_pages(struct iommufd_access *access, unsigned long iova,\n--\ndrivers/iommu/iommufd/device.c-1501-\t/* Driver's ops don't support pin_pages */\ndrivers/iommu/iommufd/device.c:1502:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST) \u0026\u0026\ndrivers/iommu/iommufd/device.c-1503-\t    WARN_ON(access-\u003eiova_alignment != PAGE_SIZE ||\n--\ndrivers/iommu/iommufd/hw_pagetable.c=11=static const struct iommu_ops *get_iommu_ops(struct iommufd_device *idev)\ndrivers/iommu/iommufd/hw_pagetable.c-12-{\ndrivers/iommu/iommufd/hw_pagetable.c:13:\tif (IS_ENABLED(CONFIG_IOMMUFD_NOIOMMU) \u0026\u0026 !idev-\u003eigroup-\u003egroup)\ndrivers/iommu/iommufd/hw_pagetable.c-14-\t\treturn \u0026iommufd_noiommu_ops;\n--\ndrivers/iommu/iommufd/io_pagetable.c=256=static int iopt_alloc_area_pages(struct io_pagetable *iopt,\n--\ndrivers/iommu/iommufd/io_pagetable.c-295-\t\t\tgoto out_unlock;\ndrivers/iommu/iommufd/io_pagetable.c:296:\t\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST) \u0026\u0026\ndrivers/iommu/iommufd/io_pagetable.c-297-\t\t    WARN_ON(iopt_check_iova(iopt, *dst_iova, length))) {\n--\ndrivers/iommu/iommufd/io_pagetable.c=325=static void iopt_abort_area(struct iopt_area *area)\ndrivers/iommu/iommufd/io_pagetable.c-326-{\ndrivers/iommu/iommufd/io_pagetable.c:327:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/io_pagetable.c-328-\t\tWARN_ON(area-\u003epages);\n--\ndrivers/iommu/iommufd/io_pagetable.c=848=int iopt_unmap_iova(struct io_pagetable *iopt, unsigned long iova,\n--\ndrivers/iommu/iommufd/io_pagetable.c-861-\ndrivers/iommu/iommufd/io_pagetable.c:862:#ifdef CONFIG_IOMMUFD_NOIOMMU\ndrivers/iommu/iommufd/io_pagetable.c-863-int iopt_get_phys(struct io_pagetable *iopt, unsigned long iova, u64 *paddr,\n--\ndrivers/iommu/iommufd/io_pagetable.c=1032=void iopt_destroy_table(struct io_pagetable *iopt)\n--\ndrivers/iommu/iommufd/io_pagetable.c-1035-\ndrivers/iommu/iommufd/io_pagetable.c:1036:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/io_pagetable.c-1037-\t\tiopt_remove_reserved_iova(iopt, NULL);\n--\ndrivers/iommu/iommufd/io_pagetable.c=1060=static void iopt_unfill_domain(struct io_pagetable *iopt,\n--\ndrivers/iommu/iommufd/io_pagetable.c-1084-\t\t\tmutex_lock(\u0026pages-\u003emutex);\ndrivers/iommu/iommufd/io_pagetable.c:1085:\t\t\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/io_pagetable.c-1086-\t\t\t\tWARN_ON(!area-\u003estorage_domain);\n--\ndrivers/iommu/iommufd/io_pagetable.c=1191=static int iopt_check_iova_alignment(struct io_pagetable *iopt,\n--\ndrivers/iommu/iommufd/io_pagetable.c-1206-\ndrivers/iommu/iommufd/io_pagetable.c:1207:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST)) {\ndrivers/iommu/iommufd/io_pagetable.c-1208-\t\tstruct iommufd_access *access;\n--\ndrivers/iommu/iommufd/io_pagetable.h=113=static inline unsigned long iopt_area_start_byte(struct iopt_area *area,\n--\ndrivers/iommu/iommufd/io_pagetable.h-115-{\ndrivers/iommu/iommufd/io_pagetable.h:116:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/io_pagetable.h-117-\t\tWARN_ON(iova \u003c iopt_area_iova(area) ||\n--\ndrivers/iommu/iommufd/ioas.c=340=int iommufd_ioas_unmap(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-377-\ndrivers/iommu/iommufd/ioas.c:378:#ifdef CONFIG_IOMMUFD_NOIOMMU\ndrivers/iommu/iommufd/ioas.c-379-int iommufd_ioas_noiommu_get_pa(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/iommufd_private.h=120=int iopt_unmap_all(struct io_pagetable *iopt, unsigned long *unmapped);\ndrivers/iommu/iommufd/iommufd_private.h:121:#ifdef CONFIG_IOMMUFD_NOIOMMU\ndrivers/iommu/iommufd/iommufd_private.h-122-int iopt_get_phys(struct io_pagetable *iopt, unsigned long iova, u64 *paddr,\n--\ndrivers/iommu/iommufd/iommufd_private.h=359=int iommufd_ioas_unmap(struct iommufd_ucmd *ucmd);\ndrivers/iommu/iommufd/iommufd_private.h:360:#ifdef CONFIG_IOMMUFD_NOIOMMU\ndrivers/iommu/iommufd/iommufd_private.h-361-int iommufd_ioas_noiommu_get_pa(struct iommufd_ucmd *ucmd);\n--\ndrivers/iommu/iommufd/iommufd_private.h=528=iommufd_device_get_iommu_dev(struct iommufd_device *idev)\ndrivers/iommu/iommufd/iommufd_private.h-529-{\ndrivers/iommu/iommufd/iommufd_private.h:530:\tif (IS_ENABLED(CONFIG_IOMMUFD_NOIOMMU) \u0026\u0026 !idev-\u003eigroup-\u003egroup)\ndrivers/iommu/iommufd/iommufd_private.h-531-\t\treturn NULL;\n--\ndrivers/iommu/iommufd/iommufd_private.h=736=static inline int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/iommufd_private.h-741-\ndrivers/iommu/iommufd/iommufd_private.h:742:#ifdef CONFIG_IOMMUFD_TEST\ndrivers/iommu/iommufd/iommufd_private.h-743-int iommufd_test(struct iommufd_ucmd *ucmd);\n--\ndrivers/iommu/iommufd/main.c=315=static int iommufd_fops_open(struct inode *inode, struct file *filp)\n--\ndrivers/iommu/iommufd/main.c-326-\t */\ndrivers/iommu/iommufd/main.c:327:\tif (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER) \u0026\u0026\ndrivers/iommu/iommufd/main.c-328-\t    filp-\u003eprivate_data == \u0026vfio_misc_dev) {\n--\ndrivers/iommu/iommufd/main.c=435=union ucmd_buffer {\n--\ndrivers/iommu/iommufd/main.c-456-\tstruct iommu_vdevice_tsm_req tsm_req;\ndrivers/iommu/iommufd/main.c:457:#ifdef CONFIG_IOMMUFD_TEST\ndrivers/iommu/iommufd/main.c-458-\tstruct iommu_test_cmd test;\n--\ndrivers/iommu/iommufd/main.c=478=static const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {\n--\ndrivers/iommu/iommufd/main.c-521-\t\t struct iommu_vdevice_tsm_req, out_tsm_code),\ndrivers/iommu/iommufd/main.c:522:#ifdef CONFIG_IOMMUFD_TEST\ndrivers/iommu/iommufd/main.c-523-\tIOCTL_OP(IOMMU_TEST_CMD, iommufd_test, struct iommu_test_cmd, last),\n--\ndrivers/iommu/iommufd/main.c=719=static const struct iommufd_object_ops iommufd_object_ops[] = {\n--\ndrivers/iommu/iommufd/main.c-756-\t},\ndrivers/iommu/iommufd/main.c:757:#ifdef CONFIG_IOMMUFD_TEST\ndrivers/iommu/iommufd/main.c-758-\t[IOMMUFD_OBJ_SELFTEST] = {\n--\ndrivers/iommu/iommufd/main.c=789=static int __init iommufd_init(void)\n--\ndrivers/iommu/iommufd/main.c-796-\ndrivers/iommu/iommufd/main.c:797:\tif (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER)) {\ndrivers/iommu/iommufd/main.c-798-\t\tret = misc_register(\u0026vfio_misc_dev);\n--\ndrivers/iommu/iommufd/main.c-807-err_vfio_misc:\ndrivers/iommu/iommufd/main.c:808:\tif (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER))\ndrivers/iommu/iommufd/main.c-809-\t\tmisc_deregister(\u0026vfio_misc_dev);\n--\ndrivers/iommu/iommufd/main.c=815=static void __exit iommufd_exit(void)\n--\ndrivers/iommu/iommufd/main.c-817-\tiommufd_test_exit();\ndrivers/iommu/iommufd/main.c:818:\tif (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER))\ndrivers/iommu/iommufd/main.c-819-\t\tmisc_deregister(\u0026vfio_misc_dev);\n--\ndrivers/iommu/iommufd/main.c=824=module_exit(iommufd_exit);\ndrivers/iommu/iommufd/main.c-825-\ndrivers/iommu/iommufd/main.c:826:#if IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER)\ndrivers/iommu/iommufd/main.c-827-MODULE_ALIAS_MISCDEV(VFIO_MINOR);\n--\ndrivers/iommu/iommufd/pages.c-62-\ndrivers/iommu/iommufd/pages.c:63:#ifndef CONFIG_IOMMUFD_TEST\ndrivers/iommu/iommufd/pages.c-64-#define TEMP_MEMORY_LIMIT 65536\n--\ndrivers/iommu/iommufd/pages.c=167=static void iopt_pages_add_npinned(struct iopt_pages *pages, size_t npages)\n--\ndrivers/iommu/iommufd/pages.c-171-\trc = check_add_overflow(pages-\u003enpinned, npages, \u0026pages-\u003enpinned);\ndrivers/iommu/iommufd/pages.c:172:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-173-\t\tWARN_ON(rc || pages-\u003enpinned \u003e pages-\u003enpages);\n--\ndrivers/iommu/iommufd/pages.c=176=static void iopt_pages_sub_npinned(struct iopt_pages *pages, size_t npages)\n--\ndrivers/iommu/iommufd/pages.c-180-\trc = check_sub_overflow(pages-\u003enpinned, npages, \u0026pages-\u003enpinned);\ndrivers/iommu/iommufd/pages.c:181:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-182-\t\tWARN_ON(rc || pages-\u003enpinned \u003e pages-\u003enpages);\n--\ndrivers/iommu/iommufd/pages.c=201=static unsigned long iopt_area_index_to_iova(struct iopt_area *area,\n--\ndrivers/iommu/iommufd/pages.c-203-{\ndrivers/iommu/iommufd/pages.c:204:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-205-\t\tWARN_ON(index \u003c iopt_area_index(area) ||\n--\ndrivers/iommu/iommufd/pages.c=213=static unsigned long iopt_area_index_to_iova_last(struct iopt_area *area,\n--\ndrivers/iommu/iommufd/pages.c-215-{\ndrivers/iommu/iommufd/pages.c:216:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-217-\t\tWARN_ON(index \u003c iopt_area_index(area) ||\n--\ndrivers/iommu/iommufd/pages.c=299=static void batch_clear_carry(struct pfn_batch *batch, unsigned int keep_pfns)\n--\ndrivers/iommu/iommufd/pages.c-303-\ndrivers/iommu/iommufd/pages.c:304:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-305-\t\tWARN_ON(!batch-\u003eend ||\n--\ndrivers/iommu/iommufd/pages.c=315=static void batch_skip_carry(struct pfn_batch *batch, unsigned int skip_pfns)\n--\ndrivers/iommu/iommufd/pages.c-318-\t\treturn;\ndrivers/iommu/iommufd/pages.c:319:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-320-\t\tWARN_ON(batch-\u003etotal_pfns != batch-\u003enpfns[0]);\n--\ndrivers/iommu/iommufd/pages.c=327=static int __batch_init(struct pfn_batch *batch, size_t max_pages, void *backup,\n--\ndrivers/iommu/iommufd/pages.c-335-\t\treturn -ENOMEM;\ndrivers/iommu/iommufd/pages.c:336:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST) \u0026\u0026 WARN_ON(size \u003c elmsz))\ndrivers/iommu/iommufd/pages.c-337-\t\treturn -EINVAL;\n--\ndrivers/iommu/iommufd/pages.c=479=static int batch_iommu_map_small(struct iommu_domain *domain,\n--\ndrivers/iommu/iommufd/pages.c-485-\ndrivers/iommu/iommufd/pages.c:486:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST))\ndrivers/iommu/iommufd/pages.c-487-\t\tWARN_ON(paddr % PAGE_SIZE || iova % PAGE_SIZE ||\n--\ndrivers/iommu/iommufd/pages.c=876=static int pfn_reader_user_pin(struct pfn_reader_user *user,\n--\ndrivers/iommu/iommufd/pages.c-887-\ndrivers/iommu/iommufd/pages.c:888:\tif (IS_ENABLED(CONFIG_IOMMUFD_TEST) \u0026\u0026\ndrivers/iommu/iommufd/pages.c-889-\t    WARN_ON(last_index \u003c start_index))\n--\ndrivers/iommu/iommufd/pages.c=1168=static int pfn_reader_fill_span(struct pfn_reader *pfns)\n\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 52088
							output: 46
							thoughts: 43
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach this task, as if these were my internal thoughts:

**Investigating Kconfig Settings for IOMMUFD, KVM, VFIO, and TSM**

Right, time to get my hands dirty with these kernel configurations. I need to figure out precisely which Kconfig options are responsible for enabling and controlling IOMMUFD, KVM, VFIO, and TSM. This isn't just a matter of knowing *if* they're enabled, but also understanding the granular controls available through Kconfig. I want to identify any related configurations too, dependencies, and any potentially relevant default settings.

My immediate instinct is to jump into the Kconfig files. I'll need to use a targeted search strategy. "TSM," "IOMMUFD," "KVM," and "VFIO" are the obvious keywords to start with, but I'll also be on the lookout for related terms or abbreviations. I need to be methodical here, not just a keyword search but also look at surrounding definitions, help texts, and any cross-references to understand the broader context of each option. I expect to be digging deep into the intricacies of these virtualisation, IOMMU and memory technologies. Let's get to work.



6/2 2026/10/08 07:00 tool grepper
0m Args:
{
  "Expression": "config TSM\\b|config IOMMUFD\\b|config IOMMUFD_TEST\\b",
  "PathPrefixes": [
    "drivers/"
  ]
}

Results:
{
  "Output": "drivers/iommu/iommufd/Kconfig=2=config IOMMUFD_DRIVER_CORE\n--\ndrivers/iommu/iommufd/Kconfig-5-\ndrivers/iommu/iommufd/Kconfig:6:config IOMMUFD\ndrivers/iommu/iommufd/Kconfig-7-\ttristate \"IOMMU Userspace API\"\n--\ndrivers/iommu/iommufd/Kconfig=31=config IOMMUFD_VFIO_CONTAINER\n--\ndrivers/iommu/iommufd/Kconfig-50-\ndrivers/iommu/iommufd/Kconfig:51:config IOMMUFD_TEST\ndrivers/iommu/iommufd/Kconfig-52-\tbool \"IOMMU Userspace API Test support\"\n--\ndrivers/virt/coco/Kconfig=20=source \"drivers/virt/coco/tdx-host/Kconfig\"\ndrivers/virt/coco/Kconfig-21-\ndrivers/virt/coco/Kconfig:22:config TSM\ndrivers/virt/coco/Kconfig-23-\tbool\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 52739
							output: 29
							thoughts: 21
						

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

**Examining Kconfig Files for Virtualization and PCI Configuration**

Alright, let's dive in. I need to get a clear picture of how things are configured related to virtualization and PCI within this kernel build. My initial thought is to zero in on a couple of key Kconfig files. Specifically, I want to review the settings in `drivers/virt/coco/Kconfig` and `drivers/pci/Kconfig`. These seem like the logical starting points for understanding the driver-level configuration options. I'm assuming that the 'coco' directory pertains to some aspect of the virtualization stack, and the PCI file, well, that's self-explanatory. This is where I can expect to find any relevant conditional compilation flags or dependencies that impact how these components are included and how they interact. A quick scan of these files should provide a high-level overview of the available configuration knobs and their relationships, which will allow me to go deeper if and as needed. This will help me to understand the dependencies and how the overall configuration works for these subsystems.



8/2 2026/10/08 07:00 tool grepper
0m Args:
{
  "Expression": "PCI_TSM\\b",
  "PathPrefixes": [
    "drivers/"
  ]
}

Results:
{
  "Output": "drivers/crypto/ccp/Kconfig=38=config CRYPTO_DEV_SP_PSP\n--\ndrivers/crypto/ccp/Kconfig-41-\tdepends on CRYPTO_DEV_CCP_DD \u0026\u0026 X86_64 \u0026\u0026 AMD_IOMMU\ndrivers/crypto/ccp/Kconfig:42:\tselect PCI_TSM if PCI\ndrivers/crypto/ccp/Kconfig-43-\thelp\n--\ndrivers/crypto/ccp/Makefile=11=ccp-$(CONFIG_CRYPTO_DEV_SP_PSP) += psp-dev.o \\\n--\ndrivers/crypto/ccp/Makefile-18-\ndrivers/crypto/ccp/Makefile:19:ifeq ($(CONFIG_PCI_TSM),y)\ndrivers/crypto/ccp/Makefile-20-ccp-$(CONFIG_CRYPTO_DEV_SP_PSP) += sev-dev-tsm.o sev-dev-tio.o\n--\ndrivers/crypto/ccp/sev-dev.c=76=MODULE_PARM_DESC(psp_init_on_probe, \"  if true, the PSP will be initialized on module init. Else the PSP will be initialized on the first command requiring it\");\ndrivers/crypto/ccp/sev-dev.c-77-\ndrivers/crypto/ccp/sev-dev.c:78:#if IS_ENABLED(CONFIG_PCI_TSM)\ndrivers/crypto/ccp/sev-dev.c-79-static bool sev_tio_enabled = true;\n--\ndrivers/pci/Kconfig=124=config PCI_IDE\n--\ndrivers/pci/Kconfig-126-\ndrivers/pci/Kconfig:127:config PCI_TSM\ndrivers/pci/Kconfig-128-\tbool \"PCI TSM: Device security protocol support\"\n--\ndrivers/pci/Makefile=37=obj-$(CONFIG_PCI_IDE)\t\t+= ide.o\ndrivers/pci/Makefile:38:obj-$(CONFIG_PCI_TSM)\t\t+= tsm.o\ndrivers/pci/Makefile-39-obj-$(CONFIG_PCI_DYNAMIC_OF_NODES) += of_property.o\n--\ndrivers/pci/pci-sysfs.c=1938=const struct attribute_group *pci_dev_attr_groups[] = {\n--\ndrivers/pci/pci-sysfs.c-1956-#endif\ndrivers/pci/pci-sysfs.c:1957:#ifdef CONFIG_PCI_TSM\ndrivers/pci/pci-sysfs.c-1958-\t\u0026pci_tsm_auth_attr_group,\n--\ndrivers/pci/pci.h=757=static inline void pci_ide_destroy(struct pci_dev *dev) { }\n--\ndrivers/pci/pci.h-759-\ndrivers/pci/pci.h:760:#ifdef CONFIG_PCI_TSM\ndrivers/pci/pci.h-761-void pci_tsm_init(struct pci_dev *pdev);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 53784
							output: 34
							thoughts: 18
						

Thoughts:
Okay, here's my attempt at summarizing that thought process, keeping in mind the expert user:

**Investigating TSM Configuration in the Kernel**

Alright, let's dive in. I need to understand how Transactional Synchronization Extensions (TSM) are configured within this specific kernel environment. My immediate focus is on the `drivers/virt/coco/Kconfig` file. That's the logical place to start looking for configuration options related to virtualized environments, CoCo being a relevant abstraction. I expect that file to hold the conditional logic, default settings, and potential dependencies that govern whether TSM support is enabled or disabled. Knowing what `Kconfig` says is fundamental to understanding this part of the system.



10/2 2026/10/08 07:00 tool read-file
0m Args:
{
  "File": "drivers/virt/coco/Kconfig",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\t#\n   3:\t# Confidential computing related collateral\n   4:\t#\n   5:\t\n   6:\tif VIRT_DRIVERS\n   7:\tsource \"drivers/virt/coco/efi_secret/Kconfig\"\n   8:\t\n   9:\tsource \"drivers/virt/coco/pkvm-guest/Kconfig\"\n  10:\t\n  11:\tsource \"drivers/virt/coco/sev-guest/Kconfig\"\n  12:\t\n  13:\tsource \"drivers/virt/coco/tdx-guest/Kconfig\"\n  14:\t\n  15:\tsource \"drivers/virt/coco/arm-cca-guest/Kconfig\"\n  16:\t\n  17:\tsource \"drivers/virt/coco/guest/Kconfig\"\n  18:\tendif\n  19:\t\n  20:\tsource \"drivers/virt/coco/tdx-host/Kconfig\"\n  21:\t\n  22:\tconfig TSM\n  23:\t\tbool\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 54268
							output: 33
							thoughts: 12
						

Thoughts:
Okay, here's my interpretation of "Let's see what selects TSM or enables it," presented as a first-person account from an expert:

**Delving into the Triggers of TSM**

Alright, let's dissect this. "Let's see what selects TSM or enables it." That's the crux of the investigation, isn't it? It's the core question when dealing with... *[insert your area of expertise, e.g., in a particular optimization problem, a specific model, etc.]*... figuring out what triggers the application or activation of TSM. What are the *necessary* and, more importantly, the *sufficient* conditions? We're not just looking for correlations here. We need the causal mechanisms.

So, am I thinking about the specific parameters or constraints? The configuration space? Or is it a higher-level consideration? Let's break this down further and look for the factors at play. What are the key variables that, when they hit a certain threshold or meet a particular combination of criteria, *push* the system towards TSM? Are we talking about input features, system states, or perhaps the model's own internal dynamics? Is it a combination of factors?

It's about establishing the *conditions*. It's about figuring out what the "if-then" statement is. If *[Condition A]* and *[Condition B]* and *[Condition C]* hold true, then TSM is selected or enabled. What are those conditionals? What are those factors? I have to analyze the mechanisms and how TSM comes into play.



12/2 2026/10/08 07:00 tool grepper
0m Args:
{
  "Expression": "select TSM\\b",
  "PathPrefixes": [
    "drivers/",
    "arch/"
  ]
}

Results:
{
  "Output": "drivers/pci/Kconfig=127=config PCI_TSM\n--\ndrivers/pci/Kconfig-130-\tselect PCI_DOE\ndrivers/pci/Kconfig:131:\tselect TSM\ndrivers/pci/Kconfig-132-\thelp\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 54734
							output: 35
							thoughts: 60
						

Thoughts:
Here's my thought process, as it stands:

**Navigating the Kernel Configuration for TSM Support**

Okay, so `PCI_TSM` is choosing `TSM`. That's the starting point. I need to understand the relationship between these two, and what that might imply.

Now, let's look at where this selection is coming from. Aha, `drivers/crypto/ccp/Kconfig` is stating that `PCI_TSM` should be selected if the parent feature `PCI` is enabled. That makes sense from a hardware perspective.

My next step is to examine what's defined in `drivers/pci/Kconfig` regarding `PCI_TSM`. This is crucial to grasp the context. The `pci` module is very important in the Linux Kernel, so it stands to reason that this is an important point in the configuration process. This is the key piece to really understanding the dependencies involved.



14/2 2026/10/08 07:01 tool read-file
0m Args:
{
  "File": "drivers/pci/Kconfig",
  "FirstLine": 125,
  "LineCount": 25
}

Results:
{
  "Contents": " 125:\t\tbool\n 126:\t\n 127:\tconfig PCI_TSM\n 128:\t\tbool \"PCI TSM: Device security protocol support\"\n 129:\t\tselect PCI_IDE\n 130:\t\tselect PCI_DOE\n 131:\t\tselect TSM\n 132:\t\thelp\n 133:\t\t  The TEE (Trusted Execution Environment) Device Interface\n 134:\t\t  Security Protocol (TDISP) defines a \"TSM\" as a platform agent\n 135:\t\t  that manages device authentication, link encryption, link\n 136:\t\t  integrity protection, and assignment of PCI device functions\n 137:\t\t  (virtual or physical) to confidential computing VMs that can\n 138:\t\t  access (DMA) guest private memory.\n 139:\t\n 140:\t\t  Enable a platform TSM driver to use this capability.\n 141:\t\n 142:\tconfig PCI_DOE\n 143:\t\tbool \"Enable PCI Data Object Exchange (DOE) support\"\n 144:\t\thelp\n 145:\t\t  Say Y here if you want be able to communicate with PCIe DOE\n 146:\t\t  mailboxes.\n 147:\t\n 148:\tconfig PCI_ECAM\n 149:\t\tbool\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 55368
							output: 40
							thoughts: 1998
						

Thoughts:
**Analyzing the KVM/IOMMUFD Patch Series**

Okay, let's break this down. First, I need to understand what this patch series is fundamentally changing. The commit message doesn't give much away, so I'll dive into the diff. It looks like it is a modification in the communication between KVM, VFIO, and IOMMUFD. My first impression is that the primary change centers around how these components are referencing the `struct kvm`.

1.  **KVM/VFIO Interaction**: I immediately see a shift from direct `struct kvm *` references to `struct file *kvm_file`. The `kvm_file` now represents the KVM instance. So, modules that used to take a direct reference on `struct kvm` are now using a file descriptor (`struct file`). I see functions like `kvm_file_to_kvm_fn`, suggesting a conversion mechanism. On x86, it is using `x86`, which seems straightforward. The `vfio_file_set_kvm` functions in both `vfio.c` and `vfio_main.c` are updated. Basically, instead of giving a `struct kvm *` around, these are being passed `struct file *`, which can then be converted to `struct kvm *`.

2.  **IOMMUFD Enhancements**: The changes in IOMMUFD are significant. It's adopting the `struct file *kvm_file` pattern. I see this in `iommufd_device_bind`, where `kvm_file` is stored. The `iommufd_viommu_alloc_ioctl` function becomes more complex. It involves TSM (translation services manager), and the allocation logic seems to be checking for different flags and initializing with either a HWPT (hardware page table) or not. In `iommufd_viommu_destroy`, I see appropriate `fput` calls to release the file descriptor. There are new ioctls introduced, such as `IOMMU_VDEVICE_TSM_REQ`, calling `iommufd_vdevice_tsm_req_ioctl`. This points to a new feature related to TSM requests within the IOMMUFD context.

3.  **x86 Page Tracking**: In `arch/x86/kvm/mmu/page_track.c`, the page tracking code has been updated to use the file descriptor for KVM instances, too. The `kvm_page_track_register_notifier` and `kvm_page_track_unregister_notifier` functions now work with `struct file *`, leveraging the `file_to_kvm_x86` conversion.

4.  **TSM and PCI Interaction**: There are also changes within the PCI and TSM code, which include functions for managing PCI and TSM devices and sysfs interaction for things like "disconnect."

Now, the critical question: *Is this code actually reachable?* I need to assess if these changes are within a code path that can be triggered. Given that this is a patch from syz-cluster, I'm going to assume it's part of a fuzzing campaign to identify vulnerabilities. KVM and IOMMUFD are definitely accessible through system calls and ioctls, specifically via `/dev/kvm` and `/dev/iommu`. Syzkaller is known to fuzz these interfaces, with comprehensive descriptions for KVM and IOMMUFD. I'm going to check syzkaller for coverage of `/dev/iommu`. And further, I need to check if the `/dev/iommu` can be opened in a standard VM without special hardware. I'll need to look at `iommufd_fops_open` to confirm how `/dev/iommu` works and is reachable in a typical virtualized environment.



16/2 2026/10/08 07:01 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "misc_register.*iommufd",
  "PathPrefixes": [
    "drivers/iommu/iommufd/"
  ]
}

Results:
{
  "error": "no matches"
}

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

Args:
null

Results:
null

Tokens:
							input: 58255
							output: 35
							thoughts: 15
						

Thoughts:
Okay, here's my summary, tailored for an expert audience, as if it's *my* train of thought:

**Diving into `/dev/iommu` Registration**

Alright, let's trace this thing. I need to understand how `/dev/iommu` gets registered within the kernel. It’s critical, obviously, because that's the interface to the IOMMU. This likely ties in closely with the IOMMU driver initialization, but *how* is the character device node itself created? Is it handled during the platform's probe sequence for the IOMMU hardware, or is it a more generic device registration process triggered later? I suspect it's platform-specific but I should confirm my assumptions. I'll need to look at the relevant driver code, likely under the `iommu` subsystem, but where does the actual `device_create` or equivalent call happen? I'm betting there's a struct somewhere which describes the device itself.



18/2 2026/10/08 07:01 tool grepper
0m Args:
{
  "Expression": "misc_register",
  "PathPrefixes": [
    "drivers/iommu/iommufd/"
  ]
}

Results:
{
  "Output": "drivers/iommu/iommufd/main.c=789=static int __init iommufd_init(void)\n--\ndrivers/iommu/iommufd/main.c-792-\ndrivers/iommu/iommufd/main.c:793:\tret = misc_register(\u0026iommu_misc_dev);\ndrivers/iommu/iommufd/main.c-794-\tif (ret)\n--\ndrivers/iommu/iommufd/main.c-797-\tif (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER)) {\ndrivers/iommu/iommufd/main.c:798:\t\tret = misc_register(\u0026vfio_misc_dev);\ndrivers/iommu/iommufd/main.c-799-\t\tif (ret)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 58744
							output: 31
							thoughts: 378
						

Thoughts:
**My Analysis of `/dev/iommu` and its Interaction with VFIO and KVM**

Okay, so `/dev/iommu`... right. I remember now, that's the misc device that comes up at boot if `CONFIG_IOMMUFD` is set.  And, if `CONFIG_IOMMUFD_TEST` is enabled, `selftest.c` uses `/dev/iommu` to create mock devices and domains using the `IOMMU_TEST_CMD` ioctl. Let's dig into that `selftest.c` file for a bit.

Ah, here's the `mock_ops` struct. It's got the usual suspects – `probe_device`, `page_response`, and then that `user_pasid_table = true` flag, and notably, the `get_viommu_ops` function.  Interesting.  And `mock_get_viommu_ops` returns `&mock_viommu_ops` when the `viommu_type` is `IOMMU_VIOMMU_TYPE_SELFTEST`.

So, `mock_viommu_ops` contains the real meat. `get_viommu_size`, `viommu_init`, `alloc_domain_nested`, `cache_invalidate`, `vdevice_init`, `hw_queue_init_phys` - all the things you'd expect in an IOMMU self-test. This shows a clear path from `/dev/iommu` through the selftest mechanisms.

Now, let's switch gears to KVM.  When I'm creating a KVM VM, the `kvm_dev_ioctl_create_vm` ioctl sets up the `kvm->file` pointer, right?  And when the VM is released in `kvm_vm_release`, that file pointer is cleared with `WRITE_ONCE`.  And of course, KVM can expose devices like `KVM_DEV_TYPE_VFIO`.  Time to jump into `virt/kvm/vfio.c` and figure out how these pieces all fit together. I want to see how KVM leverages and interacts with the IOMMU infrastructure, specifically in the context of VFIO.  It's all a matter of understanding how the file descriptor management in KVM ties into the IOMMU's operations, especially in the context of device assignment.



20/2 2026/10/08 07:02 tool grepper
0m Args:
{
  "Expression": "kvm_vfio",
  "PathPrefixes": [
    "virt/kvm/"
  ]
}

Results:
{
  "Output": "virt/kvm/kvm_main.c=6532=int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module)\n--\nvirt/kvm/kvm_main.c-6575-\nvirt/kvm/kvm_main.c:6576:\tr = kvm_vfio_ops_init();\nvirt/kvm/kvm_main.c-6577-\tif (WARN_ON_ONCE(r))\n--\nvirt/kvm/kvm_main.c-6604-err_gmem:\nvirt/kvm/kvm_main.c:6605:\tkvm_vfio_ops_exit();\nvirt/kvm/kvm_main.c-6606-err_vfio:\n--\nvirt/kvm/kvm_main.c=6620=void kvm_exit(void)\n--\nvirt/kvm/kvm_main.c-6637-\tkvm_gmem_exit();\nvirt/kvm/kvm_main.c:6638:\tkvm_vfio_ops_exit();\nvirt/kvm/kvm_main.c-6639-\tkvm_async_pf_deinit();\n--\nvirt/kvm/vfio.c-23-\nvirt/kvm/vfio.c:24:struct kvm_vfio_file {\nvirt/kvm/vfio.c-25-\tstruct list_head node;\n--\nvirt/kvm/vfio.c-31-\nvirt/kvm/vfio.c:32:struct kvm_vfio {\nvirt/kvm/vfio.c-33-\tstruct list_head file_list;\n--\nvirt/kvm/vfio.c-37-\nvirt/kvm/vfio.c:38:static void kvm_vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)\nvirt/kvm/vfio.c-39-{\n--\nvirt/kvm/vfio.c-50-\nvirt/kvm/vfio.c:51:static bool kvm_vfio_file_enforced_coherent(struct file *file)\nvirt/kvm/vfio.c-52-{\n--\nvirt/kvm/vfio.c-66-\nvirt/kvm/vfio.c:67:static bool kvm_vfio_file_is_valid(struct file *file)\nvirt/kvm/vfio.c-68-{\n--\nvirt/kvm/vfio.c-83-#ifdef CONFIG_SPAPR_TCE_IOMMU\nvirt/kvm/vfio.c:84:static struct iommu_group *kvm_vfio_file_iommu_group(struct file *file)\nvirt/kvm/vfio.c-85-{\n--\nvirt/kvm/vfio.c=100=static void kvm_spapr_tce_release_vfio_group(struct kvm *kvm,\nvirt/kvm/vfio.c:101:\t\t\t\t\t     struct kvm_vfio_file *kvf)\nvirt/kvm/vfio.c-102-{\n--\nvirt/kvm/vfio.c-119- */\nvirt/kvm/vfio.c:120:static void kvm_vfio_update_coherency(struct kvm_device *dev)\nvirt/kvm/vfio.c-121-{\nvirt/kvm/vfio.c:122:\tstruct kvm_vfio *kv = dev-\u003eprivate;\nvirt/kvm/vfio.c-123-\tbool noncoherent = false;\nvirt/kvm/vfio.c:124:\tstruct kvm_vfio_file *kvf;\nvirt/kvm/vfio.c-125-\nvirt/kvm/vfio.c-126-\tlist_for_each_entry(kvf, \u0026kv-\u003efile_list, node) {\nvirt/kvm/vfio.c:127:\t\tif (!kvm_vfio_file_enforced_coherent(kvf-\u003efile)) {\nvirt/kvm/vfio.c-128-\t\t\tnoncoherent = true;\n--\nvirt/kvm/vfio.c-142-\nvirt/kvm/vfio.c:143:static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)\nvirt/kvm/vfio.c-144-{\nvirt/kvm/vfio.c:145:\tstruct kvm_vfio *kv = dev-\u003eprivate;\nvirt/kvm/vfio.c:146:\tstruct kvm_vfio_file *kvf;\nvirt/kvm/vfio.c-147-\tstruct file *kvm_file __free(fput) = NULL;\n--\nvirt/kvm/vfio.c-154-\t/* Ensure the FD is a vfio FD. */\nvirt/kvm/vfio.c:155:\tif (!kvm_vfio_file_is_valid(filp))\nvirt/kvm/vfio.c-156-\t\treturn -EINVAL;\n--\nvirt/kvm/vfio.c-175-\nvirt/kvm/vfio.c:176:\tkvm_vfio_file_set_kvm(kvf-\u003efile, kvm_file);\nvirt/kvm/vfio.c:177:\tkvm_vfio_update_coherency(dev);\nvirt/kvm/vfio.c-178-\n--\nvirt/kvm/vfio.c-181-\nvirt/kvm/vfio.c:182:static void kvm_vfio_file_free(struct kvm_device *dev, struct kvm_vfio_file *kvf)\nvirt/kvm/vfio.c-183-{\n--\nvirt/kvm/vfio.c-186-#endif\nvirt/kvm/vfio.c:187:\tkvm_vfio_file_set_kvm(kvf-\u003efile, NULL);\nvirt/kvm/vfio.c-188-\tfput(kvf-\u003efile);\n--\nvirt/kvm/vfio.c-192-\nvirt/kvm/vfio.c:193:static int kvm_vfio_file_del(struct kvm_device *dev, unsigned int fd)\nvirt/kvm/vfio.c-194-{\nvirt/kvm/vfio.c:195:\tstruct kvm_vfio *kv = dev-\u003eprivate;\nvirt/kvm/vfio.c:196:\tstruct kvm_vfio_file *kvf;\nvirt/kvm/vfio.c-197-\tCLASS(fd, f)(fd);\n--\nvirt/kvm/vfio.c-205-\t\tif (kvf-\u003efile == fd_file(f)) {\nvirt/kvm/vfio.c:206:\t\t\tkvm_vfio_file_free(dev, kvf);\nvirt/kvm/vfio.c:207:\t\t\tkvm_vfio_update_coherency(dev);\nvirt/kvm/vfio.c-208-\t\t\treturn 0;\n--\nvirt/kvm/vfio.c-215-#ifdef CONFIG_SPAPR_TCE_IOMMU\nvirt/kvm/vfio.c:216:static int kvm_vfio_file_set_spapr_tce(struct kvm_device *dev,\nvirt/kvm/vfio.c-217-\t\t\t\t       void __user *arg)\nvirt/kvm/vfio.c-218-{\nvirt/kvm/vfio.c:219:\tstruct kvm_vfio_spapr_tce param;\nvirt/kvm/vfio.c:220:\tstruct kvm_vfio *kv = dev-\u003eprivate;\nvirt/kvm/vfio.c:221:\tstruct kvm_vfio_file *kvf;\nvirt/kvm/vfio.c-222-\nvirt/kvm/vfio.c:223:\tif (copy_from_user(\u0026param, arg, sizeof(struct kvm_vfio_spapr_tce)))\nvirt/kvm/vfio.c-224-\t\treturn -EFAULT;\n--\nvirt/kvm/vfio.c-236-\t\tif (!kvf-\u003eiommu_group) {\nvirt/kvm/vfio.c:237:\t\t\tkvf-\u003eiommu_group = kvm_vfio_file_iommu_group(kvf-\u003efile);\nvirt/kvm/vfio.c-238-\t\t\tif (WARN_ON_ONCE(!kvf-\u003eiommu_group))\n--\nvirt/kvm/vfio.c-249-\nvirt/kvm/vfio.c:250:static int kvm_vfio_set_file(struct kvm_device *dev, long attr,\nvirt/kvm/vfio.c-251-\t\t\t     void __user *arg)\n--\nvirt/kvm/vfio.c-259-\t\t\treturn -EFAULT;\nvirt/kvm/vfio.c:260:\t\treturn kvm_vfio_file_add(dev, fd);\nvirt/kvm/vfio.c-261-\n--\nvirt/kvm/vfio.c-264-\t\t\treturn -EFAULT;\nvirt/kvm/vfio.c:265:\t\treturn kvm_vfio_file_del(dev, fd);\nvirt/kvm/vfio.c-266-\n--\nvirt/kvm/vfio.c-268-\tcase KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE:\nvirt/kvm/vfio.c:269:\t\treturn kvm_vfio_file_set_spapr_tce(dev, arg);\nvirt/kvm/vfio.c-270-#endif\n--\nvirt/kvm/vfio.c-275-\nvirt/kvm/vfio.c:276:static int kvm_vfio_set_attr(struct kvm_device *dev,\nvirt/kvm/vfio.c-277-\t\t\t     struct kvm_device_attr *attr)\n--\nvirt/kvm/vfio.c-280-\tcase KVM_DEV_VFIO_FILE:\nvirt/kvm/vfio.c:281:\t\treturn kvm_vfio_set_file(dev, attr-\u003eattr,\nvirt/kvm/vfio.c-282-\t\t\t\t\t u64_to_user_ptr(attr-\u003eaddr));\n--\nvirt/kvm/vfio.c-287-\nvirt/kvm/vfio.c:288:static int kvm_vfio_has_attr(struct kvm_device *dev,\nvirt/kvm/vfio.c-289-\t\t\t     struct kvm_device_attr *attr)\n--\nvirt/kvm/vfio.c-307-\nvirt/kvm/vfio.c:308:static void kvm_vfio_release(struct kvm_device *dev)\nvirt/kvm/vfio.c-309-{\nvirt/kvm/vfio.c:310:\tstruct kvm_vfio *kv = dev-\u003eprivate;\nvirt/kvm/vfio.c:311:\tstruct kvm_vfio_file *kvf, *tmp;\nvirt/kvm/vfio.c-312-\nvirt/kvm/vfio.c-313-\tlist_for_each_entry_safe(kvf, tmp, \u0026kv-\u003efile_list, node)\nvirt/kvm/vfio.c:314:\t\tkvm_vfio_file_free(dev, kvf);\nvirt/kvm/vfio.c-315-\nvirt/kvm/vfio.c:316:\tkvm_vfio_update_coherency(dev);\nvirt/kvm/vfio.c-317-\n--\nvirt/kvm/vfio.c-321-\nvirt/kvm/vfio.c:322:static int kvm_vfio_create(struct kvm_device *dev, u32 type);\nvirt/kvm/vfio.c-323-\nvirt/kvm/vfio.c:324:static const struct kvm_device_ops kvm_vfio_ops = {\nvirt/kvm/vfio.c-325-\t.name = \"kvm-vfio\",\nvirt/kvm/vfio.c:326:\t.create = kvm_vfio_create,\nvirt/kvm/vfio.c:327:\t.release = kvm_vfio_release,\nvirt/kvm/vfio.c:328:\t.set_attr = kvm_vfio_set_attr,\nvirt/kvm/vfio.c:329:\t.has_attr = kvm_vfio_has_attr,\nvirt/kvm/vfio.c-330-};\nvirt/kvm/vfio.c-331-\nvirt/kvm/vfio.c:332:static int kvm_vfio_create(struct kvm_device *dev, u32 type)\nvirt/kvm/vfio.c-333-{\nvirt/kvm/vfio.c-334-\tstruct kvm_device *tmp;\nvirt/kvm/vfio.c:335:\tstruct kvm_vfio *kv;\nvirt/kvm/vfio.c-336-\n--\nvirt/kvm/vfio.c-340-\tlist_for_each_entry(tmp, \u0026dev-\u003ekvm-\u003edevices, vm_node)\nvirt/kvm/vfio.c:341:\t\tif (tmp-\u003eops == \u0026kvm_vfio_ops)\nvirt/kvm/vfio.c-342-\t\t\treturn -EBUSY;\n--\nvirt/kvm/vfio.c-355-\nvirt/kvm/vfio.c:356:int kvm_vfio_ops_init(void)\nvirt/kvm/vfio.c-357-{\nvirt/kvm/vfio.c:358:\treturn kvm_register_device_ops(\u0026kvm_vfio_ops, KVM_DEV_TYPE_VFIO);\nvirt/kvm/vfio.c-359-}\nvirt/kvm/vfio.c-360-\nvirt/kvm/vfio.c:361:void kvm_vfio_ops_exit(void)\nvirt/kvm/vfio.c-362-{\n--\nvirt/kvm/vfio.h-5-#ifdef CONFIG_KVM_VFIO\nvirt/kvm/vfio.h:6:int kvm_vfio_ops_init(void);\nvirt/kvm/vfio.h:7:void kvm_vfio_ops_exit(void);\nvirt/kvm/vfio.h-8-#else\nvirt/kvm/vfio.h:9:static inline int kvm_vfio_ops_init(void)\nvirt/kvm/vfio.h-10-{\n--\nvirt/kvm/vfio.h-12-}\nvirt/kvm/vfio.h:13:static inline void kvm_vfio_ops_exit(void)\nvirt/kvm/vfio.h-14-{\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 63582
							output: 40
							thoughts: 254
						

Thoughts:
**My Analysis of KVM File Handling in VFIO**

Okay, so I'm digging into how KVM handles VFIO, specifically around the file descriptor management. `KVM_DEV_TYPE_VFIO`, that's standard KVM functionality, enabled by `CONFIG_KVM_VFIO` as expected. Now, let's zoom in on `kvm_vfio_file_add`. Right, here we see `get_file_active(&dev->kvm->file)`. This means the code is taking a reference to `dev->kvm->file`. That's how it keeps track of the file descriptor associated with the KVM VM. And, of course, if that file isn't available, we get an `-ENOENT` error. Makes perfect sense.

Now, let me look at where `kvm->file` is set and released. I'm checking `kvm_main.c` now... Aha! In `kvm_dev_ioctl_create_vm`... there it is: `kvm->file = file;`. It's pretty straightforward, the file pointer is assigned to the `kvm` structure when the VM is created. And I know there's a corresponding release path. Yes, and as expected, in `kvm_vm_release` we see `WRITE_ONCE(kvm->file, NULL);`. So, it's set to NULL when the VM is destroyed. Just what I'd anticipate.

I want to double-check that `kvm->file = file;` assignment. Let me look at line 5540 in `virt/kvm/kvm_main.c` to make sure it's doing what I think it's doing.



22/2 2026/10/08 07:02 tool read-file
0m Args:
{
  "File": "virt/kvm/kvm_main.c",
  "FirstLine": 5530,
  "LineCount": 35
}

Results:
{
  "Contents": "5530:\t{\n5531:\t\tchar fdname[ITOA_MAX_LEN + 1];\n5532:\t\tint r, fd;\n5533:\t\tstruct kvm *kvm;\n5534:\t\tstruct file *file;\n5535:\t\n5536:\t\tfd = get_unused_fd_flags(O_CLOEXEC);\n5537:\t\tif (fd \u003c 0)\n5538:\t\t\treturn fd;\n5539:\t\n5540:\t\tsnprintf(fdname, sizeof(fdname), \"%d\", fd);\n5541:\t\n5542:\t\tkvm = kvm_create_vm(type, fdname);\n5543:\t\tif (IS_ERR(kvm)) {\n5544:\t\t\tr = PTR_ERR(kvm);\n5545:\t\t\tgoto put_fd;\n5546:\t\t}\n5547:\t\n5548:\t\tfile = anon_inode_getfile(\"kvm-vm\", \u0026kvm_vm_fops, kvm, O_RDWR);\n5549:\t\tif (IS_ERR(file)) {\n5550:\t\t\tr = PTR_ERR(file);\n5551:\t\t\tgoto put_kvm;\n5552:\t\t}\n5553:\t\n5554:\t\tkvm-\u003efile = file;\n5555:\t\n5556:\t\t/*\n5557:\t\t * Don't call kvm_put_kvm anymore at this point; file-\u003ef_op is\n5558:\t\t * already set, with -\u003erelease() being kvm_vm_release().  In error\n5559:\t\t * cases it will be called by the final fput(file) and will take\n5560:\t\t * care of doing kvm_put_kvm(kvm).\n5561:\t\t */\n5562:\t\tkvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);\n5563:\t\n5564:\t\tfd_install(fd, file);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 64792
							output: 19
							thoughts: 31
						

Thoughts:
Okay, here's my summarized thought process, presented as if I were thinking it:

**Investigating `get_file_active`**

Alright, I need to figure out what's going on with `get_file_active`. First, I need to pinpoint its definition. It's not immediately obvious where it's located in the codebase. My best bet at this point is to use a code search tool. Time to fire up `grepper` and see if I can rapidly locate where this function is declared. That'll give me the context I need to understand its purpose and behavior.



24/2 2026/10/08 07:02 tool grepper
0m Args:
{
  "Expression": "get_file_active"
}

Results:
{
  "Output": "drivers/gpio/gpiolib-cdev.c=2495=static int lineinfo_changed_notify(struct notifier_block *nb,\n--\ndrivers/gpio/gpiolib-cdev.c-2508-\t/* Keep the file descriptor alive for the duration of the notification. */\ndrivers/gpio/gpiolib-cdev.c:2509:\tfp = get_file_active(\u0026cdev-\u003efp);\ndrivers/gpio/gpiolib-cdev.c-2510-\tif (!fp)\n--\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c=968=static struct file *mmap_singleton(struct drm_i915_private *i915)\n--\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c-971-\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c:972:\tfile = get_file_active(\u0026i915-\u003egem.mmap_singleton);\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c-973-\tif (file)\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c=336=void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev, bool revoked)\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c-343-\tlist_for_each_entry_safe(priv, tmp, \u0026vdev-\u003edmabufs, dmabufs_elm) {\ndrivers/vfio/pci/vfio_pci_dmabuf.c:344:\t\tif (!get_file_active(\u0026priv-\u003edmabuf-\u003efile))\ndrivers/vfio/pci/vfio_pci_dmabuf.c-345-\t\t\tcontinue;\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c=380=void vfio_pci_dma_buf_cleanup(struct vfio_pci_core_device *vdev)\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c-396-\tlist_for_each_entry_safe(priv, tmp, \u0026vdev-\u003edmabufs, dmabufs_elm) {\ndrivers/vfio/pci/vfio_pci_dmabuf.c:397:\t\tif (!get_file_active(\u0026priv-\u003edmabuf-\u003efile))\ndrivers/vfio/pci/vfio_pci_dmabuf.c-398-\t\t\tcontinue;\n--\nfs/file.c=990=EXPORT_SYMBOL_GPL(get_file_rcu);\n--\nfs/file.c-992-/**\nfs/file.c:993: * get_file_active - try go get a reference to a file\nfs/file.c-994- * @f: the file to get a reference on\n--\nfs/file.c-1003- */\nfs/file.c:1004:struct file *get_file_active(struct file **f)\nfs/file.c-1005-{\n--\nfs/file.c-1014-}\nfs/file.c:1015:EXPORT_SYMBOL_GPL(get_file_active);\nfs/file.c-1016-\n--\ninclude/linux/fs.h=1311=struct file *get_file_rcu(struct file __rcu **f);\ninclude/linux/fs.h:1312:struct file *get_file_active(struct file **f);\ninclude/linux/fs.h-1313-\n--\nvirt/kvm/guest_memfd.c=290=static int kvm_gmem_release(struct inode *inode, struct file *file)\n--\nvirt/kvm/guest_memfd.c-304-\t * Since .release is called only when the reference count is zero,\nvirt/kvm/guest_memfd.c:305:\t * after which file_ref_get() and get_file_active() fail,\nvirt/kvm/guest_memfd.c-306-\t * kvm_gmem_get_pfn() cannot be using the file concurrently.\nvirt/kvm/guest_memfd.c:307:\t * file_ref_put() provides a full barrier, and get_file_active() the\nvirt/kvm/guest_memfd.c-308-\t * matching acquire barrier.\n--\nvirt/kvm/guest_memfd.c=340=static inline struct file *kvm_gmem_get_file(struct kvm_memory_slot *slot)\n--\nvirt/kvm/guest_memfd.c-346-\t */\nvirt/kvm/guest_memfd.c:347:\treturn get_file_active(\u0026slot-\u003egmem.file);\nvirt/kvm/guest_memfd.c-348-}\n--\nvirt/kvm/vfio.c=143=static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)\n--\nvirt/kvm/vfio.c-157-\nvirt/kvm/vfio.c:158:\tkvm_file = get_file_active(\u0026dev-\u003ekvm-\u003efile);\nvirt/kvm/vfio.c-159-\tif (!kvm_file)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 66355
							output: 34
							thoughts: 1745
						

Thoughts:
**Analysis of Kernel Code Refactoring for Fuzzing Potential**

Okay, so `get_file_active(&dev->kvm->file)` is the entry point, trying to grab a reference to the KVM file. This patch really overhauls the reference counting between KVM, VFIO, and IOMMUFD. Let me break down the changes.

Previously, VFIO held a `struct kvm *` and managed it with `kvm_get_kvm_safe` and `kvm_put_kvm`. IOMMUFD and PCI TSM had their own ways of handling KVM interaction, but without directly tracking the KVM file.

Now, it's all about `struct file *`. VFIO holds a `struct file *kvm` reference, acquired via `get_file()` and released with `fput()`. This `struct file *` is then passed down to `iommufd_device_bind()`, stored in various `iommufd_*` structs (`idev->kvm_file`, `viommu->kvm_file`), with proper `get_file()` and `fput()` calls to maintain the reference. This shows up in `arch/x86/kvm/mmu/page_track.c` and `arch/x86/kvm/svm/sev.c` as well, ensuring consistent handling of the file reference.

Specifically, looking at `drivers/iommu/iommufd/viommu.c` and `drivers/iommu/iommufd/hw_pagetable.c`, we see a significant reworking of the `iommufd_viommu_alloc_ioctl` call, including dealing with `tsm_dev`, `hwpt`, and the KVM file. I'm noting the changes in `drivers/iommu/iommufd/tsm.c` with the new `iommufd_vdevice_tsm_req_ioctl` and the addition of `IOMMU_VDEVICE_TSM_REQ` to the ioctl table in `drivers/iommu/iommufd/main.c`. The PCI TSM code has been refactored, too.

The critical question: Is this reachable and fuzzable? Absolutely.

The `/dev/iommu` device is standard and Syzkaller-friendly, making `iommufd` fully testable.  The `selftest.c` confirms this, allowing full hardware mocking. `/dev/kvm` is standard for virtualization. VFIO device interactions, particularly `KVM_DEV_TYPE_VFIO` ioctls like `KVM_SET_DEVICE_ATTR`, are completely reachable via syscalls.

These modifications cover a range of ioctls: `iommufd_viommu_alloc_ioctl`, `iommufd_vdevice_alloc_ioctl`, `iommufd_hwpt_alloc`, `iommufd_hw_queue_alloc_ioctl`, `iommufd_vdevice_tsm_req_ioctl`, and the KVM and SEV calls through `KVM_SET_DEVICE_ATTR` and `KVM_MEMORY_ENCRYPT_OP`. We also have the sysfs write to `disconnect`.

The modified code touches KVM, VFIO, IOMMUFD, and PCI. It's a lifecycle restructuring with new uAPI (`IOMMU_VDEVICE_TSM_REQ`) and modified ioctl handlers. It's all clearly reachable.

So:
1.  `WorthFuzzing = true`
2.  Next, I'll identify the required Kconfig flags (`EnableConfigs`)
3.  I'll then determine key, non-ubiquitous kernel functions to target (`FocusSymbols`).
4.  Reasoning: The patch significantly restructures reference counting and adds/modifies ioctls within critical, reachable kernel subsystems, making it a prime candidate for fuzzing.



26/2 2026/10/08 07:03 tool grepper
0m Args:
{
  "Expression": "config KVM_VFIO",
  "PathPrefixes": [
    "virt/",
    "arch/"
  ]
}

Results:
{
  "Output": "virt/kvm/Kconfig=59=config HAVE_KVM_CPU_RELAX_INTERCEPT\n--\nvirt/kvm/Kconfig-61-\nvirt/kvm/Kconfig:62:config KVM_VFIO\nvirt/kvm/Kconfig-63-       bool\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 69082
							output: 20
							thoughts: 12
						

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

**Delving into KVM_VFIO Selection**

Alright, let's dissect this. My immediate thought is, "What specifically *triggers* the selection or activation of the KVM_VFIO module?" It's not a generic question; I'm not looking for a definition, but rather the causal mechanisms. I'm thinking about the control path, the *why* and the *how* of its inclusion in a running kernel. Are we talking about a configuration option during the build process that's explicitly chosen? Is it dependent on the presence of specific hardware features within the system's architecture, such as an IOMMU, or specific types of devices? Perhaps it's dynamically loaded based on some detection or probe within the kernel itself. I'm keen on understanding the decision-making process within the kernel code. Where in the sequence does this happen? What conditionals are evaluated? What are the dependencies? I need to get to the root of the kernel's decision-making process for VFIO enablement.



28/2 2026/10/08 07:03 tool grepper
0m Args:
{
  "Expression": "select KVM_VFIO"
}

Results:
{
  "Output": "arch/arm64/kvm/Kconfig=20=menuconfig KVM\n--\narch/arm64/kvm/Kconfig-27-\tselect VIRT_XFER_TO_GUEST_WORK\narch/arm64/kvm/Kconfig:28:\tselect KVM_VFIO\narch/arm64/kvm/Kconfig-29-\tselect HAVE_KVM_DIRTY_RING_ACQ_REL\n--\narch/powerpc/kvm/Kconfig=20=config KVM\n--\narch/powerpc/kvm/Kconfig-22-\tselect KVM_COMMON\narch/powerpc/kvm/Kconfig:23:\tselect KVM_VFIO\narch/powerpc/kvm/Kconfig-24-\tselect HAVE_KVM_IRQ_BYPASS\n--\narch/s390/kvm/Kconfig=19=config KVM\n--\narch/s390/kvm/Kconfig-29-\tselect HAVE_KVM_NO_POLL\narch/s390/kvm/Kconfig:30:\tselect KVM_VFIO\narch/s390/kvm/Kconfig-31-\tselect VIRT_XFER_TO_GUEST_WORK\n--\narch/x86/kvm/Kconfig=20=config KVM_X86\n--\narch/x86/kvm/Kconfig-44-\tselect KVM_GENERIC_DIRTYLOG_READ_PROTECT\narch/x86/kvm/Kconfig:45:\tselect KVM_VFIO\narch/x86/kvm/Kconfig-46-\tselect HAVE_KVM_PM_NOTIFIER if PM\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 69782
							output: 48
							thoughts: 67
						

Thoughts:
Here's a breakdown of my thought process:

**KVM Configuration Deep Dive**

Okay, so `KVM_X86` is definitely the key here, as it *selects* `KVM_VFIO`. That's important to remember for VFIO setups. And naturally, both `KVM_INTEL` and `KVM_AMD` depend on `KVM_X86`, or at least on `KVM`. This dependency chain is crucial for understanding how the KVM modules are built and interact, especially in x86-based systems. To understand this in detail I should probably check `arch/x86/kvm/Kconfig`. Time to delve into the architecture-specific configuration!



30/2 2026/10/08 07:03 tool grepper
0m Args:
{
  "Expression": "config KVM\\b|config KVM_AMD|config KVM_INTEL",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Kconfig=20=config KVM_X86\n--\narch/x86/kvm/Kconfig-51-\narch/x86/kvm/Kconfig:52:config KVM\narch/x86/kvm/Kconfig-53-\ttristate \"Kernel-based Virtual Machine (KVM) support\"\n--\narch/x86/kvm/Kconfig=83=config KVM_SW_PROTECTED_VM\n--\narch/x86/kvm/Kconfig-95-\narch/x86/kvm/Kconfig:96:config KVM_INTEL\narch/x86/kvm/Kconfig-97-\ttristate \"KVM for Intel (and compatible) processors support\"\n--\narch/x86/kvm/Kconfig-106-\narch/x86/kvm/Kconfig:107:config KVM_INTEL_PROVE_VE\narch/x86/kvm/Kconfig-108-        bool \"Check that guests do not receive #VE exceptions\"\n--\narch/x86/kvm/Kconfig=122=config X86_SGX_KVM\n--\narch/x86/kvm/Kconfig-133-\narch/x86/kvm/Kconfig:134:config KVM_INTEL_TDX\narch/x86/kvm/Kconfig-135-\tbool \"Intel Trust Domain Extensions (TDX) support\"\n--\narch/x86/kvm/Kconfig-145-\narch/x86/kvm/Kconfig:146:config KVM_AMD\narch/x86/kvm/Kconfig-147-\ttristate \"KVM for AMD processors support\"\n--\narch/x86/kvm/Kconfig-155-\narch/x86/kvm/Kconfig:156:config KVM_AMD_SEV\narch/x86/kvm/Kconfig-157-\tbool \"AMD Secure Encrypted Virtualization (SEV) support\"\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 70583
							output: 31
							thoughts: 48
						

Thoughts:
Here's my take on those thoughts:

**KVM and VFIO Considerations**

Alright, let's break this down. My mind is immediately jumping to the hypervisor, specifically `KVM`. Thinking about KVM, I'm already mentally parsing it into its AMD and Intel flavors: `KVM_AMD`, `KVM_INTEL`, and even the more specialized AMD SEV implementation, `KVM_AMD_SEV`. The nuances of each are important, especially considering the hardware-specific features. 

Next up, VFIO. Obviously, the focus shifts towards direct device assignment. To confirm my understanding and to get a complete picture, I need to check the kernel configuration options, specifically the `drivers/vfio/Kconfig` file. I'm going straight to the source to solidify my understanding.



32/2 2026/10/08 07:03 tool grepper
0m Args:
{
  "Expression": "config VFIO\\b",
  "PathPrefixes": [
    "drivers/vfio/"
  ]
}

Results:
{
  "Output": "drivers/vfio/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\ndrivers/vfio/Kconfig:2:menuconfig VFIO\ndrivers/vfio/Kconfig-3-\ttristate \"VFIO Non-Privileged userspace driver framework\"\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 70914
							output: 29
							thoughts: 40
						

Thoughts:
Okay, let's break this down.

**VFIO Investigation - Diving into the Grouping**

Right, `VFIO` is the primary namespace we're dealing with for Virtual Function I/O, that much is clear. But I need to refresh my memory, or perhaps, explore some specifics. I'm thinking about the role of `VFIO_GROUP`. I *think* I recall that being a critical piece of the puzzle, so I need to understand its relationship to the broader VFIO implementation. Time to dig in a bit.

I'll check the source - specifically, let's head straight for `group.c` within the `drivers/vfio` directory and look at the `Makefile` there. That should shed some light on how `VFIO_GROUP` is defined, utilized, and linked within the module. Knowing how the modules relate to each other is key for a well-integrated vfio implementation.



34/2 2026/10/08 07:03 tool grepper
0m Args:
{
  "Expression": "group\\.o",
  "PathPrefixes": [
    "drivers/vfio/"
  ]
}

Results:
{
  "Output": "drivers/vfio/Makefile=5=vfio-$(CONFIG_VFIO_DEVICE_CDEV) += device_cdev.o\ndrivers/vfio/Makefile:6:vfio-$(CONFIG_VFIO_GROUP) += group.o\ndrivers/vfio/Makefile-7-vfio-$(CONFIG_IOMMUFD) += iommufd.o\n"
}

35/2 2026/10/08 07:03 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 71276
							output: 40
							thoughts: 88
						

Thoughts:
Okay, here's my take on those kernel config directives:

**VFIO Configuration Thoughts**

Right, so, `CONFIG_VFIO_GROUP` – that's the starting point. I need to make sure that's set. And then, there's `vfio-$(CONFIG_IOMMUFD) += iommufd.o`. Ah, this is good. Conditional compilation of `iommufd.o` based on `CONFIG_IOMMUFD`. Makes perfect sense. Then we have `device_cdev.o` is for `CONFIG_VFIO_DEVICE_CDEV`, understood.

To be completely thorough, let's head over to `drivers/vfio/Kconfig`. I need to review the Kconfig file to confirm the default settings and any dependencies for both `VFIO_GROUP` and `VFIO_DEVICE_CDEV` to ensure proper configuration. It's always best to understand the context of these settings, especially any relationships they might have with other features. Gotta keep the build clean and optimized.



36/2 2026/10/08 07:03 tool grepper
0m Args:
{
  "Expression": "config VFIO_GROUP|config VFIO_DEVICE_CDEV",
  "PathPrefixes": [
    "drivers/vfio/"
  ]
}

Results:
{
  "Output": "drivers/vfio/Kconfig=16=if VFIO\ndrivers/vfio/Kconfig:17:config VFIO_DEVICE_CDEV\ndrivers/vfio/Kconfig-18-\tbool \"Support for the VFIO cdev /dev/vfio/devices/vfioX\"\n--\ndrivers/vfio/Kconfig-28-\ndrivers/vfio/Kconfig:29:config VFIO_GROUP\ndrivers/vfio/Kconfig-30-\tbool \"Support for the VFIO group /dev/vfio/$group_id\"\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 71773
							output: 39
							thoughts: 48
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach summarizing the prompt:

**Inspecting IOMMUFD Configuration Options**

Alright, my next step is clear. I need to get a handle on the available configuration options for the `IOMMUFD` driver. It looks like the Kconfig file within the `drivers/iommu/iommufd/` directory is where those definitions reside. I should begin by reading that `drivers/iommu/iommufd/Kconfig` file. That's where I will find what options I can configure in relation to `IOMMUFD`.



38/2 2026/10/08 07:04 tool read-file
0m Args:
{
  "File": "drivers/iommu/iommufd/Kconfig",
  "FirstLine": 1,
  "LineCount": 60
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\tconfig IOMMUFD_DRIVER_CORE\n   3:\t\tbool\n   4:\t\tdefault (IOMMUFD_DRIVER || IOMMUFD) if IOMMUFD!=n\n   5:\t\n   6:\tconfig IOMMUFD\n   7:\t\ttristate \"IOMMU Userspace API\"\n   8:\t\tselect INTERVAL_TREE\n   9:\t\tselect INTERVAL_TREE_SPAN_ITER\n  10:\t\tselect IOMMU_API\n  11:\t\tdefault n\n  12:\t\thelp\n  13:\t\t  Provides /dev/iommu, the user API to control the IOMMU subsystem as\n  14:\t\t  it relates to managing IO page tables that point at user space memory.\n  15:\t\n  16:\t\t  If you don't know what to do here, say N.\n  17:\t\n  18:\tif IOMMUFD\n  19:\tconfig IOMMUFD_NOIOMMU\n  20:\t\tbool\n  21:\t\tdepends on !GENERIC_ATOMIC64 # IOMMU_PT_AMDV1 requires cmpxchg64\n  22:\t\tselect GENERIC_PT\n  23:\t\tselect IOMMU_PT\n  24:\t\tselect IOMMU_PT_AMDV1\n  25:\t\thelp\n  26:\t\t  Provides a SW-only IO page table for devices without hardware\n  27:\t\t  IOMMU backing. This uses the AMDV1 page table format for\n  28:\t\t  IOVA-to-PA lookups only, not for hardware DMA translation.\n  29:\t\t  To be selected by VFIO_NOIOMMU when VFIO_DEVICE_CDEV is enabled.\n  30:\t\n  31:\tconfig IOMMUFD_VFIO_CONTAINER\n  32:\t\tbool \"IOMMUFD provides the VFIO container /dev/vfio/vfio\"\n  33:\t\tdepends on VFIO_GROUP \u0026\u0026 !VFIO_CONTAINER\n  34:\t\tdefault VFIO_GROUP \u0026\u0026 !VFIO_CONTAINER\n  35:\t\thelp\n  36:\t\t  IOMMUFD will provide /dev/vfio/vfio instead of VFIO. This relies on\n  37:\t\t  IOMMUFD providing compatibility emulation to give the same ioctls.\n  38:\t\t  It provides an option to build a kernel with legacy VFIO components\n  39:\t\t  removed.\n  40:\t\n  41:\t\t  IOMMUFD VFIO container emulation is known to lack certain features\n  42:\t\t  of the native VFIO container, such as peer-to-peer\n  43:\t\t  DMA mapping, PPC IOMMU support, as well as other potentially\n  44:\t\t  undiscovered gaps.  This option is currently intended for the\n  45:\t\t  purpose of testing IOMMUFD with unmodified userspace supporting VFIO\n  46:\t\t  and making use of the Type1 VFIO IOMMU backend.  General purpose\n  47:\t\t  enabling of this option is currently discouraged.\n  48:\t\n  49:\t\t  Unless testing IOMMUFD, say N here.\n  50:\t\n  51:\tconfig IOMMUFD_TEST\n  52:\t\tbool \"IOMMU Userspace API Test support\"\n  53:\t\tdepends on DEBUG_KERNEL\n  54:\t\tdepends on FAULT_INJECTION\n  55:\t\tdepends on RUNTIME_TESTING_MENU\n  56:\t\tdepends on IOMMU_PT_AMDV1=y || IOMMUFD=IOMMU_PT_AMDV1\n  57:\t\tselect DMA_SHARED_BUFFER\n  58:\t\tselect IOMMUFD_DRIVER\n  59:\t\tdefault n\n  60:\t\thelp\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 72936
							output: 37
							thoughts: 49
						

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

**Investigating IOMMUFD and Related Configurations**

Right, so `IOMMUFD` and `IOMMUFD_TEST`... those flags are immediately ringing alarm bells and sparking my interest. I need to get a handle on the landscape here, and I'm instantly thinking about how these are implemented. "IOMMUFD", the IOMMU File Descriptor is clearly relevant to my work, and potentially to the way I think about IOMMU's from my perspective. I remember something about an `AMD_IOMMU_IOMMUFD` macro, but I can't quite remember where it is in the tree. The obvious place to start digging is the AMD-specific configuration, so I'm heading directly for `drivers/iommu/amd/Kconfig`. I'll need to understand the relationship between these options, their dependencies, and what they actually enable. I'm especially keen to see if there's any mention of how this affects device assignment or other related core IOMMU functionality.



40/2 2026/10/08 07:04 tool grepper
0m Args:
{
  "Expression": "AMD_IOMMU_IOMMUFD",
  "PathPrefixes": [
    "drivers/iommu/"
  ]
}

Results:
{
  "Output": "drivers/iommu/amd/Kconfig=3=config AMD_IOMMU\n--\ndrivers/iommu/amd/Kconfig-32-\ndrivers/iommu/amd/Kconfig:33:config AMD_IOMMU_IOMMUFD\ndrivers/iommu/amd/Kconfig-34-\tbool \"Enable IOMMUFD features for AMD IOMMU (EXPERIMENTAL)\"\n--\ndrivers/iommu/amd/Makefile=2=obj-y += iommu.o init.o quirks.o ppr.o pasid.o\ndrivers/iommu/amd/Makefile:3:obj-$(CONFIG_AMD_IOMMU_IOMMUFD) += iommufd.o nested.o\ndrivers/iommu/amd/Makefile-4-obj-$(CONFIG_AMD_IOMMU_DEBUGFS) += debugfs.o\n--\ndrivers/iommu/amd/iommufd.h-8-\ndrivers/iommu/amd/iommufd.h:9:#if IS_ENABLED(CONFIG_AMD_IOMMU_IOMMUFD)\ndrivers/iommu/amd/iommufd.h-10-void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_type *type);\n--\ndrivers/iommu/amd/iommufd.h=14=int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,\n--\ndrivers/iommu/amd/iommufd.h-20-#define amd_iommufd_get_viommu_ops NULL\ndrivers/iommu/amd/iommufd.h:21:#endif /* CONFIG_AMD_IOMMU_IOMMUFD */\ndrivers/iommu/amd/iommufd.h-22-\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 73723
							output: 422
							thoughts: 2985
						

Thoughts:
**Analysis and Configuration for Fuzzing Focus**

Alright, let's break this down. We're dealing with `AMD_IOMMU_IOMMUFD`, `PCI_TSM`, and `TSM`. The `Makefile` and `Kconfig` entries are clear; `PCI_TSM` selects `TSM`. The kernel config flags are straightforward: we need `KVM`, `KVM_AMD`, `KVM_INTEL`, `VFIO`, `IOMMUFD`, `IOMMUFD_TEST`, `PCI_TSM`, and `AMD_IOMMU_IOMMUFD`. No surprises there.

Now, the meat of it: the focus symbols. We have a set of functions that specifically implement or modify the logic under review.

*   **Key IOCTL entrypoints and Allocations:**
    *   `iommufd_vdevice_tsm_req_ioctl`: This is a brand new ioctl entry point, directly targeting the new TSM functionality in IOMMUFD. This is prime.
    *   `iommufd_viommu_alloc_ioctl`:  This one is important because it is modifying core viommu allocation logic. This is definitely a significant change that needs to be scrutinized.
    *   `iommufd_vdevice_alloc_ioctl`: vdevice allocation logic modification. Important.
    *   `iommufd_viommu_alloc_hwpt_nested`: nested hwpt allocation - important for nested virtualization.

*   **KVM, VFIO, and File-Based Interactions:**
    *   `kvm_vfio_file_add`: Updating the KVM-VFIO binding entrypoint. Using `struct file` is very important as this is refactoring lifetimes.
    *   `vfio_file_set_kvm`: VFIO KVM association.
    *   `file_to_kvm_x86`:  This is a new helper for KVM file conversion, and it's exported. Vital.
    *   `kvm_page_track_register_notifier`: KVM page track notifier updated. Good candidate.

*   **PCI TSM:**
    *   `pci_tsm_context_get`, `pci_tsm_context_put`: PCI TSM context tracking and releasing are fundamental.
    *   `disconnect_store`: This is the sysfs function for the "disconnect" attribute - good for fuzzing.

*   **SEV context and misc:**
    *   `sev_vm_move_enc_context_from` : Updated SEV encryption context transfer.
    *   `sev_vm_copy_enc_context_from` : Updated SEV encryption context transfer.

Let's make sure these functions will execute correctly in standard virtualized environments. All of the subsystems (KVM, VFIO, IOMMUFD) interact with userspace (via syscalls and ioctls), which will make this fuzzable.

The patch is a well-defined set of changes touching the interface and lifecycle between KVM, VFIO, and IOMMUFD (struct kvm references updated to file based), adding a new uAPI ioctl (`IOMMU_VDEVICE_TSM_REQ`), and refactoring virtual IOMMU (`viommu`) allocation and vdevice handling, nested HWPT allocation, PCI TSM context management, sysfs disconnect handling, and SEV context transfer in KVM. All these are reachable via `/dev/kvm`, `/dev/iommu`, VFIO fds, and sysfs. Good. This is a very targeted, well-defined patch, and the chosen focus symbols accurately reflect its core functionality and ensure effective fuzzing.



42/2 2026/10/08 07:04 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "VFIO",
    "VFIO_GROUP",
    "VFIO_DEVICE_CDEV",
    "IOMMUFD",
    "IOMMUFD_TEST",
    "PCI_TSM",
    "AMD_IOMMU_IOMMUFD"
  ],
  "FocusSymbols": [
    "iommufd_vdevice_tsm_req_ioctl",
    "iommufd_viommu_alloc_ioctl",
    "iommufd_vdevice_alloc_ioctl",
    "iommufd_viommu_alloc_hwpt_nested",
    "kvm_vfio_file_add",
    "vfio_file_set_kvm",
    "file_to_kvm_x86",
    "pci_tsm_context_get",
    "pci_tsm_context_put",
    "disconnect_store",
    "sev_vm_move_enc_context_from",
    "kvm_page_track_register_notifier"
  ],
  "Reasoning": "This patch series refactors reference counting and lifecycle management between KVM, VFIO, and IOMMUFD by replacing raw 'struct kvm *' pointers with 'struct file *' references. It introduces a new userspace ioctl (IOMMU_VDEVICE_TSM_REQ) handled by iommufd_vdevice_tsm_req_ioctl(), refactors virtual IOMMU (viommu) allocation and vDevice handling in IOMMUFD, refactors PCI TSM context lifecycle and sysfs disconnection handling, and updates KVM SEV context migration. These code paths are directly reachable and exercisable from userspace via /dev/kvm, /dev/iommu, VFIO file descriptors, and sysfs.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_AMD",
    "VFIO",
    "VFIO_GROUP",
    "VFIO_DEVICE_CDEV",
    "IOMMUFD",
    "IOMMUFD_TEST",
    "PCI_TSM",
    "AMD_IOMMU_IOMMUFD"
  ],
  "FocusSymbols": [
    "iommufd_vdevice_tsm_req_ioctl",
    "iommufd_viommu_alloc_ioctl",
    "iommufd_vdevice_alloc_ioctl",
    "iommufd_viommu_alloc_hwpt_nested",
    "kvm_vfio_file_add",
    "vfio_file_set_kvm",
    "file_to_kvm_x86",
    "pci_tsm_context_get",
    "pci_tsm_context_put",
    "disconnect_store",
    "sev_vm_move_enc_context_from",
    "kvm_page_track_register_notifier"
  ],
  "Reasoning": "This patch series refactors reference counting and lifecycle management between KVM, VFIO, and IOMMUFD by replacing raw 'struct kvm *' pointers with 'struct file *' references. It introduces a new userspace ioctl (IOMMU_VDEVICE_TSM_REQ) handled by iommufd_vdevice_tsm_req_ioctl(), refactors virtual IOMMU (viommu) allocation and vDevice handling in IOMMUFD, refactors PCI TSM context lifecycle and sysfs disconnection handling, and updates KVM SEV context migration. These code paths are directly reachable and exercisable from userspace via /dev/kvm, /dev/iommu, VFIO file descriptors, and sysfs.",
  "WorthFuzzing": true
}

43/1 2026/10/08 07:04 action If
6m Args:
{
  "WorthFuzzing": true
}

Results:
null

44/2 2026/10/08 07:04 agent kmsan-evaluator
6m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series makes architectural changes across KVM, VFIO, PCI/TSM, and IOMMUFD:\n1. Replaces direct 'struct kvm *' pointers in VFIO and architecture hooks with 'struct file *' back-references (via get_file_active() / fput()) to manage VM file lifetimes without circular pinning.\n2. Refactors vIOMMU driver ops lookup by introducing get_viommu_ops returning 'const struct iommufd_viommu_ops *'.\n3. Adds PCI TSM context lifecycle management and refcounting (pci_tsm_context, context_users, contexts_drained completion) to prevent premature link disconnection.\n4. Implements the IOMMU_VDEVICE_TSM_REQ ioctl (iommufd_vdevice_tsm_req_ioctl) to forward guest TSM requests to vdevices.\n\nMemory initialization and KMSAN applicability analysis:\n- Kernel-to-userspace data copying: The only new structure copied to userspace is 'struct iommu_vdevice_tsm_req' in iommufd_vdevice_tsm_req_ioctl() via iommufd_ucmd_respond(). The structure contains six 32-bit fields (24 bytes) followed by three 64-bit fields (24 bytes), totalling 48 bytes with zero padding holes. The command buffer is initialized by copy_struct_from_user() (which zeroes any remaining bytes in the kernel buffer if userspace provides fewer bytes), and 'out_tsm_code' is explicitly zero-initialized prior to execution. There is no risk of info-leaks or uninitialized byte exposures.\n- Heap structures: All newly allocated heap structures (struct pci_tsm_context via kzalloc_obj, struct iommufd_viommu and struct iommufd_device via _iommufd_object_alloc/kzalloc) are zero-initialized upon allocation.\n- Stack structures: 'struct tsm_guest_req_info info' is fully populated using a designated initializer.\n- Flow and bounds: Control flow, operations masks, and buffer lengths (req_len, resp_len \u003c= INT_MAX; op \u003c TSM_REQ_MAX) are explicitly validated.\n\nKASAN vs KMSAN applicability:\nThe primary risks introduced by these changes are reference counting mismatches (file references, module refcounts), synchronization deadlocks (completion wait loops and mutex/rwsem locks), and use-after-free conditions during object cleanup. All of these failure modes are covered by standard KASAN, LOCKDEP, and refcount tracking. Because no uninitialized memory usage or padding leaks are introduced, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

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

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

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

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

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

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

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


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

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit bf97d08b5c6e71cd454dbf6a948982dac7a9d1d3
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 8 06:59:51 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/ABI/testing/sysfs-bus-pci b/Documentation/ABI/testing/sysfs-bus-pci
index 55ea1db749a18..4c64b30544cdc 100644
--- a/Documentation/ABI/testing/sysfs-bus-pci
+++ b/Documentation/ABI/testing/sysfs-bus-pci
@@ -654,6 +654,9 @@ Contact:	linux-coco@lists.linux.dev
 Description:
 		(WO) Write the name of the TSM device that was specified
 		to 'connect' to teardown the connection.
+		The write fails with EBUSY while any vdevice depends on the
+		connection. Userspace must destroy those vdevices before
+		disconnecting the link.
 
 What:		/sys/bus/pci/devices/.../tsm/dsm
 Contact:	linux-coco@lists.linux.dev
@@ -671,20 +674,6 @@ Description:	(RO) Return PCI device name of this device's DSM (Device
 		PCIe switch port. This is a "link" TSM attribute, see
 		Documentation/ABI/testing/sysfs-class-tsm.
 
-What:		/sys/bus/pci/devices/.../tsm/bound
-Contact:	linux-coco@lists.linux.dev
-Description:	(RO) Return the device name of the TSM when the device is in a
-		TDISP (TEE Device Interface Security Protocol) operational state
-		(LOCKED, RUN, or ERROR, not UNLOCKED). Bound devices consume
-		platform TSM resources and depend on the device's configuration
-		(e.g. BME (Bus Master Enable) and MSE (Memory Space Enable)
-		among other settings) to remain stable for the duration of the
-		bound state. This attribute is only visible for devices that
-		support TDISP operation, and it is only populated after
-		successful connect and TSM bind. The TSM bind operation is
-		initiated by VFIO/IOMMUFD. This is a "link" TSM attribute, see
-		Documentation/ABI/testing/sysfs-class-tsm.
-
 What:		/sys/bus/pci/devices/.../authenticated
 Contact:	linux-pci@vger.kernel.org
 Description:
diff --git a/Documentation/userspace-api/iommufd.rst b/Documentation/userspace-api/iommufd.rst
index f1c4d21e5c5ee..8e2fa3a524f0c 100644
--- a/Documentation/userspace-api/iommufd.rst
+++ b/Documentation/userspace-api/iommufd.rst
@@ -82,11 +82,10 @@ Following IOMMUFD objects are exposed to userspace:
   * Direct assigned invalidation queues
   * Direct assigned interrupts
 
-  Such a vIOMMU object generally has the access to a nesting parent pagetable
-  to support some HW-accelerated virtualization features. So, a vIOMMU object
-  must be created given a nesting parent HWPT_PAGING object, and then it would
-  encapsulate that HWPT_PAGING object. Therefore, a vIOMMU object can be used
-  to allocate an HWPT_NESTED object in place of the encapsulated HWPT_PAGING.
+  A vIOMMU object may encapsulate a nesting parent HWPT_PAGING object to
+  support HW-accelerated virtualization features. Whether a parent is required
+  is determined by the selected vIOMMU implementation. Only a parent-backed
+  vIOMMU can be used to allocate an HWPT_NESTED object.
 
   .. note::
 
@@ -226,9 +225,9 @@ creating the objects and links::
      flag is set.
 
 4. IOMMUFD_OBJ_HWPT_NESTED can be only manually created via the IOMMU_HWPT_ALLOC
-   uAPI, provided an hwpt_id or a viommu_id of a vIOMMU object encapsulating a
-   nesting parent HWPT_PAGING via @pt_id to associate the new HWPT_NESTED object
-   to the corresponding HWPT_PAGING object. The associating HWPT_PAGING object
+   uAPI, provided an hwpt_id or a viommu_id of a parent-backed vIOMMU object
+   via @pt_id to associate the new HWPT_NESTED object to the corresponding
+   HWPT_PAGING object. The associating HWPT_PAGING object
    must be a nesting parent manually allocated via the same uAPI previously with
    an IOMMU_HWPT_ALLOC_NEST_PARENT flag, otherwise the allocation will fail. The
    allocation will be further validated by the IOMMU driver to ensure that the
@@ -245,25 +244,28 @@ creating the objects and links::
       of the object passed in via the @pt_id field of struct iommufd_hwpt_alloc.
 
 5. IOMMUFD_OBJ_VIOMMU can be only manually created via the IOMMU_VIOMMU_ALLOC
-   uAPI, provided a dev_id (for the device's physical IOMMU to back the vIOMMU)
-   and an hwpt_id (to associate the vIOMMU to a nesting parent HWPT_PAGING). The
-   iommufd core will link the vIOMMU object to the struct iommu_device that the
-   struct device is behind. And an IOMMU driver can implement a viommu_alloc op
-   to allocate its own vIOMMU data structure embedding the core-level structure
-   iommufd_viommu and some driver-specific data. If necessary, the driver can
-   also configure its HW virtualization feature for that vIOMMU (and thus for
-   the VM). Successful completion of this operation sets up the linkages between
-   the vIOMMU object and the HWPT_PAGING, then this vIOMMU object can be used
-   as a nesting parent object to allocate an HWPT_NESTED object described above.
+   uAPI, provided a dev_id identifying the device used to select the vIOMMU
+   implementation and, if the selected implementation requires a nesting
+   parent HWPT_PAGING, an hwpt_id. The hwpt_id must be zero for an
+   implementation that does not use a parent. A physical-IOMMU implementation
+   links the vIOMMU object to the struct iommu_device behind the device. Other
+   implementations, such as a TSM associated with the device, can provide their
+   own backing and device association. An implementation can allocate its own
+   vIOMMU data structure embedding the core-level structure iommufd_viommu and
+   some implementation-specific data. If necessary, it can also configure its
+   virtualization resources for that vIOMMU (and thus for the VM). A
+   parent-backed vIOMMU can be used as a nesting parent object to allocate an
+   HWPT_NESTED object described above.
 
 6. IOMMUFD_OBJ_VDEVICE can be only manually created via the IOMMU_VDEVICE_ALLOC
    uAPI, provided a viommu_id for an iommufd_viommu object and a dev_id for an
    iommufd_device object. The vDEVICE object will be the binding between these
    two parent objects. Another @virt_id will be also set via the uAPI providing
    the iommufd core an index to store the vDEVICE object to a vDEVICE array per
-   vIOMMU. If necessary, the IOMMU driver may choose to implement a vdevce_alloc
-   op to init its HW for virtualization feature related to a vDEVICE. Successful
-   completion of this operation sets up the linkages between vIOMMU and device.
+   vIOMMU. A physical-IOMMU implementation requires the device to be behind the
+   same iommu_device as the vIOMMU. Other implementations validate the device
+   association while initializing the vDEVICE. Successful initialization sets
+   up the linkage between the vIOMMU and device.
 
 A device can only bind to an iommufd due to DMA ownership claim and attach to at
 most one IOAS object (no support of PASID yet).
diff --git a/arch/s390/include/asm/kvm_host_s390.h b/arch/s390/include/asm/kvm_host_s390.h
index cd692f8fb7643..9519b8028b104 100644
--- a/arch/s390/include/asm/kvm_host_s390.h
+++ b/arch/s390/include/asm/kvm_host_s390.h
@@ -27,6 +27,8 @@
 #include <asm/isc.h>
 #include <asm/guarded_storage.h>
 
+#define kvm_file_to_kvm_arch s390
+
 #define KVM_HAVE_MMU_RWLOCK
 #define KVM_MAX_VCPUS 255
 
@@ -720,7 +722,7 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {}
 void kvm_arch_free_vm(struct kvm *kvm);
 
 struct zpci_kvm_hook {
-	int (*kvm_register)(void *opaque, struct kvm *kvm);
+	int (*kvm_register)(void *opaque, struct file *kvm_file);
 	void (*kvm_unregister)(void *opaque);
 };
 
diff --git a/arch/s390/kvm/s390/pci.c b/arch/s390/kvm/s390/pci.c
index 82892e1e03d94..d79bd3bdc68e9 100644
--- a/arch/s390/kvm/s390/pci.c
+++ b/arch/s390/kvm/s390/pci.c
@@ -498,17 +498,22 @@ static void kvm_s390_pci_dev_release(struct zpci_dev *zdev)
  * available, enable them and let userspace indicate whether or not they will
  * be used (specify SHM bit to disable).
  */
-static int kvm_s390_pci_register_kvm(void *opaque, struct kvm *kvm)
+static int kvm_s390_pci_register_kvm(void *opaque, struct file *kvm_file)
 {
 	struct zpci_dev *zdev = opaque;
+	struct kvm *kvm;
 	int rc;
 
 	if (!zdev)
 		return -EINVAL;
 
+	kvm = file_to_kvm_s390(kvm_file);
+	if (!kvm)
+		return -ENOENT;
+
 	mutex_lock(&zdev->kzdev_lock);
 
-	if (zdev->kzdev || zdev->gisa != 0 || !kvm) {
+	if (zdev->kzdev || zdev->gisa != 0) {
 		mutex_unlock(&zdev->kzdev_lock);
 		return -EINVAL;
 	}
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 683bb8bf43a94..e460073ff176d 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -44,6 +44,8 @@
 
 #include <hyperv/hvhdk.h>
 
+#define kvm_file_to_kvm_arch x86
+
 #define __KVM_HAVE_ARCH_VCPU_DEBUGFS
 
 /*
diff --git a/arch/x86/include/asm/kvm_page_track.h b/arch/x86/include/asm/kvm_page_track.h
index 3d040741044b4..ea885dd5c9aff 100644
--- a/arch/x86/include/asm/kvm_page_track.h
+++ b/arch/x86/include/asm/kvm_page_track.h
@@ -44,13 +44,15 @@ struct kvm_page_track_notifier_node {
 				    struct kvm_page_track_notifier_node *node);
 };
 
-int kvm_page_track_register_notifier(struct kvm *kvm,
+struct file;
+
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n);
-void kvm_page_track_unregister_notifier(struct kvm *kvm,
+void kvm_page_track_unregister_notifier(struct file *file,
 					struct kvm_page_track_notifier_node *n);
 
-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn);
-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn);
+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn);
+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn);
 #else
 /*
  * Allow defining a node in a structure even if page tracking is disabled, e.g.
diff --git a/arch/x86/kvm/Makefile b/arch/x86/kvm/Makefile
index 0474604ab8a14..c6bf463f50327 100644
--- a/arch/x86/kvm/Makefile
+++ b/arch/x86/kvm/Makefile
@@ -61,9 +61,7 @@ exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/a
 				-e kvm_page_track_unregister_notifier \
 				-e kvm_write_track_add_gfn \
 				-e kvm_write_track_remove_gfn \
-				-e kvm_get_kvm \
-				-e kvm_get_kvm_safe \
-				-e kvm_put_kvm
+				-e kvm_file_to_kvm_fn
 
 # Force grep to emit a goofy group separator that can in turn be replaced with
 # the above newline macro (newlines in Make are a nightmare).  Note, grep only
diff --git a/arch/x86/kvm/mmu/page_track.c b/arch/x86/kvm/mmu/page_track.c
index 7e8195a311bb0..f12558dfcd812 100644
--- a/arch/x86/kvm/mmu/page_track.c
+++ b/arch/x86/kvm/mmu/page_track.c
@@ -16,6 +16,8 @@
 #include <linux/kvm_host.h>
 #include <linux/rculist.h>
 
+#include <asm/kvm_page_track.h>
+
 #include "mmu.h"
 #include "mmu_internal.h"
 #include "page_track.h"
@@ -237,10 +239,11 @@ static int kvm_enable_external_write_tracking(struct kvm *kvm)
  * register the notifier so that event interception for the tracked guest
  * pages can be received.
  */
-int kvm_page_track_register_notifier(struct kvm *kvm,
+int kvm_page_track_register_notifier(struct file *file,
 				     struct kvm_page_track_notifier_node *n)
 {
 	struct kvm_page_track_notifier_head *head;
+	struct kvm *kvm = file_to_kvm_x86(file);
 	int r;
 
 	if (!kvm || kvm->mm != current->mm)
@@ -252,7 +255,7 @@ int kvm_page_track_register_notifier(struct kvm *kvm,
 			return r;
 	}
 
-	kvm_get_kvm(kvm);
+	get_file(file);
 
 	head = &kvm->arch.track_notifier_head;
 
@@ -267,10 +270,11 @@ EXPORT_SYMBOL_GPL(kvm_page_track_register_notifier);
  * stop receiving the event interception. It is the opposed operation of
  * kvm_page_track_register_notifier().
  */
-void kvm_page_track_unregister_notifier(struct kvm *kvm,
+void kvm_page_track_unregister_notifier(struct file *file,
 					struct kvm_page_track_notifier_node *n)
 {
 	struct kvm_page_track_notifier_head *head;
+	struct kvm *kvm = file_to_kvm_x86(file);
 
 	head = &kvm->arch.track_notifier_head;
 
@@ -279,7 +283,7 @@ void kvm_page_track_unregister_notifier(struct kvm *kvm,
 	write_unlock(&kvm->mmu_lock);
 	synchronize_srcu(&head->track_srcu);
 
-	kvm_put_kvm(kvm);
+	fput(file);
 }
 EXPORT_SYMBOL_GPL(kvm_page_track_unregister_notifier);
 
@@ -336,11 +340,12 @@ void kvm_page_track_delete_slot(struct kvm *kvm, struct kvm_memory_slot *slot)
  * add guest page to the tracking pool so that corresponding access on that
  * page will be intercepted.
  *
- * @kvm: the guest instance we are interested in.
+ * @file: the VM file of the guest instance we are interested in.
  * @gfn: the guest page.
  */
-int kvm_write_track_add_gfn(struct kvm *kvm, gfn_t gfn)
+int kvm_write_track_add_gfn(struct file *file, gfn_t gfn)
 {
+	struct kvm *kvm = file_to_kvm_x86(file);
 	struct kvm_memory_slot *slot;
 	int idx;
 
@@ -366,11 +371,12 @@ EXPORT_SYMBOL_GPL(kvm_write_track_add_gfn);
  * remove the guest page from the tracking pool which stops the interception
  * of corresponding access on that page.
  *
- * @kvm: the guest instance we are interested in.
+ * @file: the VM file of the guest instance we are interested in.
  * @gfn: the guest page.
  */
-int kvm_write_track_remove_gfn(struct kvm *kvm, gfn_t gfn)
+int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn)
 {
+	struct kvm *kvm = file_to_kvm_x86(file);
 	struct kvm_memory_slot *slot;
 	int idx;
 
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index 63eb2155a7749..db7ed11e9056f 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -2151,10 +2151,10 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
 	if (fd_empty(f))
 		return -EBADF;
 
-	if (!file_is_kvm(fd_file(f)))
+	source_kvm = file_to_kvm_x86(fd_file(f));
+	if (!source_kvm)
 		return -EBADF;
 
-	source_kvm = fd_file(f)->private_data;
 	ret = sev_lock_two_vms(kvm, source_kvm);
 	if (ret)
 		return ret;
@@ -2876,10 +2876,10 @@ int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
 	if (fd_empty(f))
 		return -EBADF;
 
-	if (!file_is_kvm(fd_file(f)))
+	source_kvm = file_to_kvm_x86(fd_file(f));
+	if (!source_kvm)
 		return -EBADF;
 
-	source_kvm = fd_file(f)->private_data;
 	ret = sev_lock_two_vms(kvm, source_kvm);
 	if (ret)
 		return ret;
diff --git a/drivers/iommu/amd/iommu.c b/drivers/iommu/amd/iommu.c
index 56262f6b1f700..a3c58dd39549b 100644
--- a/drivers/iommu/amd/iommu.c
+++ b/drivers/iommu/amd/iommu.c
@@ -3211,8 +3211,7 @@ const struct iommu_ops amd_iommu_ops = {
 	.is_attach_deferred = amd_iommu_is_attach_deferred,
 	.def_domain_type = amd_iommu_def_domain_type,
 	.page_response = amd_iommu_page_response,
-	.get_viommu_size = amd_iommufd_get_viommu_size,
-	.viommu_init = amd_iommufd_viommu_init,
+	.get_viommu_ops = amd_iommufd_get_viommu_ops,
 };
 
 #ifdef CONFIG_IRQ_REMAP
diff --git a/drivers/iommu/amd/iommufd.c b/drivers/iommu/amd/iommufd.c
index 52300b867c1f2..c1e132382adc7 100644
--- a/drivers/iommu/amd/iommufd.c
+++ b/drivers/iommu/amd/iommufd.c
@@ -32,13 +32,21 @@ void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_ty
 	return hwinfo;
 }
 
-size_t amd_iommufd_get_viommu_size(struct device *dev, enum iommu_viommu_type viommu_type)
+static size_t amd_iommufd_get_viommu_size(struct device *dev,
+		enum iommu_viommu_type viommu_type)
 {
 	return VIOMMU_STRUCT_SIZE(struct amd_iommu_viommu, core);
 }
 
-int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *parent,
-			    const struct iommu_user_data *user_data)
+const struct iommufd_viommu_ops *
+amd_iommufd_get_viommu_ops(struct device *dev, enum iommu_viommu_type viommu_type)
+{
+	return &amd_viommu_ops;
+}
+
+int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,
+		struct device *dev, struct iommu_domain *parent,
+		const struct iommu_user_data *user_data)
 {
 	unsigned long flags;
 	struct protection_domain *pdom = to_pdomain(parent);
@@ -47,8 +55,6 @@ int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *
 	xa_init_flags(&aviommu->gdomid_array, XA_FLAGS_ALLOC1);
 	aviommu->parent = pdom;
 
-	viommu->ops = &amd_viommu_ops;
-
 	spin_lock_irqsave(&pdom->lock, flags);
 	list_add(&aviommu->pdom_list, &pdom->viommu_list);
 	spin_unlock_irqrestore(&pdom->lock, flags);
@@ -73,5 +79,7 @@ static void amd_iommufd_viommu_destroy(struct iommufd_viommu *viommu)
  * struct iommufd_viommu_ops - vIOMMU specific operations
  */
 static const struct iommufd_viommu_ops amd_viommu_ops = {
+	.get_viommu_size = amd_iommufd_get_viommu_size,
+	.viommu_init = amd_iommufd_viommu_init,
 	.destroy = amd_iommufd_viommu_destroy,
 };
diff --git a/drivers/iommu/amd/iommufd.h b/drivers/iommu/amd/iommufd.h
index 62e9e1bebfbe5..0d8e7c0902cff 100644
--- a/drivers/iommu/amd/iommufd.h
+++ b/drivers/iommu/amd/iommufd.h
@@ -8,13 +8,16 @@
 
 #if IS_ENABLED(CONFIG_AMD_IOMMU_IOMMUFD)
 void *amd_iommufd_hw_info(struct device *dev, u32 *length, enum iommu_hw_info_type *type);
-size_t amd_iommufd_get_viommu_size(struct device *dev, enum iommu_viommu_type viommu_type);
-int amd_iommufd_viommu_init(struct iommufd_viommu *viommu, struct iommu_domain *parent,
-			    const struct iommu_user_data *user_data);
+const struct iommufd_viommu_ops *
+amd_iommufd_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type);
+int amd_iommufd_viommu_init(struct iommufd_viommu *viommu,
+		struct device *dev, struct iommu_domain *parent,
+		const struct iommu_user_data *user_data);
 #else
 #define amd_iommufd_hw_info NULL
 #define amd_iommufd_viommu_init NULL
-#define amd_iommufd_get_viommu_size NULL
+#define amd_iommufd_get_viommu_ops NULL
 #endif /* CONFIG_AMD_IOMMU_IOMMUFD */
 
 #endif /* AMD_IOMMUFD_H */
diff --git a/drivers/iommu/amd/nested.c b/drivers/iommu/amd/nested.c
index f1c7987fc5859..5b07136e7cd92 100644
--- a/drivers/iommu/amd/nested.c
+++ b/drivers/iommu/amd/nested.c
@@ -90,7 +90,7 @@ static void *gdom_info_load_or_alloc_locked(struct xarray *xa,
 
 /*
  * This function is assigned to struct iommufd_viommu_ops.alloc_domain_nested()
- * during the call to struct iommu_ops.viommu_init().
+ * when the vIOMMU operations are selected.
  */
 struct iommu_domain *
 amd_iommu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,
@@ -198,7 +198,7 @@ static void set_dte_nested(struct amd_iommu *iommu, struct iommu_domain *dom,
 
 	/*
 	 * The nest parent domain is attached during the call to the
-	 * struct iommu_ops.viommu_init(), which will be stored as part
+	 * struct iommufd_viommu_ops.viommu_init(), which will be stored as part
 	 * of the struct amd_iommu_viommu.parent.
 	 */
 	if (WARN_ON(!ndom->viommu || !ndom->viommu->parent))
diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c
index 25982bdbcbd9a..1dd1031963534 100644
--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c
+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-iommufd.c
@@ -417,20 +417,29 @@ int arm_vsmmu_cache_invalidate(struct iommufd_viommu *viommu,
 	return ret;
 }
 
+static size_t arm_vsmmu_get_size(struct device *dev,
+				 enum iommu_viommu_type viommu_type)
+{
+	return VIOMMU_STRUCT_SIZE(struct arm_vsmmu, core);
+}
+
 static const struct iommufd_viommu_ops arm_vsmmu_ops = {
+	.get_viommu_size = arm_vsmmu_get_size,
+	.viommu_init = arm_vsmmu_init,
 	.alloc_domain_nested = arm_vsmmu_alloc_domain_nested,
 	.cache_invalidate = arm_vsmmu_cache_invalidate,
 	.vdevice_init = arm_vsmmu_vdevice_init,
 };
 
-size_t arm_smmu_get_viommu_size(struct device *dev,
-				enum iommu_viommu_type viommu_type)
+const struct iommufd_viommu_ops *
+arm_smmu_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type)
 {
 	struct arm_smmu_master *master = dev_iommu_priv_get(dev);
 	struct arm_smmu_device *smmu = master->smmu;
 
 	if (!(smmu->features & ARM_SMMU_FEAT_NESTING))
-		return 0;
+		return NULL;
 
 	/*
 	 * FORCE_SYNC is not set with FEAT_NESTING. Some study of the exact HW
@@ -438,7 +447,7 @@ size_t arm_smmu_get_viommu_size(struct device *dev,
 	 * any change to remove this.
 	 */
 	if (WARN_ON(smmu->options & ARM_SMMU_OPT_CMDQ_FORCE_SYNC))
-		return 0;
+		return NULL;
 
 	/*
 	 * Must support some way to prevent the VM from bypassing the cache
@@ -450,19 +459,19 @@ size_t arm_smmu_get_viommu_size(struct device *dev,
 	 */
 	if (!arm_smmu_master_canwbs(master) &&
 	    !(smmu->features & ARM_SMMU_FEAT_S2FWB))
-		return 0;
+		return NULL;
 
 	if (viommu_type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3)
-		return VIOMMU_STRUCT_SIZE(struct arm_vsmmu, core);
+		return &arm_vsmmu_ops;
 
-	if (!smmu->impl_ops || !smmu->impl_ops->get_viommu_size)
-		return 0;
-	return smmu->impl_ops->get_viommu_size(viommu_type);
+	if (!smmu->impl_ops || !smmu->impl_ops->get_viommu_ops)
+		return NULL;
+	return smmu->impl_ops->get_viommu_ops(viommu_type);
 }
 
-int arm_vsmmu_init(struct iommufd_viommu *viommu,
-		   struct iommu_domain *parent_domain,
-		   const struct iommu_user_data *user_data)
+int arm_vsmmu_init(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data)
 {
 	struct arm_vsmmu *vsmmu = container_of(viommu, struct arm_vsmmu, core);
 	struct arm_smmu_device *smmu =
@@ -477,10 +486,8 @@ int arm_vsmmu_init(struct iommufd_viommu *viommu,
 	/* FIXME Move VMID allocation from the S2 domain allocation to here */
 	vsmmu->vmid = s2_parent->s2_cfg.vmid;
 
-	if (viommu->type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3) {
-		viommu->ops = &arm_vsmmu_ops;
+	if (viommu->type == IOMMU_VIOMMU_TYPE_ARM_SMMUV3)
 		return 0;
-	}
 
 	return smmu->impl_ops->vsmmu_init(vsmmu, user_data);
 }
diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c
index 5732f3ba0122d..97dfaec6dc589 100644
--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c
+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c
@@ -4389,8 +4389,7 @@ static const struct iommu_ops arm_smmu_ops = {
 	.get_resv_regions	= arm_smmu_get_resv_regions,
 	.page_response		= arm_smmu_page_response,
 	.def_domain_type	= arm_smmu_def_domain_type,
-	.get_viommu_size	= arm_smmu_get_viommu_size,
-	.viommu_init		= arm_vsmmu_init,
+	.get_viommu_ops	= arm_smmu_get_viommu_ops,
 	.user_pasid_table	= 1,
 	.owner			= THIS_MODULE,
 	.default_domain_ops = &(const struct iommu_domain_ops) {
@@ -5489,8 +5488,8 @@ static struct arm_smmu_device *arm_smmu_impl_probe(struct arm_smmu_device *smmu)
 
 	ops = new_smmu->impl_ops;
 	if (ops) {
-		/* get_viommu_size and vsmmu_init ops must be paired */
-		if (WARN_ON(!ops->get_viommu_size != !ops->vsmmu_init)) {
+		/* get_viommu_ops and vsmmu_init ops must be paired */
+		if (WARN_ON(!ops->get_viommu_ops != !ops->vsmmu_init)) {
 			ret = -EINVAL;
 			goto err_remove;
 		}
diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h
index dd2fee2f560e6..79f2adf7a1f51 100644
--- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h
+++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.h
@@ -886,7 +886,8 @@ struct arm_smmu_impl_ops {
 	 */
 	void *(*hw_info)(struct arm_smmu_device *smmu, u32 *length,
 			 enum iommu_hw_info_type *type);
-	size_t (*get_viommu_size)(enum iommu_viommu_type viommu_type);
+	const struct iommufd_viommu_ops *(*get_viommu_ops)(
+		enum iommu_viommu_type viommu_type);
 	int (*vsmmu_init)(struct arm_vsmmu *vsmmu,
 			  const struct iommu_user_data *user_data);
 };
@@ -1260,11 +1261,12 @@ struct arm_vsmmu {
 #if IS_ENABLED(CONFIG_ARM_SMMU_V3_IOMMUFD)
 void *arm_smmu_hw_info(struct device *dev, u32 *length,
 		       enum iommu_hw_info_type *type);
-size_t arm_smmu_get_viommu_size(struct device *dev,
-				enum iommu_viommu_type viommu_type);
-int arm_vsmmu_init(struct iommufd_viommu *viommu,
-		   struct iommu_domain *parent_domain,
-		   const struct iommu_user_data *user_data);
+const struct iommufd_viommu_ops *
+arm_smmu_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type);
+int arm_vsmmu_init(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data);
 int arm_smmu_attach_prepare_vmaster(struct arm_smmu_attach_state *state,
 				    struct arm_smmu_nested_domain *nested_domain);
 void arm_smmu_attach_commit_vmaster(struct arm_smmu_attach_state *state);
@@ -1276,7 +1278,7 @@ arm_vsmmu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,
 int arm_vsmmu_cache_invalidate(struct iommufd_viommu *viommu,
 			       struct iommu_user_data_array *array);
 #else
-#define arm_smmu_get_viommu_size NULL
+#define arm_smmu_get_viommu_ops NULL
 #define arm_smmu_hw_info NULL
 #define arm_vsmmu_init NULL
 #define arm_vsmmu_alloc_domain_nested NULL
diff --git a/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c b/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c
index 6644075c1431e..1c8a7939fc1c0 100644
--- a/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c
+++ b/drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c
@@ -892,11 +892,14 @@ static void *tegra241_cmdqv_hw_info(struct arm_smmu_device *smmu, u32 *length,
 	return info;
 }
 
-static size_t tegra241_cmdqv_get_vintf_size(enum iommu_viommu_type viommu_type)
+static const struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops;
+
+static const struct iommufd_viommu_ops *
+tegra241_cmdqv_get_viommu_ops(enum iommu_viommu_type viommu_type)
 {
 	if (viommu_type != IOMMU_VIOMMU_TYPE_TEGRA241_CMDQV)
-		return 0;
-	return VIOMMU_STRUCT_SIZE(struct tegra241_vintf, vsmmu.core);
+		return NULL;
+	return &tegra241_cmdqv_viommu_ops;
 }
 
 static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {
@@ -907,7 +910,7 @@ static struct arm_smmu_impl_ops tegra241_cmdqv_impl_ops = {
 	.device_remove = tegra241_cmdqv_remove,
 	/* For user-space use */
 	.hw_info = tegra241_cmdqv_hw_info,
-	.get_viommu_size = tegra241_cmdqv_get_vintf_size,
+	.get_viommu_ops = tegra241_cmdqv_get_viommu_ops,
 	.vsmmu_init = tegra241_cmdqv_init_vintf_user,
 };
 
@@ -1289,7 +1292,15 @@ static int tegra241_vintf_init_vsid(struct iommufd_vdevice *vdev)
 	return 0;
 }
 
-static struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops = {
+static size_t tegra241_cmdqv_get_vintf_size(struct device *dev,
+					    enum iommu_viommu_type viommu_type)
+{
+	return VIOMMU_STRUCT_SIZE(struct tegra241_vintf, vsmmu.core);
+}
+
+static const struct iommufd_viommu_ops tegra241_cmdqv_viommu_ops = {
+	.get_viommu_size = tegra241_cmdqv_get_vintf_size,
+	.viommu_init = arm_vsmmu_init,
 	.destroy = tegra241_cmdqv_destroy_vintf_user,
 	.alloc_domain_nested = arm_vsmmu_alloc_domain_nested,
 	/* Non-accelerated commands will be still handled by the kernel */
@@ -1312,7 +1323,7 @@ tegra241_cmdqv_init_vintf_user(struct arm_vsmmu *vsmmu,
 	int ret;
 
 	/*
-	 * Unsupported type should be rejected by tegra241_cmdqv_get_vintf_size.
+	 * Unsupported type should be rejected by tegra241_cmdqv_get_viommu_ops.
 	 * Seeing one here indicates a kernel bug or some data corruption.
 	 */
 	if (WARN_ON(vsmmu->core.type != IOMMU_VIOMMU_TYPE_TEGRA241_CMDQV))
@@ -1364,7 +1375,6 @@ tegra241_cmdqv_init_vintf_user(struct arm_vsmmu *vsmmu,
 	dev_dbg(cmdqv->dev, "VINTF%u: allocated with vmid (%d)\n", vintf->idx,
 		vintf->vsmmu.vmid);
 
-	vsmmu->core.ops = &tegra241_cmdqv_viommu_ops;
 	return 0;
 
 free_mmap:
diff --git a/drivers/iommu/iommufd/Makefile b/drivers/iommu/iommufd/Makefile
index 67207914bb6e0..f90efe2f9d106 100644
--- a/drivers/iommu/iommufd/Makefile
+++ b/drivers/iommu/iommufd/Makefile
@@ -11,6 +11,8 @@ iommufd-y := \
 	viommu.o
 
 iommufd-$(CONFIG_IOMMUFD_NOIOMMU) += hwpt_noiommu.o
+iommufd-$(CONFIG_TSM) += tsm.o
+
 iommufd-$(CONFIG_IOMMUFD_TEST) += selftest.o
 
 obj-$(CONFIG_IOMMUFD) += iommufd.o
diff --git a/drivers/iommu/iommufd/device.c b/drivers/iommu/iommufd/device.c
index a664c70a6fe73..f99f7bee2e774 100644
--- a/drivers/iommu/iommufd/device.c
+++ b/drivers/iommu/iommufd/device.c
@@ -295,6 +295,7 @@ static int iommufd_bind_noiommu(struct iommufd_device *idev)
  * iommufd_device_bind - Bind a physical device to an iommu fd
  * @ictx: iommufd file descriptor
  * @dev: Pointer to a physical device struct
+ * @kvm_file: VM file if device belongs to a KVM VM
  * @id: Output ID number to return to userspace for this device
  *
  * A successful bind establishes an ownership over the device and returns
@@ -308,7 +309,9 @@ static int iommufd_bind_noiommu(struct iommufd_device *idev)
  * The caller must undo this with iommufd_device_unbind()
  */
 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
-					   struct device *dev, u32 *id)
+					   struct device *dev,
+					   struct file *kvm_file,
+					   u32 *id)
 {
 	struct iommufd_device *idev;
 	int rc;
@@ -319,6 +322,8 @@ struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
 
 	idev->ictx = ictx;
 	idev->dev = dev;
+	/* VFIO holds the file reference while the device is open. */
+	idev->kvm_file = kvm_file;
 
 	if (!iommufd_device_is_noiommu(idev))
 		rc = iommufd_bind_iommu(idev);
diff --git a/drivers/iommu/iommufd/hw_pagetable.c b/drivers/iommu/iommufd/hw_pagetable.c
index ef6e119c2a752..bd562bc2db487 100644
--- a/drivers/iommu/iommufd/hw_pagetable.c
+++ b/drivers/iommu/iommufd/hw_pagetable.c
@@ -306,6 +306,10 @@ iommufd_viommu_alloc_hwpt_nested(struct iommufd_viommu *viommu, u32 flags,
 		return ERR_PTR(-EOPNOTSUPP);
 	if (!user_data->len)
 		return ERR_PTR(-EOPNOTSUPP);
+	if (!viommu->hwpt)
+		return ERR_PTR(-EOPNOTSUPP);
+	if (!viommu->iommu_dev)
+		return ERR_PTR(-EOPNOTSUPP);
 	if (!viommu->ops || !viommu->ops->alloc_domain_nested)
 		return ERR_PTR(-EOPNOTSUPP);
 
@@ -404,10 +408,12 @@ int iommufd_hwpt_alloc(struct iommufd_ucmd *ucmd)
 		struct iommufd_viommu *viommu;
 
 		viommu = container_of(pt_obj, struct iommufd_viommu, obj);
-		iommu_dev = iommufd_device_get_iommu_dev(idev);
-		if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
-			rc = -EINVAL;
-			goto out_unlock;
+		if (viommu->iommu_dev) {
+			iommu_dev = iommufd_device_get_iommu_dev(idev);
+			if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
+				rc = -EINVAL;
+				goto out_unlock;
+			}
 		}
 		hwpt_nested = iommufd_viommu_alloc_hwpt_nested(
 			viommu, cmd->flags, &user_data);
diff --git a/drivers/iommu/iommufd/iommufd_private.h b/drivers/iommu/iommufd/iommufd_private.h
index eb2e85b27e429..64e0d9e4da168 100644
--- a/drivers/iommu/iommufd/iommufd_private.h
+++ b/drivers/iommu/iommufd/iommufd_private.h
@@ -509,6 +509,8 @@ struct iommufd_device {
 	struct list_head group_item;
 	/* always the physical device */
 	struct device *dev;
+	/* ..and the VM file if available */
+	struct file *kvm_file;
 	bool enforce_cache_coherency;
 	struct iommufd_vdevice *vdev;
 	bool destroying;
@@ -728,6 +730,14 @@ void iommufd_vdevice_destroy(struct iommufd_object *obj);
 void iommufd_vdevice_abort(struct iommufd_object *obj);
 int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd);
 void iommufd_hw_queue_destroy(struct iommufd_object *obj);
+#ifdef CONFIG_TSM
+int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd);
+#else
+static inline int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)
+{
+	return -EOPNOTSUPP;
+}
+#endif
 
 #ifdef CONFIG_IOMMUFD_TEST
 int iommufd_test(struct iommufd_ucmd *ucmd);
diff --git a/drivers/iommu/iommufd/main.c b/drivers/iommu/iommufd/main.c
index 9a921b1531620..577eef2760a35 100644
--- a/drivers/iommu/iommufd/main.c
+++ b/drivers/iommu/iommufd/main.c
@@ -453,6 +453,7 @@ union ucmd_buffer {
 	struct iommu_veventq_alloc veventq;
 	struct iommu_vfio_ioas vfio_ioas;
 	struct iommu_viommu_alloc viommu;
+	struct iommu_vdevice_tsm_req tsm_req;
 #ifdef CONFIG_IOMMUFD_TEST
 	struct iommu_test_cmd test;
 #endif
@@ -516,6 +517,8 @@ static const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {
 		 __reserved),
 	IOCTL_OP(IOMMU_VIOMMU_ALLOC, iommufd_viommu_alloc_ioctl,
 		 struct iommu_viommu_alloc, out_viommu_id),
+	IOCTL_OP(IOMMU_VDEVICE_TSM_REQ, iommufd_vdevice_tsm_req_ioctl,
+		 struct iommu_vdevice_tsm_req, out_tsm_code),
 #ifdef CONFIG_IOMMUFD_TEST
 	IOCTL_OP(IOMMU_TEST_CMD, iommufd_test, struct iommu_test_cmd, last),
 #endif
diff --git a/drivers/iommu/iommufd/selftest.c b/drivers/iommu/iommufd/selftest.c
index ee706f18f7e91..426ea94467ffe 100644
--- a/drivers/iommu/iommufd/selftest.c
+++ b/drivers/iommu/iommufd/selftest.c
@@ -774,7 +774,19 @@ static int mock_hw_queue_init_phys(struct iommufd_hw_queue *hw_queue, u32 index,
 	return rc;
 }
 
-static struct iommufd_viommu_ops mock_viommu_ops = {
+static int mock_viommu_init(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data);
+
+static size_t mock_get_viommu_size(struct device *dev,
+				   enum iommu_viommu_type viommu_type)
+{
+	return VIOMMU_STRUCT_SIZE(struct mock_viommu, core);
+}
+
+static const struct iommufd_viommu_ops mock_viommu_ops = {
+	.get_viommu_size = mock_get_viommu_size,
+	.viommu_init = mock_viommu_init,
 	.destroy = mock_viommu_destroy,
 	.alloc_domain_nested = mock_viommu_alloc_domain_nested,
 	.cache_invalidate = mock_viommu_cache_invalidate,
@@ -782,17 +794,18 @@ static struct iommufd_viommu_ops mock_viommu_ops = {
 	.hw_queue_init_phys = mock_hw_queue_init_phys,
 };
 
-static size_t mock_get_viommu_size(struct device *dev,
-				   enum iommu_viommu_type viommu_type)
+static const struct iommufd_viommu_ops *
+mock_get_viommu_ops(struct device *dev,
+		enum iommu_viommu_type viommu_type)
 {
 	if (viommu_type != IOMMU_VIOMMU_TYPE_SELFTEST)
-		return 0;
-	return VIOMMU_STRUCT_SIZE(struct mock_viommu, core);
+		return NULL;
+	return &mock_viommu_ops;
 }
 
 static int mock_viommu_init(struct iommufd_viommu *viommu,
-			    struct iommu_domain *parent_domain,
-			    const struct iommu_user_data *user_data)
+		struct device *dev, struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data)
 {
 	struct mock_iommu_device *mock_iommu = container_of(
 		viommu->iommu_dev, struct mock_iommu_device, iommu_dev);
@@ -834,7 +847,6 @@ static int mock_viommu_init(struct iommufd_viommu *viommu,
 	mutex_init(&mock_viommu->queue_mutex);
 	mock_viommu->s2_parent = to_mock_domain(parent_domain);
 
-	viommu->ops = &mock_viommu_ops;
 	return 0;
 
 err_destroy_mmap:
@@ -861,8 +873,7 @@ static const struct iommu_ops mock_ops = {
 	.probe_device = mock_probe_device,
 	.page_response = mock_domain_page_response,
 	.user_pasid_table = true,
-	.get_viommu_size = mock_get_viommu_size,
-	.viommu_init = mock_viommu_init,
+	.get_viommu_ops = mock_get_viommu_ops,
 };
 
 static void mock_domain_free_nested(struct iommu_domain *domain)
@@ -1074,7 +1085,7 @@ static int iommufd_test_mock_domain(struct iommufd_ucmd *ucmd,
 		goto out_sobj;
 	}
 
-	idev = iommufd_device_bind(ucmd->ictx, &sobj->idev.mock_dev->dev,
+	idev = iommufd_device_bind(ucmd->ictx, &sobj->idev.mock_dev->dev, NULL,
 				   &idev_id);
 	if (IS_ERR(idev)) {
 		rc = PTR_ERR(idev);
diff --git a/drivers/iommu/iommufd/tsm.c b/drivers/iommu/iommufd/tsm.c
new file mode 100644
index 0000000000000..b28ff86403456
--- /dev/null
+++ b/drivers/iommu/iommufd/tsm.c
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2026 ARM Ltd.
+ */
+
+#include <linux/bits.h>
+#include <linux/build_bug.h>
+#include <linux/limits.h>
+#include <linux/tsm.h>
+#include "iommufd_private.h"
+
+/**
+ * iommufd_vdevice_tsm_req_ioctl - Forward TSM requests
+ * @ucmd: user command data for IOMMU_VDEVICE_TSM_REQ
+ *
+ * Resolve @iommu_vdevice_tsm_req::vdevice_id to a vdevice and pass the
+ * request/response buffers to its vIOMMU implementation.
+ *
+ * Return:
+ *  -errno on error.
+ *  positive residue if response/request bytes were left unconsumed.
+ *    if response buffer is provided, residue indicates the number of bytes
+ *    not used in response buffer
+ *    if there is no response buffer, residue indicates the number of bytes
+ *    not consumed in req buffer
+ *  0 otherwise.
+ */
+int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)
+{
+	int ret;
+	struct iommufd_object *obj;
+	struct iommufd_vdevice *vdev;
+	struct iommu_vdevice_tsm_req *cmd = ucmd->cmd;
+	struct tsm_guest_req_info info = {
+		.op = cmd->op,
+		.tvm_arch = cmd->tvm_arch,
+		.req = u64_to_user_ptr(cmd->req_uptr),
+		.req_len = cmd->req_len,
+		.resp = u64_to_user_ptr(cmd->resp_uptr),
+		.resp_len = cmd->resp_len,
+	};
+
+	/* Every defined operation must fit in the vdevice's u64 mask. */
+	BUILD_BUG_ON(BITS_PER_TYPE(u64) < TSM_REQ_MAX);
+
+	/* Successful residues must fit in the ioctl's int return value. */
+	if (cmd->req_len > INT_MAX || cmd->resp_len > INT_MAX)
+		return -EINVAL;
+
+	obj = iommufd_get_object(ucmd->ictx, cmd->vdevice_id,
+				 IOMMUFD_OBJ_VDEVICE);
+	if (IS_ERR(obj))
+		return PTR_ERR(obj);
+	vdev = container_of(obj, struct iommufd_vdevice, obj);
+
+	cmd->out_tsm_code = 0;
+	if (!vdev->viommu->ops || !vdev->viommu->ops->vdevice_tsm_req ||
+	    !vdev->tsm_req_op_mask) {
+		ret = -EOPNOTSUPP;
+		goto out_respond;
+	}
+	/* Bounds-check the user-supplied shift before BIT_ULL(). */
+	if (cmd->tvm_arch != vdev->tsm_tvm_arch ||
+	    cmd->op >= TSM_REQ_MAX ||
+	    !(vdev->tsm_req_op_mask & BIT_ULL(cmd->op))) {
+		ret = -EINVAL;
+		goto out_put_object;
+	}
+	ret = vdev->viommu->ops->vdevice_tsm_req(vdev, &info,
+						 &cmd->out_tsm_code);
+
+out_respond:
+	/* Always copy the tsm_code as response */
+	if (iommufd_ucmd_respond(ucmd, sizeof(*cmd)))
+		ret = -EFAULT;
+
+out_put_object:
+	iommufd_put_object(ucmd->ictx, obj);
+	return ret;
+}
diff --git a/drivers/iommu/iommufd/viommu.c b/drivers/iommu/iommufd/viommu.c
index f7951057a1e56..9155d0dcb4b40 100644
--- a/drivers/iommu/iommufd/viommu.c
+++ b/drivers/iommu/iommufd/viommu.c
@@ -1,6 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /* Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES
  */
+#include <linux/file.h>
+#include <linux/cleanup.h>
+#include <linux/tsm.h>
+
 #include "iommufd_private.h"
 
 void iommufd_viommu_destroy(struct iommufd_object *obj)
@@ -10,7 +14,12 @@ void iommufd_viommu_destroy(struct iommufd_object *obj)
 
 	if (viommu->ops && viommu->ops->destroy)
 		viommu->ops->destroy(viommu);
-	refcount_dec(&viommu->hwpt->common.obj.users);
+	if (viommu->tsm_dev)
+		tsm_put_device(viommu->tsm_dev);
+	if (viommu->hwpt)
+		refcount_dec(&viommu->hwpt->common.obj.users);
+	if (viommu->kvm_file)
+		fput(viommu->kvm_file);
 	xa_destroy(&viommu->vdevs);
 }
 
@@ -22,11 +31,12 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 		.uptr = u64_to_user_ptr(cmd->data_uptr),
 		.len = cmd->data_len,
 	};
-	struct iommufd_hwpt_paging *hwpt_paging;
+	struct iommufd_hwpt_paging *hwpt_paging = NULL;
+	struct tsm_dev *tsm_dev = NULL;
 	struct iommufd_viommu *viommu;
 	struct iommufd_device *idev;
-	struct iommu_device *iommu_dev;
-	const struct iommu_ops *ops;
+	struct iommu_device *iommu_dev = NULL;
+	const struct iommufd_viommu_ops *ops;
 	size_t viommu_size;
 	int rc;
 
@@ -37,41 +47,66 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	if (IS_ERR(idev))
 		return PTR_ERR(idev);
 
-	iommu_dev = iommufd_device_get_iommu_dev(idev);
-	if (!iommu_dev) {
-		rc = -EOPNOTSUPP;
+	tsm_dev = tsm_get_device(idev->dev);
+	if (IS_ERR(tsm_dev)) {
+		rc = PTR_ERR(tsm_dev);
+		tsm_dev = NULL;
 		goto out_put_idev;
 	}
-	ops = iommu_dev->ops;
-	if (!ops->get_viommu_size || !ops->viommu_init) {
-		rc = -EOPNOTSUPP;
+	ops = tsm_dev ? tsm_viommu_get_ops(tsm_dev, idev->dev, cmd->type) : NULL;
+	if (IS_ERR(ops)) {
+		rc = PTR_ERR(ops);
 		goto out_put_idev;
 	}
-
-	viommu_size = ops->get_viommu_size(idev->dev, cmd->type);
-	if (!viommu_size) {
-		rc = -EOPNOTSUPP;
-		goto out_put_idev;
+	if (!ops) {
+		if (tsm_dev) {
+			tsm_put_device(tsm_dev);
+			tsm_dev = NULL;
+		}
+		iommu_dev = iommufd_device_get_iommu_dev(idev);
+		if (!iommu_dev) {
+			rc = -EOPNOTSUPP;
+			goto out_put_idev;
+		}
+		if (!iommu_dev->ops->get_viommu_ops) {
+			rc = -EOPNOTSUPP;
+			goto out_put_idev;
+		}
+		ops = iommu_dev->ops->get_viommu_ops(idev->dev, cmd->type);
+		if (!ops) {
+			rc = -EOPNOTSUPP;
+			goto out_put_idev;
+		}
 	}
 
 	/*
-	 * It is a driver bug for providing a viommu_size smaller than the core
-	 * vIOMMU structure size
+	 * It is a driver bug to omit the required operations or provide a size
+	 * smaller than the core vIOMMU structure.
 	 */
-	if (WARN_ON_ONCE(viommu_size < sizeof(*viommu))) {
+	if (WARN_ON_ONCE(!ops->get_viommu_size || !ops->viommu_init)) {
 		rc = -EOPNOTSUPP;
 		goto out_put_idev;
 	}
-
-	hwpt_paging = iommufd_get_hwpt_paging(ucmd, cmd->hwpt_id);
-	if (IS_ERR(hwpt_paging)) {
-		rc = PTR_ERR(hwpt_paging);
+	viommu_size = ops->get_viommu_size(idev->dev, cmd->type);
+	if (!viommu_size || WARN_ON_ONCE(viommu_size < sizeof(*viommu))) {
+		rc = -EOPNOTSUPP;
 		goto out_put_idev;
 	}
 
-	if (!hwpt_paging->nest_parent) {
+	if ((ops->flags & IOMMUFD_VIOMMU_NO_HWPT) && cmd->hwpt_id) {
 		rc = -EINVAL;
-		goto out_put_hwpt;
+		goto out_put_idev;
+	}
+	if (!(ops->flags & IOMMUFD_VIOMMU_NO_HWPT)) {
+		hwpt_paging = iommufd_get_hwpt_paging(ucmd, cmd->hwpt_id);
+		if (IS_ERR(hwpt_paging)) {
+			rc = PTR_ERR(hwpt_paging);
+			goto out_put_idev;
+		}
+		if (!hwpt_paging->nest_parent) {
+			rc = -EINVAL;
+			goto out_put_hwpt;
+		}
 	}
 
 	viommu = (struct iommufd_viommu *)_iommufd_object_alloc_ucmd(
@@ -82,10 +117,15 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	}
 
 	xa_init(&viommu->vdevs);
+	if (idev->kvm_file)
+		viommu->kvm_file = get_file(idev->kvm_file);
 	viommu->type = cmd->type;
 	viommu->ictx = ucmd->ictx;
+	viommu->tsm_dev = tsm_dev;
+	tsm_dev = NULL;
 	viommu->hwpt = hwpt_paging;
-	refcount_inc(&viommu->hwpt->common.obj.users);
+	if (viommu->hwpt)
+		refcount_inc(&viommu->hwpt->common.obj.users);
 	INIT_LIST_HEAD(&viommu->veventqs);
 	init_rwsem(&viommu->veventqs_rwsem);
 	/*
@@ -95,23 +135,22 @@ int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	 */
 	viommu->iommu_dev = iommu_dev;
 
-	rc = ops->viommu_init(viommu, hwpt_paging->common.domain,
+	rc = ops->viommu_init(viommu, idev->dev,
+			      hwpt_paging ? hwpt_paging->common.domain : NULL,
 			      user_data.len ? &user_data : NULL);
 	if (rc)
 		goto out_put_hwpt;
-
-	/* It is a driver bug that viommu->ops isn't filled */
-	if (WARN_ON_ONCE(!viommu->ops)) {
-		rc = -EOPNOTSUPP;
-		goto out_put_hwpt;
-	}
+	viommu->ops = ops;
 
 	cmd->out_viommu_id = viommu->obj.id;
 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
 
 out_put_hwpt:
-	iommufd_put_object(ucmd->ictx, &hwpt_paging->common.obj);
+	if (hwpt_paging)
+		iommufd_put_object(ucmd->ictx, &hwpt_paging->common.obj);
 out_put_idev:
+	if (tsm_dev)
+		tsm_put_device(tsm_dev);
 	iommufd_put_object(ucmd->ictx, &idev->obj);
 	return rc;
 }
@@ -171,10 +210,12 @@ int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd)
 		goto out_put_viommu;
 	}
 
-	iommu_dev = iommufd_device_get_iommu_dev(idev);
-	if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
-		rc = -EINVAL;
-		goto out_put_idev;
+	if (viommu->iommu_dev) {
+		iommu_dev = iommufd_device_get_iommu_dev(idev);
+		if (!iommu_dev || viommu->iommu_dev != iommu_dev) {
+			rc = -EINVAL;
+			goto out_put_idev;
+		}
 	}
 
 	mutex_lock(&idev->igroup->lock);
@@ -394,7 +435,7 @@ int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)
 	if (IS_ERR(viommu))
 		return PTR_ERR(viommu);
 
-	if (!viommu->ops || !viommu->ops->get_hw_queue_size ||
+	if (!viommu->hwpt || !viommu->ops || !viommu->ops->get_hw_queue_size ||
 	    !viommu->ops->hw_queue_init_phys) {
 		rc = -EOPNOTSUPP;
 		goto out_put_viommu;
diff --git a/drivers/pci/tsm.c b/drivers/pci/tsm.c
index 5fdcd7f2e8207..8aa74ba31932b 100644
--- a/drivers/pci/tsm.c
+++ b/drivers/pci/tsm.c
@@ -9,9 +9,15 @@
 #define dev_fmt(fmt) "PCI/TSM: " fmt
 
 #include <linux/bitfield.h>
+#include <linux/iommufd.h>
+#include <linux/jiffies.h>
+#include <linux/module.h>
 #include <linux/pci.h>
 #include <linux/pci-doe.h>
 #include <linux/pci-tsm.h>
+#include <linux/pid.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
 #include <linux/sysfs.h>
 #include <linux/tsm.h>
 #include <linux/xarray.h>
@@ -35,6 +41,25 @@ static const struct pci_tsm_ops *to_pci_tsm_ops(struct pci_tsm *tsm)
 	return tsm->tsm_dev->pci_ops;
 }
 
+struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)
+{
+	const struct pci_tsm_ops *ops;
+	struct tsm_dev *tsm_dev;
+
+	guard(rwsem_read)(&pci_tsm_rwsem);
+	if (!pdev->tsm)
+		return NULL;
+
+	tsm_dev = pdev->tsm->tsm_dev;
+	ops = tsm_dev->pci_ops;
+	if (!ops->viommu_get_ops)
+		return NULL;
+	if (!try_module_get(ops->owner))
+		return ERR_PTR(-ENODEV);
+	return tsm_dev;
+}
+EXPORT_SYMBOL_GPL(pci_tsm_get_device);
+
 static inline bool is_dsm(struct pci_dev *pdev)
 {
 	return pdev->tsm && pdev->tsm->dsm_dev == pdev;
@@ -292,156 +317,103 @@ static int remove_fn(struct pci_dev *pdev, void *data)
 	return 0;
 }
 
-/*
- * Note, this helper only returns an error code and takes an argument for
- * compatibility with the pci_walk_bus() callback prototype. pci_tsm_unbind()
- * always succeeds.
- */
-static int __pci_tsm_unbind(struct pci_dev *pdev, void *data)
+bool pci_tsm_is_configured(struct pci_dev *pdev)
 {
-	struct pci_tdi *tdi;
-	struct pci_tsm_pf0 *tsm_pf0;
-
-	lockdep_assert_held(&pci_tsm_rwsem);
-
-	if (!pdev->tsm)
-		return 0;
-
-	tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
-	guard(mutex)(&tsm_pf0->lock);
-
-	tdi = pdev->tsm->tdi;
-	if (!tdi)
-		return 0;
-
-	to_pci_tsm_ops(pdev->tsm)->unbind(tdi);
-	pdev->tsm->tdi = NULL;
+	guard(rwsem_read)(&pci_tsm_rwsem);
 
-	return 0;
+	return !!pdev->tsm;
 }
+EXPORT_SYMBOL_GPL(pci_tsm_is_configured);
 
-void pci_tsm_unbind(struct pci_dev *pdev)
-{
-	guard(rwsem_read)(&pci_tsm_rwsem);
-	__pci_tsm_unbind(pdev, NULL);
-}
-EXPORT_SYMBOL_GPL(pci_tsm_unbind);
+struct pci_tsm_context {
+	struct pci_tsm_pf0 *pf0;
+	struct pci_dev *pdev;
+	struct pci_dev *dsm_dev;
+};
 
-/**
- * pci_tsm_bind() - Bind @pdev as a TDI for @kvm
- * @pdev: PCI device function to bind
- * @kvm: Private memory attach context
- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM
- *
- * Returns 0 on success, or a negative error code on failure.
- *
- * Context: Caller is responsible for constraining the bind lifetime to the
- * registered state of the device. For example, pci_tsm_bind() /
- * pci_tsm_unbind() limited to the VFIO driver bound state of the device.
- */
-int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id)
+struct pci_tsm_context *pci_tsm_context_get(struct pci_dev *pdev,
+					    struct tsm_dev *viommu_tsm_dev)
 {
-	struct pci_tsm_pf0 *tsm_pf0;
-	struct pci_tdi *tdi;
-
-	if (!kvm)
-		return -EINVAL;
+	struct pci_tsm_context *context;
+	struct pci_tsm_pf0 *pf0;
 
 	guard(rwsem_read)(&pci_tsm_rwsem);
+	if (!pdev->tsm || !is_link_tsm(pdev->tsm->tsm_dev))
+		return ERR_PTR(-EOPNOTSUPP);
+	/*
+	 * The vdevice can use a different PCI function from VIOMMU_ALLOC. The
+	 * module pin keeps the vIOMMU's TSM registered, but does not freeze this
+	 * function's link. Match its current TSM before pinning the link below.
+	 */
+	if (pdev->tsm->tsm_dev != viommu_tsm_dev)
+		return ERR_PTR(-EXDEV);
 
-	if (!pdev->tsm)
-		return -EINVAL;
-
-	if (!is_link_tsm(pdev->tsm->tsm_dev))
-		return -ENXIO;
+	pf0 = to_pci_tsm_pf0(pdev->tsm);
+	if (!pf0)
+		return ERR_PTR(-ENXIO);
 
-	tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
-	guard(mutex)(&tsm_pf0->lock);
+	context = kzalloc_obj(*context);
+	if (!context)
+		return ERR_PTR(-ENOMEM);
 
-	/* Resolve races to bind a TDI */
-	if (pdev->tsm->tdi) {
-		if (pdev->tsm->tdi->kvm != kvm)
-			return -EBUSY;
-		return 0;
+	guard(mutex)(&pf0->lock);
+	if (pf0->removing) {
+		kfree(context);
+		return ERR_PTR(-ENODEV);
 	}
-
-	tdi = to_pci_tsm_ops(pdev->tsm)->bind(pdev, kvm, tdi_id);
-	if (IS_ERR(tdi))
-		return PTR_ERR(tdi);
-
-	pdev->tsm->tdi = tdi;
-
-	return 0;
+	if (!pf0->context_users)
+		reinit_completion(&pf0->contexts_drained);
+	pf0->context_users++;
+	context->pf0 = pf0;
+	context->pdev = pci_dev_get(pdev);
+	context->dsm_dev = pci_dev_get(pf0->base_tsm.pdev);
+	return context;
 }
-EXPORT_SYMBOL_GPL(pci_tsm_bind);
+EXPORT_SYMBOL_GPL(pci_tsm_context_get);
 
-/**
- * pci_tsm_guest_req() - helper to marshal guest requests to the TSM driver
- * @pdev: @pdev representing a bound tdi
- * @scope: caller asserts this passthrough request is limited to TDISP operations
- * @req_in: Input payload forwarded from the guest
- * @in_len: Length of @req_in
- * @req_out: Output payload buffer response to the guest
- * @out_len: Length of @req_out on input, bytes filled in @req_out on output
- * @tsm_code: Optional TSM arch specific result code for the guest TSM
- *
- * This is a common entry point for requests triggered by userspace KVM-exit
- * service handlers responding to TDI information or state change requests. The
- * scope parameter limits requests to TDISP state management, or limited debug.
- * This path is only suitable for commands and results that are the host kernel
- * has no use, the host is only facilitating guest to TSM communication.
- *
- * Returns 0 on success and -error on failure and positive "residue" on success
- * but @req_out is filled with less then @out_len, or @req_out is NULL and a
- * residue number of bytes were not consumed from @req_in.  On success or
- * failure @tsm_code may be populated with a TSM implementation specific result
- * code for the guest to consume.
- *
- * Context: Caller is responsible for calling this within the pci_tsm_bind()
- * state of the TDI.
- */
-ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope,
-			  sockptr_t req_in, size_t in_len, sockptr_t req_out,
-			  size_t out_len, u64 *tsm_code)
+void pci_tsm_context_put(struct pci_tsm_context *context)
 {
-	struct pci_tsm_pf0 *tsm_pf0;
-	struct pci_tdi *tdi;
-	int rc;
-
-	/* Forbid requests that are not directly related to TDISP operations */
-	if (scope > PCI_TSM_REQ_STATE_CHANGE)
-		return -EINVAL;
+	struct pci_tsm_pf0 *pf0 = context->pf0;
 
-	ACQUIRE(rwsem_read_intr, lock)(&pci_tsm_rwsem);
-	if ((rc = ACQUIRE_ERR(rwsem_read_intr, &lock)))
-		return rc;
+	down_read(&pci_tsm_rwsem);
+	mutex_lock(&pf0->lock);
+	if (WARN_ON(!pf0->context_users))
+		goto out_unlock;
+	if (!--pf0->context_users)
+		complete_all(&pf0->contexts_drained);
+out_unlock:
+	mutex_unlock(&pf0->lock);
+	up_read(&pci_tsm_rwsem);
 
-	if (!pdev->tsm)
-		return -ENXIO;
-
-	if (!is_link_tsm(pdev->tsm->tsm_dev))
-		return -ENXIO;
+	pci_dev_put(context->pdev);
+	pci_dev_put(context->dsm_dev);
+	kfree(context);
+}
+EXPORT_SYMBOL_GPL(pci_tsm_context_put);
 
-	tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
-	ACQUIRE(mutex_intr, ops_lock)(&tsm_pf0->lock);
-	if ((rc = ACQUIRE_ERR(mutex_intr, &ops_lock)))
-		return rc;
+struct pci_tsm_pf0 *pci_tsm_context_pf0(struct pci_tsm_context *context)
+{
+	return context->pf0;
+}
+EXPORT_SYMBOL_GPL(pci_tsm_context_pf0);
 
-	tdi = pdev->tsm->tdi;
-	if (!tdi)
-		return -ENXIO;
-	return to_pci_tsm_ops(pdev->tsm)->guest_req(tdi, scope, req_in, in_len,
-						    req_out, out_len, tsm_code);
+struct pci_dev *pci_tsm_context_dsm_dev(struct pci_tsm_context *context)
+{
+	return context->dsm_dev;
 }
-EXPORT_SYMBOL_GPL(pci_tsm_guest_req);
+EXPORT_SYMBOL_GPL(pci_tsm_context_dsm_dev);
 
-static void pci_tsm_unbind_all(struct pci_dev *pdev)
+bool pci_tsm_context_match_device(struct pci_tsm_context *context,
+				  struct pci_dev *pdev)
 {
-	pci_tsm_walk_fns_reverse(pdev, __pci_tsm_unbind, NULL);
-	__pci_tsm_unbind(pdev, NULL);
+	guard(rwsem_read)(&pci_tsm_rwsem);
+
+	return pdev->tsm && is_link_tsm(pdev->tsm->tsm_dev) &&
+	       to_pci_tsm_pf0(pdev->tsm) == context->pf0;
 }
+EXPORT_SYMBOL_GPL(pci_tsm_context_match_device);
 
-static void __pci_tsm_disconnect(struct pci_dev *pdev)
+static int __pci_tsm_disconnect(struct pci_dev *pdev)
 {
 	struct pci_tsm_pf0 *tsm_pf0 = to_pci_tsm_pf0(pdev->tsm);
 	const struct pci_tsm_ops *ops = to_pci_tsm_ops(pdev->tsm);
@@ -449,21 +421,29 @@ static void __pci_tsm_disconnect(struct pci_dev *pdev)
 	/* disconnect() mutually exclusive with subfunction pci_tsm_init() */
 	lockdep_assert_held_write(&pci_tsm_rwsem);
 
-	pci_tsm_unbind_all(pdev);
-
 	/*
-	 * disconnect() is uninterruptible as it may be called for device
-	 * teardown
+	 * A vdevice holds a context for its lifetime. Refuse to tear down the
+	 * link until userspace destroys all dependent vdevices.
+	 *
+	 * disconnect() is uninterruptible as it may also be called for device
+	 * teardown.
 	 */
 	guard(mutex)(&tsm_pf0->lock);
+	if (tsm_pf0->context_users)
+		return -EBUSY;
 	pci_tsm_walk_fns_reverse(pdev, remove_fn, NULL);
 	ops->disconnect(pdev);
+	return 0;
 }
 
-static void pci_tsm_disconnect(struct pci_dev *pdev)
+static int pci_tsm_disconnect(struct pci_dev *pdev)
 {
-	__pci_tsm_disconnect(pdev);
+	int ret = __pci_tsm_disconnect(pdev);
+
+	if (ret)
+		return ret;
 	tsm_remove(pdev->tsm);
+	return 0;
 }
 
 static ssize_t disconnect_store(struct device *dev,
@@ -484,39 +464,17 @@ static ssize_t disconnect_store(struct device *dev,
 	tsm_dev = pdev->tsm->tsm_dev;
 	if (!sysfs_streq(buf, dev_name(&tsm_dev->dev)))
 		return -EINVAL;
+	if (is_link_tsm(tsm_dev) && is_pci_tsm_pf0(pdev) &&
+	    to_pci_tsm_pf0(pdev->tsm)->removing)
+		return -ENODEV;
 
-	pci_tsm_disconnect(pdev);
+	rc = pci_tsm_disconnect(pdev);
+	if (rc)
+		return rc;
 	return len;
 }
 static DEVICE_ATTR_WO(disconnect);
 
-static ssize_t bound_show(struct device *dev,
-			  struct device_attribute *attr, char *buf)
-{
-	struct pci_dev *pdev = to_pci_dev(dev);
-	struct pci_tsm_pf0 *tsm_pf0;
-	struct pci_tsm *tsm;
-	int rc;
-
-	ACQUIRE(rwsem_read_intr, lock)(&pci_tsm_rwsem);
-	if ((rc = ACQUIRE_ERR(rwsem_read_intr, &lock)))
-		return rc;
-
-	tsm = pdev->tsm;
-	if (!tsm)
-		return sysfs_emit(buf, "\n");
-	tsm_pf0 = to_pci_tsm_pf0(tsm);
-
-	ACQUIRE(mutex_intr, ops_lock)(&tsm_pf0->lock);
-	if ((rc = ACQUIRE_ERR(mutex_intr, &ops_lock)))
-		return rc;
-
-	if (!tsm->tdi)
-		return sysfs_emit(buf, "\n");
-	return sysfs_emit(buf, "%s\n", dev_name(&tsm->tsm_dev->dev));
-}
-static DEVICE_ATTR_RO(bound);
-
 static ssize_t dsm_show(struct device *dev, struct device_attribute *attr,
 			char *buf)
 {
@@ -571,13 +529,6 @@ static umode_t pci_tsm_attr_visible(struct kobject *kobj,
 	if (pci_tsm_link_group_visible(kobj)) {
 		struct pci_dev *pdev = to_pci_dev(kobj_to_dev(kobj));
 
-		if (attr == &dev_attr_bound.attr) {
-			if (is_pci_tsm_pf0(pdev) && has_tee(pdev))
-				return attr->mode;
-			if (pdev->tsm && has_tee(pdev->tsm->dsm_dev))
-				return attr->mode;
-		}
-
 		if (attr == &dev_attr_dsm.attr) {
 			if (is_pci_tsm_pf0(pdev))
 				return attr->mode;
@@ -604,7 +555,6 @@ DEFINE_SYSFS_GROUP_VISIBLE(pci_tsm);
 static struct attribute *pci_tsm_attrs[] = {
 	&dev_attr_connect.attr,
 	&dev_attr_disconnect.attr,
-	&dev_attr_bound.attr,
 	&dev_attr_dsm.attr,
 	NULL
 };
@@ -694,22 +644,6 @@ static struct pci_dev *find_dsm_dev(struct pci_dev *pdev)
 	return NULL;
 }
 
-/**
- * pci_tsm_tdi_constructor() - base 'struct pci_tdi' initialization for link TSMs
- * @pdev: PCI device function representing the TDI
- * @tdi: context to initialize
- * @kvm: Private memory attach context
- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM
- */
-void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi,
-			     struct kvm *kvm, u32 tdi_id)
-{
-	tdi->pdev = pdev;
-	tdi->kvm = kvm;
-	tdi->tdi_id = tdi_id;
-}
-EXPORT_SYMBOL_GPL(pci_tsm_tdi_constructor);
-
 /**
  * pci_tsm_link_constructor() - base 'struct pci_tsm' initialization for link TSMs
  * @pdev: The PCI device
@@ -744,6 +678,9 @@ int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm,
 			    struct tsm_dev *tsm_dev)
 {
 	mutex_init(&tsm->lock);
+	init_completion(&tsm->contexts_drained);
+	tsm->context_users = 0;
+	tsm->removing = false;
 	tsm->doe_mb = pci_find_doe_mailbox(pdev, PCI_VENDOR_ID_PCI_SIG,
 					   PCI_DOE_FEATURE_CMA);
 	if (!tsm->doe_mb) {
@@ -789,12 +726,6 @@ int pci_tsm_register(struct tsm_dev *tsm_dev)
 	return 0;
 }
 
-static void pci_tsm_fn_exit(struct pci_dev *pdev)
-{
-	__pci_tsm_unbind(pdev, NULL);
-	tsm_remove(pdev->tsm);
-}
-
 /**
  * __pci_tsm_destroy() - destroy the TSM context for @pdev
  * @pdev: device to cleanup
@@ -828,16 +759,54 @@ static void __pci_tsm_destroy(struct pci_dev *pdev, struct tsm_dev *tsm_dev)
 	else if (tsm_dev != tsm->tsm_dev)
 		return;
 
-	if (is_link_tsm(tsm_dev) && is_pci_tsm_pf0(pdev))
-		pci_tsm_disconnect(pdev);
-	else
-		pci_tsm_fn_exit(pdev);
+	if (is_link_tsm(tsm_dev) && is_pci_tsm_pf0(pdev)) {
+		if (pci_tsm_disconnect(pdev))
+			pci_warn(pdev, "TSM connection is still in use\n");
+	} else {
+		tsm_remove(pdev->tsm);
+	}
 }
 
 void pci_tsm_destroy(struct pci_dev *pdev)
 {
-	guard(rwsem_write)(&pci_tsm_rwsem);
+	struct pci_tsm_pf0 *pf0 = NULL;
+	struct completion *drained;
+	bool interrupted = false;
+	long rc;
+
+	down_write(&pci_tsm_rwsem);
+	if (pdev->tsm && is_link_tsm(pdev->tsm->tsm_dev) &&
+	    is_pci_tsm_pf0(pdev)) {
+		pf0 = to_pci_tsm_pf0(pdev->tsm);
+		drained = &pf0->contexts_drained;
+		mutex_lock(&pf0->lock);
+		pf0->removing = true;
+		mutex_unlock(&pf0->lock);
+
+		/* An unused DSM may never have completed contexts_drained. */
+		rc = pf0->context_users ?
+			try_wait_for_completion(drained) : 1;
+		/* Context release needs the read side of pci_tsm_rwsem. */
+		up_write(&pci_tsm_rwsem);
+		while (rc <= 0) {
+			if (interrupted) {
+				rc = wait_for_completion_timeout(drained, HZ * 10);
+			} else {
+				rc = wait_for_completion_interruptible_timeout(drained,
+									       HZ * 10);
+				if (rc < 0) {
+					interrupted = true;
+					pci_warn(pdev, "Task \"%s\" (%d) blocked until vdevices are released\n",
+						 current->comm, task_pid_nr(current));
+				}
+			}
+			if (!rc)
+				pci_warn(pdev, "TSM connection is in use, waiting for vdevices\n");
+		}
+		down_write(&pci_tsm_rwsem);
+	}
 	__pci_tsm_destroy(pdev, NULL);
+	up_write(&pci_tsm_rwsem);
 }
 
 void pci_tsm_init(struct pci_dev *pdev)
@@ -864,6 +833,9 @@ void pci_tsm_init(struct pci_dev *pdev)
 		 */
 		if (!dsm->tsm)
 			return;
+		if (is_link_tsm(dsm->tsm->tsm_dev) &&
+		    to_pci_tsm_pf0(dsm->tsm)->removing)
+			return;
 
 		probe_fn(pdev, dsm);
 	}
diff --git a/drivers/s390/crypto/vfio_ap_ops.c b/drivers/s390/crypto/vfio_ap_ops.c
index 4db878c18f41c..373ce574c4319 100644
--- a/drivers/s390/crypto/vfio_ap_ops.c
+++ b/drivers/s390/crypto/vfio_ap_ops.c
@@ -1822,17 +1822,27 @@ static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
 
 /**
  * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed
- * to manage AP resources for the guest whose state is represented by @kvm
+ * to manage AP resources for the guest whose state is represented by
+ * @kvm_file
  *
  * @matrix_mdev: a mediated matrix device
- * @kvm: reference to KVM instance
+ * @kvm_file: the KVM VM file this vfio device is associated with
  *
- * Return: 0 if no other mediated matrix device has a reference to @kvm;
+ * Return: 0 if no other mediated matrix device has a reference to the VM;
  * otherwise, returns an -EPERM.
  */
 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
-				struct kvm *kvm)
+				struct file *kvm_file)
 {
+	struct kvm *kvm;
+
+	if (!kvm_file)
+		return -ENOENT;
+
+	kvm = file_to_kvm_s390(kvm_file);
+	if (!kvm)
+		return -ENOENT;
+
 	if (kvm->arch.crypto.crycbd) {
 		get_update_locks_for_kvm(kvm);
 		if (kvm->arch.crypto.pqap_hook) {
@@ -1841,7 +1851,6 @@ static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
 		}
 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
 
-		kvm_get_kvm(kvm);
 		matrix_mdev->kvm = kvm;
 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
 		release_update_locks_for_kvm(kvm);
@@ -1894,7 +1903,6 @@ static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
 		matrix_mdev->kvm = NULL;
 
 		release_update_locks_for_kvm(kvm);
-		kvm_put_kvm(kvm);
 	}
 }
 
diff --git a/drivers/vfio/group.c b/drivers/vfio/group.c
index b2299e5bc6df3..5bf8cbdff377c 100644
--- a/drivers/vfio/group.c
+++ b/drivers/vfio/group.c
@@ -860,11 +860,20 @@ bool vfio_group_enforced_coherent(struct vfio_group *group)
 	return ret;
 }
 
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)
 {
+	struct file *old;
+
+	if (kvm)
+		get_file(kvm);
+
 	spin_lock(&group->kvm_ref_lock);
+	old = group->kvm;
 	group->kvm = kvm;
 	spin_unlock(&group->kvm_ref_lock);
+
+	if (old)
+		fput(old);
 }
 
 /**
diff --git a/drivers/vfio/iommufd.c b/drivers/vfio/iommufd.c
index e9893d34d07be..3beb1b1bae368 100644
--- a/drivers/vfio/iommufd.c
+++ b/drivers/vfio/iommufd.c
@@ -123,7 +123,8 @@ int vfio_iommufd_physical_bind(struct vfio_device *vdev,
 {
 	struct iommufd_device *idev;
 
-	idev = iommufd_device_bind(ictx, vdev->dev, out_device_id);
+	idev = iommufd_device_bind(ictx, vdev->dev, vdev->kvm,
+				   out_device_id);
 	if (IS_ERR(idev))
 		return PTR_ERR(idev);
 	vdev->iommufd_device = idev;
diff --git a/drivers/vfio/vfio.h b/drivers/vfio/vfio.h
index 7728bc99b63d1..9b619951a5d0c 100644
--- a/drivers/vfio/vfio.h
+++ b/drivers/vfio/vfio.h
@@ -23,7 +23,7 @@ struct vfio_device_file {
 	u8 access_granted;
 	u32 devid; /* only valid when iommufd is valid */
 	spinlock_t kvm_ref_lock; /* protect kvm field */
-	struct kvm *kvm;
+	struct file *kvm;
 	struct iommufd_ctx *iommufd; /* protected by struct vfio_device_set::lock */
 };
 
@@ -88,7 +88,7 @@ struct vfio_group {
 #endif
 	enum vfio_group_type		type;
 	struct mutex			group_lock;
-	struct kvm			*kvm;
+	struct file			*kvm;
 	struct file			*opened_file;
 	struct iommufd_ctx		*iommufd;
 	spinlock_t			kvm_ref_lock;
@@ -107,7 +107,7 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device);
 void vfio_df_group_close(struct vfio_device_file *df);
 struct vfio_group *vfio_group_from_file(struct file *file);
 bool vfio_group_enforced_coherent(struct vfio_group *group);
-void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm);
+void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm);
 bool vfio_device_has_container(struct vfio_device *device);
 int __init vfio_group_init(void);
 void vfio_group_cleanup(void);
@@ -165,7 +165,7 @@ static inline bool vfio_group_enforced_coherent(struct vfio_group *group)
 	return true;
 }
 
-static inline void vfio_group_set_kvm(struct vfio_group *group, struct kvm *kvm)
+static inline void vfio_group_set_kvm(struct vfio_group *group, struct file *kvm)
 {
 }
 
@@ -429,11 +429,11 @@ static inline void vfio_virqfd_exit(void)
 #endif
 
 #if IS_ENABLED(CONFIG_KVM)
-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm);
+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm);
 void vfio_device_put_kvm(struct vfio_device *device);
 #else
 static inline void vfio_device_get_kvm_safe(struct vfio_device *device,
-					    struct kvm *kvm)
+					    struct file *kvm)
 {
 }
 
diff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c
index 423ead48aafe3..ed96acfa86358 100644
--- a/drivers/vfio/vfio_main.c
+++ b/drivers/vfio/vfio_main.c
@@ -472,36 +472,14 @@ void vfio_unregister_group_dev(struct vfio_device *device)
 EXPORT_SYMBOL_GPL(vfio_unregister_group_dev);
 
 #if IS_ENABLED(CONFIG_KVM)
-void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm)
+void vfio_device_get_kvm_safe(struct vfio_device *device, struct file *kvm)
 {
-	void (*pfn)(struct kvm *kvm);
-	bool (*fn)(struct kvm *kvm);
-	bool ret;
-
 	lockdep_assert_held(&device->dev_set->lock);
 
 	if (!kvm)
 		return;
 
-	pfn = symbol_get(kvm_put_kvm);
-	if (WARN_ON(!pfn))
-		return;
-
-	fn = symbol_get(kvm_get_kvm_safe);
-	if (WARN_ON(!fn)) {
-		symbol_put(kvm_put_kvm);
-		return;
-	}
-
-	ret = fn(kvm);
-	symbol_put(kvm_get_kvm_safe);
-	if (!ret) {
-		symbol_put(kvm_put_kvm);
-		return;
-	}
-
-	device->put_kvm = pfn;
-	device->kvm = kvm;
+	device->kvm = get_file(kvm);
 }
 
 void vfio_device_put_kvm(struct vfio_device *device)
@@ -511,14 +489,7 @@ void vfio_device_put_kvm(struct vfio_device *device)
 	if (!device->kvm)
 		return;
 
-	if (WARN_ON(!device->put_kvm))
-		goto clear;
-
-	device->put_kvm(device->kvm);
-	device->put_kvm = NULL;
-	symbol_put(kvm_put_kvm);
-
-clear:
+	fput(device->kvm);
 	device->kvm = NULL;
 }
 #endif
@@ -1544,9 +1515,13 @@ bool vfio_file_enforced_coherent(struct file *file)
 }
 EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);
 
-static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)
+static void vfio_device_file_set_kvm(struct file *file, struct file *kvm)
 {
 	struct vfio_device_file *df = file->private_data;
+	struct file *old;
+
+	if (kvm)
+		get_file(kvm);
 
 	/*
 	 * The kvm is first recorded in the vfio_device_file, and will
@@ -1554,28 +1529,32 @@ static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)
 	 * iommufd successfully in the vfio device cdev path.
 	 */
 	spin_lock(&df->kvm_ref_lock);
+	old = df->kvm;
 	df->kvm = kvm;
 	spin_unlock(&df->kvm_ref_lock);
+
+	if (old)
+		fput(old);
 }
 
 /**
  * vfio_file_set_kvm - Link a kvm with VFIO drivers
- * @file: VFIO group file or VFIO device file
- * @kvm: KVM to link
+ * @vfio_file: VFIO group file or VFIO device file
+ * @kvm: KVM file to link
  *
  * When a VFIO device is first opened the KVM will be available in
  * device->kvm if one was associated with the file.
  */
-void vfio_file_set_kvm(struct file *file, struct kvm *kvm)
+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)
 {
 	struct vfio_group *group;
 
-	group = vfio_group_from_file(file);
+	group = vfio_group_from_file(vfio_file);
 	if (group)
 		vfio_group_set_kvm(group, kvm);
 
-	if (vfio_device_from_file(file))
-		vfio_device_file_set_kvm(file, kvm);
+	if (vfio_device_from_file(vfio_file))
+		vfio_device_file_set_kvm(vfio_file, kvm);
 }
 EXPORT_SYMBOL_GPL(vfio_file_set_kvm);
 
diff --git a/drivers/virt/coco/tsm-core.c b/drivers/virt/coco/tsm-core.c
index e784993353d8f..2fce341ff9231 100644
--- a/drivers/virt/coco/tsm-core.c
+++ b/drivers/virt/coco/tsm-core.c
@@ -9,6 +9,16 @@
 #include <linux/cleanup.h>
 #include <linux/pci-tsm.h>
 
+/* The caller must hold a tsm_get_device() reference for the entire use. */
+const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,
+		struct device *dev, enum iommu_viommu_type type)
+{
+	if (!tsm_dev->pci_ops->viommu_get_ops)
+		return NULL;
+	return tsm_dev->pci_ops->viommu_get_ops(dev, type);
+}
+EXPORT_SYMBOL_GPL(tsm_viommu_get_ops);
+
 static void tsm_release(struct device *);
 static const struct class tsm_class = {
 	.name		= "tsm",
@@ -16,6 +26,29 @@ static const struct class tsm_class = {
 };
 static DEFINE_IDA(tsm_ida);
 
+/**
+ * tsm_get_device() - Pin the TSM attached to a device
+ * @dev: device whose TSM is to be pinned
+ *
+ * A successful lookup pins the backend module. Backends providing vIOMMU
+ * operations must not unregister their TSM independently of module unload.
+ * Return: NULL if no vIOMMU-capable TSM is attached, an error if the module
+ * cannot be pinned, or the TSM device associated with the pinned backend.
+ */
+struct tsm_dev *tsm_get_device(struct device *dev)
+{
+	if (!dev_is_pci(dev))
+		return NULL;
+	return pci_tsm_get_device(to_pci_dev(dev));
+}
+EXPORT_SYMBOL_GPL(tsm_get_device);
+
+void tsm_put_device(struct tsm_dev *tsm_dev)
+{
+	module_put(tsm_dev->pci_ops->owner);
+}
+EXPORT_SYMBOL_GPL(tsm_put_device);
+
 static int match_id(struct device *dev, const void *data)
 {
 	struct tsm_dev *tsm_dev = container_of(dev, struct tsm_dev, dev);
@@ -56,26 +89,25 @@ static struct tsm_dev *alloc_tsm_dev(struct device *parent)
 	return no_free_ptr(tsm_dev);
 }
 
-static struct tsm_dev *tsm_register_pci_or_reset(struct tsm_dev *tsm_dev,
-						 struct pci_tsm_ops *pci_ops)
+static int tsm_register_pci(struct tsm_dev *tsm_dev, struct pci_tsm_ops *pci_ops)
 {
 	int rc;
 
 	if (!pci_ops)
-		return tsm_dev;
+		return 0;
 
 	tsm_dev->pci_ops = pci_ops;
 	rc = pci_tsm_register(tsm_dev);
 	if (rc) {
+		tsm_dev->pci_ops = NULL;
 		dev_err(tsm_dev->dev.parent,
 			"PCI/TSM registration failure: %d\n", rc);
-		device_unregister(&tsm_dev->dev);
-		return ERR_PTR(rc);
+		return rc;
 	}
 
 	/* Notify TSM userspace that PCI/TSM operations are now possible */
 	kobject_uevent(&tsm_dev->dev.kobj, KOBJ_CHANGE);
-	return tsm_dev;
+	return 0;
 }
 
 struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *pci_ops)
@@ -96,15 +128,22 @@ struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *pci_ops)
 	if (rc)
 		return ERR_PTR(rc);
 
-	return tsm_register_pci_or_reset(no_free_ptr(tsm_dev), pci_ops);
+	rc = tsm_register_pci(tsm_dev, pci_ops);
+	if (rc) {
+		device_del(dev);
+		return ERR_PTR(rc);
+	}
+	return no_free_ptr(tsm_dev);
 }
 EXPORT_SYMBOL_GPL(tsm_register);
 
 void tsm_unregister(struct tsm_dev *tsm_dev)
 {
+	/* Remove the class lookup first. */
+	device_del(&tsm_dev->dev);
 	if (tsm_dev->pci_ops)
 		pci_tsm_unregister(tsm_dev);
-	device_unregister(&tsm_dev->dev);
+	put_device(&tsm_dev->dev);
 }
 EXPORT_SYMBOL_GPL(tsm_unregister);
 
diff --git a/include/linux/iommu.h b/include/linux/iommu.h
index ac43b8b93f14a..9931c96e5dd33 100644
--- a/include/linux/iommu.h
+++ b/include/linux/iommu.h
@@ -46,6 +46,7 @@ struct iommu_dma_msi_cookie;
 struct iommu_fault_param;
 struct iommufd_ctx;
 struct iommufd_viommu;
+struct iommufd_viommu_ops;
 struct msi_desc;
 struct msi_msg;
 
@@ -669,16 +670,8 @@ __iommu_copy_struct_to_user(const struct iommu_user_data *dst_data,
  *		- IOMMU_DOMAIN_DMA: must use a dma domain
  *		- 0: use the default setting
  * @default_domain_ops: the default ops for domains
- * @get_viommu_size: Get the size of a driver-level vIOMMU structure for a given
- *                   @dev corresponding to @viommu_type. Driver should return 0
- *                   if vIOMMU isn't supported accordingly. It is required for
- *                   driver to use the VIOMMU_STRUCT_SIZE macro to sanitize the
- *                   driver-level vIOMMU structure related to the core one
- * @viommu_init: Init the driver-level struct of an iommufd_viommu on a physical
- *               IOMMU instance @viommu->iommu_dev, as the set of virtualization
- *               resources shared/passed to user space IOMMU instance. Associate
- *               it with a nesting @parent_domain. It is required for driver to
- *               set @viommu->ops pointing to its own viommu_ops
+ * @get_viommu_ops: Return the vIOMMU operations supported by @dev for a type.
+ *                  Return NULL if the type is unsupported.
  * @owner: Driver module providing these ops
  * @identity_domain: An always available, always attachable identity
  *                   translation.
@@ -729,11 +722,8 @@ struct iommu_ops {
 
 	int (*def_domain_type)(struct device *dev);
 
-	size_t (*get_viommu_size)(struct device *dev,
-				  enum iommu_viommu_type viommu_type);
-	int (*viommu_init)(struct iommufd_viommu *viommu,
-			   struct iommu_domain *parent_domain,
-			   const struct iommu_user_data *user_data);
+	const struct iommufd_viommu_ops *(*get_viommu_ops)(
+		struct device *dev, enum iommu_viommu_type viommu_type);
 
 	const struct iommu_domain_ops *default_domain_ops;
 	struct module *owner;
diff --git a/include/linux/iommufd.h b/include/linux/iommufd.h
index 6e7efe83bc5d8..2e67846d6f35a 100644
--- a/include/linux/iommufd.h
+++ b/include/linux/iommufd.h
@@ -6,6 +6,7 @@
 #ifndef __LINUX_IOMMUFD_H
 #define __LINUX_IOMMUFD_H
 
+#include <linux/bits.h>
 #include <linux/err.h>
 #include <linux/errno.h>
 #include <linux/iommu.h>
@@ -23,7 +24,9 @@ struct iommufd_access;
 struct iommufd_ctx;
 struct iommufd_device;
 struct iommufd_viommu_ops;
+struct tsm_dev;
 struct page;
+struct tsm_guest_req_info;
 
 enum iommufd_object_type {
 	IOMMUFD_OBJ_NONE,
@@ -59,7 +62,9 @@ struct iommufd_object {
 };
 
 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
-					   struct device *dev, u32 *id);
+					   struct device *dev,
+					   struct file *kvm_file,
+					   u32 *id);
 void iommufd_device_unbind(struct iommufd_device *idev);
 
 int iommufd_device_attach(struct iommufd_device *idev, ioasid_t pasid,
@@ -99,8 +104,11 @@ void iommufd_ctx_get(struct iommufd_ctx *ictx);
 struct iommufd_viommu {
 	struct iommufd_object obj;
 	struct iommufd_ctx *ictx;
+	/* Physical IOMMU backing, or NULL. */
 	struct iommu_device *iommu_dev;
 	struct iommufd_hwpt_paging *hwpt;
+	struct file *kvm_file;
+	struct tsm_dev *tsm_dev;
 
 	const struct iommufd_viommu_ops *ops;
 
@@ -122,6 +130,10 @@ struct iommufd_vdevice {
 	 */
 	u64 virt_id;
 
+	/* Guest TSM requests accepted by this vdevice; set by vdevice_init(). */
+	u64 tsm_req_op_mask;
+	u32 tsm_tvm_arch;
+
 	/* Clean up all driver-specific parts of an iommufd_vdevice */
 	void (*destroy)(struct iommufd_vdevice *vdev);
 };
@@ -140,8 +152,19 @@ struct iommufd_hw_queue {
 	void (*destroy)(struct iommufd_hw_queue *hw_queue);
 };
 
+#define IOMMUFD_VIOMMU_NO_HWPT	BIT(0)
+
 /**
  * struct iommufd_viommu_ops - vIOMMU specific operations
+ * @flags: Properties needed by the core before vIOMMU initialization
+ * @get_viommu_size: Get the size of a driver-level vIOMMU structure for a given
+ *                   @dev corresponding to @viommu_type. Driver should return 0
+ *                   if vIOMMU isn't supported accordingly. It is required for
+ *                   driver to use the VIOMMU_STRUCT_SIZE macro to sanitize the
+ *                   driver-level vIOMMU structure related to the core one
+ * @viommu_init: Initialize the selected driver-level iommufd_viommu for @dev.
+ *               @parent_domain is the nesting parent, or NULL for an
+ *               implementation that does not use a parent HWPT.
  * @destroy: Clean up all driver-specific parts of an iommufd_viommu. The memory
  *           of the vIOMMU will be free-ed by iommufd core after calling this op
  * @alloc_domain_nested: Allocate a IOMMU_DOMAIN_NESTED on a vIOMMU that holds a
@@ -164,6 +187,7 @@ struct iommufd_hw_queue {
  *                include/uapi/linux/iommufd.h)
  *                If driver has a deinit function to revert what vdevice_init op
  *                does, it should set it to the @vdev->destroy function pointer
+ * @vdevice_tsm_req: Forward a guest TSM request to a driver-owned vDEVICE
  * @get_hw_queue_size: Get the size of a driver-defined HW queue structure for a
  *                     given @viommu corresponding to @queue_type. Driver should
  *                     return 0 if HW queue aren't supported accordingly. It is
@@ -182,6 +206,12 @@ struct iommufd_hw_queue {
  *                      does, it should set it to the @hw_queue->destroy pointer
  */
 struct iommufd_viommu_ops {
+	unsigned long flags;
+	size_t (*get_viommu_size)(struct device *dev,
+		enum iommu_viommu_type type);
+	int (*viommu_init)(struct iommufd_viommu *viommu, struct device *dev,
+		struct iommu_domain *parent_domain,
+		const struct iommu_user_data *user_data);
 	void (*destroy)(struct iommufd_viommu *viommu);
 	struct iommu_domain *(*alloc_domain_nested)(
 		struct iommufd_viommu *viommu, u32 flags,
@@ -190,6 +220,9 @@ struct iommufd_viommu_ops {
 				struct iommu_user_data_array *array);
 	const size_t vdevice_size;
 	int (*vdevice_init)(struct iommufd_vdevice *vdev);
+	ssize_t (*vdevice_tsm_req)(struct iommufd_vdevice *vdev,
+				   struct tsm_guest_req_info *info,
+				   u64 *tsm_code);
 	size_t (*get_hw_queue_size)(struct iommufd_viommu *viommu,
 				    enum iommu_hw_queue_type queue_type);
 	/* AMD's HW will add hw_queue_init simply using @hw_queue->base_addr */
diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
index cf7fe835c4ad2..586f6e8bb81b3 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -784,6 +784,12 @@ struct kvm {
 	 * kvm_swap_active_memslots().
 	 */
 	struct mutex slots_arch_lock;
+	/*
+	 * Back-reference to the VM file for subsystems (e.g., VFIO). Holds no
+	 * reference to avoid pinning the VM. Callers storing the file must
+	 * take their own reference.
+	 */
+	struct file *file;
 	struct mm_struct *mm; /* userspace tied to this vm */
 	unsigned long nr_memslot_pages;
 	/* The two memslot sets - active and inactive (per address space) */
@@ -1081,7 +1087,18 @@ void kvm_exit(void);
 void kvm_get_kvm(struct kvm *kvm);
 bool kvm_get_kvm_safe(struct kvm *kvm);
 void kvm_put_kvm(struct kvm *kvm);
-bool file_is_kvm(struct file *file);
+
+/*
+ * Architectures define kvm_file_to_kvm_arch to <arch>
+ * to get a typed, arch-namespaced helper:
+ *
+ *   struct kvm *file_to_kvm_<arch>(struct file *file)
+ */
+#ifdef kvm_file_to_kvm_arch
+#define kvm_file_to_kvm_fn CONCATENATE(file_to_kvm_, kvm_file_to_kvm_arch)
+struct kvm *kvm_file_to_kvm_fn(struct file *file);
+#endif /* kvm_file_to_kvm_arch */
+
 void kvm_put_kvm_no_destroy(struct kvm *kvm);
 
 static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id)
diff --git a/include/linux/pci-tsm.h b/include/linux/pci-tsm.h
index a6435aba03f9b..3adc317d0f9bc 100644
--- a/include/linux/pci-tsm.h
+++ b/include/linux/pci-tsm.h
@@ -1,14 +1,15 @@
 /* SPDX-License-Identifier: GPL-2.0 */
 #ifndef __PCI_TSM_H
 #define __PCI_TSM_H
+#include <linux/completion.h>
 #include <linux/mutex.h>
 #include <linux/pci.h>
-#include <linux/sockptr.h>
 
+struct iommufd_viommu_ops;
+struct module;
 struct pci_tsm;
+struct pci_tsm_context;
 struct tsm_dev;
-struct kvm;
-enum pci_tsm_req_scope;
 
 /*
  * struct pci_tsm_ops - manage confidential links and security state
@@ -18,12 +19,26 @@ enum pci_tsm_req_scope;
  * @devsec_ops: Lock, unlock, and interrogate the security state of the
  *		function via the platform TSM (typically virtual function
  *		operations).
+ * @viommu_get_ops: Return operations for a supported TSM-owned vIOMMU type,
+ *		  or NULL if unsupported
+ * @owner: Module providing the vIOMMU operations, if built as a module
+ *
+ * The vIOMMU owner pins the backend module before querying @viommu_get_ops
+ * and releases it after vIOMMU destruction. A backend providing this callback
+ * must not unregister its TSM while the module is pinned.
  *
  * This operations are mutually exclusive either a tsm_dev instance
  * manages physical link properties or it manages function security
  * states like TDISP lock/unlock.
+ *
+ * @viommu_get_ops runs with the backend module pinned. The PCI/TSM
+ * association is checked during acquisition under pci_tsm_rwsem.
  */
 struct pci_tsm_ops {
+	struct module *owner;
+	const struct iommufd_viommu_ops *(*viommu_get_ops)(
+		struct device *dev, enum iommu_viommu_type type);
+
 	/*
 	 * struct pci_tsm_link_ops - Manage physical link and the TSM/DSM session
 	 * @probe: establish context with the TSM (allocate / wrap 'struct
@@ -32,17 +47,12 @@ struct pci_tsm_ops {
 	 * @connect: establish / validate a secure connection (e.g. IDE)
 	 *	     with the device
 	 * @disconnect: teardown the secure link
-	 * @bind: bind a TDI in preparation for it to be accepted by a TVM
-	 * @unbind: remove a TDI from secure operation with a TVM
-	 * @guest_req: marshal TVM information and state change requests
 	 *
 	 * Context: @probe, @remove, @connect, and @disconnect run under
 	 * pci_tsm_rwsem held for write to sync with TSM unregistration and
 	 * mutual exclusion of @connect and @disconnect. @connect and
 	 * @disconnect additionally run under the DSM lock (struct
 	 * pci_tsm_pf0::lock) as well as @probe and @remove of the subfunctions.
-	 * @bind, @unbind, and @guest_req run under pci_tsm_rwsem held for read
-	 * and the DSM lock.
 	 */
 	struct_group_tagged(pci_tsm_link_ops, link_ops,
 		struct pci_tsm *(*probe)(struct tsm_dev *tsm_dev,
@@ -50,14 +60,6 @@ struct pci_tsm_ops {
 		void (*remove)(struct pci_tsm *tsm);
 		int (*connect)(struct pci_dev *pdev);
 		void (*disconnect)(struct pci_dev *pdev);
-		struct pci_tdi *(*bind)(struct pci_dev *pdev,
-					struct kvm *kvm, u32 tdi_id);
-		void (*unbind)(struct pci_tdi *tdi);
-		ssize_t (*guest_req)(struct pci_tdi *tdi,
-				     enum pci_tsm_req_scope scope,
-				     sockptr_t req_in, size_t in_len,
-				     sockptr_t req_out, size_t out_len,
-				     u64 *tsm_code);
 	);
 
 	/*
@@ -77,25 +79,12 @@ struct pci_tsm_ops {
 	);
 };
 
-/**
- * struct pci_tdi - Core TEE I/O Device Interface (TDI) context
- * @pdev: host side representation of guest-side TDI
- * @kvm: TEE VM context of bound TDI
- * @tdi_id: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM
- */
-struct pci_tdi {
-	struct pci_dev *pdev;
-	struct kvm *kvm;
-	u32 tdi_id;
-};
-
 /**
  * struct pci_tsm - Core TSM context for a given PCIe endpoint
  * @pdev: Back ref to device function, distinguishes type of pci_tsm context
  * @dsm_dev: PCI Device Security Manager for link operations on @pdev
  * @tsm_dev: PCI TEE Security Manager device for Link Confidentiality or Device
  *	     Function Security operations
- * @tdi: TDI context established by the @bind link operation
  *
  * This structure is wrapped by low level TSM driver data and returned by
  * probe()/lock(), it is freed by the corresponding remove()/unlock().
@@ -111,18 +100,24 @@ struct pci_tsm {
 	struct pci_dev *pdev;
 	struct pci_dev *dsm_dev;
 	struct tsm_dev *tsm_dev;
-	struct pci_tdi *tdi;
 };
 
 /**
  * struct pci_tsm_pf0 - Physical Function 0 TDISP link context
  * @base_tsm: generic core "tsm" context
  * @lock: mutual exclustion for pci_tsm_ops invocation
+ * @context_users: live per-function contexts on this PF0; a nonzero count
+ *	blocks link disconnect
+ * @contexts_drained: completed when the last context is released
+ * @removing: reject new contexts while the DSM is being removed
  * @doe_mb: PCIe Data Object Exchange mailbox
  */
 struct pci_tsm_pf0 {
 	struct pci_tsm base_tsm;
 	struct mutex lock;
+	unsigned int context_users;
+	struct completion contexts_drained;
+	bool removing;
 	struct pci_doe_mb *doe_mb;
 };
 
@@ -159,46 +154,6 @@ static inline bool is_pci_tsm_pf0(struct pci_dev *pdev)
 	return PCI_FUNC(pdev->devfn) == 0;
 }
 
-/**
- * enum pci_tsm_req_scope - Scope of guest requests to be validated by TSM
- *
- * Guest requests are a transport for a TVM to communicate with a TSM + DSM for
- * a given TDI. A TSM driver is responsible for maintaining the kernel security
- * model and limit commands that may affect the host, or are otherwise outside
- * the typical TDISP operational model.
- */
-enum pci_tsm_req_scope {
-	/**
-	 * @PCI_TSM_REQ_INFO: Read-only, without side effects, request for
-	 * typical TDISP collateral information like Device Interface Reports.
-	 * No device secrets are permitted, and no device state is changed.
-	 */
-	PCI_TSM_REQ_INFO = 0,
-	/**
-	 * @PCI_TSM_REQ_STATE_CHANGE: Request to change the TDISP state from
-	 * UNLOCKED->LOCKED, LOCKED->RUN, or other architecture specific state
-	 * changes to support those transitions for a TDI. No other (unrelated
-	 * to TDISP) device / host state, configuration, or data change is
-	 * permitted.
-	 */
-	PCI_TSM_REQ_STATE_CHANGE = 1,
-	/**
-	 * @PCI_TSM_REQ_DEBUG_READ: Read-only request for debug information
-	 *
-	 * A method to facilitate TVM information retrieval outside of typical
-	 * TDISP operational requirements. No device secrets are permitted.
-	 */
-	PCI_TSM_REQ_DEBUG_READ = 2,
-	/**
-	 * @PCI_TSM_REQ_DEBUG_WRITE: Device state changes for debug purposes
-	 *
-	 * The request may affect the operational state of the device outside of
-	 * the TDISP operational model. If allowed, requires CAP_SYS_RAW_IO, and
-	 * will taint the kernel.
-	 */
-	PCI_TSM_REQ_DEBUG_WRITE = 3,
-};
-
 #ifdef CONFIG_PCI_TSM
 int pci_tsm_register(struct tsm_dev *tsm_dev);
 void pci_tsm_unregister(struct tsm_dev *tsm_dev);
@@ -209,13 +164,15 @@ int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm,
 void pci_tsm_pf0_destructor(struct pci_tsm_pf0 *tsm);
 int pci_tsm_doe_transfer(struct pci_dev *pdev, u8 type, const void *req,
 			 size_t req_sz, void *resp, size_t resp_sz);
-int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id);
-void pci_tsm_unbind(struct pci_dev *pdev);
-void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi,
-			     struct kvm *kvm, u32 tdi_id);
-ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope,
-			  sockptr_t req_in, size_t in_len, sockptr_t req_out,
-			  size_t out_len, u64 *tsm_code);
+bool pci_tsm_is_configured(struct pci_dev *pdev);
+struct pci_tsm_context *pci_tsm_context_get(struct pci_dev *pdev,
+					    struct tsm_dev *viommu_tsm_dev);
+void pci_tsm_context_put(struct pci_tsm_context *context);
+struct pci_tsm_pf0 *pci_tsm_context_pf0(struct pci_tsm_context *context);
+struct pci_dev *pci_tsm_context_dsm_dev(struct pci_tsm_context *context);
+bool pci_tsm_context_match_device(struct pci_tsm_context *context,
+				  struct pci_dev *pdev);
+struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev);
 #else
 static inline int pci_tsm_register(struct tsm_dev *tsm_dev)
 {
@@ -224,20 +181,44 @@ static inline int pci_tsm_register(struct tsm_dev *tsm_dev)
 static inline void pci_tsm_unregister(struct tsm_dev *tsm_dev)
 {
 }
-static inline int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u64 tdi_id)
+
+static inline bool pci_tsm_is_configured(struct pci_dev *pdev)
 {
-	return -ENXIO;
+	return false;
 }
-static inline void pci_tsm_unbind(struct pci_dev *pdev)
+
+static inline struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)
 {
+	return NULL;
 }
-static inline ssize_t pci_tsm_guest_req(struct pci_dev *pdev,
-					enum pci_tsm_req_scope scope,
-					sockptr_t req_in, size_t in_len,
-					sockptr_t req_out, size_t out_len,
-					u64 *tsm_code)
+
+static inline struct pci_tsm_context *
+pci_tsm_context_get(struct pci_dev *pdev, struct tsm_dev *viommu_tsm_dev)
+{
+	return ERR_PTR(-EOPNOTSUPP);
+}
+
+static inline void pci_tsm_context_put(struct pci_tsm_context *context)
+{
+}
+
+static inline struct pci_tsm_pf0 *
+pci_tsm_context_pf0(struct pci_tsm_context *context)
+{
+	return NULL;
+}
+
+static inline struct pci_dev *
+pci_tsm_context_dsm_dev(struct pci_tsm_context *context)
+{
+	return NULL;
+}
+
+static inline bool
+pci_tsm_context_match_device(struct pci_tsm_context *context,
+			     struct pci_dev *pdev)
 {
-	return -ENXIO;
+	return false;
 }
 #endif
 #endif /*__PCI_TSM_H */
diff --git a/include/linux/tsm.h b/include/linux/tsm.h
index 381c53244c835..e5d14f9a23e9f 100644
--- a/include/linux/tsm.h
+++ b/include/linux/tsm.h
@@ -6,6 +6,7 @@
 #include <linux/types.h>
 #include <linux/uuid.h>
 #include <linux/device.h>
+#include <uapi/linux/iommufd.h>
 
 #define TSM_REPORT_INBLOB_MAX 64
 #define TSM_REPORT_OUTBLOB_MAX SZ_16M
@@ -109,6 +110,8 @@ struct tsm_report_ops {
 };
 
 struct pci_tsm_ops;
+struct iommufd_viommu_ops;
+
 struct tsm_dev {
 	struct device dev;
 	int id;
@@ -123,4 +126,47 @@ int tsm_report_unregister(const struct tsm_report_ops *ops);
 struct tsm_dev *tsm_register(struct device *parent, struct pci_tsm_ops *ops);
 void tsm_unregister(struct tsm_dev *tsm_dev);
 struct tsm_dev *find_tsm_dev(int id);
+
+#ifdef CONFIG_TSM
+struct tsm_dev *tsm_get_device(struct device *dev);
+void tsm_put_device(struct tsm_dev *tsm_dev);
+const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,
+		struct device *dev, enum iommu_viommu_type type);
+
+/**
+ * struct tsm_guest_req_info - parameters for a guest-initiated TSM request
+ * @op: operation for the guest-initiated request
+ * @tvm_arch: guest TVM architecture
+ * @req: userspace buffer containing the guest request
+ * @req_len: request size in bytes, at most INT_MAX
+ * @resp: userspace buffer for the response
+ * @resp_len: response buffer capacity in bytes, at most INT_MAX
+ */
+struct tsm_guest_req_info {
+	enum iommu_vdevice_tsm_guest_req_op op;
+	enum iommu_vdevice_tsm_guest_tvm_arch tvm_arch;
+	const void __user *req;
+	u32 req_len;
+	void __user *resp;
+	u32 resp_len;
+};
+#else
+static inline struct tsm_dev *tsm_get_device(struct device *dev)
+{
+	return NULL;
+}
+
+static inline void tsm_put_device(struct tsm_dev *tsm_dev)
+{
+}
+
+static inline const struct iommufd_viommu_ops *
+tsm_viommu_get_ops(struct tsm_dev *tsm_dev, struct device *dev,
+		enum iommu_viommu_type type)
+{
+	return NULL;
+}
+
+struct tsm_guest_req_info;
+#endif
 #endif /* __TSM_H */
diff --git a/include/linux/vfio.h b/include/linux/vfio.h
index 45f08986359e4..0cc91c6f96d2b 100644
--- a/include/linux/vfio.h
+++ b/include/linux/vfio.h
@@ -54,7 +54,7 @@ struct vfio_device {
 	struct list_head dev_set_list;
 	unsigned int migration_flags;
 	u8 precopy_info_v2;
-	struct kvm *kvm;
+	struct file *kvm;
 
 	/* Members below here are private, not for driver use */
 	unsigned int index;
@@ -66,7 +66,6 @@ struct vfio_device {
 	unsigned int open_count;
 	struct completion comp;
 	struct iommufd_access *iommufd_access;
-	void (*put_kvm)(struct kvm *kvm);
 	struct inode *inode;
 #if IS_ENABLED(CONFIG_IOMMUFD)
 	struct iommufd_device *iommufd_device;
@@ -378,7 +377,7 @@ static inline bool vfio_file_has_dev(struct file *file, struct vfio_device *devi
 #endif
 bool vfio_file_is_valid(struct file *file);
 bool vfio_file_enforced_coherent(struct file *file);
-void vfio_file_set_kvm(struct file *file, struct kvm *kvm);
+void vfio_file_set_kvm(struct file *vfio_file, struct file *kvm);
 
 #define VFIO_PIN_PAGES_MAX_ENTRIES	(PAGE_SIZE/sizeof(unsigned long))
 
diff --git a/include/uapi/linux/iommufd.h b/include/uapi/linux/iommufd.h
index 206fa667c7828..3d1ebbdf39488 100644
--- a/include/uapi/linux/iommufd.h
+++ b/include/uapi/linux/iommufd.h
@@ -58,6 +58,7 @@ enum {
 	IOMMUFD_CMD_VEVENTQ_ALLOC = 0x93,
 	IOMMUFD_CMD_HW_QUEUE_ALLOC = 0x94,
 	IOMMUFD_CMD_IOAS_NOIOMMU_GET_PA = 0x95,
+	IOMMUFD_CMD_VDEVICE_TSM_REQ = 0x96,
 };
 
 /**
@@ -1129,7 +1130,8 @@ struct iommu_viommu_tegra241_cmdqv {
  * @flags: Must be 0
  * @type: Type of the virtual IOMMU. Must be defined in enum iommu_viommu_type
  * @dev_id: The device's physical IOMMU will be used to back the virtual IOMMU
- * @hwpt_id: ID of a nesting parent HWPT to associate to
+ * @hwpt_id: ID of a nesting parent HWPT to associate to. Must be zero when the
+ *           selected vIOMMU implementation does not use a parent HWPT
  * @out_viommu_id: Output virtual IOMMU ID for the allocated object
  * @data_len: Length of the type specific data
  * @__reserved: Must be 0
@@ -1390,4 +1392,85 @@ struct iommu_hw_queue_alloc {
 	__aligned_u64 length;
 };
 #define IOMMU_HW_QUEUE_ALLOC _IO(IOMMUFD_TYPE, IOMMUFD_CMD_HW_QUEUE_ALLOC)
+
+/**
+ * enum iommu_vdevice_tsm_guest_tvm_arch - guest TVM architecture
+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_CCA: Arm CCA TVM
+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_SEV: AMD SEV TVM
+ * @IOMMU_VDEVICE_TSM_TVM_ARCH_TDX: Intel TDX TVM
+ */
+enum iommu_vdevice_tsm_guest_tvm_arch {
+	IOMMU_VDEVICE_TSM_TVM_ARCH_CCA = 1,
+	IOMMU_VDEVICE_TSM_TVM_ARCH_SEV,
+	IOMMU_VDEVICE_TSM_TVM_ARCH_TDX,
+};
+
+/**
+ * enum iommu_vdevice_tsm_guest_req_op - Guest TSM request operations
+ * @TSM_REQ_VALIDATE_MMIO: Validate and map a guest MMIO range for the trusted
+ *                         device.
+ * @TSM_REQ_SET_TDI_STATE: Transition the trusted device to the unlocked,
+ *                         locked, or running state.
+ * @TSM_REQ_SEV_ENABLE_DMA: Enable DMA for an SEV device.
+ * @TSM_REQ_SEV_DISABLE_DMA: Disable DMA for an SEV device.
+ * @TSM_REQ_READ_OBJECT: Read bytes from a device object, such as a certificate,
+ *                       measurement, or interface report.
+ * @TSM_REQ_REGEN_OBJECT: Regenerate a device object, such as a measurement or
+ *                        interface report.
+ * @TSM_REQ_OBJECT_INFO: Query the size of a device object.
+ * @TSM_REQ_MAX: One past the last request operation; not a command.
+ *
+ * The request payload and response format depend on the TVM architecture.
+ */
+enum iommu_vdevice_tsm_guest_req_op {
+	TSM_REQ_VALIDATE_MMIO = 1,
+	TSM_REQ_SET_TDI_STATE,
+	TSM_REQ_SEV_ENABLE_DMA,
+	TSM_REQ_SEV_DISABLE_DMA,
+	TSM_REQ_READ_OBJECT,
+	TSM_REQ_REGEN_OBJECT,
+	TSM_REQ_OBJECT_INFO,
+	TSM_REQ_MAX,
+};
+
+/**
+ * struct iommu_vdevice_tsm_req - ioctl(IOMMU_VDEVICE_TSM_REQ)
+ * @size: sizeof(struct iommu_vdevice_tsm_req)
+ * @vdevice_id: vDevice ID the guest request is for
+ * @op: One of enum iommu_vdevice_tsm_guest_req_op, excluding TSM_REQ_MAX
+ * @tvm_arch: One of enum iommu_vdevice_tsm_guest_tvm_arch
+ * @req_len: Size in bytes of the input payload at @req_uptr, at most INT_MAX
+ * @resp_len: Size in bytes of the output buffer at @resp_uptr, at most INT_MAX
+ * @req_uptr: Userspace pointer to the guest-provided request payload
+ * @resp_uptr: Userspace pointer to the guest response buffer
+ * @out_tsm_code: TSM-specific result code returned by the TSM implementation
+ *
+ * Forward a TSM request to the TSM bound vDevice. This is intended for
+ * guest TSM/TDISP message transport where the host kernel only marshals
+ * bytes between userspace and the TSM implementation.
+ *
+ * The request operation is guest initiated. The vDEVICE implementation
+ * declares the TVM architecture and operations it accepts; iommufd checks
+ * both before forwarding the request.
+ *
+ * The request payload is read from @req_uptr/@req_len. If a response is
+ * expected, userspace provides @resp_uptr/@resp_len as writable storage for
+ * response bytes returned by the TSM path.
+ *
+ * The ioctl is only suitable for commands and results that the host kernel
+ * has no use, the host is only facilitating guest to TSM communication.
+ */
+struct iommu_vdevice_tsm_req {
+	__u32 size;
+	__u32 vdevice_id;
+	__u32 op;
+	__u32 tvm_arch;
+	__u32 req_len;
+	__u32 resp_len;
+	__aligned_u64 req_uptr;
+	__aligned_u64 resp_uptr;
+	__aligned_u64 out_tsm_code;
+};
+
+#define IOMMU_VDEVICE_TSM_REQ _IO(IOMMUFD_TYPE, IOMMUFD_CMD_VDEVICE_TSM_REQ)
 #endif
diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index 85f42289748dc..60e614795a36c 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -1314,7 +1314,7 @@ void kvm_get_kvm(struct kvm *kvm)
 {
 	refcount_inc(&kvm->users_count);
 }
-EXPORT_SYMBOL_GPL(kvm_get_kvm);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm);
 
 /*
  * Make sure the vm is not during destruction, which is a safe version of
@@ -1324,14 +1324,14 @@ bool kvm_get_kvm_safe(struct kvm *kvm)
 {
 	return refcount_inc_not_zero(&kvm->users_count);
 }
-EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_kvm_safe);
 
 void kvm_put_kvm(struct kvm *kvm)
 {
 	if (refcount_dec_and_test(&kvm->users_count))
 		kvm_destroy_vm(kvm);
 }
-EXPORT_SYMBOL_GPL(kvm_put_kvm);
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_put_kvm);
 
 /*
  * Used to put a reference that was taken on behalf of an object associated
@@ -1352,6 +1352,8 @@ static int kvm_vm_release(struct inode *inode, struct file *filp)
 
 	kvm_irqfd_release(kvm);
 
+	WRITE_ONCE(kvm->file, NULL);
+
 	kvm_put_kvm(kvm);
 	return 0;
 }
@@ -5513,11 +5515,16 @@ static struct file_operations kvm_vm_fops = {
 	KVM_COMPAT(kvm_vm_compat_ioctl),
 };
 
-bool file_is_kvm(struct file *file)
+#ifdef kvm_file_to_kvm_arch
+struct kvm *kvm_file_to_kvm_fn(struct file *file)
 {
-	return file && file->f_op == &kvm_vm_fops;
+	if (!file || file->f_op != &kvm_vm_fops)
+		return NULL;
+
+	return file->private_data;
 }
-EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_is_kvm);
+EXPORT_SYMBOL_GPL(kvm_file_to_kvm_fn);
+#endif
 
 static int kvm_dev_ioctl_create_vm(unsigned long type)
 {
@@ -5544,6 +5551,8 @@ static int kvm_dev_ioctl_create_vm(unsigned long type)
 		goto put_kvm;
 	}
 
+	kvm->file = file;
+
 	/*
 	 * Don't call kvm_put_kvm anymore at this point; file->f_op is
 	 * already set, with ->release() being kvm_vm_release().  In error
diff --git a/virt/kvm/vfio.c b/virt/kvm/vfio.c
index 6cdc4e9a333a3..19548a4309426 100644
--- a/virt/kvm/vfio.c
+++ b/virt/kvm/vfio.c
@@ -35,15 +35,15 @@ struct kvm_vfio {
 	bool noncoherent;
 };
 
-static void kvm_vfio_file_set_kvm(struct file *file, struct kvm *kvm)
+static void kvm_vfio_file_set_kvm(struct file *vfio_file, struct file *kvm)
 {
-	void (*fn)(struct file *file, struct kvm *kvm);
+	void (*fn)(struct file *vfio_file, struct file *kvm);
 
 	fn = symbol_get(vfio_file_set_kvm);
 	if (!fn)
 		return;
 
-	fn(file, kvm);
+	fn(vfio_file, kvm);
 
 	symbol_put(vfio_file_set_kvm);
 }
@@ -144,6 +144,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 {
 	struct kvm_vfio *kv = dev->private;
 	struct kvm_vfio_file *kvf;
+	struct file *kvm_file __free(fput) = NULL;
 	struct file *filp __free(fput) = NULL;
 
 	filp = fget(fd);
@@ -154,6 +155,10 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 	if (!kvm_vfio_file_is_valid(filp))
 		return -EINVAL;
 
+	kvm_file = get_file_active(&dev->kvm->file);
+	if (!kvm_file)
+		return -ENOENT;
+
 	guard(mutex)(&kv->lock);
 
 	list_for_each_entry(kvf, &kv->file_list, node) {
@@ -168,7 +173,7 @@ static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)
 	kvf->file = get_file(filp);
 	list_add_tail(&kvf->node, &kv->file_list);
 
-	kvm_vfio_file_set_kvm(kvf->file, dev->kvm);
+	kvm_vfio_file_set_kvm(kvf->file, kvm_file);
 	kvm_vfio_update_coherency(dev);
 
 	return 0;

45/3 2026/10/08 07:04 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43586
							output: 23
							thoughts: 1802
						

Thoughts:
**KMSAN Evaluation for this Patch Series**

Okay, let's break this down. My goal is to determine if this patch series warrants a dedicated KMSAN fuzzing session. The guidelines are pretty clear: KMSAN is for catching *uninitialized* memory reads and kernel-to-user info leaks that KASAN or other standard tools would miss. So, if KASAN, LOCKDEP, or UB-sanitizers can catch it, no need for KMSAN. I need to be sure that the code touches or introduces uninitialized memory, only detectable with KMSAN.

First, I see a bunch of refactoring across different parts of the iommu and kvm code: taking `struct file *` instead of `struct kvm *` in various functions, and then converting them. There's also some restructuring of iommu operations. None of this *immediately* screams KMSAN territory. It seems like a consolidation and refactoring effort. So far, nothing indicates the introduction or modification of kernel structures sent to user space or conditional logic using uninitialized variables.

Then, there's a new file: `drivers/iommu/iommufd/tsm.c`. This is where my attention needs to be concentrated. The `iommufd_vdevice_tsm_req_ioctl` function within `tsm.c` is the key. Inside, the code takes a `struct iommu_vdevice_tsm_req` from user space, fills a `tsm_guest_req_info` struct, and passes it to an iommu operation. Crucially, the members of `tsm_guest_req_info`, `req` and `resp`, are pointers to user buffers, `req_uptr` and `resp_uptr`, respectively, which are converted using `u64_to_user_ptr`. The function also does some bounds checking and uses the `ucmd` structure, and it calls `iommufd_ucmd_respond` which seems critical for sending the information back to userspace.

Now, what is `iommufd_ucmd_respond`? How does it copy the data back to user space? If there's any chance of uninitialized data in the `struct iommu_vdevice_tsm_req` being copied to user space without proper initialization *before* `iommufd_ucmd_respond` is called, that's a KMSAN candidate. That `tsm.c` code also uses a new `struct iommu_vdevice_tsm_req`, which will also need examination.

So, I need to check `iommufd_ucmd_respond` and, as always, understand exactly how the ioctl buffers are allocated and copied to user space. It is looking like this is the critical section to audit. The pointers to user buffers passed in `tsm_guest_req_info` and the `out_tsm_code` member within `cmd` are the red flags here. If those are not carefully handled with proper zeroing or initialization, KMSAN is probably justified to prevent information leakage. I need to carefully analyze the memory management and initialization of `tsm_guest_req_info` and the contents of `cmd` within the ioctl.



46/3 2026/10/08 07:05 tool grepper
0m Args:
{
  "Expression": "iommufd_ucmd_respond"
}

Results:
{
  "Output": "drivers/iommu/iommufd/device.c=1634=int iommufd_get_hw_info(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/device.c-1747-\ndrivers/iommu/iommufd/device.c:1748:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/device.c-1749-out_free:\n--\ndrivers/iommu/iommufd/eventq.c=441=int iommufd_fault_alloc(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/eventq.c-466-\ndrivers/iommu/iommufd/eventq.c:467:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/eventq.c-468-\tif (rc)\n--\ndrivers/iommu/iommufd/eventq.c=504=int iommufd_veventq_alloc(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/eventq.c-553-\ndrivers/iommu/iommufd/eventq.c:554:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/eventq.c-555-\tif (rc)\n--\ndrivers/iommu/iommufd/hw_pagetable.c=349=int iommufd_hwpt_alloc(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/hw_pagetable.c-444-\tcmd-\u003eout_hwpt_id = hwpt-\u003eobj.id;\ndrivers/iommu/iommufd/hw_pagetable.c:445:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/hw_pagetable.c-446-\tif (rc)\n--\ndrivers/iommu/iommufd/hw_pagetable.c=514=int iommufd_hwpt_invalidate(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/hw_pagetable.c-578-\tcmd-\u003eentry_num = done_num;\ndrivers/iommu/iommufd/hw_pagetable.c:579:\tif (iommufd_ucmd_respond(ucmd, sizeof(*cmd)))\ndrivers/iommu/iommufd/hw_pagetable.c-580-\t\treturn -EFAULT;\n--\ndrivers/iommu/iommufd/ioas.c=38=int iommufd_ioas_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-51-\tcmd-\u003eout_ioas_id = ioas-\u003eobj.id;\ndrivers/iommu/iommufd/ioas.c:52:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-53-\tif (rc)\n--\ndrivers/iommu/iommufd/ioas.c=66=int iommufd_ioas_iova_ranges(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-104-\t}\ndrivers/iommu/iommufd/ioas.c:105:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-106-\tif (rc)\n--\ndrivers/iommu/iommufd/ioas.c=204=int iommufd_ioas_map_file(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-237-\tcmd-\u003eiova = iova;\ndrivers/iommu/iommufd/ioas.c:238:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-239-out_put:\n--\ndrivers/iommu/iommufd/ioas.c=244=int iommufd_ioas_map(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-276-\tcmd-\u003eiova = iova;\ndrivers/iommu/iommufd/ioas.c:277:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-278-out_put:\n--\ndrivers/iommu/iommufd/ioas.c=283=int iommufd_ioas_copy(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-331-\tcmd-\u003edst_iova = iova;\ndrivers/iommu/iommufd/ioas.c:332:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-333-out_put_dst:\n--\ndrivers/iommu/iommufd/ioas.c=340=int iommufd_ioas_unmap(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-370-\tcmd-\u003elength = unmapped;\ndrivers/iommu/iommufd/ioas.c:371:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-372-\n--\ndrivers/iommu/iommufd/ioas.c=379=int iommufd_ioas_noiommu_get_pa(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/ioas.c-405-\ndrivers/iommu/iommufd/ioas.c:406:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/ioas.c-407-out_put:\n--\ndrivers/iommu/iommufd/iommufd_private.h=166=int iommufd_vfio_ioctl(struct iommufd_ctx *ictx, unsigned int cmd,\n--\ndrivers/iommu/iommufd/iommufd_private.h-169-/* Copy the response in ucmd-\u003ecmd back to userspace. */\ndrivers/iommu/iommufd/iommufd_private.h:170:static inline int iommufd_ucmd_respond(struct iommufd_ucmd *ucmd,\ndrivers/iommu/iommufd/iommufd_private.h-171-\t\t\t\t       size_t cmd_len)\n--\ndrivers/iommu/iommufd/selftest.c=1062=static int iommufd_test_mock_domain(struct iommufd_ucmd *ucmd,\n--\ndrivers/iommu/iommufd/selftest.c-1105-\tcmd-\u003emock_domain.out_idev_id = idev_id;\ndrivers/iommu/iommufd/selftest.c:1106:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1107-\tif (rc)\n--\ndrivers/iommu/iommufd/selftest.c=1148=static int iommufd_test_mock_domain_replace(struct iommufd_ucmd *ucmd,\n--\ndrivers/iommu/iommufd/selftest.c-1165-\tcmd-\u003emock_domain_replace.pt_id = pt_id;\ndrivers/iommu/iommufd/selftest.c:1166:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1167-\n--\ndrivers/iommu/iommufd/selftest.c=1459=static int iommufd_test_create_access(struct iommufd_ucmd *ucmd,\n--\ndrivers/iommu/iommufd/selftest.c-1495-\tcmd-\u003ecreate_access.out_access_fd = fdno;\ndrivers/iommu/iommufd/selftest.c:1496:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1497-\tif (rc)\n--\ndrivers/iommu/iommufd/selftest.c=1551=static int iommufd_test_access_pages(struct iommufd_ucmd *ucmd,\n--\ndrivers/iommu/iommufd/selftest.c-1627-\tcmd-\u003eaccess_pages.out_access_pages_id = item-\u003eid;\ndrivers/iommu/iommufd/selftest.c:1628:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1629-\tif (rc)\n--\ndrivers/iommu/iommufd/selftest.c=1705=static int iommufd_test_dirty(struct iommufd_ucmd *ucmd, unsigned int mockpt_id,\n--\ndrivers/iommu/iommufd/selftest.c-1752-\tcmd-\u003edirty.out_nr_dirty = count;\ndrivers/iommu/iommufd/selftest.c:1753:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1754-out_free:\n--\ndrivers/iommu/iommufd/selftest.c=1886=static int iommufd_test_pasid_attach(struct iommufd_ucmd *ucmd,\n--\ndrivers/iommu/iommufd/selftest.c-1902-\ndrivers/iommu/iommufd/selftest.c:1903:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1904-\tif (rc) {\n--\ndrivers/iommu/iommufd/selftest.c=1915=static int iommufd_test_pasid_replace(struct iommufd_ucmd *ucmd,\n--\ndrivers/iommu/iommufd/selftest.c-1931-\ndrivers/iommu/iommufd/selftest.c:1932:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/selftest.c-1933-\n--\ndrivers/iommu/iommufd/tsm.c=28=int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/tsm.c-73-\t/* Always copy the tsm_code as response */\ndrivers/iommu/iommufd/tsm.c:74:\tif (iommufd_ucmd_respond(ucmd, sizeof(*cmd)))\ndrivers/iommu/iommufd/tsm.c-75-\t\tret = -EFAULT;\n--\ndrivers/iommu/iommufd/vfio_compat.c=123=int iommufd_vfio_ioas(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/vfio_compat.c-136-\t\tiommufd_put_object(ucmd-\u003eictx, \u0026ioas-\u003eobj);\ndrivers/iommu/iommufd/vfio_compat.c:137:\t\treturn iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/vfio_compat.c-138-\n--\ndrivers/iommu/iommufd/viommu.c=26=int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-145-\tcmd-\u003eout_viommu_id = viommu-\u003eobj.id;\ndrivers/iommu/iommufd/viommu.c:146:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/viommu.c-147-\n--\ndrivers/iommu/iommufd/viommu.c=188=int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-292-\tcmd-\u003eout_vdevice_id = vdev-\u003eobj.id;\ndrivers/iommu/iommufd/viommu.c:293:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/viommu.c-294-\tif (rc)\n--\ndrivers/iommu/iommufd/viommu.c=415=int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-483-\tcmd-\u003eout_hw_queue_id = hw_queue-\u003eobj.id;\ndrivers/iommu/iommufd/viommu.c:484:\trc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));\ndrivers/iommu/iommufd/viommu.c-485-\n"
}

47/3 2026/10/08 07:05 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49898
							output: 47
							thoughts: 36
						

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

**Diving into iommufd_ucmd_respond and ioctl Handling**

Alright, let's get down to brass tacks. I need to refresh my understanding of the user-command response mechanism within the `iommufd` framework, specifically how it's implemented in `drivers/iommu/iommufd/main.c`. I'm especially interested in tracing the call flow of `iommufd_ucmd_respond`. I want to see how that ties into ioctl handling and data transfer. Understanding this will help me troubleshoot the recent issue I've been seeing with [insert problem description, or specific use case relevant to user's field]. I need to see how the user-space interaction is managed: specifically how commands get parsed, validated, and dispatched down the IOMMU stack. I'm looking for potential race conditions, or bottlenecks within the processing loop. I'm expecting to delve into locking mechanisms, error handling, and memory management. Hopefully, I'll see where I can insert instrumentation for debugging.



48/3 2026/10/08 07:05 tool read-file
0m Args:
{
  "File": "drivers/iommu/iommufd/iommufd_private.h",
  "FirstLine": 165,
  "LineCount": 40
}

Results:
{
  "Contents": " 165:\t\n 166:\tint iommufd_vfio_ioctl(struct iommufd_ctx *ictx, unsigned int cmd,\n 167:\t\t\t       unsigned long arg);\n 168:\t\n 169:\t/* Copy the response in ucmd-\u003ecmd back to userspace. */\n 170:\tstatic inline int iommufd_ucmd_respond(struct iommufd_ucmd *ucmd,\n 171:\t\t\t\t\t       size_t cmd_len)\n 172:\t{\n 173:\t\tif (copy_to_user(ucmd-\u003eubuffer, ucmd-\u003ecmd,\n 174:\t\t\t\t min_t(size_t, ucmd-\u003euser_size, cmd_len)))\n 175:\t\t\treturn -EFAULT;\n 176:\t\treturn 0;\n 177:\t}\n 178:\t\n 179:\tstatic inline bool iommufd_lock_obj(struct iommufd_object *obj)\n 180:\t{\n 181:\t\tif (!refcount_inc_not_zero(\u0026obj-\u003eusers))\n 182:\t\t\treturn false;\n 183:\t\tif (!refcount_inc_not_zero(\u0026obj-\u003ewait_cnt)) {\n 184:\t\t\t/*\n 185:\t\t\t * If the caller doesn't already have a ref on obj this must be\n 186:\t\t\t * called under the xa_lock. Otherwise the caller is holding a\n 187:\t\t\t * ref on users. Thus it cannot be one before this decrement.\n 188:\t\t\t */\n 189:\t\t\trefcount_dec(\u0026obj-\u003eusers);\n 190:\t\t\treturn false;\n 191:\t\t}\n 192:\t\treturn true;\n 193:\t}\n 194:\t\n 195:\tint iommufd_try_inc_users(struct iommufd_ctx *ictx, struct iommufd_object *obj);\n 196:\tstruct iommufd_object *iommufd_get_object(struct iommufd_ctx *ictx, u32 id,\n 197:\t\t\t\t\t\t  enum iommufd_object_type type);\n 198:\tstatic inline void iommufd_put_object(struct iommufd_ctx *ictx,\n 199:\t\t\t\t\t      struct iommufd_object *obj)\n 200:\t{\n 201:\t\t/*\n 202:\t\t * Users first, then wait_cnt so that REMOVE_WAIT never sees a spurious\n 203:\t\t * !0 users with a 0 wait_cnt.\n 204:\t\t */\n"
}

49/3 2026/10/08 07:05 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50910
							output: 42
							thoughts: 17
						

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

**Investigating the Command Dispatch in `main.c`**

Alright, time to dig in. My primary concern right now is understanding the command dispatch process. Specifically, I need to see exactly how `ucmd` is handled within `main.c`. I need to trace the execution flow. I want to see how the command parsing and routing is managed. I'm looking for the dispatch logic - is it a giant switch statement? A lookup table? Something more sophisticated? I'm anticipating there could be some interesting design choices in play, maybe some clever use of function pointers or polymorphism, depending on the scope. I need to get a clear picture of how those user commands are interpreted and then mapped to their respective implementations within the program. Let's see how they do it.



50/3 2026/10/08 07:05 tool read-file
0m Args:
{
  "File": "drivers/iommu/iommufd/main.c",
  "FirstLine": 460,
  "LineCount": 70
}

Results:
{
  "Contents": " 460:\t};\n 461:\t\n 462:\tstruct iommufd_ioctl_op {\n 463:\t\tunsigned int size;\n 464:\t\tunsigned int min_size;\n 465:\t\tunsigned int ioctl_num;\n 466:\t\tint (*execute)(struct iommufd_ucmd *ucmd);\n 467:\t};\n 468:\t\n 469:\t#define IOCTL_OP(_ioctl, _fn, _struct, _last)                                  \\\n 470:\t\t[_IOC_NR(_ioctl) - IOMMUFD_CMD_BASE] = {                               \\\n 471:\t\t\t.size = sizeof(_struct) +                                      \\\n 472:\t\t\t\tBUILD_BUG_ON_ZERO(sizeof(union ucmd_buffer) \u003c          \\\n 473:\t\t\t\t\t\t  sizeof(_struct)),                    \\\n 474:\t\t\t.min_size = offsetofend(_struct, _last),                       \\\n 475:\t\t\t.ioctl_num = _ioctl,                                           \\\n 476:\t\t\t.execute = _fn,                                                \\\n 477:\t\t}\n 478:\tstatic const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {\n 479:\t\tIOCTL_OP(IOMMU_DESTROY, iommufd_destroy, struct iommu_destroy, id),\n 480:\t\tIOCTL_OP(IOMMU_FAULT_QUEUE_ALLOC, iommufd_fault_alloc,\n 481:\t\t\t struct iommu_fault_alloc, out_fault_fd),\n 482:\t\tIOCTL_OP(IOMMU_GET_HW_INFO, iommufd_get_hw_info, struct iommu_hw_info,\n 483:\t\t\t __reserved),\n 484:\t\tIOCTL_OP(IOMMU_HW_QUEUE_ALLOC, iommufd_hw_queue_alloc_ioctl,\n 485:\t\t\t struct iommu_hw_queue_alloc, length),\n 486:\t\tIOCTL_OP(IOMMU_HWPT_ALLOC, iommufd_hwpt_alloc, struct iommu_hwpt_alloc,\n 487:\t\t\t __reserved),\n 488:\t\tIOCTL_OP(IOMMU_HWPT_GET_DIRTY_BITMAP, iommufd_hwpt_get_dirty_bitmap,\n 489:\t\t\t struct iommu_hwpt_get_dirty_bitmap, data),\n 490:\t\tIOCTL_OP(IOMMU_HWPT_INVALIDATE, iommufd_hwpt_invalidate,\n 491:\t\t\t struct iommu_hwpt_invalidate, __reserved),\n 492:\t\tIOCTL_OP(IOMMU_HWPT_SET_DIRTY_TRACKING, iommufd_hwpt_set_dirty_tracking,\n 493:\t\t\t struct iommu_hwpt_set_dirty_tracking, __reserved),\n 494:\t\tIOCTL_OP(IOMMU_IOAS_ALLOC, iommufd_ioas_alloc_ioctl,\n 495:\t\t\t struct iommu_ioas_alloc, out_ioas_id),\n 496:\t\tIOCTL_OP(IOMMU_IOAS_ALLOW_IOVAS, iommufd_ioas_allow_iovas,\n 497:\t\t\t struct iommu_ioas_allow_iovas, allowed_iovas),\n 498:\t\tIOCTL_OP(IOMMU_IOAS_CHANGE_PROCESS, iommufd_ioas_change_process,\n 499:\t\t\t struct iommu_ioas_change_process, __reserved),\n 500:\t\tIOCTL_OP(IOMMU_IOAS_COPY, iommufd_ioas_copy, struct iommu_ioas_copy,\n 501:\t\t\t src_iova),\n 502:\t\tIOCTL_OP(IOMMU_IOAS_IOVA_RANGES, iommufd_ioas_iova_ranges,\n 503:\t\t\t struct iommu_ioas_iova_ranges, out_iova_alignment),\n 504:\t\tIOCTL_OP(IOMMU_IOAS_MAP, iommufd_ioas_map, struct iommu_ioas_map, iova),\n 505:\t\tIOCTL_OP(IOMMU_IOAS_MAP_FILE, iommufd_ioas_map_file,\n 506:\t\t\t struct iommu_ioas_map_file, iova),\n 507:\t\tIOCTL_OP(IOMMU_IOAS_NOIOMMU_GET_PA, iommufd_ioas_noiommu_get_pa, struct iommu_ioas_noiommu_get_pa,\n 508:\t\t\t out_phys),\n 509:\t\tIOCTL_OP(IOMMU_IOAS_UNMAP, iommufd_ioas_unmap, struct iommu_ioas_unmap,\n 510:\t\t\t length),\n 511:\t\tIOCTL_OP(IOMMU_OPTION, iommufd_option, struct iommu_option, val64),\n 512:\t\tIOCTL_OP(IOMMU_VDEVICE_ALLOC, iommufd_vdevice_alloc_ioctl,\n 513:\t\t\t struct iommu_vdevice_alloc, virt_id),\n 514:\t\tIOCTL_OP(IOMMU_VEVENTQ_ALLOC, iommufd_veventq_alloc,\n 515:\t\t\t struct iommu_veventq_alloc, out_veventq_fd),\n 516:\t\tIOCTL_OP(IOMMU_VFIO_IOAS, iommufd_vfio_ioas, struct iommu_vfio_ioas,\n 517:\t\t\t __reserved),\n 518:\t\tIOCTL_OP(IOMMU_VIOMMU_ALLOC, iommufd_viommu_alloc_ioctl,\n 519:\t\t\t struct iommu_viommu_alloc, out_viommu_id),\n 520:\t\tIOCTL_OP(IOMMU_VDEVICE_TSM_REQ, iommufd_vdevice_tsm_req_ioctl,\n 521:\t\t\t struct iommu_vdevice_tsm_req, out_tsm_code),\n 522:\t#ifdef CONFIG_IOMMUFD_TEST\n 523:\t\tIOCTL_OP(IOMMU_TEST_CMD, iommufd_test, struct iommu_test_cmd, last),\n 524:\t#endif\n 525:\t};\n 526:\t\n 527:\tstatic long iommufd_fops_ioctl(struct file *filp, unsigned int cmd,\n 528:\t\t\t\t       unsigned long arg)\n 529:\t{\n"
}

51/3 2026/10/08 07:05 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 52887
							output: 42
							thoughts: 19
						

Thoughts:
Okay, here's my interpretation of what's going through my mind, rendered in first person, focusing on the given code reference:

**Diving into `main.c` - Line 528-560**

Alright, I need to get my bearings. I'm being pointed to lines 528 through 560 in `main.c`. Immediately, my brain starts to contextualize: `main.c` is the likely entry point, the central hub. Those lines… that's a decent chunk of code, not a small snippet. It's likely a function, or at least a significant block within a function, given the typical structure of C code.

Now, I start to mentally map what I *expect* to find there. Based on the usual organization, and the fact that we're talking about `main.c`, these lines could be involved in:

*   **Initialization:** Setting up data structures, potentially calling initialization routines for various modules.
*   **Argument Parsing:**  Handling command-line arguments, options, or configuration settings.
*   **Main Program Loop:** The heart of the program; could be an event loop, processing user input, calling other modules.
*   **Resource Management:** Allocating or freeing resources.
*   **Error Handling:** Checking conditions and handling exceptions.

I'm mentally preparing for a specific type of code; this isn't just a basic variable declaration, so I'll be looking for blocks with a purpose. Based on the lines involved, I should understand a high-level function. My first approach will be to read through the block and check the variables and what kind of actions they are involved in. After that, I will connect the block with the larger architecture.

I'm ready to read, analyze, and build a mental model of what's happening in those lines. Bring it on.



52/3 2026/10/08 07:05 tool read-file
0m Args:
{
  "File": "drivers/iommu/iommufd/main.c",
  "FirstLine": 528,
  "LineCount": 40
}

Results:
{
  "Contents": " 528:\t\t\t\t       unsigned long arg)\n 529:\t{\n 530:\t\tstruct iommufd_ctx *ictx = filp-\u003eprivate_data;\n 531:\t\tconst struct iommufd_ioctl_op *op;\n 532:\t\tstruct iommufd_ucmd ucmd = {};\n 533:\t\tunion ucmd_buffer buf;\n 534:\t\tunsigned int nr;\n 535:\t\tint ret;\n 536:\t\n 537:\t\tnr = _IOC_NR(cmd);\n 538:\t\tif (nr \u003c IOMMUFD_CMD_BASE ||\n 539:\t\t    (nr - IOMMUFD_CMD_BASE) \u003e= ARRAY_SIZE(iommufd_ioctl_ops))\n 540:\t\t\treturn iommufd_vfio_ioctl(ictx, cmd, arg);\n 541:\t\n 542:\t\tucmd.ictx = ictx;\n 543:\t\tucmd.ubuffer = (void __user *)arg;\n 544:\t\tret = get_user(ucmd.user_size, (u32 __user *)ucmd.ubuffer);\n 545:\t\tif (ret)\n 546:\t\t\treturn ret;\n 547:\t\n 548:\t\top = \u0026iommufd_ioctl_ops[nr - IOMMUFD_CMD_BASE];\n 549:\t\tif (op-\u003eioctl_num != cmd)\n 550:\t\t\treturn -ENOIOCTLCMD;\n 551:\t\tif (ucmd.user_size \u003c op-\u003emin_size)\n 552:\t\t\treturn -EINVAL;\n 553:\t\n 554:\t\tucmd.cmd = \u0026buf;\n 555:\t\tret = copy_struct_from_user(ucmd.cmd, op-\u003esize, ucmd.ubuffer,\n 556:\t\t\t\t\t    ucmd.user_size);\n 557:\t\tif (ret)\n 558:\t\t\treturn ret;\n 559:\t\tret = op-\u003eexecute(\u0026ucmd);\n 560:\t\n 561:\t\tif (ucmd.new_obj) {\n 562:\t\t\tif (ret)\n 563:\t\t\t\tiommufd_object_abort_and_destroy(ictx, ucmd.new_obj);\n 564:\t\t\telse\n 565:\t\t\t\tiommufd_object_finalize(ictx, ucmd.new_obj);\n 566:\t\t}\n 567:\t\treturn ret;\n"
}

53/3 2026/10/08 07:05 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 54005
							output: 26
							thoughts: 1178
						

Thoughts:
**Analyzing the `iommufd_vdevice_tsm_req_ioctl` Implementation**

Okay, let's break this down. My initial concern was centered around potential vulnerabilities in the `iommufd_vdevice_tsm_req_ioctl` function, specifically related to how data is copied from userspace. I started by looking closely at the `copy_struct_from_user` function. The key observation is that it zeroes any trailing bytes if the user-provided size is smaller than the target structure's size. That's good, but I need to make sure I understand the full context.

I went through the code and noted that the `struct iommu_vdevice_tsm_req` is the structure copied from user space. Now, let's examine `struct iommu_vdevice_tsm_req` itself. I need to know the layout, specifically if there's any padding that could lead to uninitialized memory being exposed. I checked the offsets and sizes: the struct is 48 bytes long, a multiple of 8, and there isn't any internal padding. Great!

Okay, so `cmd` is populated by `copy_struct_from_user`. Crucially, before calling `vdev->viommu->ops->vdevice_tsm_req`, `cmd->out_tsm_code = 0;` is executed. This initializes the `out_tsm_code` field to zero. Even if the function returns early via `out_respond`, the `out_tsm_code` is explicitly set to zero before being copied back to userspace.

But I'm a bit paranoid, so I decided to widen the scope of my investigation. What about other structures? Other allocations? I need to check all memory allocations introduced by this patch to rule out any potential issues.

I quickly scanned the code and found a couple of allocations: one in `pci_tsm_context_get` using `kzalloc`, which is good because it zero-initializes the allocated memory. The second allocation is in `iommufd_viommu_alloc_ioctl`. I need to dig deeper into the `_iommufd_object_alloc_ucmd` function to verify if it also uses zero-initialization or at least does appropriate initialization. I am going to check if `_iommufd_object_alloc_ucmd` calls `kzalloc`. This is important.



54/3 2026/10/08 07:06 tool grepper
0m Args:
{
  "Expression": "_iommufd_object_alloc_ucmd"
}

Results:
{
  "Output": "drivers/iommu/iommufd/eventq.c=441=int iommufd_fault_alloc(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/eventq.c-450-\ndrivers/iommu/iommufd/eventq.c:451:\tfault = __iommufd_object_alloc_ucmd(ucmd, fault, IOMMUFD_OBJ_FAULT,\ndrivers/iommu/iommufd/eventq.c-452-\t\t\t\t\t    common.obj);\n--\ndrivers/iommu/iommufd/iommufd_private.h=306=struct iommufd_object *\ndrivers/iommu/iommufd/iommufd_private.h:307:_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd, size_t size,\ndrivers/iommu/iommufd/iommufd_private.h-308-\t\t\t   enum iommufd_object_type type);\ndrivers/iommu/iommufd/iommufd_private.h-309-\ndrivers/iommu/iommufd/iommufd_private.h:310:#define __iommufd_object_alloc_ucmd(ucmd, ptr, type, obj)                      \\\ndrivers/iommu/iommufd/iommufd_private.h:311:\tcontainer_of(_iommufd_object_alloc_ucmd(                               \\\ndrivers/iommu/iommufd/iommufd_private.h-312-\t\t\t     ucmd,                                             \\\n--\ndrivers/iommu/iommufd/iommufd_private.h-319-#define iommufd_object_alloc_ucmd(ucmd, ptr, type) \\\ndrivers/iommu/iommufd/iommufd_private.h:320:\t__iommufd_object_alloc_ucmd(ucmd, ptr, type, obj)\ndrivers/iommu/iommufd/iommufd_private.h-321-\n--\ndrivers/iommu/iommufd/main.c=34=struct iommufd_object *_iommufd_object_alloc(struct iommufd_ctx *ictx,\n--\ndrivers/iommu/iommufd/main.c-65-\ndrivers/iommu/iommufd/main.c:66:struct iommufd_object *_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd,\ndrivers/iommu/iommufd/main.c-67-\t\t\t\t\t\t  size_t size,\n--\ndrivers/iommu/iommufd/main.c-77-\t * An abort op means that its caller needs to invoke it within a lock in\ndrivers/iommu/iommufd/main.c:78:\t * the caller. So it doesn't work with _iommufd_object_alloc_ucmd() that\ndrivers/iommu/iommufd/main.c-79-\t * will invoke the abort op in iommufd_object_abort_and_destroy(), which\n--\ndrivers/iommu/iommufd/viommu.c=26=int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-111-\ndrivers/iommu/iommufd/viommu.c:112:\tviommu = (struct iommufd_viommu *)_iommufd_object_alloc_ucmd(\ndrivers/iommu/iommufd/viommu.c-113-\t\tucmd, viommu_size, IOMMUFD_OBJ_VIOMMU);\n--\ndrivers/iommu/iommufd/viommu.c=415=int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-458-\ndrivers/iommu/iommufd/viommu.c:459:\thw_queue = (struct iommufd_hw_queue *)_iommufd_object_alloc_ucmd(\ndrivers/iommu/iommufd/viommu.c-460-\t\tucmd, hw_queue_size, IOMMUFD_OBJ_HW_QUEUE);\n"
}

55/3 2026/10/08 07:06 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 56899
							output: 41
							thoughts: 28
						

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

**Deep Dive into `drivers/iommu/iommufd/main.c`**

Alright, I need to get a handle on what's happening in `drivers/iommu/iommufd/main.c`. Let's specifically focus on lines 34 through 75. That range probably covers a critical initialization or control flow piece, maybe related to device registration, resource allocation, or event handling for the IOMMU. This is likely where the core of the IOMMU File Descriptor driver is either set up or handled, that's my hunch. I'm assuming that it involves something that could be either performance sensitive or error prone. I need to understand this section thoroughly to properly troubleshoot or contribute in my area. I need to keep in mind, the driver could be checking and configuring hardware, it could be creating and initializing data structures related to file descriptor management, or it may be setting up interrupt handlers. Let's see what the code actually reveals. I need to keep an eye out for potential race conditions, memory leaks, and any unusual locking schemes, as well as if there's any obvious optimization opportunities that can be identified quickly.



56/3 2026/10/08 07:06 tool read-file
0m Args:
{
  "File": "drivers/iommu/iommufd/main.c",
  "FirstLine": 34,
  "LineCount": 45
}

Results:
{
  "Contents": "  34:\tstruct iommufd_object *_iommufd_object_alloc(struct iommufd_ctx *ictx,\n  35:\t\t\t\t\t\t     size_t size,\n  36:\t\t\t\t\t\t     enum iommufd_object_type type)\n  37:\t{\n  38:\t\tstruct iommufd_object *obj;\n  39:\t\tint rc;\n  40:\t\n  41:\t\tobj = kzalloc(size, GFP_KERNEL_ACCOUNT);\n  42:\t\tif (!obj)\n  43:\t\t\treturn ERR_PTR(-ENOMEM);\n  44:\t\tobj-\u003etype = type;\n  45:\t\t/* Starts out bias'd by 1 until it is removed from the xarray */\n  46:\t\trefcount_set(\u0026obj-\u003ewait_cnt, 1);\n  47:\t\trefcount_set(\u0026obj-\u003eusers, 1);\n  48:\t\n  49:\t\t/*\n  50:\t\t * Reserve an ID in the xarray but do not publish the pointer yet since\n  51:\t\t * the caller hasn't initialized it yet. Once the pointer is published\n  52:\t\t * in the xarray and visible to other threads we can't reliably destroy\n  53:\t\t * it anymore, so the caller must complete all errorable operations\n  54:\t\t * before calling iommufd_object_finalize().\n  55:\t\t */\n  56:\t\trc = xa_alloc(\u0026ictx-\u003eobjects, \u0026obj-\u003eid, XA_ZERO_ENTRY, xa_limit_31b,\n  57:\t\t\t      GFP_KERNEL_ACCOUNT);\n  58:\t\tif (rc)\n  59:\t\t\tgoto out_free;\n  60:\t\treturn obj;\n  61:\tout_free:\n  62:\t\tkfree(obj);\n  63:\t\treturn ERR_PTR(rc);\n  64:\t}\n  65:\t\n  66:\tstruct iommufd_object *_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd,\n  67:\t\t\t\t\t\t\t  size_t size,\n  68:\t\t\t\t\t\t\t  enum iommufd_object_type type)\n  69:\t{\n  70:\t\tstruct iommufd_object *new_obj;\n  71:\t\n  72:\t\t/* Something is coded wrong if this is hit */\n  73:\t\tif (WARN_ON(ucmd-\u003enew_obj))\n  74:\t\t\treturn ERR_PTR(-EBUSY);\n  75:\t\n  76:\t\t/*\n  77:\t\t * An abort op means that its caller needs to invoke it within a lock in\n  78:\t\t * the caller. So it doesn't work with _iommufd_object_alloc_ucmd() that\n"
}

57/3 2026/10/08 07:06 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 57933
							output: 21
							thoughts: 375
						

Thoughts:
**Analyzing iommu/iommufd Allocation and TSM Request Handling**

Okay, so `_iommufd_object_alloc` uses `kzalloc` with `GFP_KERNEL_ACCOUNT`. That means any new `viommu` object gets zeroed out completely during allocation. That's good to know, a baseline of cleanliness.

Now, let's look at how the Translation Services Management (TSM) requests are handled, specifically the `tsm_guest_req_info` structure. Diving into `drivers/iommu/iommufd/tsm.c`, I see `iommufd_vdevice_tsm_req_ioctl` and that stack variable `info`. It's initialized using designated initializers, which is nice and explicit. All fields are intentionally initialized. Excellent.

I see that `cmd->out_tsm_code` is explicitly set to `0` before the call to `vdev->viommu->ops->vdevice_tsm_req`. That suggests a clear expectation of what the initial state is.

But wait a minute... what actually *does* `vdevice_tsm_req` do? I'm not seeing any immediate implementations in *this* patch. I'd better check the wider tree to get a clearer picture. Let's fire up a `grep` for `vdevice_tsm_req`. I need to understand where this function pointer is *actually* pointing to!



58/3 2026/10/08 07:06 tool grepper
0m Args:
{
  "Expression": "vdevice_tsm_req"
}

Results:
{
  "Output": "drivers/iommu/iommufd/iommufd_private.h=732=void iommufd_hw_queue_destroy(struct iommufd_object *obj);\ndrivers/iommu/iommufd/iommufd_private.h-733-#ifdef CONFIG_TSM\ndrivers/iommu/iommufd/iommufd_private.h:734:int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd);\ndrivers/iommu/iommufd/iommufd_private.h-735-#else\ndrivers/iommu/iommufd/iommufd_private.h:736:static inline int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)\ndrivers/iommu/iommufd/iommufd_private.h-737-{\n--\ndrivers/iommu/iommufd/main.c=435=union ucmd_buffer {\n--\ndrivers/iommu/iommufd/main.c-455-\tstruct iommu_viommu_alloc viommu;\ndrivers/iommu/iommufd/main.c:456:\tstruct iommu_vdevice_tsm_req tsm_req;\ndrivers/iommu/iommufd/main.c-457-#ifdef CONFIG_IOMMUFD_TEST\n--\ndrivers/iommu/iommufd/main.c=478=static const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {\n--\ndrivers/iommu/iommufd/main.c-519-\t\t struct iommu_viommu_alloc, out_viommu_id),\ndrivers/iommu/iommufd/main.c:520:\tIOCTL_OP(IOMMU_VDEVICE_TSM_REQ, iommufd_vdevice_tsm_req_ioctl,\ndrivers/iommu/iommufd/main.c:521:\t\t struct iommu_vdevice_tsm_req, out_tsm_code),\ndrivers/iommu/iommufd/main.c-522-#ifdef CONFIG_IOMMUFD_TEST\n--\ndrivers/iommu/iommufd/tsm.c-12-/**\ndrivers/iommu/iommufd/tsm.c:13: * iommufd_vdevice_tsm_req_ioctl - Forward TSM requests\ndrivers/iommu/iommufd/tsm.c-14- * @ucmd: user command data for IOMMU_VDEVICE_TSM_REQ\ndrivers/iommu/iommufd/tsm.c-15- *\ndrivers/iommu/iommufd/tsm.c:16: * Resolve @iommu_vdevice_tsm_req::vdevice_id to a vdevice and pass the\ndrivers/iommu/iommufd/tsm.c-17- * request/response buffers to its vIOMMU implementation.\n--\ndrivers/iommu/iommufd/tsm.c-27- */\ndrivers/iommu/iommufd/tsm.c:28:int iommufd_vdevice_tsm_req_ioctl(struct iommufd_ucmd *ucmd)\ndrivers/iommu/iommufd/tsm.c-29-{\n--\ndrivers/iommu/iommufd/tsm.c-32-\tstruct iommufd_vdevice *vdev;\ndrivers/iommu/iommufd/tsm.c:33:\tstruct iommu_vdevice_tsm_req *cmd = ucmd-\u003ecmd;\ndrivers/iommu/iommufd/tsm.c-34-\tstruct tsm_guest_req_info info = {\n--\ndrivers/iommu/iommufd/tsm.c-56-\tcmd-\u003eout_tsm_code = 0;\ndrivers/iommu/iommufd/tsm.c:57:\tif (!vdev-\u003eviommu-\u003eops || !vdev-\u003eviommu-\u003eops-\u003evdevice_tsm_req ||\ndrivers/iommu/iommufd/tsm.c-58-\t    !vdev-\u003etsm_req_op_mask) {\n--\ndrivers/iommu/iommufd/tsm.c-68-\t}\ndrivers/iommu/iommufd/tsm.c:69:\tret = vdev-\u003eviommu-\u003eops-\u003evdevice_tsm_req(vdev, \u0026info,\ndrivers/iommu/iommufd/tsm.c-70-\t\t\t\t\t\t \u0026cmd-\u003eout_tsm_code);\n--\ninclude/linux/iommufd.h=141=struct iommufd_hw_queue {\n--\ninclude/linux/iommufd.h-189- *                does, it should set it to the @vdev-\u003edestroy function pointer\ninclude/linux/iommufd.h:190: * @vdevice_tsm_req: Forward a guest TSM request to a driver-owned vDEVICE\ninclude/linux/iommufd.h-191- * @get_hw_queue_size: Get the size of a driver-defined HW queue structure for a\n--\ninclude/linux/iommufd.h=208=struct iommufd_viommu_ops {\n--\ninclude/linux/iommufd.h-222-\tint (*vdevice_init)(struct iommufd_vdevice *vdev);\ninclude/linux/iommufd.h:223:\tssize_t (*vdevice_tsm_req)(struct iommufd_vdevice *vdev,\ninclude/linux/iommufd.h-224-\t\t\t\t   struct tsm_guest_req_info *info,\n--\ninclude/uapi/linux/iommufd.h=1425=enum iommu_vdevice_tsm_guest_req_op {\n--\ninclude/uapi/linux/iommufd.h-1436-/**\ninclude/uapi/linux/iommufd.h:1437: * struct iommu_vdevice_tsm_req - ioctl(IOMMU_VDEVICE_TSM_REQ)\ninclude/uapi/linux/iommufd.h:1438: * @size: sizeof(struct iommu_vdevice_tsm_req)\ninclude/uapi/linux/iommufd.h-1439- * @vdevice_id: vDevice ID the guest request is for\n--\ninclude/uapi/linux/iommufd.h-1462- */\ninclude/uapi/linux/iommufd.h:1463:struct iommu_vdevice_tsm_req {\ninclude/uapi/linux/iommufd.h-1464-\t__u32 size;\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 60409
							output: 21
							thoughts: 35
						

Thoughts:
Here's my summary, as the expert, thinking through this:

**Investigating the Implementation and Usage of `tsm_viommu_get_ops`**

Okay, I'm at a point in the code where I need to understand how the `tsm_viommu_get_ops` function is being handled, and potentially, how it relates to `viommu_get_ops`. It's likely that `tsm_viommu_get_ops` is a specific implementation or wrapper, or perhaps a part of an upstream integration. My immediate thought is to use `grep` to quickly find occurrences of `viommu_get_ops`. This will allow me to track the call paths to `tsm_viommu_get_ops` and understand the context within which it's being employed. This grep will also reveal instances of `viommu_get_ops` and give me a point of comparison. Essentially, I need to see if `tsm_viommu_get_ops` provides an abstraction or some other value add.



60/3 2026/10/08 07:06 tool grepper
0m Args:
{
  "Expression": "viommu_get_ops"
}

Results:
{
  "Output": "drivers/iommu/iommufd/viommu.c=26=int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-55-\t}\ndrivers/iommu/iommufd/viommu.c:56:\tops = tsm_dev ? tsm_viommu_get_ops(tsm_dev, idev-\u003edev, cmd-\u003etype) : NULL;\ndrivers/iommu/iommufd/viommu.c-57-\tif (IS_ERR(ops)) {\n--\ndrivers/pci/tsm.c=44=struct tsm_dev *pci_tsm_get_device(struct pci_dev *pdev)\n--\ndrivers/pci/tsm.c-54-\tops = tsm_dev-\u003epci_ops;\ndrivers/pci/tsm.c:55:\tif (!ops-\u003eviommu_get_ops)\ndrivers/pci/tsm.c-56-\t\treturn NULL;\n--\ndrivers/virt/coco/tsm-core.c-12-/* The caller must hold a tsm_get_device() reference for the entire use. */\ndrivers/virt/coco/tsm-core.c:13:const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,\ndrivers/virt/coco/tsm-core.c-14-\t\tstruct device *dev, enum iommu_viommu_type type)\ndrivers/virt/coco/tsm-core.c-15-{\ndrivers/virt/coco/tsm-core.c:16:\tif (!tsm_dev-\u003epci_ops-\u003eviommu_get_ops)\ndrivers/virt/coco/tsm-core.c-17-\t\treturn NULL;\ndrivers/virt/coco/tsm-core.c:18:\treturn tsm_dev-\u003epci_ops-\u003eviommu_get_ops(dev, type);\ndrivers/virt/coco/tsm-core.c-19-}\ndrivers/virt/coco/tsm-core.c:20:EXPORT_SYMBOL_GPL(tsm_viommu_get_ops);\ndrivers/virt/coco/tsm-core.c-21-\n--\ninclude/linux/pci-tsm.h=12=struct tsm_dev;\n--\ninclude/linux/pci-tsm.h-21- *\t\toperations).\ninclude/linux/pci-tsm.h:22: * @viommu_get_ops: Return operations for a supported TSM-owned vIOMMU type,\ninclude/linux/pci-tsm.h-23- *\t\t  or NULL if unsupported\n--\ninclude/linux/pci-tsm.h-25- *\ninclude/linux/pci-tsm.h:26: * The vIOMMU owner pins the backend module before querying @viommu_get_ops\ninclude/linux/pci-tsm.h-27- * and releases it after vIOMMU destruction. A backend providing this callback\n--\ninclude/linux/pci-tsm.h-33- *\ninclude/linux/pci-tsm.h:34: * @viommu_get_ops runs with the backend module pinned. The PCI/TSM\ninclude/linux/pci-tsm.h-35- * association is checked during acquisition under pci_tsm_rwsem.\n--\ninclude/linux/pci-tsm.h=37=struct pci_tsm_ops {\ninclude/linux/pci-tsm.h-38-\tstruct module *owner;\ninclude/linux/pci-tsm.h:39:\tconst struct iommufd_viommu_ops *(*viommu_get_ops)(\ninclude/linux/pci-tsm.h-40-\t\tstruct device *dev, enum iommu_viommu_type type);\n--\ninclude/linux/tsm.h=132=void tsm_put_device(struct tsm_dev *tsm_dev);\ninclude/linux/tsm.h:133:const struct iommufd_viommu_ops *tsm_viommu_get_ops(struct tsm_dev *tsm_dev,\ninclude/linux/tsm.h-134-\t\tstruct device *dev, enum iommu_viommu_type type);\n--\ninclude/linux/tsm.h=163=static inline const struct iommufd_viommu_ops *\ninclude/linux/tsm.h:164:tsm_viommu_get_ops(struct tsm_dev *tsm_dev, struct device *dev,\ninclude/linux/tsm.h-165-\t\tenum iommu_viommu_type type)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 61918
							output: 21
							thoughts: 152
						

Thoughts:
Okay, let's break this down.

**Diving into the S390 KVM Changes**

Alright, I need to get a handle on these modifications. It looks like they've tweaked the `kvm_register` function, specifically in the S390 architecture. The signature in `arch/s390/include/asm/kvm_host_s390.h` has been updated; instead of receiving a `struct kvm *kvm`, it now takes a `struct file *kvm_file`. The implication here is that they're using the file pointer directly, and then converting it back to a KVM pointer using `file_to_kvm_s390()`.

This is interesting; typically you'd expect a KVM structure directly, so they're probably using the file context for some reason, maybe security or file operations. Now I need to know where else this `kvm_register` function and the related `zpci_kvm_hook` are used and implemented. Are there any other places in the code where this new file-based approach impacts the KVM setup on S390? I need to track down all the callers and implementations of both. This is going to be my key focus.



62/3 2026/10/08 07:06 tool grepper
0m Args:
{
  "Expression": "zpci_kvm_hook"
}

Results:
{
  "Output": "arch/s390/include/asm/kvm_host_s390.h=722=void kvm_arch_free_vm(struct kvm *kvm);\narch/s390/include/asm/kvm_host_s390.h-723-\narch/s390/include/asm/kvm_host_s390.h:724:struct zpci_kvm_hook {\narch/s390/include/asm/kvm_host_s390.h-725-\tint (*kvm_register)(void *opaque, struct file *kvm_file);\n--\narch/s390/include/asm/kvm_host_s390.h-728-\narch/s390/include/asm/kvm_host_s390.h:729:extern struct zpci_kvm_hook zpci_kvm_hook;\narch/s390/include/asm/kvm_host_s390.h-730-\n--\narch/s390/kvm/s390/pci.c=734=int __init kvm_s390_pci_init(void)\narch/s390/kvm/s390/pci.c-735-{\narch/s390/kvm/s390/pci.c:736:\tzpci_kvm_hook.kvm_register = kvm_s390_pci_register_kvm;\narch/s390/kvm/s390/pci.c:737:\tzpci_kvm_hook.kvm_unregister = kvm_s390_pci_unregister_kvm;\narch/s390/kvm/s390/pci.c-738-\n--\narch/s390/kvm/s390/pci.c=752=void kvm_s390_pci_exit(void)\narch/s390/kvm/s390/pci.c-753-{\narch/s390/kvm/s390/pci.c:754:\tzpci_kvm_hook.kvm_register = NULL;\narch/s390/kvm/s390/pci.c:755:\tzpci_kvm_hook.kvm_unregister = NULL;\narch/s390/kvm/s390/pci.c-756-\n--\narch/s390/pci/pci_kvm_hook.c-11-\narch/s390/pci/pci_kvm_hook.c:12:struct zpci_kvm_hook zpci_kvm_hook;\narch/s390/pci/pci_kvm_hook.c:13:EXPORT_SYMBOL_GPL(zpci_kvm_hook);\n--\ndrivers/vfio/pci/vfio_pci_zdev.c=184=int vfio_pci_zdev_open_device(struct vfio_pci_core_device *vdev)\n--\ndrivers/vfio/pci/vfio_pci_zdev.c-197-\tret = -ENOENT;\ndrivers/vfio/pci/vfio_pci_zdev.c:198:\tif (zpci_kvm_hook.kvm_register)\ndrivers/vfio/pci/vfio_pci_zdev.c:199:\t\tret = zpci_kvm_hook.kvm_register(zdev, vdev-\u003evdev.kvm);\ndrivers/vfio/pci/vfio_pci_zdev.c-200-\n--\ndrivers/vfio/pci/vfio_pci_zdev.c=207=void vfio_pci_zdev_close_device(struct vfio_pci_core_device *vdev)\n--\ndrivers/vfio/pci/vfio_pci_zdev.c-218-\ndrivers/vfio/pci/vfio_pci_zdev.c:219:\tif (zpci_kvm_hook.kvm_unregister)\ndrivers/vfio/pci/vfio_pci_zdev.c:220:\t\tzpci_kvm_hook.kvm_unregister(zdev);\ndrivers/vfio/pci/vfio_pci_zdev.c-221-}\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 63509
							output: 26
							thoughts: 130
						

Thoughts:
Here's my analysis of the code changes, from my perspective as an expert:

**Investigating KVM File Pointer Updates in VFIO Context**

Okay, so I'm seeing a significant change in `vfio_pci_zdev.c`. Specifically, the `vdev->vdev.kvm` pointer, which I understand is crucial for KVM integration within VFIO, has been redefined. It's now a `struct file *kvm`, and that's because the underlying `vdev`, which is a `vfio_device`, has had its `kvm` field updated to the same type. This suggests a more direct interaction with the kernel's file handling mechanisms.

Next, I need to understand the implications of this change throughout the VFIO-related code. My immediate concern is how this affects other drivers interacting with VFIO. Let's look at the `drivers/s390/crypto/vfio_ap_ops.c` file. I see a function, `vfio_ap_mdev_set_kvm(matrix_mdev, kvm_file)`. This definitely sounds like it's relevant, as it seems to be setting the KVM file for a matrix-based device. I'll need to dig into this function to understand how the new `struct file *kvm` is being used.

Now, let's figure out who is calling the `vfio_ap_mdev_set_kvm` function. I need to trace back from this function and see where this pointer is being set and used. That will give me a better understanding of the overall impact and how the file is being handled. This is the key. Finding the callers of `vfio_ap_mdev_set_kvm` will provide the context I need.



64/3 2026/10/08 07:07 tool grepper
0m Args:
{
  "Expression": "vfio_ap_mdev_set_kvm"
}

Results:
{
  "Output": "drivers/s390/crypto/vfio_ap_ops.c=1818=static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {\n--\ndrivers/s390/crypto/vfio_ap_ops.c-1823-/**\ndrivers/s390/crypto/vfio_ap_ops.c:1824: * vfio_ap_mdev_set_kvm - sets all data for @matrix_mdev that are needed\ndrivers/s390/crypto/vfio_ap_ops.c-1825- * to manage AP resources for the guest whose state is represented by\n--\ndrivers/s390/crypto/vfio_ap_ops.c-1833- */\ndrivers/s390/crypto/vfio_ap_ops.c:1834:static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,\ndrivers/s390/crypto/vfio_ap_ops.c-1835-\t\t\t\tstruct file *kvm_file)\n--\ndrivers/s390/crypto/vfio_ap_ops.c=2068=static int vfio_ap_mdev_open_device(struct vfio_device *vdev)\n--\ndrivers/s390/crypto/vfio_ap_ops.c-2075-\ndrivers/s390/crypto/vfio_ap_ops.c:2076:\treturn vfio_ap_mdev_set_kvm(matrix_mdev, vdev-\u003ekvm);\ndrivers/s390/crypto/vfio_ap_ops.c-2077-}\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 64484
							output: 32
							thoughts: 73
						

Thoughts:
Here's my analysis of this code snippet:

**Diving into KVM Page Tracking**

Okay, so I see that `vdev->kvm` is being passed along here. That's a key piece of context. Now, I want to understand how this ties into the larger picture of KVM's page tracking. My next step is clear: I need to investigate the call sites of `kvm_page_track_register_notifier`, `kvm_page_track_unregister_notifier`, `kvm_write_track_add_gfn`, and `kvm_write_track_remove_gfn`. These functions are central to the whole mechanism, so understanding who calls them and when will give me a better understanding of the data flow and how this particular piece of code interacts with the bigger picture. I'm especially interested in tracking the global frame number (gfn) additions and subtractions here. This seems to be the critical aspect of the tracking. Knowing this I can then work to improve the code.



66/3 2026/10/08 07:07 tool grepper
0m Args:
{
  "Expression": "kvm_page_track_register_notifier|kvm_write_track_"
}

Results:
{
  "Output": "arch/x86/include/asm/kvm_page_track.h=47=struct file;\narch/x86/include/asm/kvm_page_track.h-48-\narch/x86/include/asm/kvm_page_track.h:49:int kvm_page_track_register_notifier(struct file *file,\narch/x86/include/asm/kvm_page_track.h-50-\t\t\t\t     struct kvm_page_track_notifier_node *n);\narch/x86/include/asm/kvm_page_track.h=51=void kvm_page_track_unregister_notifier(struct file *file,\n--\narch/x86/include/asm/kvm_page_track.h-53-\narch/x86/include/asm/kvm_page_track.h:54:int kvm_write_track_add_gfn(struct file *file, gfn_t gfn);\narch/x86/include/asm/kvm_page_track.h:55:int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn);\narch/x86/include/asm/kvm_page_track.h-56-#else\n--\narch/x86/kvm/Makefile=59=exports_grep_trailer := --include='*.[ch]' -nrw $(srctree)/virt/kvm $(srctree)/arch/x86/kvm | \\\narch/x86/kvm/Makefile:60:\t\t\tgrep -v -e kvm_page_track_register_notifier \\\narch/x86/kvm/Makefile-61-\t\t\t\t-e kvm_page_track_unregister_notifier \\\narch/x86/kvm/Makefile:62:\t\t\t\t-e kvm_write_track_add_gfn \\\narch/x86/kvm/Makefile:63:\t\t\t\t-e kvm_write_track_remove_gfn \\\narch/x86/kvm/Makefile-64-\t\t\t\t-e kvm_file_to_kvm_fn\n--\narch/x86/kvm/mmu/mmu.c=781=static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)\n--\narch/x86/kvm/mmu/mmu.c-802-\tif (sp-\u003erole.level \u003e PG_LEVEL_4K)\narch/x86/kvm/mmu/mmu.c:803:\t\treturn __kvm_write_track_add_gfn(kvm, slot, gfn);\narch/x86/kvm/mmu/mmu.c-804-\n--\narch/x86/kvm/mmu/mmu.c=840=static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)\n--\narch/x86/kvm/mmu/mmu.c-850-\tif (sp-\u003erole.level \u003e PG_LEVEL_4K)\narch/x86/kvm/mmu/mmu.c:851:\t\treturn __kvm_write_track_remove_gfn(kvm, slot, gfn);\narch/x86/kvm/mmu/mmu.c-852-\n--\narch/x86/kvm/mmu/page_track.c=77=static void update_gfn_write_track(struct kvm_memory_slot *slot, gfn_t gfn,\n--\narch/x86/kvm/mmu/page_track.c-91-\narch/x86/kvm/mmu/page_track.c:92:void __kvm_write_track_add_gfn(struct kvm *kvm, struct kvm_memory_slot *slot,\narch/x86/kvm/mmu/page_track.c-93-\t\t\t       gfn_t gfn)\n--\narch/x86/kvm/mmu/page_track.c-114-\narch/x86/kvm/mmu/page_track.c:115:void __kvm_write_track_remove_gfn(struct kvm *kvm,\narch/x86/kvm/mmu/page_track.c-116-\t\t\t\t  struct kvm_memory_slot *slot, gfn_t gfn)\n--\narch/x86/kvm/mmu/page_track.c=191=static int kvm_enable_external_write_tracking(struct kvm *kvm)\n--\narch/x86/kvm/mmu/page_track.c-241- */\narch/x86/kvm/mmu/page_track.c:242:int kvm_page_track_register_notifier(struct file *file,\narch/x86/kvm/mmu/page_track.c-243-\t\t\t\t     struct kvm_page_track_notifier_node *n)\n--\narch/x86/kvm/mmu/page_track.c-266-}\narch/x86/kvm/mmu/page_track.c:267:EXPORT_SYMBOL_GPL(kvm_page_track_register_notifier);\narch/x86/kvm/mmu/page_track.c-268-\n--\narch/x86/kvm/mmu/page_track.c-270- * stop receiving the event interception. It is the opposed operation of\narch/x86/kvm/mmu/page_track.c:271: * kvm_page_track_register_notifier().\narch/x86/kvm/mmu/page_track.c-272- */\n--\narch/x86/kvm/mmu/page_track.c=320=void kvm_page_track_delete_slot(struct kvm *kvm, struct kvm_memory_slot *slot)\n--\narch/x86/kvm/mmu/page_track.c-345- */\narch/x86/kvm/mmu/page_track.c:346:int kvm_write_track_add_gfn(struct file *file, gfn_t gfn)\narch/x86/kvm/mmu/page_track.c-347-{\n--\narch/x86/kvm/mmu/page_track.c-360-\twrite_lock(\u0026kvm-\u003emmu_lock);\narch/x86/kvm/mmu/page_track.c:361:\t__kvm_write_track_add_gfn(kvm, slot, gfn);\narch/x86/kvm/mmu/page_track.c-362-\twrite_unlock(\u0026kvm-\u003emmu_lock);\n--\narch/x86/kvm/mmu/page_track.c-367-}\narch/x86/kvm/mmu/page_track.c:368:EXPORT_SYMBOL_GPL(kvm_write_track_add_gfn);\narch/x86/kvm/mmu/page_track.c-369-\n--\narch/x86/kvm/mmu/page_track.c-376- */\narch/x86/kvm/mmu/page_track.c:377:int kvm_write_track_remove_gfn(struct file *file, gfn_t gfn)\narch/x86/kvm/mmu/page_track.c-378-{\n--\narch/x86/kvm/mmu/page_track.c-391-\twrite_lock(\u0026kvm-\u003emmu_lock);\narch/x86/kvm/mmu/page_track.c:392:\t__kvm_write_track_remove_gfn(kvm, slot, gfn);\narch/x86/kvm/mmu/page_track.c-393-\twrite_unlock(\u0026kvm-\u003emmu_lock);\n--\narch/x86/kvm/mmu/page_track.c-398-}\narch/x86/kvm/mmu/page_track.c:399:EXPORT_SYMBOL_GPL(kvm_write_track_remove_gfn);\narch/x86/kvm/mmu/page_track.c-400-#endif\n--\narch/x86/kvm/mmu/page_track.h=14=int kvm_page_track_create_memslot(struct kvm *kvm,\n--\narch/x86/kvm/mmu/page_track.h-17-\narch/x86/kvm/mmu/page_track.h:18:void __kvm_write_track_add_gfn(struct kvm *kvm, struct kvm_memory_slot *slot,\narch/x86/kvm/mmu/page_track.h-19-\t\t\t       gfn_t gfn);\narch/x86/kvm/mmu/page_track.h:20:void __kvm_write_track_remove_gfn(struct kvm *kvm,\narch/x86/kvm/mmu/page_track.h-21-\t\t\t\t  struct kvm_memory_slot *slot, gfn_t gfn);\n--\ndrivers/gpu/drm/i915/gvt/kvmgt.c=663=static int intel_vgpu_open_device(struct vfio_device *vfio_dev)\n--\ndrivers/gpu/drm/i915/gvt/kvmgt.c-672-\tvgpu-\u003etrack_node.track_remove_region = kvmgt_page_track_remove_region;\ndrivers/gpu/drm/i915/gvt/kvmgt.c:673:\tret = kvm_page_track_register_notifier(vgpu-\u003evfio_device.kvm,\ndrivers/gpu/drm/i915/gvt/kvmgt.c-674-\t\t\t\t\t       \u0026vgpu-\u003etrack_node);\n--\ndrivers/gpu/drm/i915/gvt/kvmgt.c=1525=int intel_gvt_page_track_add(struct intel_vgpu *info, u64 gfn)\n--\ndrivers/gpu/drm/i915/gvt/kvmgt.c-1534-\ndrivers/gpu/drm/i915/gvt/kvmgt.c:1535:\tr = kvm_write_track_add_gfn(info-\u003evfio_device.kvm, gfn);\ndrivers/gpu/drm/i915/gvt/kvmgt.c-1536-\tif (r)\n--\ndrivers/gpu/drm/i915/gvt/kvmgt.c=1543=int intel_gvt_page_track_remove(struct intel_vgpu *info, u64 gfn)\n--\ndrivers/gpu/drm/i915/gvt/kvmgt.c-1552-\ndrivers/gpu/drm/i915/gvt/kvmgt.c:1553:\tr = kvm_write_track_remove_gfn(info-\u003evfio_device.kvm, gfn);\ndrivers/gpu/drm/i915/gvt/kvmgt.c-1554-\tif (r)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 67681
							output: 26
							thoughts: 2696
						

Thoughts:
**TSM and vIOMMU Deep Dive**

Okay, so I've been tracing through these changes related to TSM (Translated System Memory) and virtual IOMMU (vIOMMU), and I need to get a clear picture of what's happening. First, the `vgpu->vfio_device.kvm` being passed as a `struct file *` to `kvm_page_track_register_notifier` in kvmgt is interesting, and worth remembering for later. Now, focusing on the core TSM/vIOMMU integration...

I started by looking at the interactions between `drivers/pci/tsm.c`, `drivers/virt/coco/tsm-core.c`, `drivers/iommu/iommufd/viommu.c`, and `drivers/iommu/iommufd/tsm.c`, specifically around the sysfs attributes, to see how the PCI device is getting linked in.

In `drivers/pci/tsm.c`, the `pci_tsm_get_device` function reveals the basic structure. The `pci_tsm_rwsem` read lock is obtained, and it looks for a `tsm_dev` attached to the PCI device (`pdev`). It uses `try_module_get` on `ops->owner`, which suggests module reference counting. If everything checks out, it returns the `tsm_dev`. The `pci_tsm_context_get` function is where a new `struct pci_tsm_context` is being allocated with `kzalloc_obj`, and importantly, the fields `pf0`, `pdev`, and `dsm_dev` are all set. This context seems to be tied to a specific PCI function (PF0) and the DSM (Domain Specific Manager) device. The corresponding put function, `pci_tsm_context_put`, cleanly decrements and frees the context. The `pci_tsm_pf0_constructor` function shows the initialization of the `tsm->lock`, `contexts_drained` completion, and `context_users`. All new fields in `pci_tsm_pf0` are initialized.

Now, the `iommufd_viommu_alloc_ioctl` is the real heart of it, I need to analyze this change. A lot of validation and checks are in place. The function gets an `iommufd_device`, then attempts to get a `tsm_dev`.  It retrieves operation structures depending on whether a TSM is associated with the device. If the TSM path is taken, `tsm_viommu_get_ops` is used, otherwise `iommu_dev->ops->get_viommu_ops` is used.  Error handling is comprehensive. It retrieves `hwpt_paging` and validates that `hwpt_paging->nest_parent` is not NULL.

A `viommu` is allocated using `_iommufd_object_alloc_ucmd`, and this is where I need to focus: it gets associated with the `iommufd_device` and TSM device. The allocation, however, is a very critical step, because there's a reference to this `viommu` and `hwpt` that the code takes care of.
If the `viommu_init` fails, it jumps to `out_put_hwpt:`, which frees up the `hwpt_paging` using `iommufd_put_object`. BUT, the code that frees `viommu` in `out_put_hwpt:` is missing because I haven't yet confirmed whether `_iommufd_object_alloc_ucmd` stores `viommu` into `ucmd->new_obj`. I'll need to double check how the object allocation works.



68/3 2026/10/08 07:08 tool grepper
0m Args:
{
  "Expression": "_iommufd_object_alloc_ucmd"
}

Results:
{
  "Output": "drivers/iommu/iommufd/eventq.c=441=int iommufd_fault_alloc(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/eventq.c-450-\ndrivers/iommu/iommufd/eventq.c:451:\tfault = __iommufd_object_alloc_ucmd(ucmd, fault, IOMMUFD_OBJ_FAULT,\ndrivers/iommu/iommufd/eventq.c-452-\t\t\t\t\t    common.obj);\n--\ndrivers/iommu/iommufd/iommufd_private.h=306=struct iommufd_object *\ndrivers/iommu/iommufd/iommufd_private.h:307:_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd, size_t size,\ndrivers/iommu/iommufd/iommufd_private.h-308-\t\t\t   enum iommufd_object_type type);\ndrivers/iommu/iommufd/iommufd_private.h-309-\ndrivers/iommu/iommufd/iommufd_private.h:310:#define __iommufd_object_alloc_ucmd(ucmd, ptr, type, obj)                      \\\ndrivers/iommu/iommufd/iommufd_private.h:311:\tcontainer_of(_iommufd_object_alloc_ucmd(                               \\\ndrivers/iommu/iommufd/iommufd_private.h-312-\t\t\t     ucmd,                                             \\\n--\ndrivers/iommu/iommufd/iommufd_private.h-319-#define iommufd_object_alloc_ucmd(ucmd, ptr, type) \\\ndrivers/iommu/iommufd/iommufd_private.h:320:\t__iommufd_object_alloc_ucmd(ucmd, ptr, type, obj)\ndrivers/iommu/iommufd/iommufd_private.h-321-\n--\ndrivers/iommu/iommufd/main.c=34=struct iommufd_object *_iommufd_object_alloc(struct iommufd_ctx *ictx,\n--\ndrivers/iommu/iommufd/main.c-65-\ndrivers/iommu/iommufd/main.c:66:struct iommufd_object *_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd,\ndrivers/iommu/iommufd/main.c-67-\t\t\t\t\t\t  size_t size,\n--\ndrivers/iommu/iommufd/main.c-77-\t * An abort op means that its caller needs to invoke it within a lock in\ndrivers/iommu/iommufd/main.c:78:\t * the caller. So it doesn't work with _iommufd_object_alloc_ucmd() that\ndrivers/iommu/iommufd/main.c-79-\t * will invoke the abort op in iommufd_object_abort_and_destroy(), which\n--\ndrivers/iommu/iommufd/viommu.c=26=int iommufd_viommu_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-111-\ndrivers/iommu/iommufd/viommu.c:112:\tviommu = (struct iommufd_viommu *)_iommufd_object_alloc_ucmd(\ndrivers/iommu/iommufd/viommu.c-113-\t\tucmd, viommu_size, IOMMUFD_OBJ_VIOMMU);\n--\ndrivers/iommu/iommufd/viommu.c=415=int iommufd_hw_queue_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-458-\ndrivers/iommu/iommufd/viommu.c:459:\thw_queue = (struct iommufd_hw_queue *)_iommufd_object_alloc_ucmd(\ndrivers/iommu/iommufd/viommu.c-460-\t\tucmd, hw_queue_size, IOMMUFD_OBJ_HW_QUEUE);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 72405
							output: 41
							thoughts: 26
						

Thoughts:
Okay, here's my interpretation of what's going on, formatted as you requested:

**Digging into iommufd/main.c**

Alright, let's take a look at `drivers/iommu/iommufd/main.c`, focusing around line 66. I need to refresh my memory on how they're handling this part of the IOMMU framework, specifically within this userspace driver. I'm assuming, given the location within `main.c`, this likely concerns the core initialization or entry point logic. I'm probably looking for how they are handling the device node or major/minor number assignment, the initialization of the file operations structure, the creation of any necessary character devices, or maybe the registration of the IOMMU FD. I need to quickly scan the context to figure out the exact point that's happening here, so I can understand the intended flow. Probably initializing the FD right now. Let's see...



70/3 2026/10/08 07:09 tool read-file
0m Args:
{
  "File": "drivers/iommu/iommufd/main.c",
  "FirstLine": 66,
  "LineCount": 40
}

Results:
{
  "Contents": "  66:\tstruct iommufd_object *_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd,\n  67:\t\t\t\t\t\t\t  size_t size,\n  68:\t\t\t\t\t\t\t  enum iommufd_object_type type)\n  69:\t{\n  70:\t\tstruct iommufd_object *new_obj;\n  71:\t\n  72:\t\t/* Something is coded wrong if this is hit */\n  73:\t\tif (WARN_ON(ucmd-\u003enew_obj))\n  74:\t\t\treturn ERR_PTR(-EBUSY);\n  75:\t\n  76:\t\t/*\n  77:\t\t * An abort op means that its caller needs to invoke it within a lock in\n  78:\t\t * the caller. So it doesn't work with _iommufd_object_alloc_ucmd() that\n  79:\t\t * will invoke the abort op in iommufd_object_abort_and_destroy(), which\n  80:\t\t * must be outside the caller's lock.\n  81:\t\t */\n  82:\t\tif (WARN_ON(iommufd_object_ops[type].abort))\n  83:\t\t\treturn ERR_PTR(-EOPNOTSUPP);\n  84:\t\n  85:\t\tnew_obj = _iommufd_object_alloc(ucmd-\u003eictx, size, type);\n  86:\t\tif (IS_ERR(new_obj))\n  87:\t\t\treturn new_obj;\n  88:\t\n  89:\t\tucmd-\u003enew_obj = new_obj;\n  90:\t\treturn new_obj;\n  91:\t}\n  92:\t\n  93:\t/*\n  94:\t * Allow concurrent access to the object.\n  95:\t *\n  96:\t * Once another thread can see the object pointer it can prevent object\n  97:\t * destruction. Expect for special kernel-only objects there is no in-kernel way\n  98:\t * to reliably destroy a single object. Thus all APIs that are creating objects\n  99:\t * must use iommufd_object_abort() to handle their errors and only call\n 100:\t * iommufd_object_finalize() once object creation cannot fail.\n 101:\t */\n 102:\tvoid iommufd_object_finalize(struct iommufd_ctx *ictx,\n 103:\t\t\t\t     struct iommufd_object *obj)\n 104:\t{\n 105:\t\tXA_STATE(xas, \u0026ictx-\u003eobjects, obj-\u003eid);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 73332
							output: 19
							thoughts: 1284
						

Thoughts:
**Analyzing Potential Resource Leaks in the IOMMU Driver's Cleanup Path**

Okay, so I'm diving into this iommu driver code, specifically the `iommufd_fops_ioctl` path.  My initial observation is that `ucmd->new_obj` is assigned to `new_obj`, which makes sense. Then, I see this conditional:

```c
	if (ucmd.new_obj) {
		if (ret)
			iommufd_object_abort_and_destroy(ictx, ucmd.new_obj);
		else
			iommufd_object_finalize(ictx, ucmd.new_obj);
	}
```

If `ret` is an error, then we abort and destroy the `new_obj`. Otherwise, we finalize it.  Now, the crucial part is what happens during destruction via `iommufd_object_abort_and_destroy`. It calls `iommufd_object_ops[obj->type].destroy(obj)` which resolves to `iommufd_viommu_destroy(obj)`!

Inside `iommufd_viommu_destroy`, I'm looking at:

```c
void iommufd_viommu_destroy(struct iommufd_object *obj)
{
	struct iommufd_viommu *viommu =
		container_of(obj, struct iommufd_viommu, obj);

	if (viommu->ops && viommu->ops->destroy)
		viommu->ops->destroy(viommu);
	if (viommu->tsm_dev)
		tsm_put_device(viommu->tsm_dev);
	if (viommu->hwpt)
		refcount_dec(&viommu->hwpt->common.obj.users);
	if (viommu->kvm_file)
		fput(viommu->kvm_file);
	xa_destroy(&viommu->vdevs);
}
```

Now, the important thing I noticed before was that the `refcount_dec` call used to be unconditional, but is now guarded by `if (viommu->hwpt)`.  That's a potential change. Also, the `tsm_put_device` and `fput(viommu->kvm_file)` calls have guards, too. So, all these resources might not be getting cleaned up.

So I need to check what happens to `tsm_dev` and `kvm_file`.
Let's see where that goes: `tsm_put_device` call goes to `pci_tsm_destroy` defined in `drivers/pci/tsm.c`.
I need to be absolutely certain there are no uninitialized variables or potential double frees, and if there are race conditions.

```c
void pci_tsm_destroy(struct pci_dev *pdev)
{
	struct pci_tsm_pf0 *pf0 = NULL;
	struct completion *drained;
	bool interrupted = false;
	long rc;

	down_write(&pci_tsm_rwsem);
	if (pdev->tsm && is_link_tsm(pdev->tsm->tsm_dev) &&
	    is_pci_tsm_pf0(pdev)) {
		pf0 = to_pci_tsm_pf0(pdev->tsm);
		drained = &pf0->contexts_drained;
		mutex_lock(&pf0->lock);
		pf0->removing = true;
		mutex_unlock(&pf0->lock);

		/* An unused DSM may never have completed contexts_drained. */
		rc = pf0->context_users ?
			try_wait_for_completion(drained) : 1;
		/* Context release needs the read side of pci_tsm_rwsem. */
		up_write(&pci_tsm_rwsem);
		while (rc <= 0) {
			if (interrupted) {
				rc = wait_for_completion_timeout(drained, HZ * 10);
			} else {
				rc = wait_for_completion_interruptible_timeout(drained,
									       HZ * 10);
				if (rc < 0) {
					interrupted = true;
					pci_warn(pdev, "Task \"%s\" (%d


72/3 2026/10/08 07:09 tool grepper
0m Args:
{
  "Expression": "get_file_active"
}

Results:
{
  "Output": "drivers/gpio/gpiolib-cdev.c=2495=static int lineinfo_changed_notify(struct notifier_block *nb,\n--\ndrivers/gpio/gpiolib-cdev.c-2508-\t/* Keep the file descriptor alive for the duration of the notification. */\ndrivers/gpio/gpiolib-cdev.c:2509:\tfp = get_file_active(\u0026cdev-\u003efp);\ndrivers/gpio/gpiolib-cdev.c-2510-\tif (!fp)\n--\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c=968=static struct file *mmap_singleton(struct drm_i915_private *i915)\n--\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c-971-\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c:972:\tfile = get_file_active(\u0026i915-\u003egem.mmap_singleton);\ndrivers/gpu/drm/i915/gem/i915_gem_mman.c-973-\tif (file)\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c=336=void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev, bool revoked)\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c-343-\tlist_for_each_entry_safe(priv, tmp, \u0026vdev-\u003edmabufs, dmabufs_elm) {\ndrivers/vfio/pci/vfio_pci_dmabuf.c:344:\t\tif (!get_file_active(\u0026priv-\u003edmabuf-\u003efile))\ndrivers/vfio/pci/vfio_pci_dmabuf.c-345-\t\t\tcontinue;\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c=380=void vfio_pci_dma_buf_cleanup(struct vfio_pci_core_device *vdev)\n--\ndrivers/vfio/pci/vfio_pci_dmabuf.c-396-\tlist_for_each_entry_safe(priv, tmp, \u0026vdev-\u003edmabufs, dmabufs_elm) {\ndrivers/vfio/pci/vfio_pci_dmabuf.c:397:\t\tif (!get_file_active(\u0026priv-\u003edmabuf-\u003efile))\ndrivers/vfio/pci/vfio_pci_dmabuf.c-398-\t\t\tcontinue;\n--\nfs/file.c=990=EXPORT_SYMBOL_GPL(get_file_rcu);\n--\nfs/file.c-992-/**\nfs/file.c:993: * get_file_active - try go get a reference to a file\nfs/file.c-994- * @f: the file to get a reference on\n--\nfs/file.c-1003- */\nfs/file.c:1004:struct file *get_file_active(struct file **f)\nfs/file.c-1005-{\n--\nfs/file.c-1014-}\nfs/file.c:1015:EXPORT_SYMBOL_GPL(get_file_active);\nfs/file.c-1016-\n--\ninclude/linux/fs.h=1311=struct file *get_file_rcu(struct file __rcu **f);\ninclude/linux/fs.h:1312:struct file *get_file_active(struct file **f);\ninclude/linux/fs.h-1313-\n--\nvirt/kvm/guest_memfd.c=290=static int kvm_gmem_release(struct inode *inode, struct file *file)\n--\nvirt/kvm/guest_memfd.c-304-\t * Since .release is called only when the reference count is zero,\nvirt/kvm/guest_memfd.c:305:\t * after which file_ref_get() and get_file_active() fail,\nvirt/kvm/guest_memfd.c-306-\t * kvm_gmem_get_pfn() cannot be using the file concurrently.\nvirt/kvm/guest_memfd.c:307:\t * file_ref_put() provides a full barrier, and get_file_active() the\nvirt/kvm/guest_memfd.c-308-\t * matching acquire barrier.\n--\nvirt/kvm/guest_memfd.c=340=static inline struct file *kvm_gmem_get_file(struct kvm_memory_slot *slot)\n--\nvirt/kvm/guest_memfd.c-346-\t */\nvirt/kvm/guest_memfd.c:347:\treturn get_file_active(\u0026slot-\u003egmem.file);\nvirt/kvm/guest_memfd.c-348-}\n--\nvirt/kvm/vfio.c=143=static int kvm_vfio_file_add(struct kvm_device *dev, unsigned int fd)\n--\nvirt/kvm/vfio.c-157-\nvirt/kvm/vfio.c:158:\tkvm_file = get_file_active(\u0026dev-\u003ekvm-\u003efile);\nvirt/kvm/vfio.c-159-\tif (!kvm_file)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 77046
							output: 56
							thoughts: 2114
						

Thoughts:
**KMSAN Assessment: Deep Dive**

Okay, let's break this down. My goal is to determine if this patch necessitates `NeedsKMSAN=true`. I need to meticulously examine each criterion for potential uninitialized memory issues.

First, I examined `kvm_file_to_kvm_fn`, but that's just pointer manipulation and file references, nothing to worry about. Next, I’ve gone through the instructions to check for potentially uninitialized memory usage or info-leaks, and I'm at the point where I'm examining each of the 4 criteria:

**Criterion 1: Kernel Structures to Userspace**

The primary concern here is data being sent from the kernel to userspace and whether it could contain uninitialized fields. The code under scrutiny is `iommufd_vdevice_tsm_req_ioctl`. My initial instinct is to go straight to `iommufd_ucmd_respond` and the `copy_to_user` call.  The critical structure is `struct iommu_vdevice_tsm_req` which gets copied.

I traced the `cmd` pointer, which points to `buf` and is populated from userspace via `copy_struct_from_user`. I confirmed the `op->size` and `user_size` variables. I verified the layout of `struct iommu_vdevice_tsm_req` using offsets. Crucially, I checked the struct members to make certain that there is zero padding (the size is 48 bytes), and every byte is part of a named field. I then looked at `copy_struct_from_user` and understood that any fields copied from userspace are initialized, and the rest zeroed. I then explicitly checked `cmd->out_tsm_code = 0;` which initializes a field, and ensures it's zeroed. So, every byte within `cmd` is either copied or zeroed before it is returned to userspace, so, no uninitialized data being sent.

The `tsm_guest_req_info` struct is passed to `vdevice_tsm_req`, which isn't sent to userspace. I verified that initializer `={}` would fully zero out this structure, so I can ignore any padding concerns.

I double-checked `disconnect_store` in the sysfs code, but there's no data being sent there. Then I looked at `iommufd_viommu_alloc_ioctl`. And checked `iommufd_viommu_alloc_ioctl` to make certain that it had no changes in the outputs. No problems there either.

**Conclusion for Criterion 1:** No uninitialized kernel structures are being sent to user space in this patch.

*(The following criteria were not included in the prompt, so I don't analyze them.)*



74/3 2026/10/08 07:10 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "_iommufd_object_alloc.*IOMMUFD_OBJ_VDEVICE",
  "PathPrefixes": [
    "drivers/iommu/iommufd/viommu.c"
  ]
}

Results:
{
  "error": "no matches"
}

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

Args:
null

Results:
null

Tokens:
							input: 79841
							output: 46
							thoughts: 26
						

Thoughts:
Here's your summary:

**Digging into the IOMMU Virtual Device Allocation**

Okay, so I need to understand where and how the `IOMMUFD_OBJ_VDEVICE` object is being brought into existence. My first instinct is to dive directly into the `viommu.c` source file, as it seems the most likely location for this virtual device allocation logic. I'm going to leverage my search tools – likely `grep` or a similar utility, or if I'm working with a code browser, its search capabilities – and look for the specific string `IOMMUFD_OBJ_VDEVICE` within that file. This should quickly pinpoint the lines of code responsible for the object's instantiation, which will hopefully be a starting point to trace from. I expect to be able to understand the allocation path, and ideally, the rationale behind the design based on the surrounding code. From there I can likely then search the code for all calls of the object.



76/3 2026/10/08 07:10 tool grepper
0m Args:
{
  "Expression": "IOMMUFD_OBJ_VDEVICE",
  "PathPrefixes": [
    "drivers/iommu/iommufd/viommu.c"
  ]
}

Results:
{
  "Output": "drivers/iommu/iommufd/viommu.c=188=int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd)\n--\ndrivers/iommu/iommufd/viommu.c-246-\tvdev = (struct iommufd_vdevice *)_iommufd_object_alloc(\ndrivers/iommu/iommufd/viommu.c:247:\t\tucmd-\u003eictx, vdev_size, IOMMUFD_OBJ_VDEVICE);\ndrivers/iommu/iommufd/viommu.c-248-\tif (IS_ERR(vdev)) {\n"
}

77/3 2026/10/08 07:10 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 80303
							output: 620
							thoughts: 4934
						

Thoughts:
**KMSAN Assessment: No Need for KMSAN in This Patch Series**

Okay, after a thorough review of this patch series, I'm confident in assessing that KMSAN is *not* necessary here. My analysis focused on potential uninitialized memory reads, copies to userspace, or usage in control flow, but I found no such risks.

The core of the patch series involves refactoring KVM/VFIO integration with file pointers, improving IOMMUFD vIOMMU operations retrieval, introducing PCI/TSM context tracking with refcounting, and adding a new IOMMU ioctl.  I scrutinized all new and modified code.

Here's my rationale:

*   **User Space Interactions:** The main structure copied to userspace is `struct iommu_vdevice_tsm_req`. But that structure is small (48 bytes) and is *fully* initialized from userspace via `copy_struct_from_user`, with the output fields explicitly set before responding. I've confirmed there are no padding holes or potential uninitialized data leaking.

*   **Heap Allocations:** All dynamic allocations of critical structs (`pci_tsm_context`, `iommufd_viommu`, `iommufd_vdevice`, `iommufd_device`) use `kzalloc` or `kzalloc_obj`. This guarantees *zero* initialization of all struct members, eliminating the risk of uninitialized fields.

*   **Stack Variables:** Any local stack variables were explicitly initialized (e.g. `struct tsm_guest_req_info info = { ... }`).

*   **Bounds Checks:**  While the patch *adds* bounds checks, it doesn't modify existing buffer handling in ways that could expose uninitialized memory. The checks ensure that the guest-supplied `cmd->req_len` and `cmd->resp_len` fit within `INT_MAX`, and that the operation `cmd->op` is valid for the vdevice.

*   **File and Object Management:**  The patch deals primarily with `struct file` reference counting, module pinning, locking for synchronization, and object lifetime across KVM, VFIO, and IOMMUFD. I see risks *here*, but these are all standard memory/synchronization errors (use-after-free, refcount leaks, deadlocks, and NULL dereferences). *These types of risks are precisely the domain of KASAN, LOCKDEP, and other standard kernel debuggers.*

*   **Conclusion:** KMSAN isn't needed here. The critical risks are *not* related to uninitialized memory. They revolve around resource management and synchronization, which are best caught by standard kernel debugging tools.  There's no additional benefit from running a KMSAN fuzzing session.



78/3 2026/10/08 07:11 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series makes architectural changes across KVM, VFIO, PCI/TSM, and IOMMUFD:\n1. Replaces direct 'struct kvm *' pointers in VFIO and architecture hooks with 'struct file *' back-references (via get_file_active() / fput()) to manage VM file lifetimes without circular pinning.\n2. Refactors vIOMMU driver ops lookup by introducing get_viommu_ops returning 'const struct iommufd_viommu_ops *'.\n3. Adds PCI TSM context lifecycle management and refcounting (pci_tsm_context, context_users, contexts_drained completion) to prevent premature link disconnection.\n4. Implements the IOMMU_VDEVICE_TSM_REQ ioctl (iommufd_vdevice_tsm_req_ioctl) to forward guest TSM requests to vdevices.\n\nMemory initialization and KMSAN applicability analysis:\n- Kernel-to-userspace data copying: The only new structure copied to userspace is 'struct iommu_vdevice_tsm_req' in iommufd_vdevice_tsm_req_ioctl() via iommufd_ucmd_respond(). The structure contains six 32-bit fields (24 bytes) followed by three 64-bit fields (24 bytes), totalling 48 bytes with zero padding holes. The command buffer is initialized by copy_struct_from_user() (which zeroes any remaining bytes in the kernel buffer if userspace provides fewer bytes), and 'out_tsm_code' is explicitly zero-initialized prior to execution. There is no risk of info-leaks or uninitialized byte exposures.\n- Heap structures: All newly allocated heap structures (struct pci_tsm_context via kzalloc_obj, struct iommufd_viommu and struct iommufd_device via _iommufd_object_alloc/kzalloc) are zero-initialized upon allocation.\n- Stack structures: 'struct tsm_guest_req_info info' is fully populated using a designated initializer.\n- Flow and bounds: Control flow, operations masks, and buffer lengths (req_len, resp_len \u003c= INT_MAX; op \u003c TSM_REQ_MAX) are explicitly validated.\n\nKASAN vs KMSAN applicability:\nThe primary risks introduced by these changes are reference counting mismatches (file references, module refcounts), synchronization deadlocks (completion wait loops and mutex/rwsem locks), and use-after-free conditions during object cleanup. All of these failure modes are covered by standard KASAN, LOCKDEP, and refcount tracking. Because no uninitialized memory usage or padding leaks are introduced, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series makes architectural changes across KVM, VFIO, PCI/TSM, and IOMMUFD:\n1. Replaces direct 'struct kvm *' pointers in VFIO and architecture hooks with 'struct file *' back-references (via get_file_active() / fput()) to manage VM file lifetimes without circular pinning.\n2. Refactors vIOMMU driver ops lookup by introducing get_viommu_ops returning 'const struct iommufd_viommu_ops *'.\n3. Adds PCI TSM context lifecycle management and refcounting (pci_tsm_context, context_users, contexts_drained completion) to prevent premature link disconnection.\n4. Implements the IOMMU_VDEVICE_TSM_REQ ioctl (iommufd_vdevice_tsm_req_ioctl) to forward guest TSM requests to vdevices.\n\nMemory initialization and KMSAN applicability analysis:\n- Kernel-to-userspace data copying: The only new structure copied to userspace is 'struct iommu_vdevice_tsm_req' in iommufd_vdevice_tsm_req_ioctl() via iommufd_ucmd_respond(). The structure contains six 32-bit fields (24 bytes) followed by three 64-bit fields (24 bytes), totalling 48 bytes with zero padding holes. The command buffer is initialized by copy_struct_from_user() (which zeroes any remaining bytes in the kernel buffer if userspace provides fewer bytes), and 'out_tsm_code' is explicitly zero-initialized prior to execution. There is no risk of info-leaks or uninitialized byte exposures.\n- Heap structures: All newly allocated heap structures (struct pci_tsm_context via kzalloc_obj, struct iommufd_viommu and struct iommufd_device via _iommufd_object_alloc/kzalloc) are zero-initialized upon allocation.\n- Stack structures: 'struct tsm_guest_req_info info' is fully populated using a designated initializer.\n- Flow and bounds: Control flow, operations masks, and buffer lengths (req_len, resp_len \u003c= INT_MAX; op \u003c TSM_REQ_MAX) are explicitly validated.\n\nKASAN vs KMSAN applicability:\nThe primary risks introduced by these changes are reference counting mismatches (file references, module refcounts), synchronization deadlocks (completion wait loops and mutex/rwsem locks), and use-after-free conditions during object cleanup. All of these failure modes are covered by standard KASAN, LOCKDEP, and refcount tracking. Because no uninitialized memory usage or padding leaks are introduced, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

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