RE: [PATCH v2 3/4] iommufd: Destroy vdevice on idevice destroy
From: Tian, Kevin
Date: Tue Jun 24 2025 - 04:22:29 EST
> From: Xu Yilun <yilun.xu@xxxxxxxxxxxxxxx>
> Sent: Monday, June 23, 2025 5:50 PM
>
> +static void iommufd_device_remove_vdev(struct iommufd_device *idev)
> +{
> + bool vdev_removing = false;
> +
> + mutex_lock(&idev->igroup->lock);
> + if (idev->vdev) {
> + struct iommufd_vdevice *vdev;
> +
> + vdev = iommufd_get_vdevice(idev->ictx, idev->vdev->obj.id);
> + if (IS_ERR(vdev)) {
> + /* vdev is removed from xarray, but is not
> destroyed/freed */
> + vdev_removing = true;
> + goto unlock;
> + }
> +
> + /* Should never happen */
> + if (WARN_ON(vdev != idev->vdev)) {
> + idev->vdev = NULL;
> + iommufd_put_object(idev->ictx, &vdev->obj);
> + goto unlock;
> + }
> +
> + /*
> + * vdev cannot be destroyed after refcount_inc, safe to
> release
"vdev cannot be destroyed by userspace"
> + * idev->igroup->lock and use idev->vdev afterward.
> + */
> + refcount_inc(&idev->vdev->obj.users);
> + iommufd_put_object(idev->ictx, &idev->vdev->obj);
s/idev->vdev/vdev/
> @@ -124,18 +139,28 @@ int iommufd_vdevice_alloc_ioctl(struct
> iommufd_ucmd *ucmd)
> goto out_put_idev;
> }
>
> + 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_put_idev;
> + goto out_unlock_igroup;
> }
>
> + /* vdev can't outlive idev, vdev->idev is always valid, need no refcnt
> */
> + vdev->idev = idev;
> vdev->ictx = ucmd->ictx;
> vdev->id = virt_id;
> vdev->dev = idev->dev;
> get_device(idev->dev);
this is not necessary now, as idevice already holds a reference to device
and now vdevice cannot outlive idevice.