Re: [PATCH v2 1/2] vfio: Prevent open_count decrement to negative
From: Alex Williamson
Date: Fri Jun 13 2025 - 18:31:18 EST
Hi Jacob,
On Tue, 3 Jun 2025 08:23:42 -0700
Jacob Pan <jacob.pan@xxxxxxxxxxxxxxxxxxx> wrote:
> When vfio_df_close() is called with open_count=0, it triggers a warning in
> vfio_assert_device_open() but still decrements open_count to -1. This
> allows a subsequent open to incorrectly pass the open_count == 0 check,
> leading to unintended behavior, such as setting df->access_granted = true.
>
> For example, running an IOMMUFD compat no-IOMMU device with VFIO tests
> (https://github.com/awilliam/tests/blob/master/vfio-noiommu-pci-device-open.c)
> results in a warning and a failed VFIO_GROUP_GET_DEVICE_FD ioctl on the
> first run, but the second run succeeds incorrectly.
>
> Add checks to avoid decrementing open_count below zero.
The example above suggests to me that this is a means by which we could
see this, but in reality it seems it is the only means by which we can
create this scenario, right?
Why does VFIO_GROUP_GET_DEVICE_FD fail on the first iteration? It
seems like things are pretty broken, we won't have access_granted set,
but I don't spot why the ioctl fails.
Doesn't this also (begin) to fix 6086efe73498 as well? I think that
introduced skipping vfio_df_open() entirely for noiommu devices. It
seems like this should have a Fixes: tag and the warning in the
assertion was unreachable until 608... so maybe it should be linked
here. Thanks,
Alex
> Reviewed-by: Jason Gunthorpe <jgg@xxxxxxxxxx>
> Reviewed-by: Yi Liu <yi.l.liu@xxxxxxxxx>
> Signed-off-by: Jacob Pan <jacob.pan@xxxxxxxxxxxxxxxxxxx>
> ---
> v2: Added Reviewed-by tags
> ---
> drivers/vfio/vfio_main.c | 3 ++-
> 1 file changed, 2 insertions(+), 1 deletion(-)
>
> diff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c
> index 1fd261efc582..5046cae05222 100644
> --- a/drivers/vfio/vfio_main.c
> +++ b/drivers/vfio/vfio_main.c
> @@ -583,7 +583,8 @@ void vfio_df_close(struct vfio_device_file *df)
>
> lockdep_assert_held(&device->dev_set->lock);
>
> - vfio_assert_device_open(device);
> + if (!vfio_assert_device_open(device))
> + return;
> if (device->open_count == 1)
> vfio_df_device_last_close(df);
> device->open_count--;