Re: [PATCH 17/24] iommu/amd: Introduce helper function for updating domain ID mapping table

From: Suthikulpanit, Suravee

Date: Wed Sep 02 2026 - 23:34:01 EST




On 8/19/2026 5:45 PM, guanghuifeng@xxxxxxxxxxxxxxxxx wrote:
diff --git a/drivers/iommu/amd/viommu.c b/drivers/iommu/amd/viommu.c
index 91d0dd3ac912..708f2c7496a4 100644
--- a/drivers/iommu/amd/viommu.c
+++ b/drivers/iommu/amd/viommu.c
@@ -40,6 +40,8 @@
  #define VIOMMU_DOMID_MAPPING_BASE    0x2000000000ULL
  #define VIOMMU_DOMID_MAPPING_ENTRY_SIZE    (1 << 19)
+#define VIOMMU_VFCTRL_GUEST_DID_MAP_CONTROL1_OFFSET    0x08
+
  LIST_HEAD(viommu_devid_map);
  static int viommu_init_pci_vsc(struct amd_iommu *iommu)
@@ -420,6 +422,22 @@ static void __maybe_unused free_private_vm_region(struct amd_iommu *iommu, u64 *
      *entry = NULL;
  }
+static void viommu_clear_mapping(struct amd_iommu *iommu,
+                 struct amd_iommu_viommu *aviommu)
+{
+    int i;
+    u16 gid = aviommu->gid;
+
+    /*
+     * IOMMU hardware uses the domain ID mapping table to map gdom ID to hdom ID.
+     * If the mapping does not exist, the hardware would generate error in the event log.
+     * Therefore, initialize all gdom ID entries to map to parent domain ID to prevent
+     * unknown mapping scenario.
+     */
+    for (i = 0; i <= VIOMMU_MAX_GDOMID; i++)
+        amd_viommu_domain_id_update(iommu, gid, aviommu->parent->id, i);
+}
+
  void amd_viommu_uninit_one(struct amd_iommu *iommu, struct amd_iommu_viommu *aviommu)
  {
      pr_debug("%s: gid=%u\n", __func__, aviommu->gid);
@@ -432,6 +450,7 @@ void amd_viommu_uninit_one(struct amd_iommu *iommu, struct amd_iommu_viommu *avi
                     VIOMMU_DOMID_MAPPING_BASE,
                     VIOMMU_DOMID_MAPPING_ENTRY_SIZE,
                     aviommu->gid);
+    viommu_clear_mapping(iommu, aviommu);
  }

Use-after-free in vIOMMU teardown ordering
The teardown path releases the DevID/DomID mapping table memory
BEFORE resetting the vIOMMU state:

     free_private_vm_region(iommu, &aviommu->devid_table, ...);
     free_private_vm_region(iommu, &aviommu->domid_table, ...);
     ...
     viommu_clear_mapping(iommu, aviommu);   /* too late */

   Since the IOMMU hardware may still reference these tables until the
   guest vIOMMU state is reset, freeing the backing memory first can
   result in a use-after-free by hardware.

Thanks. Fixing in v5.

Suravee