> From: Nicolin Chen <nicolinc@xxxxxxxxxx> > Sent: Saturday, October 26, 2024 7:51 AM > > + > +/** > + * struct iommu_vdevice_alloc - ioctl(IOMMU_VDEVICE_ALLOC) > + * @size: sizeof(struct iommu_vdevice_alloc) > + * @viommu_id: vIOMMU ID to associate with the virtual device > + * @dev_id: The pyhsical device to allocate a virtual instance on the > vIOMMU s/pyhsical/physical/, or just say 'iommufd device" > + > +int iommufd_vdevice_alloc_ioctl(struct iommufd_ucmd *ucmd) > +{ > + struct iommu_vdevice_alloc *cmd = ucmd->cmd; > + struct iommufd_vdevice *vdev, *curr; > + struct iommufd_viommu *viommu; > + struct iommufd_device *idev; > + u64 virt_id = cmd->virt_id; > + int rc = 0; > + > + if (virt_id > ULONG_MAX) > + return -EINVAL; > + > + viommu = iommufd_get_viommu(ucmd, cmd->viommu_id); > + if (IS_ERR(viommu)) > + return PTR_ERR(viommu); > + > + idev = iommufd_get_device(ucmd, cmd->dev_id); > + if (IS_ERR(idev)) { > + rc = PTR_ERR(idev); > + goto out_put_viommu; > + } > + > + mutex_lock(&idev->igroup->lock); > + if (idev->vdev) { > + rc = -EEXIST; > + goto out_unlock_igroup; > + } > + > + vdev = iommufd_object_alloc(ucmd->ictx, vdev, > IOMMUFD_OBJ_VDEVICE); > + if (IS_ERR(vdev)) { > + rc = PTR_ERR(vdev); > + goto out_unlock_igroup; > + } > + also need to check that the device and the viommu are associated to a same physical iommu. > + rc = iommufd_verify_unfinalized_object(ucmd->ictx, &vdev->obj); > + if (rc) { > + kfree(vdev); > + goto out_unlock_igroup; > + } > + > + vdev->idev = idev; > + vdev->id = virt_id; > + vdev->viommu = viommu; > + > + idev->vdev = vdev; > + refcount_inc(&idev->obj.users); > + refcount_inc(&viommu->obj.users); > + > + curr = xa_cmpxchg(&viommu->vdevs, virt_id, NULL, vdev, > GFP_KERNEL); > + if (curr) { > + rc = xa_err(curr) ?: -EBUSY; > + goto out_abort; > + } > + > + cmd->out_vdevice_id = vdev->obj.id; > + rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd)); > + if (rc) > + goto out_abort; > + iommufd_object_finalize(ucmd->ictx, &vdev->obj); > + goto out_unlock_igroup; > + > +out_abort: > + iommufd_object_abort_and_destroy(ucmd->ictx, &vdev->obj); > +out_unlock_igroup: > + mutex_unlock(&idev->igroup->lock); > + iommufd_put_object(ucmd->ictx, &idev->obj); > +out_put_viommu: > + iommufd_put_object(ucmd->ictx, &viommu->obj); > + return rc; > +} > -- > 2.43.0