diff mbox series

[v12,Kernel,4/7] vfio iommu: Implementation of ioctl to for dirty pages tracking.

Message ID 1581104554-10704-5-git-send-email-kwankhede@nvidia.com (mailing list archive)
State New, archived
Headers show
Series KABIs to support migration for VFIO devices | expand

Commit Message

Kirti Wankhede Feb. 7, 2020, 7:42 p.m. UTC
VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
- Start pinned and unpinned pages tracking while migration is active
- Stop pinned and unpinned dirty pages tracking. This is also used to
  stop dirty pages tracking if migration failed or cancelled.
- Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
  user space application responsibility to copy content of dirty pages
  from source to destination during migration.

To prevent DoS attack, memory for bitmap is allocated per vfio_dma
structure. Bitmap size is calculated considering smallest supported page
size. Bitmap is allocated when dirty logging is enabled for those
vfio_dmas whose vpfn list is not empty or whole range is mapped, in
case of pass-through device.

There could be multiple option as to when bitmap should be populated:
* Polulate bitmap for already pinned pages when bitmap is allocated for
  a vfio_dma with the smallest supported page size. Updates bitmap from
  page pinning and unpinning functions. When user application queries
  bitmap, check if requested page size is same as page size used to
  populated bitmap. If it is equal, copy bitmap. But if not equal,
  re-populated bitmap according to requested page size and then copy to
  user.
  Pros: Bitmap gets populated on the fly after dirty tracking has
        started.
  Cons: If requested page size is different than smallest supported
        page size, then bitmap has to be re-populated again, with
        additional overhead of allocating bitmap memory again for
        re-population of bitmap.

* Populate bitmap when bitmap is queried by user application.
  Pros: Bitmap is populated with requested page size. This eliminates
        the need to re-populate bitmap if requested page size is
        different than smallest supported pages size.
  Cons: There is one time processing time, when bitmap is queried.

I prefer later option with simple logic and to eliminate over-head of
bitmap repopulation in case of differnt page sizes. Later option is
implemented in this patch.

Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
Reviewed-by: Neo Jia <cjia@nvidia.com>
---
 drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 287 insertions(+), 12 deletions(-)

Comments

Yan Zhao Feb. 10, 2020, 9:49 a.m. UTC | #1
On Sat, Feb 08, 2020 at 03:42:31AM +0800, Kirti Wankhede wrote:
> VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> - Start pinned and unpinned pages tracking while migration is active
> - Stop pinned and unpinned dirty pages tracking. This is also used to
>   stop dirty pages tracking if migration failed or cancelled.
> - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
>   user space application responsibility to copy content of dirty pages
>   from source to destination during migration.
> 
> To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> structure. Bitmap size is calculated considering smallest supported page
> size. Bitmap is allocated when dirty logging is enabled for those
> vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> case of pass-through device.
> 
> There could be multiple option as to when bitmap should be populated:
> * Polulate bitmap for already pinned pages when bitmap is allocated for
>   a vfio_dma with the smallest supported page size. Updates bitmap from
>   page pinning and unpinning functions. When user application queries
>   bitmap, check if requested page size is same as page size used to
>   populated bitmap. If it is equal, copy bitmap. But if not equal,
>   re-populated bitmap according to requested page size and then copy to
>   user.
>   Pros: Bitmap gets populated on the fly after dirty tracking has
>         started.
>   Cons: If requested page size is different than smallest supported
>         page size, then bitmap has to be re-populated again, with
>         additional overhead of allocating bitmap memory again for
>         re-population of bitmap.
> 
> * Populate bitmap when bitmap is queried by user application.
>   Pros: Bitmap is populated with requested page size. This eliminates
>         the need to re-populate bitmap if requested page size is
>         different than smallest supported pages size.
>   Cons: There is one time processing time, when bitmap is queried.
> 
> I prefer later option with simple logic and to eliminate over-head of
> bitmap repopulation in case of differnt page sizes. Later option is
> implemented in this patch.
> 
> Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> Reviewed-by: Neo Jia <cjia@nvidia.com>
> ---
>  drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
>  1 file changed, 287 insertions(+), 12 deletions(-)
> 
> diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> index d386461e5d11..df358dc1c85b 100644
> --- a/drivers/vfio/vfio_iommu_type1.c
> +++ b/drivers/vfio/vfio_iommu_type1.c
> @@ -70,6 +70,7 @@ struct vfio_iommu {
>  	unsigned int		dma_avail;
>  	bool			v2;
>  	bool			nesting;
> +	bool			dirty_page_tracking;
>  };
>  
>  struct vfio_domain {
> @@ -90,6 +91,7 @@ struct vfio_dma {
>  	bool			lock_cap;	/* capable(CAP_IPC_LOCK) */
>  	struct task_struct	*task;
>  	struct rb_root		pfn_list;	/* Ex-user pinned pfn list */
> +	unsigned long		*bitmap;
>  };
>  
>  struct vfio_group {
> @@ -125,6 +127,7 @@ struct vfio_regions {
>  					(!list_empty(&iommu->domain_list))
>  
>  static int put_pfn(unsigned long pfn, int prot);
> +static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu);
>  
>  /*
>   * This code handles mapping and unmapping of user data buffers
> @@ -174,6 +177,57 @@ static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
>  	rb_erase(&old->node, &iommu->dma_list);
>  }
>  
> +static inline unsigned long dirty_bitmap_bytes(unsigned int npages)
> +{
> +	if (!npages)
> +		return 0;
> +
> +	return ALIGN(npages, BITS_PER_LONG) / sizeof(unsigned long);
> +}
> +
> +static int vfio_dma_bitmap_alloc(struct vfio_iommu *iommu,
> +				 struct vfio_dma *dma, unsigned long pgsizes)
> +{
> +	unsigned long pgshift = __ffs(pgsizes);
> +
> +	if (!RB_EMPTY_ROOT(&dma->pfn_list) || dma->iommu_mapped) {
> +		unsigned long npages = dma->size >> pgshift;
> +		unsigned long bsize = dirty_bitmap_bytes(npages);
> +
> +		dma->bitmap = kvzalloc(bsize, GFP_KERNEL);
> +		if (!dma->bitmap)
> +			return -ENOMEM;
> +	}
> +	return 0;
> +}
> +
> +static int vfio_dma_all_bitmap_alloc(struct vfio_iommu *iommu,
> +				     unsigned long pgsizes)
> +{
> +	struct rb_node *n = rb_first(&iommu->dma_list);
> +	int ret;
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> +
> +		ret = vfio_dma_bitmap_alloc(iommu, dma, pgsizes);
> +		if (ret)
> +			return ret;
> +	}
> +	return 0;
> +}
> +
> +static void vfio_dma_all_bitmap_free(struct vfio_iommu *iommu)
> +{
> +	struct rb_node *n = rb_first(&iommu->dma_list);
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> +
> +		kfree(dma->bitmap);
> +	}
> +}
> +
>  /*
>   * Helper Functions for host iova-pfn list
>   */
> @@ -244,6 +298,29 @@ static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
>  	kfree(vpfn);
>  }
>  
> +static void vfio_remove_unpinned_from_pfn_list(struct vfio_dma *dma)
> +{
> +	struct rb_node *n = rb_first(&dma->pfn_list);
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_pfn *vpfn = rb_entry(n, struct vfio_pfn, node);
> +
> +		if (!vpfn->ref_count)
> +			vfio_remove_from_pfn_list(dma, vpfn);
> +	}
> +}
> +
> +static void vfio_remove_unpinned_from_dma_list(struct vfio_iommu *iommu)
> +{
> +	struct rb_node *n = rb_first(&iommu->dma_list);
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> +
> +		vfio_remove_unpinned_from_pfn_list(dma);
> +	}
> +}
> +
>  static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
>  					       unsigned long iova)
>  {
> @@ -261,7 +338,8 @@ static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
>  	vpfn->ref_count--;
>  	if (!vpfn->ref_count) {
>  		ret = put_pfn(vpfn->pfn, dma->prot);
> -		vfio_remove_from_pfn_list(dma, vpfn);
> +		if (!dma->bitmap)
> +			vfio_remove_from_pfn_list(dma, vpfn);
>  	}
>  	return ret;
>  }
> @@ -483,13 +561,14 @@ static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
>  	return ret;
>  }
>  
> -static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
> +static int vfio_unpin_page_external(struct vfio_iommu *iommu,
> +				    struct vfio_dma *dma, dma_addr_t iova,
>  				    bool do_accounting)
>  {
>  	int unlocked;
>  	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
>  
> -	if (!vpfn)
> +	if (!vpfn || !vpfn->ref_count)
>  		return 0;
>  
>  	unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
> @@ -510,6 +589,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  	unsigned long remote_vaddr;
>  	struct vfio_dma *dma;
>  	bool do_accounting;
> +	unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>  
>  	if (!iommu || !user_pfn || !phys_pfn)
>  		return -EINVAL;
> @@ -551,8 +631,10 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  
>  		vpfn = vfio_iova_get_vfio_pfn(dma, iova);
>  		if (vpfn) {
> -			phys_pfn[i] = vpfn->pfn;
> -			continue;
> +			if (vpfn->ref_count > 1) {
> +				phys_pfn[i] = vpfn->pfn;
> +				continue;
> +			}
>  		}
>  
>  		remote_vaddr = dma->vaddr + iova - dma->iova;
> @@ -560,11 +642,23 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  					     do_accounting);
>  		if (ret)
>  			goto pin_unwind;
> -
> -		ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
> -		if (ret) {
> -			vfio_unpin_page_external(dma, iova, do_accounting);
> -			goto pin_unwind;
> +		if (!vpfn) {
> +			ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
> +			if (ret) {
> +				vfio_unpin_page_external(iommu, dma, iova,
> +							 do_accounting);
> +				goto pin_unwind;
> +			}
> +		} else
> +			vpfn->pfn = phys_pfn[i];
> +
> +		if (iommu->dirty_page_tracking && !dma->bitmap) {
> +			ret = vfio_dma_bitmap_alloc(iommu, dma, iommu_pgsizes);
> +			if (ret) {
> +				vfio_unpin_page_external(iommu, dma, iova,
> +							 do_accounting);
> +				goto pin_unwind;
> +			}
>  		}
>  	}
>  
> @@ -578,7 +672,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  
>  		iova = user_pfn[j] << PAGE_SHIFT;
>  		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
> -		vfio_unpin_page_external(dma, iova, do_accounting);
> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
>  		phys_pfn[j] = 0;
>  	}
>  pin_done:
> @@ -612,7 +706,7 @@ static int vfio_iommu_type1_unpin_pages(void *iommu_data,
>  		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
>  		if (!dma)
>  			goto unpin_exit;
> -		vfio_unpin_page_external(dma, iova, do_accounting);
> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
>  	}
>  
>  unpin_exit:
> @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
>  	return bitmap;
>  }
>  
> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> +				  size_t size, uint64_t pgsize,
> +				  unsigned char __user *bitmap)
> +{
> +	struct vfio_dma *dma;
> +	dma_addr_t i = iova, iova_limit;
> +	unsigned int bsize, nbits = 0, l = 0;
> +	unsigned long pgshift = __ffs(pgsize);
> +
> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> +		int ret, j;
> +		unsigned int npages = 0, shift = 0;
> +		unsigned char temp = 0;
> +
> +		/* mark all pages dirty if all pages are pinned and mapped. */
> +		if (dma->iommu_mapped) {
> +			iova_limit = min(dma->iova + dma->size, iova + size);
> +			npages = iova_limit/pgsize;
> +			bitmap_set(dma->bitmap, 0, npages);
for pass-through devices, it's not good to always return all pinned pages as
dirty. could it also call vfio_pin_pages to track dirty pages? or any
other interface provided to do that?
> +		} else if (dma->bitmap) {
> +			struct rb_node *n = rb_first(&dma->pfn_list);
> +			bool found = false;
> +
> +			for (; n; n = rb_next(n)) {
> +				struct vfio_pfn *vpfn = rb_entry(n,
> +						struct vfio_pfn, node);
> +				if (vpfn->iova >= i) {
> +					found = true;
> +					break;
> +				}
> +			}
> +
> +			if (!found) {
> +				i += dma->size;
> +				continue;
> +			}
> +
> +			for (; n; n = rb_next(n)) {
> +				unsigned int s;
> +				struct vfio_pfn *vpfn = rb_entry(n,
> +						struct vfio_pfn, node);
> +
> +				if (vpfn->iova >= iova + size)
> +					break;
> +
> +				s = (vpfn->iova - dma->iova) >> pgshift;
> +				bitmap_set(dma->bitmap, s, 1);
> +
should not set the dma->bitmap when user space asks for dirty bitmap.
should set the bits for all vpfns when dirty page tracking starts, and clear
it after putting them to user space.
dma->bitmap is set when vfio_pin_pages is called during dirty page
tracking.
> +				iova_limit = vpfn->iova + pgsize;
> +			}
> +			npages = iova_limit/pgsize;
> +		}
> +
> +		bsize = dirty_bitmap_bytes(npages);
> +		shift = nbits % BITS_PER_BYTE;
> +
> +		if (npages && shift) {
> +			l--;
> +			if (!access_ok((void __user *)bitmap + l,
> +					sizeof(unsigned char)))
> +				return -EINVAL;
> +
> +			ret = __get_user(temp, bitmap + l);
> +			if (ret)
> +				return ret;
> +		}
> +
> +		for (j = 0; j < bsize; j++, l++) {
> +			temp = temp |
> +			       (*((unsigned char *)dma->bitmap + j) << shift);
> +			if (!access_ok((void __user *)bitmap + l,
> +					sizeof(unsigned char)))
> +				return -EINVAL;
> +
> +			ret = __put_user(temp, bitmap + l);
> +			if (ret)
> +				return ret;
> +			if (shift) {
> +				temp = *((unsigned char *)dma->bitmap + j) >>
> +					(BITS_PER_BYTE - shift);
> +			}
> +		}
> +
> +		nbits += npages;
> +
> +		i = min(dma->iova + dma->size, iova + size);
> +		if (i >= iova + size)
> +			break;
> +	}
> +	return 0;
> +}
> +
> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
> +{
> +	long bsize;
> +
> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
> +		return -EINVAL;
> +
> +	bsize = dirty_bitmap_bytes(npages);
> +
> +	if (bitmap_size < bsize)
> +		return -EINVAL;
> +
> +	return bsize;
> +}
> +
>  static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
>  			     struct vfio_iommu_type1_dma_unmap *unmap)
>  {
> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
>  
>  		return copy_to_user((void __user *)arg, &unmap, minsz) ?
>  			-EFAULT : 0;
> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
> +		struct vfio_iommu_type1_dirty_bitmap range;
> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
> +		int ret;
> +
> +		if (!iommu->v2)
> +			return -EACCES;
> +
> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
> +				    bitmap);
> +
> +		if (copy_from_user(&range, (void __user *)arg, minsz))
> +			return -EFAULT;
> +
> +		if (range.argsz < minsz || range.flags & ~mask)
> +			return -EINVAL;
> +
> +		/* only one flag should be set at a time */
> +		if (__ffs(range.flags) != __fls(range.flags))
> +			return -EINVAL;
> +
> +		if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
> +			unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> +
> +			mutex_lock(&iommu->lock);
> +			iommu->dirty_page_tracking = true;
should only set iommu->dirty_page_tracking = true after bitmap alloc
succeeds.
> +			ret = vfio_dma_all_bitmap_alloc(iommu, iommu_pgsizes);
> +			mutex_unlock(&iommu->lock);
> +			return ret;
> +		} else if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
> +			mutex_lock(&iommu->lock);
> +			iommu->dirty_page_tracking = false;
> +			vfio_dma_all_bitmap_free(iommu);
> +			vfio_remove_unpinned_from_dma_list(iommu);
> +			mutex_unlock(&iommu->lock);
> +			return 0;
> +		} else if (range.flags &
> +				 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
> +			long bsize;
> +			unsigned long pgshift = __ffs(range.pgsize);
> +			uint64_t iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> +			uint64_t iommu_pgmask =
> +				 ((uint64_t)1 << __ffs(iommu_pgsizes)) - 1;
> +
> +			if ((range.pgsize & iommu_pgsizes) != range.pgsize)
> +				return -EINVAL;
> +			if (range.iova & iommu_pgmask)
> +				return -EINVAL;
> +			if (!range.size || range.size & iommu_pgmask)
> +				return -EINVAL;
> +			if (range.iova + range.size < range.iova)
> +				return -EINVAL;
> +			if (!access_ok((void __user *)range.bitmap,
> +				       range.bitmap_size))
> +				return -EINVAL;
> +
> +			bsize = verify_bitmap_size(range.size >> pgshift,
> +						   range.bitmap_size);
> +			if (bsize < 0)
> +				return bsize;
> +
> +			mutex_lock(&iommu->lock);
> +			if (iommu->dirty_page_tracking)
> +				ret = vfio_iova_dirty_bitmap(iommu, range.iova,
> +					 range.size, range.pgsize,
> +					 (unsigned char __user *)range.bitmap);
> +			else
> +				ret = -EINVAL;
> +			mutex_unlock(&iommu->lock);
> +
> +			return ret;
> +		}
>  	}
>  
>  	return -ENOTTY;
> -- 
> 2.7.0
>
Alex Williamson Feb. 10, 2020, 5:25 p.m. UTC | #2
On Sat, 8 Feb 2020 01:12:31 +0530
Kirti Wankhede <kwankhede@nvidia.com> wrote:

> VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> - Start pinned and unpinned pages tracking while migration is active
> - Stop pinned and unpinned dirty pages tracking. This is also used to
>   stop dirty pages tracking if migration failed or cancelled.
> - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
>   user space application responsibility to copy content of dirty pages
>   from source to destination during migration.
> 
> To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> structure. Bitmap size is calculated considering smallest supported page
> size. Bitmap is allocated when dirty logging is enabled for those
> vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> case of pass-through device.
> 
> There could be multiple option as to when bitmap should be populated:
> * Polulate bitmap for already pinned pages when bitmap is allocated for
>   a vfio_dma with the smallest supported page size. Updates bitmap from
>   page pinning and unpinning functions. When user application queries
>   bitmap, check if requested page size is same as page size used to
>   populated bitmap. If it is equal, copy bitmap. But if not equal,
>   re-populated bitmap according to requested page size and then copy to
>   user.
>   Pros: Bitmap gets populated on the fly after dirty tracking has
>         started.
>   Cons: If requested page size is different than smallest supported
>         page size, then bitmap has to be re-populated again, with
>         additional overhead of allocating bitmap memory again for
>         re-population of bitmap.

No memory needs to be allocated to re-populate the bitmap.  The bitmap
is clear-on-read and by tracking the bitmap in the smallest supported
page size we can guarantee that we can fit the user requested bitmap
size within the space occupied by that minimal page size range of the
bitmap.  Therefore we'd destructively translate the requested region of
the bitmap to a different page size, write it out to the user, and
clear it.  Also we expect userspace to use the minimum page size almost
exclusively, which is optimized by this approach as dirty bit tracking
is spread out over each page pinning operation.

> 
> * Populate bitmap when bitmap is queried by user application.
>   Pros: Bitmap is populated with requested page size. This eliminates
>         the need to re-populate bitmap if requested page size is
>         different than smallest supported pages size.
>   Cons: There is one time processing time, when bitmap is queried.

Another significant Con is that the vpfn list needs to track and manage
unpinned pages, which makes it more complex and intrusive.  The
previous option seems to have both time and complexity advantages,
especially in the case we expect to be most common of the user
accessing the bitmap with the minimum page size, ie. PAGE_SIZE.  It's
also not clear why we pre-allocate the bitmap at all with this approach.

> I prefer later option with simple logic and to eliminate over-head of
> bitmap repopulation in case of differnt page sizes. Later option is
> implemented in this patch.

Hmm, we'll see below, but I not convinced based on the above rationale.

> Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> Reviewed-by: Neo Jia <cjia@nvidia.com>
> ---
>  drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
>  1 file changed, 287 insertions(+), 12 deletions(-)
> 
> diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> index d386461e5d11..df358dc1c85b 100644
> --- a/drivers/vfio/vfio_iommu_type1.c
> +++ b/drivers/vfio/vfio_iommu_type1.c
> @@ -70,6 +70,7 @@ struct vfio_iommu {
>  	unsigned int		dma_avail;
>  	bool			v2;
>  	bool			nesting;
> +	bool			dirty_page_tracking;
>  };
>  
>  struct vfio_domain {
> @@ -90,6 +91,7 @@ struct vfio_dma {
>  	bool			lock_cap;	/* capable(CAP_IPC_LOCK) */
>  	struct task_struct	*task;
>  	struct rb_root		pfn_list;	/* Ex-user pinned pfn list */
> +	unsigned long		*bitmap;
>  };
>  
>  struct vfio_group {
> @@ -125,6 +127,7 @@ struct vfio_regions {
>  					(!list_empty(&iommu->domain_list))
>  
>  static int put_pfn(unsigned long pfn, int prot);
> +static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu);
>  
>  /*
>   * This code handles mapping and unmapping of user data buffers
> @@ -174,6 +177,57 @@ static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
>  	rb_erase(&old->node, &iommu->dma_list);
>  }
>  
> +static inline unsigned long dirty_bitmap_bytes(unsigned int npages)
> +{
> +	if (!npages)
> +		return 0;
> +
> +	return ALIGN(npages, BITS_PER_LONG) / sizeof(unsigned long);
> +}
> +
> +static int vfio_dma_bitmap_alloc(struct vfio_iommu *iommu,
> +				 struct vfio_dma *dma, unsigned long pgsizes)
> +{
> +	unsigned long pgshift = __ffs(pgsizes);
> +
> +	if (!RB_EMPTY_ROOT(&dma->pfn_list) || dma->iommu_mapped) {
> +		unsigned long npages = dma->size >> pgshift;
> +		unsigned long bsize = dirty_bitmap_bytes(npages);
> +
> +		dma->bitmap = kvzalloc(bsize, GFP_KERNEL);

nit, we don't need to store bsize in a local variable.

> +		if (!dma->bitmap)
> +			return -ENOMEM;
> +	}
> +	return 0;
> +}
> +
> +static int vfio_dma_all_bitmap_alloc(struct vfio_iommu *iommu,
> +				     unsigned long pgsizes)
> +{
> +	struct rb_node *n = rb_first(&iommu->dma_list);
> +	int ret;
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> +
> +		ret = vfio_dma_bitmap_alloc(iommu, dma, pgsizes);
> +		if (ret)
> +			return ret;

This doesn't unwind on failure, so we're left with partially allocated
bitmap cruft.

> +	}
> +	return 0;
> +}
> +
> +static void vfio_dma_all_bitmap_free(struct vfio_iommu *iommu)
> +{
> +	struct rb_node *n = rb_first(&iommu->dma_list);
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> +
> +		kfree(dma->bitmap);

We don't set dma->bitmap = NULL and we don't even prevent the case of a
user making multiple STOP calls, so we have a user triggerable double
free :(

> +	}
> +}
> +
>  /*
>   * Helper Functions for host iova-pfn list
>   */
> @@ -244,6 +298,29 @@ static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
>  	kfree(vpfn);
>  }
>  
> +static void vfio_remove_unpinned_from_pfn_list(struct vfio_dma *dma)
> +{
> +	struct rb_node *n = rb_first(&dma->pfn_list);
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_pfn *vpfn = rb_entry(n, struct vfio_pfn, node);
> +
> +		if (!vpfn->ref_count)
> +			vfio_remove_from_pfn_list(dma, vpfn);
> +	}
> +}
> +
> +static void vfio_remove_unpinned_from_dma_list(struct vfio_iommu *iommu)
> +{
> +	struct rb_node *n = rb_first(&iommu->dma_list);
> +
> +	for (; n; n = rb_next(n)) {
> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> +
> +		vfio_remove_unpinned_from_pfn_list(dma);
> +	}
> +}
> +
>  static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
>  					       unsigned long iova)
>  {
> @@ -261,7 +338,8 @@ static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
>  	vpfn->ref_count--;
>  	if (!vpfn->ref_count) {
>  		ret = put_pfn(vpfn->pfn, dma->prot);
> -		vfio_remove_from_pfn_list(dma, vpfn);
> +		if (!dma->bitmap)
> +			vfio_remove_from_pfn_list(dma, vpfn);
>  	}
>  	return ret;
>  }
> @@ -483,13 +561,14 @@ static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
>  	return ret;
>  }
>  
> -static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
> +static int vfio_unpin_page_external(struct vfio_iommu *iommu,

We added a parameter but didn't use it in this patch.

> +				    struct vfio_dma *dma, dma_addr_t iova,
>  				    bool do_accounting)
>  {
>  	int unlocked;
>  	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
>  
> -	if (!vpfn)
> +	if (!vpfn || !vpfn->ref_count)
>  		return 0;
>  
>  	unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
> @@ -510,6 +589,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  	unsigned long remote_vaddr;
>  	struct vfio_dma *dma;
>  	bool do_accounting;
> +	unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>  
>  	if (!iommu || !user_pfn || !phys_pfn)
>  		return -EINVAL;
> @@ -551,8 +631,10 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  
>  		vpfn = vfio_iova_get_vfio_pfn(dma, iova);
>  		if (vpfn) {
> -			phys_pfn[i] = vpfn->pfn;
> -			continue;
> +			if (vpfn->ref_count > 1) {
> +				phys_pfn[i] = vpfn->pfn;
> +				continue;
> +			}
>  		}
>  
>  		remote_vaddr = dma->vaddr + iova - dma->iova;
> @@ -560,11 +642,23 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  					     do_accounting);
>  		if (ret)
>  			goto pin_unwind;
> -
> -		ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
> -		if (ret) {
> -			vfio_unpin_page_external(dma, iova, do_accounting);
> -			goto pin_unwind;
> +		if (!vpfn) {
> +			ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
> +			if (ret) {
> +				vfio_unpin_page_external(iommu, dma, iova,
> +							 do_accounting);
> +				goto pin_unwind;
> +			}
> +		} else
> +			vpfn->pfn = phys_pfn[i];
> +
> +		if (iommu->dirty_page_tracking && !dma->bitmap) {
> +			ret = vfio_dma_bitmap_alloc(iommu, dma, iommu_pgsizes);
> +			if (ret) {
> +				vfio_unpin_page_external(iommu, dma, iova,
> +							 do_accounting);
> +				goto pin_unwind;
> +			}
>  		}
>  	}
>  
> @@ -578,7 +672,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>  
>  		iova = user_pfn[j] << PAGE_SHIFT;
>  		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
> -		vfio_unpin_page_external(dma, iova, do_accounting);
> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
>  		phys_pfn[j] = 0;
>  	}
>  pin_done:
> @@ -612,7 +706,7 @@ static int vfio_iommu_type1_unpin_pages(void *iommu_data,
>  		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
>  		if (!dma)
>  			goto unpin_exit;
> -		vfio_unpin_page_external(dma, iova, do_accounting);
> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
>  	}
>  
>  unpin_exit:
> @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
>  	return bitmap;
>  }
>  
> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> +				  size_t size, uint64_t pgsize,
> +				  unsigned char __user *bitmap)
> +{
> +	struct vfio_dma *dma;
> +	dma_addr_t i = iova, iova_limit;
> +	unsigned int bsize, nbits = 0, l = 0;
> +	unsigned long pgshift = __ffs(pgsize);
> +
> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> +		int ret, j;
> +		unsigned int npages = 0, shift = 0;
> +		unsigned char temp = 0;
> +
> +		/* mark all pages dirty if all pages are pinned and mapped. */
> +		if (dma->iommu_mapped) {
> +			iova_limit = min(dma->iova + dma->size, iova + size);
> +			npages = iova_limit/pgsize;
> +			bitmap_set(dma->bitmap, 0, npages);

npages is derived from iova_limit, which is the number of bits to set
dirty relative to the first requested iova, not iova zero, ie. the set
of dirty bits is offset from those requested unless iova == dma->iova.

Also I hope dma->bitmap was actually allocated.  Not only does the
START error path potentially leave dirty tracking enabled without all
the bitmap allocated, when does the bitmap get allocated for a new
vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
vpfn gets marked dirty.

> +		} else if (dma->bitmap) {
> +			struct rb_node *n = rb_first(&dma->pfn_list);
> +			bool found = false;
> +
> +			for (; n; n = rb_next(n)) {
> +				struct vfio_pfn *vpfn = rb_entry(n,
> +						struct vfio_pfn, node);
> +				if (vpfn->iova >= i) {
> +					found = true;
> +					break;
> +				}
> +			}
> +
> +			if (!found) {
> +				i += dma->size;
> +				continue;
> +			}
> +
> +			for (; n; n = rb_next(n)) {
> +				unsigned int s;
> +				struct vfio_pfn *vpfn = rb_entry(n,
> +						struct vfio_pfn, node);
> +
> +				if (vpfn->iova >= iova + size)
> +					break;
> +
> +				s = (vpfn->iova - dma->iova) >> pgshift;
> +				bitmap_set(dma->bitmap, s, 1);
> +
> +				iova_limit = vpfn->iova + pgsize;
> +			}
> +			npages = iova_limit/pgsize;

Isn't iova_limit potentially uninitialized here?  For example, if our
vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
(4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
4096 and break, and npages = ????/pgsize.

> +		}
> +
> +		bsize = dirty_bitmap_bytes(npages);
> +		shift = nbits % BITS_PER_BYTE;
> +
> +		if (npages && shift) {
> +			l--;
> +			if (!access_ok((void __user *)bitmap + l,
> +					sizeof(unsigned char)))
> +				return -EINVAL;
> +
> +			ret = __get_user(temp, bitmap + l);

I don't understand why we care to get the user's bitmap, are we trying
to leave whatever garbage they might have set in it and only also set
the dirty bits?  That seems unnecessary.

Also why do we need these access_ok() checks when we already checked
the range at the start of the ioctl?

> +			if (ret)
> +				return ret;
> +		}
> +
> +		for (j = 0; j < bsize; j++, l++) {
> +			temp = temp |
> +			       (*((unsigned char *)dma->bitmap + j) << shift);

|=

> +			if (!access_ok((void __user *)bitmap + l,
> +					sizeof(unsigned char)))
> +				return -EINVAL;
> +
> +			ret = __put_user(temp, bitmap + l);
> +			if (ret)
> +				return ret;
> +			if (shift) {
> +				temp = *((unsigned char *)dma->bitmap + j) >>
> +					(BITS_PER_BYTE - shift);
> +			}

When shift == 0, temp just seems to accumulate bits that never get
cleared.

> +		}
> +
> +		nbits += npages;
> +
> +		i = min(dma->iova + dma->size, iova + size);
> +		if (i >= iova + size)
> +			break;

So whether we error or succeed, we leave cruft in dma->bitmap for the
next pass.  It doesn't seem to make any sense why we pre-allocated the
bitmap, we might as well just allocate it on demand here.  Actually, if
we're not going to do a copy_to_user() for some range of the bitmap,
I'm not sure what it's purpose is at all.  I think the big advantages
of the bitmap are that we can't amortize the cost across every pinned
page or DMA mapping, we don't need the overhead of tracking unmapped
vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
getting any of those advantages here.

> +	}
> +	return 0;
> +}
> +
> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
> +{
> +	long bsize;
> +
> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
> +		return -EINVAL;
> +
> +	bsize = dirty_bitmap_bytes(npages);
> +
> +	if (bitmap_size < bsize)
> +		return -EINVAL;
> +
> +	return bsize;
> +}

Seems like this could simply return int, -errno or zero for success.
The returned bsize is not used for anything else.

> +
>  static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
>  			     struct vfio_iommu_type1_dma_unmap *unmap)
>  {
> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
>  
>  		return copy_to_user((void __user *)arg, &unmap, minsz) ?
>  			-EFAULT : 0;
> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
> +		struct vfio_iommu_type1_dirty_bitmap range;
> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
> +		int ret;
> +
> +		if (!iommu->v2)
> +			return -EACCES;
> +
> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
> +				    bitmap);

We require the user to provide iova, size, pgsize, bitmap_size, and
bitmap fields to START/STOP?  Why?

> +
> +		if (copy_from_user(&range, (void __user *)arg, minsz))
> +			return -EFAULT;
> +
> +		if (range.argsz < minsz || range.flags & ~mask)
> +			return -EINVAL;
> +
> +		/* only one flag should be set at a time */
> +		if (__ffs(range.flags) != __fls(range.flags))
> +			return -EINVAL;
> +
> +		if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
> +			unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> +
> +			mutex_lock(&iommu->lock);
> +			iommu->dirty_page_tracking = true;
> +			ret = vfio_dma_all_bitmap_alloc(iommu, iommu_pgsizes);

So dirty page tracking is enabled even if we fail to allocate all the
bitmaps?  Shouldn't this return an error if dirty tracking is already
enabled?

> +			mutex_unlock(&iommu->lock);
> +			return ret;
> +		} else if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
> +			mutex_lock(&iommu->lock);
> +			iommu->dirty_page_tracking = false;

Shouldn't we only allow STOP if tracking is enabled?

> +			vfio_dma_all_bitmap_free(iommu);

Here's where that user induced double free enters the picture.

> +			vfio_remove_unpinned_from_dma_list(iommu);
> +			mutex_unlock(&iommu->lock);
> +			return 0;
> +		} else if (range.flags &
> +				 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
> +			long bsize;
> +			unsigned long pgshift = __ffs(range.pgsize);
> +			uint64_t iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> +			uint64_t iommu_pgmask =
> +				 ((uint64_t)1 << __ffs(iommu_pgsizes)) - 1;
> +
> +			if ((range.pgsize & iommu_pgsizes) != range.pgsize)
> +				return -EINVAL;
> +			if (range.iova & iommu_pgmask)
> +				return -EINVAL;
> +			if (!range.size || range.size & iommu_pgmask)
> +				return -EINVAL;
> +			if (range.iova + range.size < range.iova)
> +				return -EINVAL;
> +			if (!access_ok((void __user *)range.bitmap,
> +				       range.bitmap_size))
> +				return -EINVAL;
> +
> +			bsize = verify_bitmap_size(range.size >> pgshift,
> +						   range.bitmap_size);
> +			if (bsize < 0)
> +				return bsize;
> +
> +			mutex_lock(&iommu->lock);
> +			if (iommu->dirty_page_tracking)
> +				ret = vfio_iova_dirty_bitmap(iommu, range.iova,
> +					 range.size, range.pgsize,
> +					 (unsigned char __user *)range.bitmap);
> +			else
> +				ret = -EINVAL;
> +			mutex_unlock(&iommu->lock);
> +
> +			return ret;
> +		}
>  	}
>  
>  	return -ENOTTY;

Thanks,
Alex
Alex Williamson Feb. 10, 2020, 7:44 p.m. UTC | #3
On Mon, 10 Feb 2020 04:49:54 -0500
Yan Zhao <yan.y.zhao@intel.com> wrote:

> On Sat, Feb 08, 2020 at 03:42:31AM +0800, Kirti Wankhede wrote:
> > VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> > - Start pinned and unpinned pages tracking while migration is active
> > - Stop pinned and unpinned dirty pages tracking. This is also used to
> >   stop dirty pages tracking if migration failed or cancelled.
> > - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
> >   user space application responsibility to copy content of dirty pages
> >   from source to destination during migration.
> > 
> > To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> > structure. Bitmap size is calculated considering smallest supported page
> > size. Bitmap is allocated when dirty logging is enabled for those
> > vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> > case of pass-through device.
> > 
> > There could be multiple option as to when bitmap should be populated:
> > * Polulate bitmap for already pinned pages when bitmap is allocated for
> >   a vfio_dma with the smallest supported page size. Updates bitmap from
> >   page pinning and unpinning functions. When user application queries
> >   bitmap, check if requested page size is same as page size used to
> >   populated bitmap. If it is equal, copy bitmap. But if not equal,
> >   re-populated bitmap according to requested page size and then copy to
> >   user.
> >   Pros: Bitmap gets populated on the fly after dirty tracking has
> >         started.
> >   Cons: If requested page size is different than smallest supported
> >         page size, then bitmap has to be re-populated again, with
> >         additional overhead of allocating bitmap memory again for
> >         re-population of bitmap.
> > 
> > * Populate bitmap when bitmap is queried by user application.
> >   Pros: Bitmap is populated with requested page size. This eliminates
> >         the need to re-populate bitmap if requested page size is
> >         different than smallest supported pages size.
> >   Cons: There is one time processing time, when bitmap is queried.
> > 
> > I prefer later option with simple logic and to eliminate over-head of
> > bitmap repopulation in case of differnt page sizes. Later option is
> > implemented in this patch.
> > 
> > Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> > Reviewed-by: Neo Jia <cjia@nvidia.com>
> > ---
> >  drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
> >  1 file changed, 287 insertions(+), 12 deletions(-)
> > 
> > diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> > index d386461e5d11..df358dc1c85b 100644
> > --- a/drivers/vfio/vfio_iommu_type1.c
> > +++ b/drivers/vfio/vfio_iommu_type1.c
[snip]
> > @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
> >  	return bitmap;
> >  }
> >  
> > +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> > +				  size_t size, uint64_t pgsize,
> > +				  unsigned char __user *bitmap)
> > +{
> > +	struct vfio_dma *dma;
> > +	dma_addr_t i = iova, iova_limit;
> > +	unsigned int bsize, nbits = 0, l = 0;
> > +	unsigned long pgshift = __ffs(pgsize);
> > +
> > +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> > +		int ret, j;
> > +		unsigned int npages = 0, shift = 0;
> > +		unsigned char temp = 0;
> > +
> > +		/* mark all pages dirty if all pages are pinned and mapped. */
> > +		if (dma->iommu_mapped) {
> > +			iova_limit = min(dma->iova + dma->size, iova + size);
> > +			npages = iova_limit/pgsize;
> > +			bitmap_set(dma->bitmap, 0, npages);  
> for pass-through devices, it's not good to always return all pinned pages as
> dirty. could it also call vfio_pin_pages to track dirty pages? or any
> other interface provided to do that?

See patch 7/7.  Thanks,

Alex
Yan Zhao Feb. 11, 2020, 2:52 a.m. UTC | #4
On Tue, Feb 11, 2020 at 03:44:54AM +0800, Alex Williamson wrote:
> On Mon, 10 Feb 2020 04:49:54 -0500
> Yan Zhao <yan.y.zhao@intel.com> wrote:
> 
> > On Sat, Feb 08, 2020 at 03:42:31AM +0800, Kirti Wankhede wrote:
> > > VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> > > - Start pinned and unpinned pages tracking while migration is active
> > > - Stop pinned and unpinned dirty pages tracking. This is also used to
> > >   stop dirty pages tracking if migration failed or cancelled.
> > > - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
> > >   user space application responsibility to copy content of dirty pages
> > >   from source to destination during migration.
> > > 
> > > To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> > > structure. Bitmap size is calculated considering smallest supported page
> > > size. Bitmap is allocated when dirty logging is enabled for those
> > > vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> > > case of pass-through device.
> > > 
> > > There could be multiple option as to when bitmap should be populated:
> > > * Polulate bitmap for already pinned pages when bitmap is allocated for
> > >   a vfio_dma with the smallest supported page size. Updates bitmap from
> > >   page pinning and unpinning functions. When user application queries
> > >   bitmap, check if requested page size is same as page size used to
> > >   populated bitmap. If it is equal, copy bitmap. But if not equal,
> > >   re-populated bitmap according to requested page size and then copy to
> > >   user.
> > >   Pros: Bitmap gets populated on the fly after dirty tracking has
> > >         started.
> > >   Cons: If requested page size is different than smallest supported
> > >         page size, then bitmap has to be re-populated again, with
> > >         additional overhead of allocating bitmap memory again for
> > >         re-population of bitmap.
> > > 
> > > * Populate bitmap when bitmap is queried by user application.
> > >   Pros: Bitmap is populated with requested page size. This eliminates
> > >         the need to re-populate bitmap if requested page size is
> > >         different than smallest supported pages size.
> > >   Cons: There is one time processing time, when bitmap is queried.
> > > 
> > > I prefer later option with simple logic and to eliminate over-head of
> > > bitmap repopulation in case of differnt page sizes. Later option is
> > > implemented in this patch.
> > > 
> > > Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> > > Reviewed-by: Neo Jia <cjia@nvidia.com>
> > > ---
> > >  drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
> > >  1 file changed, 287 insertions(+), 12 deletions(-)
> > > 
> > > diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> > > index d386461e5d11..df358dc1c85b 100644
> > > --- a/drivers/vfio/vfio_iommu_type1.c
> > > +++ b/drivers/vfio/vfio_iommu_type1.c
> [snip]
> > > @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
> > >  	return bitmap;
> > >  }
> > >  
> > > +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> > > +				  size_t size, uint64_t pgsize,
> > > +				  unsigned char __user *bitmap)
> > > +{
> > > +	struct vfio_dma *dma;
> > > +	dma_addr_t i = iova, iova_limit;
> > > +	unsigned int bsize, nbits = 0, l = 0;
> > > +	unsigned long pgshift = __ffs(pgsize);
> > > +
> > > +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> > > +		int ret, j;
> > > +		unsigned int npages = 0, shift = 0;
> > > +		unsigned char temp = 0;
> > > +
> > > +		/* mark all pages dirty if all pages are pinned and mapped. */
> > > +		if (dma->iommu_mapped) {
> > > +			iova_limit = min(dma->iova + dma->size, iova + size);
> > > +			npages = iova_limit/pgsize;
> > > +			bitmap_set(dma->bitmap, 0, npages);  
> > for pass-through devices, it's not good to always return all pinned pages as
> > dirty. could it also call vfio_pin_pages to track dirty pages? or any
> > other interface provided to do that?
> 
> See patch 7/7.  Thanks,
>
hi Alex and Kirti,
for pass-through devices, though patch 7/7 enables the vendor driver to
set dirty pages by calling vfio_pin_pages, however, its overhead is much
higher than the previous way of generating a bitmap directly to user.
And it also requires pass-through device vendor driver to track guest
operations to know when to call vfio_pin_pages.
There are still use cases like a pass-through device is able to track
dirty pages in its hardware buffer, so is there a way for it pass its
dirty bitmap to user?

Thanks
Yan
Alex Williamson Feb. 11, 2020, 3:45 a.m. UTC | #5
On Mon, 10 Feb 2020 21:52:51 -0500
Yan Zhao <yan.y.zhao@intel.com> wrote:

> On Tue, Feb 11, 2020 at 03:44:54AM +0800, Alex Williamson wrote:
> > On Mon, 10 Feb 2020 04:49:54 -0500
> > Yan Zhao <yan.y.zhao@intel.com> wrote:
> >   
> > > On Sat, Feb 08, 2020 at 03:42:31AM +0800, Kirti Wankhede wrote:  
> > > > VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> > > > - Start pinned and unpinned pages tracking while migration is active
> > > > - Stop pinned and unpinned dirty pages tracking. This is also used to
> > > >   stop dirty pages tracking if migration failed or cancelled.
> > > > - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
> > > >   user space application responsibility to copy content of dirty pages
> > > >   from source to destination during migration.
> > > > 
> > > > To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> > > > structure. Bitmap size is calculated considering smallest supported page
> > > > size. Bitmap is allocated when dirty logging is enabled for those
> > > > vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> > > > case of pass-through device.
> > > > 
> > > > There could be multiple option as to when bitmap should be populated:
> > > > * Polulate bitmap for already pinned pages when bitmap is allocated for
> > > >   a vfio_dma with the smallest supported page size. Updates bitmap from
> > > >   page pinning and unpinning functions. When user application queries
> > > >   bitmap, check if requested page size is same as page size used to
> > > >   populated bitmap. If it is equal, copy bitmap. But if not equal,
> > > >   re-populated bitmap according to requested page size and then copy to
> > > >   user.
> > > >   Pros: Bitmap gets populated on the fly after dirty tracking has
> > > >         started.
> > > >   Cons: If requested page size is different than smallest supported
> > > >         page size, then bitmap has to be re-populated again, with
> > > >         additional overhead of allocating bitmap memory again for
> > > >         re-population of bitmap.
> > > > 
> > > > * Populate bitmap when bitmap is queried by user application.
> > > >   Pros: Bitmap is populated with requested page size. This eliminates
> > > >         the need to re-populate bitmap if requested page size is
> > > >         different than smallest supported pages size.
> > > >   Cons: There is one time processing time, when bitmap is queried.
> > > > 
> > > > I prefer later option with simple logic and to eliminate over-head of
> > > > bitmap repopulation in case of differnt page sizes. Later option is
> > > > implemented in this patch.
> > > > 
> > > > Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> > > > Reviewed-by: Neo Jia <cjia@nvidia.com>
> > > > ---
> > > >  drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
> > > >  1 file changed, 287 insertions(+), 12 deletions(-)
> > > > 
> > > > diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> > > > index d386461e5d11..df358dc1c85b 100644
> > > > --- a/drivers/vfio/vfio_iommu_type1.c
> > > > +++ b/drivers/vfio/vfio_iommu_type1.c  
> > [snip]  
> > > > @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
> > > >  	return bitmap;
> > > >  }
> > > >  
> > > > +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> > > > +				  size_t size, uint64_t pgsize,
> > > > +				  unsigned char __user *bitmap)
> > > > +{
> > > > +	struct vfio_dma *dma;
> > > > +	dma_addr_t i = iova, iova_limit;
> > > > +	unsigned int bsize, nbits = 0, l = 0;
> > > > +	unsigned long pgshift = __ffs(pgsize);
> > > > +
> > > > +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> > > > +		int ret, j;
> > > > +		unsigned int npages = 0, shift = 0;
> > > > +		unsigned char temp = 0;
> > > > +
> > > > +		/* mark all pages dirty if all pages are pinned and mapped. */
> > > > +		if (dma->iommu_mapped) {
> > > > +			iova_limit = min(dma->iova + dma->size, iova + size);
> > > > +			npages = iova_limit/pgsize;
> > > > +			bitmap_set(dma->bitmap, 0, npages);    
> > > for pass-through devices, it's not good to always return all pinned pages as
> > > dirty. could it also call vfio_pin_pages to track dirty pages? or any
> > > other interface provided to do that?  
> > 
> > See patch 7/7.  Thanks,
> >  
> hi Alex and Kirti,
> for pass-through devices, though patch 7/7 enables the vendor driver to
> set dirty pages by calling vfio_pin_pages, however, its overhead is much
> higher than the previous way of generating a bitmap directly to user.
> And it also requires pass-through device vendor driver to track guest
> operations to know when to call vfio_pin_pages.
> There are still use cases like a pass-through device is able to track
> dirty pages in its hardware buffer, so is there a way for it pass its
> dirty bitmap to user?

Not currently and this sounds like another argument in favor of using
the dirty bitmap per vfio_dma to directly track dirty pages.
Passthrough drivers could be provided an interface to set dirty bits
which could be merged with pfn list entries when the user requests the
bitmap, rather than requiring passthrough drivers to unnecessarily
allocate pfn list entries directly.  Thanks,

Alex
Yan Zhao Feb. 11, 2020, 4:11 a.m. UTC | #6
On Tue, Feb 11, 2020 at 11:45:43AM +0800, Alex Williamson wrote:
> On Mon, 10 Feb 2020 21:52:51 -0500
> Yan Zhao <yan.y.zhao@intel.com> wrote:
> 
> > On Tue, Feb 11, 2020 at 03:44:54AM +0800, Alex Williamson wrote:
> > > On Mon, 10 Feb 2020 04:49:54 -0500
> > > Yan Zhao <yan.y.zhao@intel.com> wrote:
> > >   
> > > > On Sat, Feb 08, 2020 at 03:42:31AM +0800, Kirti Wankhede wrote:  
> > > > > VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> > > > > - Start pinned and unpinned pages tracking while migration is active
> > > > > - Stop pinned and unpinned dirty pages tracking. This is also used to
> > > > >   stop dirty pages tracking if migration failed or cancelled.
> > > > > - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
> > > > >   user space application responsibility to copy content of dirty pages
> > > > >   from source to destination during migration.
> > > > > 
> > > > > To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> > > > > structure. Bitmap size is calculated considering smallest supported page
> > > > > size. Bitmap is allocated when dirty logging is enabled for those
> > > > > vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> > > > > case of pass-through device.
> > > > > 
> > > > > There could be multiple option as to when bitmap should be populated:
> > > > > * Polulate bitmap for already pinned pages when bitmap is allocated for
> > > > >   a vfio_dma with the smallest supported page size. Updates bitmap from
> > > > >   page pinning and unpinning functions. When user application queries
> > > > >   bitmap, check if requested page size is same as page size used to
> > > > >   populated bitmap. If it is equal, copy bitmap. But if not equal,
> > > > >   re-populated bitmap according to requested page size and then copy to
> > > > >   user.
> > > > >   Pros: Bitmap gets populated on the fly after dirty tracking has
> > > > >         started.
> > > > >   Cons: If requested page size is different than smallest supported
> > > > >         page size, then bitmap has to be re-populated again, with
> > > > >         additional overhead of allocating bitmap memory again for
> > > > >         re-population of bitmap.
> > > > > 
> > > > > * Populate bitmap when bitmap is queried by user application.
> > > > >   Pros: Bitmap is populated with requested page size. This eliminates
> > > > >         the need to re-populate bitmap if requested page size is
> > > > >         different than smallest supported pages size.
> > > > >   Cons: There is one time processing time, when bitmap is queried.
> > > > > 
> > > > > I prefer later option with simple logic and to eliminate over-head of
> > > > > bitmap repopulation in case of differnt page sizes. Later option is
> > > > > implemented in this patch.
> > > > > 
> > > > > Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> > > > > Reviewed-by: Neo Jia <cjia@nvidia.com>
> > > > > ---
> > > > >  drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
> > > > >  1 file changed, 287 insertions(+), 12 deletions(-)
> > > > > 
> > > > > diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> > > > > index d386461e5d11..df358dc1c85b 100644
> > > > > --- a/drivers/vfio/vfio_iommu_type1.c
> > > > > +++ b/drivers/vfio/vfio_iommu_type1.c  
> > > [snip]  
> > > > > @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
> > > > >  	return bitmap;
> > > > >  }
> > > > >  
> > > > > +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> > > > > +				  size_t size, uint64_t pgsize,
> > > > > +				  unsigned char __user *bitmap)
> > > > > +{
> > > > > +	struct vfio_dma *dma;
> > > > > +	dma_addr_t i = iova, iova_limit;
> > > > > +	unsigned int bsize, nbits = 0, l = 0;
> > > > > +	unsigned long pgshift = __ffs(pgsize);
> > > > > +
> > > > > +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> > > > > +		int ret, j;
> > > > > +		unsigned int npages = 0, shift = 0;
> > > > > +		unsigned char temp = 0;
> > > > > +
> > > > > +		/* mark all pages dirty if all pages are pinned and mapped. */
> > > > > +		if (dma->iommu_mapped) {
> > > > > +			iova_limit = min(dma->iova + dma->size, iova + size);
> > > > > +			npages = iova_limit/pgsize;
> > > > > +			bitmap_set(dma->bitmap, 0, npages);    
> > > > for pass-through devices, it's not good to always return all pinned pages as
> > > > dirty. could it also call vfio_pin_pages to track dirty pages? or any
> > > > other interface provided to do that?  
> > > 
> > > See patch 7/7.  Thanks,
> > >  
> > hi Alex and Kirti,
> > for pass-through devices, though patch 7/7 enables the vendor driver to
> > set dirty pages by calling vfio_pin_pages, however, its overhead is much
> > higher than the previous way of generating a bitmap directly to user.
> > And it also requires pass-through device vendor driver to track guest
> > operations to know when to call vfio_pin_pages.
> > There are still use cases like a pass-through device is able to track
> > dirty pages in its hardware buffer, so is there a way for it pass its
> > dirty bitmap to user?
> 
> Not currently and this sounds like another argument in favor of using
> the dirty bitmap per vfio_dma to directly track dirty pages.
it may need an interface to get max iova in all vfio_dma and then generate a
hardware bitmap for the whole guest system memory.

> Passthrough drivers could be provided an interface to set dirty bits
> which could be merged with pfn list entries when the user requests the
> bitmap, rather than requiring passthrough drivers to unnecessarily
> allocate pfn list entries directly.  Thanks,
yes, it's better.
and for devices with ability to track dirty pages in hardware,
maybe an interface to let vfio know where is the hardware bitmap?

Thanks
Yan
Kirti Wankhede Feb. 12, 2020, 8:56 p.m. UTC | #7
On 2/10/2020 10:55 PM, Alex Williamson wrote:
> On Sat, 8 Feb 2020 01:12:31 +0530
> Kirti Wankhede <kwankhede@nvidia.com> wrote:
> 
>> VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
>> - Start pinned and unpinned pages tracking while migration is active
>> - Stop pinned and unpinned dirty pages tracking. This is also used to
>>    stop dirty pages tracking if migration failed or cancelled.
>> - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
>>    user space application responsibility to copy content of dirty pages
>>    from source to destination during migration.
>>
>> To prevent DoS attack, memory for bitmap is allocated per vfio_dma
>> structure. Bitmap size is calculated considering smallest supported page
>> size. Bitmap is allocated when dirty logging is enabled for those
>> vfio_dmas whose vpfn list is not empty or whole range is mapped, in
>> case of pass-through device.
>>
>> There could be multiple option as to when bitmap should be populated:
>> * Polulate bitmap for already pinned pages when bitmap is allocated for
>>    a vfio_dma with the smallest supported page size. Updates bitmap from
>>    page pinning and unpinning functions. When user application queries
>>    bitmap, check if requested page size is same as page size used to
>>    populated bitmap. If it is equal, copy bitmap. But if not equal,
>>    re-populated bitmap according to requested page size and then copy to
>>    user.
>>    Pros: Bitmap gets populated on the fly after dirty tracking has
>>          started.
>>    Cons: If requested page size is different than smallest supported
>>          page size, then bitmap has to be re-populated again, with
>>          additional overhead of allocating bitmap memory again for
>>          re-population of bitmap.
> 
> No memory needs to be allocated to re-populate the bitmap.  The bitmap
> is clear-on-read and by tracking the bitmap in the smallest supported
> page size we can guarantee that we can fit the user requested bitmap
> size within the space occupied by that minimal page size range of the
> bitmap.  Therefore we'd destructively translate the requested region of
> the bitmap to a different page size, write it out to the user, and
> clear it.  Also we expect userspace to use the minimum page size almost
> exclusively, which is optimized by this approach as dirty bit tracking
> is spread out over each page pinning operation.
> 
>>
>> * Populate bitmap when bitmap is queried by user application.
>>    Pros: Bitmap is populated with requested page size. This eliminates
>>          the need to re-populate bitmap if requested page size is
>>          different than smallest supported pages size.
>>    Cons: There is one time processing time, when bitmap is queried.
> 
> Another significant Con is that the vpfn list needs to track and manage
> unpinned pages, which makes it more complex and intrusive.  The
> previous option seems to have both time and complexity advantages,
> especially in the case we expect to be most common of the user
> accessing the bitmap with the minimum page size, ie. PAGE_SIZE.  It's
> also not clear why we pre-allocate the bitmap at all with this approach.
> 
>> I prefer later option with simple logic and to eliminate over-head of
>> bitmap repopulation in case of differnt page sizes. Later option is
>> implemented in this patch.
> 
> Hmm, we'll see below, but I not convinced based on the above rationale.
> 
>> Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
>> Reviewed-by: Neo Jia <cjia@nvidia.com>
>> ---
>>   drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
>>   1 file changed, 287 insertions(+), 12 deletions(-)
>>
>> diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
>> index d386461e5d11..df358dc1c85b 100644
>> --- a/drivers/vfio/vfio_iommu_type1.c
>> +++ b/drivers/vfio/vfio_iommu_type1.c
>> @@ -70,6 +70,7 @@ struct vfio_iommu {
>>   	unsigned int		dma_avail;
>>   	bool			v2;
>>   	bool			nesting;
>> +	bool			dirty_page_tracking;
>>   };
>>   
>>   struct vfio_domain {
>> @@ -90,6 +91,7 @@ struct vfio_dma {
>>   	bool			lock_cap;	/* capable(CAP_IPC_LOCK) */
>>   	struct task_struct	*task;
>>   	struct rb_root		pfn_list;	/* Ex-user pinned pfn list */
>> +	unsigned long		*bitmap;
>>   };
>>   
>>   struct vfio_group {
>> @@ -125,6 +127,7 @@ struct vfio_regions {
>>   					(!list_empty(&iommu->domain_list))
>>   
>>   static int put_pfn(unsigned long pfn, int prot);
>> +static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu);
>>   
>>   /*
>>    * This code handles mapping and unmapping of user data buffers
>> @@ -174,6 +177,57 @@ static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
>>   	rb_erase(&old->node, &iommu->dma_list);
>>   }
>>   
>> +static inline unsigned long dirty_bitmap_bytes(unsigned int npages)
>> +{
>> +	if (!npages)
>> +		return 0;
>> +
>> +	return ALIGN(npages, BITS_PER_LONG) / sizeof(unsigned long);
>> +}
>> +
>> +static int vfio_dma_bitmap_alloc(struct vfio_iommu *iommu,
>> +				 struct vfio_dma *dma, unsigned long pgsizes)
>> +{
>> +	unsigned long pgshift = __ffs(pgsizes);
>> +
>> +	if (!RB_EMPTY_ROOT(&dma->pfn_list) || dma->iommu_mapped) {
>> +		unsigned long npages = dma->size >> pgshift;
>> +		unsigned long bsize = dirty_bitmap_bytes(npages);
>> +
>> +		dma->bitmap = kvzalloc(bsize, GFP_KERNEL);
> 
> nit, we don't need to store bsize in a local variable.
> 
>> +		if (!dma->bitmap)
>> +			return -ENOMEM;
>> +	}
>> +	return 0;
>> +}
>> +
>> +static int vfio_dma_all_bitmap_alloc(struct vfio_iommu *iommu,
>> +				     unsigned long pgsizes)
>> +{
>> +	struct rb_node *n = rb_first(&iommu->dma_list);
>> +	int ret;
>> +
>> +	for (; n; n = rb_next(n)) {
>> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
>> +
>> +		ret = vfio_dma_bitmap_alloc(iommu, dma, pgsizes);
>> +		if (ret)
>> +			return ret;
> 
> This doesn't unwind on failure, so we're left with partially allocated
> bitmap cruft.
>

Good point. Adding unwind on failure.

>> +	}
>> +	return 0;
>> +}
>> +
>> +static void vfio_dma_all_bitmap_free(struct vfio_iommu *iommu)
>> +{
>> +	struct rb_node *n = rb_first(&iommu->dma_list);
>> +
>> +	for (; n; n = rb_next(n)) {
>> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
>> +
>> +		kfree(dma->bitmap);
> 
> We don't set dma->bitmap = NULL and we don't even prevent the case of a
> user making multiple STOP calls, so we have a user triggerable double
> free :(
> 

Ok.

>> +	}
>> +}
>> +
>>   /*
>>    * Helper Functions for host iova-pfn list
>>    */
>> @@ -244,6 +298,29 @@ static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
>>   	kfree(vpfn);
>>   }
>>   
>> +static void vfio_remove_unpinned_from_pfn_list(struct vfio_dma *dma)
>> +{
>> +	struct rb_node *n = rb_first(&dma->pfn_list);
>> +
>> +	for (; n; n = rb_next(n)) {
>> +		struct vfio_pfn *vpfn = rb_entry(n, struct vfio_pfn, node);
>> +
>> +		if (!vpfn->ref_count)
>> +			vfio_remove_from_pfn_list(dma, vpfn);
>> +	}
>> +}
>> +
>> +static void vfio_remove_unpinned_from_dma_list(struct vfio_iommu *iommu)
>> +{
>> +	struct rb_node *n = rb_first(&iommu->dma_list);
>> +
>> +	for (; n; n = rb_next(n)) {
>> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
>> +
>> +		vfio_remove_unpinned_from_pfn_list(dma);
>> +	}
>> +}
>> +
>>   static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
>>   					       unsigned long iova)
>>   {
>> @@ -261,7 +338,8 @@ static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
>>   	vpfn->ref_count--;
>>   	if (!vpfn->ref_count) {
>>   		ret = put_pfn(vpfn->pfn, dma->prot);
>> -		vfio_remove_from_pfn_list(dma, vpfn);
>> +		if (!dma->bitmap)
>> +			vfio_remove_from_pfn_list(dma, vpfn);
>>   	}
>>   	return ret;
>>   }
>> @@ -483,13 +561,14 @@ static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
>>   	return ret;
>>   }
>>   
>> -static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
>> +static int vfio_unpin_page_external(struct vfio_iommu *iommu,
> 
> We added a parameter but didn't use it in this patch.
> 

Ok, Moving it to relevant patch.

>> +				    struct vfio_dma *dma, dma_addr_t iova,
>>   				    bool do_accounting)
>>   {
>>   	int unlocked;
>>   	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
>>   
>> -	if (!vpfn)
>> +	if (!vpfn || !vpfn->ref_count)
>>   		return 0;
>>   
>>   	unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
>> @@ -510,6 +589,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>>   	unsigned long remote_vaddr;
>>   	struct vfio_dma *dma;
>>   	bool do_accounting;
>> +	unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>>   
>>   	if (!iommu || !user_pfn || !phys_pfn)
>>   		return -EINVAL;
>> @@ -551,8 +631,10 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>>   
>>   		vpfn = vfio_iova_get_vfio_pfn(dma, iova);
>>   		if (vpfn) {
>> -			phys_pfn[i] = vpfn->pfn;
>> -			continue;
>> +			if (vpfn->ref_count > 1) {
>> +				phys_pfn[i] = vpfn->pfn;
>> +				continue;
>> +			}
>>   		}
>>   
>>   		remote_vaddr = dma->vaddr + iova - dma->iova;
>> @@ -560,11 +642,23 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>>   					     do_accounting);
>>   		if (ret)
>>   			goto pin_unwind;
>> -
>> -		ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
>> -		if (ret) {
>> -			vfio_unpin_page_external(dma, iova, do_accounting);
>> -			goto pin_unwind;
>> +		if (!vpfn) {
>> +			ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
>> +			if (ret) {
>> +				vfio_unpin_page_external(iommu, dma, iova,
>> +							 do_accounting);
>> +				goto pin_unwind;
>> +			}
>> +		} else
>> +			vpfn->pfn = phys_pfn[i];
>> +
>> +		if (iommu->dirty_page_tracking && !dma->bitmap) {
>> +			ret = vfio_dma_bitmap_alloc(iommu, dma, iommu_pgsizes);
>> +			if (ret) {
>> +				vfio_unpin_page_external(iommu, dma, iova,
>> +							 do_accounting);
>> +				goto pin_unwind;
>> +			}
>>   		}
>>   	}
>>   
>> @@ -578,7 +672,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
>>   
>>   		iova = user_pfn[j] << PAGE_SHIFT;
>>   		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
>> -		vfio_unpin_page_external(dma, iova, do_accounting);
>> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
>>   		phys_pfn[j] = 0;
>>   	}
>>   pin_done:
>> @@ -612,7 +706,7 @@ static int vfio_iommu_type1_unpin_pages(void *iommu_data,
>>   		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
>>   		if (!dma)
>>   			goto unpin_exit;
>> -		vfio_unpin_page_external(dma, iova, do_accounting);
>> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
>>   	}
>>   
>>   unpin_exit:
>> @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
>>   	return bitmap;
>>   }
>>   
>> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
>> +				  size_t size, uint64_t pgsize,
>> +				  unsigned char __user *bitmap)
>> +{
>> +	struct vfio_dma *dma;
>> +	dma_addr_t i = iova, iova_limit;
>> +	unsigned int bsize, nbits = 0, l = 0;
>> +	unsigned long pgshift = __ffs(pgsize);
>> +
>> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
>> +		int ret, j;
>> +		unsigned int npages = 0, shift = 0;
>> +		unsigned char temp = 0;
>> +
>> +		/* mark all pages dirty if all pages are pinned and mapped. */
>> +		if (dma->iommu_mapped) {
>> +			iova_limit = min(dma->iova + dma->size, iova + size);
>> +			npages = iova_limit/pgsize;
>> +			bitmap_set(dma->bitmap, 0, npages);
> 
> npages is derived from iova_limit, which is the number of bits to set
> dirty relative to the first requested iova, not iova zero, ie. the set
> of dirty bits is offset from those requested unless iova == dma->iova.
> 

Right, fixing.

> Also I hope dma->bitmap was actually allocated.  Not only does the
> START error path potentially leave dirty tracking enabled without all
> the bitmap allocated, when does the bitmap get allocated for a new
> vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
> vpfn gets marked dirty.
> 

Right.

Fixing error paths.


>> +		} else if (dma->bitmap) {
>> +			struct rb_node *n = rb_first(&dma->pfn_list);
>> +			bool found = false;
>> +
>> +			for (; n; n = rb_next(n)) {
>> +				struct vfio_pfn *vpfn = rb_entry(n,
>> +						struct vfio_pfn, node);
>> +				if (vpfn->iova >= i) {
>> +					found = true;
>> +					break;
>> +				}
>> +			}
>> +
>> +			if (!found) {
>> +				i += dma->size;
>> +				continue;
>> +			}
>> +
>> +			for (; n; n = rb_next(n)) {
>> +				unsigned int s;
>> +				struct vfio_pfn *vpfn = rb_entry(n,
>> +						struct vfio_pfn, node);
>> +
>> +				if (vpfn->iova >= iova + size)
>> +					break;
>> +
>> +				s = (vpfn->iova - dma->iova) >> pgshift;
>> +				bitmap_set(dma->bitmap, s, 1);
>> +
>> +				iova_limit = vpfn->iova + pgsize;
>> +			}
>> +			npages = iova_limit/pgsize;
> 
> Isn't iova_limit potentially uninitialized here?  For example, if our
> vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
> there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
> (4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
> 4096 and break, and npages = ????/pgsize.
> 

Right, Fixing it.

>> +		}
>> +
>> +		bsize = dirty_bitmap_bytes(npages);
>> +		shift = nbits % BITS_PER_BYTE;
>> +
>> +		if (npages && shift) {
>> +			l--;
>> +			if (!access_ok((void __user *)bitmap + l,
>> +					sizeof(unsigned char)))
>> +				return -EINVAL;
>> +
>> +			ret = __get_user(temp, bitmap + l);
> 
> I don't understand why we care to get the user's bitmap, are we trying
> to leave whatever garbage they might have set in it and only also set
> the dirty bits?  That seems unnecessary.
> 

Suppose dma mapped ranges are {start, size}:
{0, 0xa000}, {0xa000, 0x10000}

Bitmap asked from 0 - 0x10000. Say suppose all pages are dirty.
Then in first iteration for dma {0,0xa000} there are 10 pages, so 10 
bits are set, put_user() happens for 2 bytes, (00000011 11111111b).
In second iteration for dma {0xa000, 0x10000} there are 6 pages and 
these bits should be appended to previous byte. So get_user() that byte, 
then shift-OR rest of the bitmap, result should be: (11111111 11111111b)

Without get_user() and shift-OR, resulting bitmap would be
111111 00000011 11111111b which would be wrong.

> Also why do we need these access_ok() checks when we already checked
> the range at the start of the ioctl?

Since pointer is updated runtime here, better to check that pointer 
before using that pointer.

> 
>> +			if (ret)
>> +				return ret;
>> +		}
>> +
>> +		for (j = 0; j < bsize; j++, l++) {
>> +			temp = temp |
>> +			       (*((unsigned char *)dma->bitmap + j) << shift);
> 
> |=
> 
>> +			if (!access_ok((void __user *)bitmap + l,
>> +					sizeof(unsigned char)))
>> +				return -EINVAL;
>> +
>> +			ret = __put_user(temp, bitmap + l);
>> +			if (ret)
>> +				return ret;
>> +			if (shift) {
>> +				temp = *((unsigned char *)dma->bitmap + j) >>
>> +					(BITS_PER_BYTE - shift);
>> +			}
> 
> When shift == 0, temp just seems to accumulate bits that never get
> cleared.
> 

Hope example above explains the shift logic.

>> +		}
>> +
>> +		nbits += npages;
>> +
>> +		i = min(dma->iova + dma->size, iova + size);
>> +		if (i >= iova + size)
>> +			break;
> 
> So whether we error or succeed, we leave cruft in dma->bitmap for the
> next pass.  It doesn't seem to make any sense why we pre-allocated the
> bitmap, we might as well just allocate it on demand here.  Actually, if
> we're not going to do a copy_to_user() for some range of the bitmap,
> I'm not sure what it's purpose is at all.  I think the big advantages
> of the bitmap are that we can't amortize the cost across every pinned
> page or DMA mapping, we don't need the overhead of tracking unmapped
> vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
> getting any of those advantages here.
> 

That would still not work if dma range size is not multiples of 8 pages. 
See example above.


>> +	}
>> +	return 0;
>> +}
>> +
>> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
>> +{
>> +	long bsize;
>> +
>> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
>> +		return -EINVAL;
>> +
>> +	bsize = dirty_bitmap_bytes(npages);
>> +
>> +	if (bitmap_size < bsize)
>> +		return -EINVAL;
>> +
>> +	return bsize;
>> +}
> 
> Seems like this could simply return int, -errno or zero for success.
> The returned bsize is not used for anything else.
> 

ok.

>> +
>>   static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
>>   			     struct vfio_iommu_type1_dma_unmap *unmap)
>>   {
>> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
>>   
>>   		return copy_to_user((void __user *)arg, &unmap, minsz) ?
>>   			-EFAULT : 0;
>> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
>> +		struct vfio_iommu_type1_dirty_bitmap range;
>> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
>> +		int ret;
>> +
>> +		if (!iommu->v2)
>> +			return -EACCES;
>> +
>> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
>> +				    bitmap);
> 
> We require the user to provide iova, size, pgsize, bitmap_size, and
> bitmap fields to START/STOP?  Why?
>

No. But those are part of structure.

>> +
>> +		if (copy_from_user(&range, (void __user *)arg, minsz))
>> +			return -EFAULT;
>> +
>> +		if (range.argsz < minsz || range.flags & ~mask)
>> +			return -EINVAL;
>> +
>> +		/* only one flag should be set at a time */
>> +		if (__ffs(range.flags) != __fls(range.flags))
>> +			return -EINVAL;
>> +
>> +		if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
>> +			unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>> +
>> +			mutex_lock(&iommu->lock);
>> +			iommu->dirty_page_tracking = true;
>> +			ret = vfio_dma_all_bitmap_alloc(iommu, iommu_pgsizes);
> 
> So dirty page tracking is enabled even if we fail to allocate all the
> bitmaps?  Shouldn't this return an error if dirty tracking is already
> enabled?
> 

Adding error handling here in next patch.

>> +			mutex_unlock(&iommu->lock);
>> +			return ret;
>> +		} else if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
>> +			mutex_lock(&iommu->lock);
>> +			iommu->dirty_page_tracking = false;
> 
> Shouldn't we only allow STOP if tracking is enabled?
> 

Right,adding.

>> +			vfio_dma_all_bitmap_free(iommu);
> 
> Here's where that user induced double free enters the picture.
> 

Error handling as mentioned above will prevent double free.

Thanks,
Kirti

>> +			vfio_remove_unpinned_from_dma_list(iommu);
>> +			mutex_unlock(&iommu->lock);
>> +			return 0;
>> +		} else if (range.flags &
>> +				 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
>> +			long bsize;
>> +			unsigned long pgshift = __ffs(range.pgsize);
>> +			uint64_t iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>> +			uint64_t iommu_pgmask =
>> +				 ((uint64_t)1 << __ffs(iommu_pgsizes)) - 1;
>> +
>> +			if ((range.pgsize & iommu_pgsizes) != range.pgsize)
>> +				return -EINVAL;
>> +			if (range.iova & iommu_pgmask)
>> +				return -EINVAL;
>> +			if (!range.size || range.size & iommu_pgmask)
>> +				return -EINVAL;
>> +			if (range.iova + range.size < range.iova)
>> +				return -EINVAL;
>> +			if (!access_ok((void __user *)range.bitmap,
>> +				       range.bitmap_size))
>> +				return -EINVAL;
>> +
>> +			bsize = verify_bitmap_size(range.size >> pgshift,
>> +						   range.bitmap_size);
>> +			if (bsize < 0)
>> +				return bsize;
>> +
>> +			mutex_lock(&iommu->lock);
>> +			if (iommu->dirty_page_tracking)
>> +				ret = vfio_iova_dirty_bitmap(iommu, range.iova,
>> +					 range.size, range.pgsize,
>> +					 (unsigned char __user *)range.bitmap);
>> +			else
>> +				ret = -EINVAL;
>> +			mutex_unlock(&iommu->lock);
>> +
>> +			return ret;
>> +		}
>>   	}
>>   
>>   	return -ENOTTY;
> 
> Thanks,
> Alex
>
Alex Williamson Feb. 12, 2020, 11:13 p.m. UTC | #8
On Thu, 13 Feb 2020 02:26:23 +0530
Kirti Wankhede <kwankhede@nvidia.com> wrote:

> On 2/10/2020 10:55 PM, Alex Williamson wrote:
> > On Sat, 8 Feb 2020 01:12:31 +0530
> > Kirti Wankhede <kwankhede@nvidia.com> wrote:
> >   
> >> VFIO_IOMMU_DIRTY_PAGES ioctl performs three operations:
> >> - Start pinned and unpinned pages tracking while migration is active
> >> - Stop pinned and unpinned dirty pages tracking. This is also used to
> >>    stop dirty pages tracking if migration failed or cancelled.
> >> - Get dirty pages bitmap. This ioctl returns bitmap of dirty pages, its
> >>    user space application responsibility to copy content of dirty pages
> >>    from source to destination during migration.
> >>
> >> To prevent DoS attack, memory for bitmap is allocated per vfio_dma
> >> structure. Bitmap size is calculated considering smallest supported page
> >> size. Bitmap is allocated when dirty logging is enabled for those
> >> vfio_dmas whose vpfn list is not empty or whole range is mapped, in
> >> case of pass-through device.
> >>
> >> There could be multiple option as to when bitmap should be populated:
> >> * Polulate bitmap for already pinned pages when bitmap is allocated for
> >>    a vfio_dma with the smallest supported page size. Updates bitmap from
> >>    page pinning and unpinning functions. When user application queries
> >>    bitmap, check if requested page size is same as page size used to
> >>    populated bitmap. If it is equal, copy bitmap. But if not equal,
> >>    re-populated bitmap according to requested page size and then copy to
> >>    user.
> >>    Pros: Bitmap gets populated on the fly after dirty tracking has
> >>          started.
> >>    Cons: If requested page size is different than smallest supported
> >>          page size, then bitmap has to be re-populated again, with
> >>          additional overhead of allocating bitmap memory again for
> >>          re-population of bitmap.  
> > 
> > No memory needs to be allocated to re-populate the bitmap.  The bitmap
> > is clear-on-read and by tracking the bitmap in the smallest supported
> > page size we can guarantee that we can fit the user requested bitmap
> > size within the space occupied by that minimal page size range of the
> > bitmap.  Therefore we'd destructively translate the requested region of
> > the bitmap to a different page size, write it out to the user, and
> > clear it.  Also we expect userspace to use the minimum page size almost
> > exclusively, which is optimized by this approach as dirty bit tracking
> > is spread out over each page pinning operation.
> >   
> >>
> >> * Populate bitmap when bitmap is queried by user application.
> >>    Pros: Bitmap is populated with requested page size. This eliminates
> >>          the need to re-populate bitmap if requested page size is
> >>          different than smallest supported pages size.
> >>    Cons: There is one time processing time, when bitmap is queried.  
> > 
> > Another significant Con is that the vpfn list needs to track and manage
> > unpinned pages, which makes it more complex and intrusive.  The
> > previous option seems to have both time and complexity advantages,
> > especially in the case we expect to be most common of the user
> > accessing the bitmap with the minimum page size, ie. PAGE_SIZE.  It's
> > also not clear why we pre-allocate the bitmap at all with this approach.
> >   
> >> I prefer later option with simple logic and to eliminate over-head of
> >> bitmap repopulation in case of differnt page sizes. Later option is
> >> implemented in this patch.  
> > 
> > Hmm, we'll see below, but I not convinced based on the above rationale.
> >   
> >> Signed-off-by: Kirti Wankhede <kwankhede@nvidia.com>
> >> Reviewed-by: Neo Jia <cjia@nvidia.com>
> >> ---
> >>   drivers/vfio/vfio_iommu_type1.c | 299 ++++++++++++++++++++++++++++++++++++++--
> >>   1 file changed, 287 insertions(+), 12 deletions(-)
> >>
> >> diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
> >> index d386461e5d11..df358dc1c85b 100644
> >> --- a/drivers/vfio/vfio_iommu_type1.c
> >> +++ b/drivers/vfio/vfio_iommu_type1.c
> >> @@ -70,6 +70,7 @@ struct vfio_iommu {
> >>   	unsigned int		dma_avail;
> >>   	bool			v2;
> >>   	bool			nesting;
> >> +	bool			dirty_page_tracking;
> >>   };
> >>   
> >>   struct vfio_domain {
> >> @@ -90,6 +91,7 @@ struct vfio_dma {
> >>   	bool			lock_cap;	/* capable(CAP_IPC_LOCK) */
> >>   	struct task_struct	*task;
> >>   	struct rb_root		pfn_list;	/* Ex-user pinned pfn list */
> >> +	unsigned long		*bitmap;
> >>   };
> >>   
> >>   struct vfio_group {
> >> @@ -125,6 +127,7 @@ struct vfio_regions {
> >>   					(!list_empty(&iommu->domain_list))
> >>   
> >>   static int put_pfn(unsigned long pfn, int prot);
> >> +static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu);
> >>   
> >>   /*
> >>    * This code handles mapping and unmapping of user data buffers
> >> @@ -174,6 +177,57 @@ static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
> >>   	rb_erase(&old->node, &iommu->dma_list);
> >>   }
> >>   
> >> +static inline unsigned long dirty_bitmap_bytes(unsigned int npages)
> >> +{
> >> +	if (!npages)
> >> +		return 0;
> >> +
> >> +	return ALIGN(npages, BITS_PER_LONG) / sizeof(unsigned long);
> >> +}
> >> +
> >> +static int vfio_dma_bitmap_alloc(struct vfio_iommu *iommu,
> >> +				 struct vfio_dma *dma, unsigned long pgsizes)
> >> +{
> >> +	unsigned long pgshift = __ffs(pgsizes);
> >> +
> >> +	if (!RB_EMPTY_ROOT(&dma->pfn_list) || dma->iommu_mapped) {
> >> +		unsigned long npages = dma->size >> pgshift;
> >> +		unsigned long bsize = dirty_bitmap_bytes(npages);
> >> +
> >> +		dma->bitmap = kvzalloc(bsize, GFP_KERNEL);  
> > 
> > nit, we don't need to store bsize in a local variable.
> >   
> >> +		if (!dma->bitmap)
> >> +			return -ENOMEM;
> >> +	}
> >> +	return 0;
> >> +}
> >> +
> >> +static int vfio_dma_all_bitmap_alloc(struct vfio_iommu *iommu,
> >> +				     unsigned long pgsizes)
> >> +{
> >> +	struct rb_node *n = rb_first(&iommu->dma_list);
> >> +	int ret;
> >> +
> >> +	for (; n; n = rb_next(n)) {
> >> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> >> +
> >> +		ret = vfio_dma_bitmap_alloc(iommu, dma, pgsizes);
> >> +		if (ret)
> >> +			return ret;  
> > 
> > This doesn't unwind on failure, so we're left with partially allocated
> > bitmap cruft.
> >  
> 
> Good point. Adding unwind on failure.
> 
> >> +	}
> >> +	return 0;
> >> +}
> >> +
> >> +static void vfio_dma_all_bitmap_free(struct vfio_iommu *iommu)
> >> +{
> >> +	struct rb_node *n = rb_first(&iommu->dma_list);
> >> +
> >> +	for (; n; n = rb_next(n)) {
> >> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> >> +
> >> +		kfree(dma->bitmap);  
> > 
> > We don't set dma->bitmap = NULL and we don't even prevent the case of a
> > user making multiple STOP calls, so we have a user triggerable double
> > free :(
> >   
> 
> Ok.
> 
> >> +	}
> >> +}
> >> +
> >>   /*
> >>    * Helper Functions for host iova-pfn list
> >>    */
> >> @@ -244,6 +298,29 @@ static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
> >>   	kfree(vpfn);
> >>   }
> >>   
> >> +static void vfio_remove_unpinned_from_pfn_list(struct vfio_dma *dma)
> >> +{
> >> +	struct rb_node *n = rb_first(&dma->pfn_list);
> >> +
> >> +	for (; n; n = rb_next(n)) {
> >> +		struct vfio_pfn *vpfn = rb_entry(n, struct vfio_pfn, node);
> >> +
> >> +		if (!vpfn->ref_count)
> >> +			vfio_remove_from_pfn_list(dma, vpfn);
> >> +	}
> >> +}
> >> +
> >> +static void vfio_remove_unpinned_from_dma_list(struct vfio_iommu *iommu)
> >> +{
> >> +	struct rb_node *n = rb_first(&iommu->dma_list);
> >> +
> >> +	for (; n; n = rb_next(n)) {
> >> +		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
> >> +
> >> +		vfio_remove_unpinned_from_pfn_list(dma);
> >> +	}
> >> +}
> >> +
> >>   static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
> >>   					       unsigned long iova)
> >>   {
> >> @@ -261,7 +338,8 @@ static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
> >>   	vpfn->ref_count--;
> >>   	if (!vpfn->ref_count) {
> >>   		ret = put_pfn(vpfn->pfn, dma->prot);
> >> -		vfio_remove_from_pfn_list(dma, vpfn);
> >> +		if (!dma->bitmap)
> >> +			vfio_remove_from_pfn_list(dma, vpfn);
> >>   	}
> >>   	return ret;
> >>   }
> >> @@ -483,13 +561,14 @@ static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
> >>   	return ret;
> >>   }
> >>   
> >> -static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
> >> +static int vfio_unpin_page_external(struct vfio_iommu *iommu,  
> > 
> > We added a parameter but didn't use it in this patch.
> >   
> 
> Ok, Moving it to relevant patch.
> 
> >> +				    struct vfio_dma *dma, dma_addr_t iova,
> >>   				    bool do_accounting)
> >>   {
> >>   	int unlocked;
> >>   	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
> >>   
> >> -	if (!vpfn)
> >> +	if (!vpfn || !vpfn->ref_count)
> >>   		return 0;
> >>   
> >>   	unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
> >> @@ -510,6 +589,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
> >>   	unsigned long remote_vaddr;
> >>   	struct vfio_dma *dma;
> >>   	bool do_accounting;
> >> +	unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> >>   
> >>   	if (!iommu || !user_pfn || !phys_pfn)
> >>   		return -EINVAL;
> >> @@ -551,8 +631,10 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
> >>   
> >>   		vpfn = vfio_iova_get_vfio_pfn(dma, iova);
> >>   		if (vpfn) {
> >> -			phys_pfn[i] = vpfn->pfn;
> >> -			continue;
> >> +			if (vpfn->ref_count > 1) {
> >> +				phys_pfn[i] = vpfn->pfn;
> >> +				continue;
> >> +			}
> >>   		}
> >>   
> >>   		remote_vaddr = dma->vaddr + iova - dma->iova;
> >> @@ -560,11 +642,23 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
> >>   					     do_accounting);
> >>   		if (ret)
> >>   			goto pin_unwind;
> >> -
> >> -		ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
> >> -		if (ret) {
> >> -			vfio_unpin_page_external(dma, iova, do_accounting);
> >> -			goto pin_unwind;
> >> +		if (!vpfn) {
> >> +			ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
> >> +			if (ret) {
> >> +				vfio_unpin_page_external(iommu, dma, iova,
> >> +							 do_accounting);
> >> +				goto pin_unwind;
> >> +			}
> >> +		} else
> >> +			vpfn->pfn = phys_pfn[i];
> >> +
> >> +		if (iommu->dirty_page_tracking && !dma->bitmap) {
> >> +			ret = vfio_dma_bitmap_alloc(iommu, dma, iommu_pgsizes);
> >> +			if (ret) {
> >> +				vfio_unpin_page_external(iommu, dma, iova,
> >> +							 do_accounting);
> >> +				goto pin_unwind;
> >> +			}
> >>   		}
> >>   	}
> >>   
> >> @@ -578,7 +672,7 @@ static int vfio_iommu_type1_pin_pages(void *iommu_data,
> >>   
> >>   		iova = user_pfn[j] << PAGE_SHIFT;
> >>   		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
> >> -		vfio_unpin_page_external(dma, iova, do_accounting);
> >> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
> >>   		phys_pfn[j] = 0;
> >>   	}
> >>   pin_done:
> >> @@ -612,7 +706,7 @@ static int vfio_iommu_type1_unpin_pages(void *iommu_data,
> >>   		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
> >>   		if (!dma)
> >>   			goto unpin_exit;
> >> -		vfio_unpin_page_external(dma, iova, do_accounting);
> >> +		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
> >>   	}
> >>   
> >>   unpin_exit:
> >> @@ -830,6 +924,113 @@ static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
> >>   	return bitmap;
> >>   }
> >>   
> >> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> >> +				  size_t size, uint64_t pgsize,
> >> +				  unsigned char __user *bitmap)
> >> +{
> >> +	struct vfio_dma *dma;
> >> +	dma_addr_t i = iova, iova_limit;
> >> +	unsigned int bsize, nbits = 0, l = 0;
> >> +	unsigned long pgshift = __ffs(pgsize);
> >> +
> >> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> >> +		int ret, j;
> >> +		unsigned int npages = 0, shift = 0;
> >> +		unsigned char temp = 0;
> >> +
> >> +		/* mark all pages dirty if all pages are pinned and mapped. */
> >> +		if (dma->iommu_mapped) {
> >> +			iova_limit = min(dma->iova + dma->size, iova + size);
> >> +			npages = iova_limit/pgsize;
> >> +			bitmap_set(dma->bitmap, 0, npages);  
> > 
> > npages is derived from iova_limit, which is the number of bits to set
> > dirty relative to the first requested iova, not iova zero, ie. the set
> > of dirty bits is offset from those requested unless iova == dma->iova.
> >   
> 
> Right, fixing.
> 
> > Also I hope dma->bitmap was actually allocated.  Not only does the
> > START error path potentially leave dirty tracking enabled without all
> > the bitmap allocated, when does the bitmap get allocated for a new
> > vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
> > vpfn gets marked dirty.
> >   
> 
> Right.
> 
> Fixing error paths.
> 
> 
> >> +		} else if (dma->bitmap) {
> >> +			struct rb_node *n = rb_first(&dma->pfn_list);
> >> +			bool found = false;
> >> +
> >> +			for (; n; n = rb_next(n)) {
> >> +				struct vfio_pfn *vpfn = rb_entry(n,
> >> +						struct vfio_pfn, node);
> >> +				if (vpfn->iova >= i) {
> >> +					found = true;
> >> +					break;
> >> +				}
> >> +			}
> >> +
> >> +			if (!found) {
> >> +				i += dma->size;
> >> +				continue;
> >> +			}
> >> +
> >> +			for (; n; n = rb_next(n)) {
> >> +				unsigned int s;
> >> +				struct vfio_pfn *vpfn = rb_entry(n,
> >> +						struct vfio_pfn, node);
> >> +
> >> +				if (vpfn->iova >= iova + size)
> >> +					break;
> >> +
> >> +				s = (vpfn->iova - dma->iova) >> pgshift;
> >> +				bitmap_set(dma->bitmap, s, 1);
> >> +
> >> +				iova_limit = vpfn->iova + pgsize;
> >> +			}
> >> +			npages = iova_limit/pgsize;  
> > 
> > Isn't iova_limit potentially uninitialized here?  For example, if our
> > vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
> > there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
> > (4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
> > 4096 and break, and npages = ????/pgsize.
> >   
> 
> Right, Fixing it.
> 
> >> +		}
> >> +
> >> +		bsize = dirty_bitmap_bytes(npages);
> >> +		shift = nbits % BITS_PER_BYTE;
> >> +
> >> +		if (npages && shift) {
> >> +			l--;
> >> +			if (!access_ok((void __user *)bitmap + l,
> >> +					sizeof(unsigned char)))
> >> +				return -EINVAL;
> >> +
> >> +			ret = __get_user(temp, bitmap + l);  
> > 
> > I don't understand why we care to get the user's bitmap, are we trying
> > to leave whatever garbage they might have set in it and only also set
> > the dirty bits?  That seems unnecessary.
> >   
> 
> Suppose dma mapped ranges are {start, size}:
> {0, 0xa000}, {0xa000, 0x10000}
> 
> Bitmap asked from 0 - 0x10000. Say suppose all pages are dirty.
> Then in first iteration for dma {0,0xa000} there are 10 pages, so 10 
> bits are set, put_user() happens for 2 bytes, (00000011 11111111b).
> In second iteration for dma {0xa000, 0x10000} there are 6 pages and 
> these bits should be appended to previous byte. So get_user() that byte, 
> then shift-OR rest of the bitmap, result should be: (11111111 11111111b)
> 
> Without get_user() and shift-OR, resulting bitmap would be
> 111111 00000011 11111111b which would be wrong.

Seems like if we use a put_user() approach then we should look for
adjacent vfio_dmas within the same byte/word/dword before we push it to
the user to avoid this sort of inefficiency.

> > Also why do we need these access_ok() checks when we already checked
> > the range at the start of the ioctl?  
> 
> Since pointer is updated runtime here, better to check that pointer 
> before using that pointer.

Sorry, I still don't understand this, we check access_ok() with a
pointer and a length, therefore as long as we're incrementing the
pointer within that length, why do we need to retest?

> >   
> >> +			if (ret)
> >> +				return ret;
> >> +		}
> >> +
> >> +		for (j = 0; j < bsize; j++, l++) {
> >> +			temp = temp |
> >> +			       (*((unsigned char *)dma->bitmap + j) << shift);  
> > 
> > |=
> >   
> >> +			if (!access_ok((void __user *)bitmap + l,
> >> +					sizeof(unsigned char)))
> >> +				return -EINVAL;
> >> +
> >> +			ret = __put_user(temp, bitmap + l);
> >> +			if (ret)
> >> +				return ret;
> >> +			if (shift) {
> >> +				temp = *((unsigned char *)dma->bitmap + j) >>
> >> +					(BITS_PER_BYTE - shift);
> >> +			}  
> > 
> > When shift == 0, temp just seems to accumulate bits that never get
> > cleared.
> >   
> 
> Hope example above explains the shift logic.

But that example is when shift is non-zero.  When shift is zero, each
iteration of the loop just ORs in new bits to temp without ever
clearing the bits for the previous iteration.


> >> +		}
> >> +
> >> +		nbits += npages;
> >> +
> >> +		i = min(dma->iova + dma->size, iova + size);
> >> +		if (i >= iova + size)
> >> +			break;  
> > 
> > So whether we error or succeed, we leave cruft in dma->bitmap for the
> > next pass.  It doesn't seem to make any sense why we pre-allocated the
> > bitmap, we might as well just allocate it on demand here.  Actually, if
> > we're not going to do a copy_to_user() for some range of the bitmap,
> > I'm not sure what it's purpose is at all.  I think the big advantages
> > of the bitmap are that we can't amortize the cost across every pinned
> > page or DMA mapping, we don't need the overhead of tracking unmapped
> > vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
> > getting any of those advantages here.
> >   
> 
> That would still not work if dma range size is not multiples of 8 pages. 
> See example above.

I don't understand this comment, what about the example above justifies
the bitmap?  As I understand the above algorithm, we find a vfio_dma
overlapping the request and populate the bitmap for that range.  Then
we go back and put_user() for each byte that we touched.  We could
instead simply work on a one byte buffer as we enumerate the requested
range and do a put_user() ever time we reach the end of it and have bits
set.  That would greatly simplify the above example.  But I would expect
that we're a) more likely to get asked for ranges covering a single
vfio_dma and b) we're going to spend far more time operating in the
middle of the range and limiting ourselves to one-byte operations there
seems absurd.  If we want to specify that the user provides 4-byte
aligned buffers and naturally aligned iova ranges to make our lives
easier in the kernel, now would be the time to do that.

> >> +	}
> >> +	return 0;
> >> +}
> >> +
> >> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
> >> +{
> >> +	long bsize;
> >> +
> >> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
> >> +		return -EINVAL;
> >> +
> >> +	bsize = dirty_bitmap_bytes(npages);
> >> +
> >> +	if (bitmap_size < bsize)
> >> +		return -EINVAL;
> >> +
> >> +	return bsize;
> >> +}  
> > 
> > Seems like this could simply return int, -errno or zero for success.
> > The returned bsize is not used for anything else.
> >   
> 
> ok.
> 
> >> +
> >>   static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
> >>   			     struct vfio_iommu_type1_dma_unmap *unmap)
> >>   {
> >> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
> >>   
> >>   		return copy_to_user((void __user *)arg, &unmap, minsz) ?
> >>   			-EFAULT : 0;
> >> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
> >> +		struct vfio_iommu_type1_dirty_bitmap range;
> >> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
> >> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
> >> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
> >> +		int ret;
> >> +
> >> +		if (!iommu->v2)
> >> +			return -EACCES;
> >> +
> >> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
> >> +				    bitmap);  
> > 
> > We require the user to provide iova, size, pgsize, bitmap_size, and
> > bitmap fields to START/STOP?  Why?
> >  
> 
> No. But those are part of structure.

But we do require it, minsz here includes all those fields, which would
probably make a user scratch their head wondering why they need to pass
irrelevant data for START/STOP.  It almost implies that we support
starting and stopping dirty logging for specific ranges of the IOVA
space.  We could define the structure, for example:

struct vfio_iommu_type1_dirty_bitmap {
	__u32	argsz;
	__u32	flags;
	__u8	data[];
};

struct vfio_iommu_type1_dirty_bitmap_get {
	__u64	iova;
	__u64	size;
	__u64	pgsize;
	__u64	bitmap_size;
	void __user *bitmap;
};

Where data[] is defined as the latter structure when FLAG_GET_BITMAP is
specified.  BTW, don't we need to specify the trailing void* as __u64?
We could theoretically be talking to an ILP32 user process.  Thanks,

Alex

> >> +
> >> +		if (copy_from_user(&range, (void __user *)arg, minsz))
> >> +			return -EFAULT;
> >> +
> >> +		if (range.argsz < minsz || range.flags & ~mask)
> >> +			return -EINVAL;
> >> +
> >> +		/* only one flag should be set at a time */
> >> +		if (__ffs(range.flags) != __fls(range.flags))
> >> +			return -EINVAL;
> >> +
> >> +		if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
> >> +			unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> >> +
> >> +			mutex_lock(&iommu->lock);
> >> +			iommu->dirty_page_tracking = true;
> >> +			ret = vfio_dma_all_bitmap_alloc(iommu, iommu_pgsizes);  
> > 
> > So dirty page tracking is enabled even if we fail to allocate all the
> > bitmaps?  Shouldn't this return an error if dirty tracking is already
> > enabled?
> >   
> 
> Adding error handling here in next patch.
> 
> >> +			mutex_unlock(&iommu->lock);
> >> +			return ret;
> >> +		} else if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
> >> +			mutex_lock(&iommu->lock);
> >> +			iommu->dirty_page_tracking = false;  
> > 
> > Shouldn't we only allow STOP if tracking is enabled?
> >   
> 
> Right,adding.
> 
> >> +			vfio_dma_all_bitmap_free(iommu);  
> > 
> > Here's where that user induced double free enters the picture.
> >   
> 
> Error handling as mentioned above will prevent double free.
> 
> Thanks,
> Kirti
> 
> >> +			vfio_remove_unpinned_from_dma_list(iommu);
> >> +			mutex_unlock(&iommu->lock);
> >> +			return 0;
> >> +		} else if (range.flags &
> >> +				 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
> >> +			long bsize;
> >> +			unsigned long pgshift = __ffs(range.pgsize);
> >> +			uint64_t iommu_pgsizes = vfio_pgsize_bitmap(iommu);
> >> +			uint64_t iommu_pgmask =
> >> +				 ((uint64_t)1 << __ffs(iommu_pgsizes)) - 1;
> >> +
> >> +			if ((range.pgsize & iommu_pgsizes) != range.pgsize)
> >> +				return -EINVAL;
> >> +			if (range.iova & iommu_pgmask)
> >> +				return -EINVAL;
> >> +			if (!range.size || range.size & iommu_pgmask)
> >> +				return -EINVAL;
> >> +			if (range.iova + range.size < range.iova)
> >> +				return -EINVAL;
> >> +			if (!access_ok((void __user *)range.bitmap,
> >> +				       range.bitmap_size))
> >> +				return -EINVAL;
> >> +
> >> +			bsize = verify_bitmap_size(range.size >> pgshift,
> >> +						   range.bitmap_size);
> >> +			if (bsize < 0)
> >> +				return bsize;
> >> +
> >> +			mutex_lock(&iommu->lock);
> >> +			if (iommu->dirty_page_tracking)
> >> +				ret = vfio_iova_dirty_bitmap(iommu, range.iova,
> >> +					 range.size, range.pgsize,
> >> +					 (unsigned char __user *)range.bitmap);
> >> +			else
> >> +				ret = -EINVAL;
> >> +			mutex_unlock(&iommu->lock);
> >> +
> >> +			return ret;
> >> +		}
> >>   	}
> >>   
> >>   	return -ENOTTY;  
> > 
> > Thanks,
> > Alex
> >   
>
Kirti Wankhede Feb. 13, 2020, 8:11 p.m. UTC | #9
<snip>

>>>>    
>>>> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
>>>> +				  size_t size, uint64_t pgsize,
>>>> +				  unsigned char __user *bitmap)
>>>> +{
>>>> +	struct vfio_dma *dma;
>>>> +	dma_addr_t i = iova, iova_limit;
>>>> +	unsigned int bsize, nbits = 0, l = 0;
>>>> +	unsigned long pgshift = __ffs(pgsize);
>>>> +
>>>> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
>>>> +		int ret, j;
>>>> +		unsigned int npages = 0, shift = 0;
>>>> +		unsigned char temp = 0;
>>>> +
>>>> +		/* mark all pages dirty if all pages are pinned and mapped. */
>>>> +		if (dma->iommu_mapped) {
>>>> +			iova_limit = min(dma->iova + dma->size, iova + size);
>>>> +			npages = iova_limit/pgsize;
>>>> +			bitmap_set(dma->bitmap, 0, npages);
>>>
>>> npages is derived from iova_limit, which is the number of bits to set
>>> dirty relative to the first requested iova, not iova zero, ie. the set
>>> of dirty bits is offset from those requested unless iova == dma->iova.
>>>    
>>
>> Right, fixing.
>>
>>> Also I hope dma->bitmap was actually allocated.  Not only does the
>>> START error path potentially leave dirty tracking enabled without all
>>> the bitmap allocated, when does the bitmap get allocated for a new
>>> vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
>>> vpfn gets marked dirty.
>>>    
>>
>> Right.
>>
>> Fixing error paths.
>>
>>
>>>> +		} else if (dma->bitmap) {
>>>> +			struct rb_node *n = rb_first(&dma->pfn_list);
>>>> +			bool found = false;
>>>> +
>>>> +			for (; n; n = rb_next(n)) {
>>>> +				struct vfio_pfn *vpfn = rb_entry(n,
>>>> +						struct vfio_pfn, node);
>>>> +				if (vpfn->iova >= i) {
>>>> +					found = true;
>>>> +					break;
>>>> +				}
>>>> +			}
>>>> +
>>>> +			if (!found) {
>>>> +				i += dma->size;
>>>> +				continue;
>>>> +			}
>>>> +
>>>> +			for (; n; n = rb_next(n)) {
>>>> +				unsigned int s;
>>>> +				struct vfio_pfn *vpfn = rb_entry(n,
>>>> +						struct vfio_pfn, node);
>>>> +
>>>> +				if (vpfn->iova >= iova + size)
>>>> +					break;
>>>> +
>>>> +				s = (vpfn->iova - dma->iova) >> pgshift;
>>>> +				bitmap_set(dma->bitmap, s, 1);
>>>> +
>>>> +				iova_limit = vpfn->iova + pgsize;
>>>> +			}
>>>> +			npages = iova_limit/pgsize;
>>>
>>> Isn't iova_limit potentially uninitialized here?  For example, if our
>>> vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
>>> there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
>>> (4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
>>> 4096 and break, and npages = ????/pgsize.
>>>    
>>
>> Right, Fixing it.
>>
>>>> +		}
>>>> +
>>>> +		bsize = dirty_bitmap_bytes(npages);
>>>> +		shift = nbits % BITS_PER_BYTE;
>>>> +
>>>> +		if (npages && shift) {
>>>> +			l--;
>>>> +			if (!access_ok((void __user *)bitmap + l,
>>>> +					sizeof(unsigned char)))
>>>> +				return -EINVAL;
>>>> +
>>>> +			ret = __get_user(temp, bitmap + l);
>>>
>>> I don't understand why we care to get the user's bitmap, are we trying
>>> to leave whatever garbage they might have set in it and only also set
>>> the dirty bits?  That seems unnecessary.
>>>    
>>
>> Suppose dma mapped ranges are {start, size}:
>> {0, 0xa000}, {0xa000, 0x10000}
>>
>> Bitmap asked from 0 - 0x10000. Say suppose all pages are dirty.
>> Then in first iteration for dma {0,0xa000} there are 10 pages, so 10
>> bits are set, put_user() happens for 2 bytes, (00000011 11111111b).
>> In second iteration for dma {0xa000, 0x10000} there are 6 pages and
>> these bits should be appended to previous byte. So get_user() that byte,
>> then shift-OR rest of the bitmap, result should be: (11111111 11111111b)
>>
>> Without get_user() and shift-OR, resulting bitmap would be
>> 111111 00000011 11111111b which would be wrong.
> 
> Seems like if we use a put_user() approach then we should look for
> adjacent vfio_dmas within the same byte/word/dword before we push it to
> the user to avoid this sort of inefficiency.
> 

Won't that add more complication to logic?

>>> Also why do we need these access_ok() checks when we already checked
>>> the range at the start of the ioctl?
>>
>> Since pointer is updated runtime here, better to check that pointer
>> before using that pointer.
> 
> Sorry, I still don't understand this, we check access_ok() with a
> pointer and a length, therefore as long as we're incrementing the
> pointer within that length, why do we need to retest?
> 

Ideally caller for put_user() and get_user() must check the pointer with 
access_ok() which is used as argument to these functions before calling 
this function. That makes sure that pointer is correct after pointer 
arithematic. May be lets remove previous check of pointer and length, 
but keep these checks.

>>>    
>>>> +			if (ret)
>>>> +				return ret;
>>>> +		}
>>>> +
>>>> +		for (j = 0; j < bsize; j++, l++) {
>>>> +			temp = temp |
>>>> +			       (*((unsigned char *)dma->bitmap + j) << shift);
>>>
>>> |=
>>>    
>>>> +			if (!access_ok((void __user *)bitmap + l,
>>>> +					sizeof(unsigned char)))
>>>> +				return -EINVAL;
>>>> +
>>>> +			ret = __put_user(temp, bitmap + l);
>>>> +			if (ret)
>>>> +				return ret;
>>>> +			if (shift) {
>>>> +				temp = *((unsigned char *)dma->bitmap + j) >>
>>>> +					(BITS_PER_BYTE - shift);
>>>> +			}
>>>
>>> When shift == 0, temp just seems to accumulate bits that never get
>>> cleared.
>>>    
>>
>> Hope example above explains the shift logic.
> 
> But that example is when shift is non-zero.  When shift is zero, each
> iteration of the loop just ORs in new bits to temp without ever
> clearing the bits for the previous iteration.
> 
> 

Oh right, fixing it.

>>>> +		}
>>>> +
>>>> +		nbits += npages;
>>>> +
>>>> +		i = min(dma->iova + dma->size, iova + size);
>>>> +		if (i >= iova + size)
>>>> +			break;
>>>
>>> So whether we error or succeed, we leave cruft in dma->bitmap for the
>>> next pass.  It doesn't seem to make any sense why we pre-allocated the
>>> bitmap, we might as well just allocate it on demand here.  Actually, if
>>> we're not going to do a copy_to_user() for some range of the bitmap,
>>> I'm not sure what it's purpose is at all.  I think the big advantages
>>> of the bitmap are that we can't amortize the cost across every pinned
>>> page or DMA mapping, we don't need the overhead of tracking unmapped
>>> vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
>>> getting any of those advantages here.
>>>    
>>
>> That would still not work if dma range size is not multiples of 8 pages.
>> See example above.
> 
> I don't understand this comment, what about the example above justifies
> the bitmap?

copy_to_user() could be used if dma range size is not multiple of 8 pages.

>  As I understand the above algorithm, we find a vfio_dma
> overlapping the request and populate the bitmap for that range.  Then
> we go back and put_user() for each byte that we touched.  We could
> instead simply work on a one byte buffer as we enumerate the requested
> range and do a put_user() ever time we reach the end of it and have bits
> set. That would greatly simplify the above example.  But I would expect > that we're a) more likely to get asked for ranges covering a single
> vfio_dma 

QEMU ask for single vfio_dma during each iteration.

If we restrict this ABI to cover single vfio_dma only, then it 
simplifies the logic here. That was my original suggestion. Should we 
think about that again?

> and b) we're going to spend far more time operating in the
> middle of the range and limiting ourselves to one-byte operations there
> seems absurd.  If we want to specify that the user provides 4-byte
> aligned buffers and naturally aligned iova ranges to make our lives
> easier in the kernel, now would be the time to do that.
> 
>>>> +	}
>>>> +	return 0;
>>>> +}
>>>> +
>>>> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
>>>> +{
>>>> +	long bsize;
>>>> +
>>>> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
>>>> +		return -EINVAL;
>>>> +
>>>> +	bsize = dirty_bitmap_bytes(npages);
>>>> +
>>>> +	if (bitmap_size < bsize)
>>>> +		return -EINVAL;
>>>> +
>>>> +	return bsize;
>>>> +}
>>>
>>> Seems like this could simply return int, -errno or zero for success.
>>> The returned bsize is not used for anything else.
>>>    
>>
>> ok.
>>
>>>> +
>>>>    static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
>>>>    			     struct vfio_iommu_type1_dma_unmap *unmap)
>>>>    {
>>>> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
>>>>    
>>>>    		return copy_to_user((void __user *)arg, &unmap, minsz) ?
>>>>    			-EFAULT : 0;
>>>> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
>>>> +		struct vfio_iommu_type1_dirty_bitmap range;
>>>> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
>>>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
>>>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
>>>> +		int ret;
>>>> +
>>>> +		if (!iommu->v2)
>>>> +			return -EACCES;
>>>> +
>>>> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
>>>> +				    bitmap);
>>>
>>> We require the user to provide iova, size, pgsize, bitmap_size, and
>>> bitmap fields to START/STOP?  Why?
>>>   
>>
>> No. But those are part of structure.
> 
> But we do require it, minsz here includes all those fields, which would
> probably make a user scratch their head wondering why they need to pass
> irrelevant data for START/STOP.  It almost implies that we support
> starting and stopping dirty logging for specific ranges of the IOVA
> space.  We could define the structure, for example:
> 
> struct vfio_iommu_type1_dirty_bitmap {
> 	__u32	argsz;
> 	__u32	flags;
> 	__u8	data[];
> };
> 
> struct vfio_iommu_type1_dirty_bitmap_get {
> 	__u64	iova;
> 	__u64	size;
> 	__u64	pgsize;
> 	__u64	bitmap_size;
> 	void __user *bitmap;
> };
> 
> Where data[] is defined as the latter structure when FLAG_GET_BITMAP is
> specified.

Ok. Changing as above.

>  BTW, don't we need to specify the trailing void* as __u64?
> We could theoretically be talking to an ILP32 user process.  Thanks,
> 

Even on ILP32, using void* pointer will reserve the size required to 
save a pointer address. I don't think using void* should be problem.

Thanks,
Kirti


> Alex
> 
>>>> +
>>>> +		if (copy_from_user(&range, (void __user *)arg, minsz))
>>>> +			return -EFAULT;
>>>> +
>>>> +		if (range.argsz < minsz || range.flags & ~mask)
>>>> +			return -EINVAL;
>>>> +
>>>> +		/* only one flag should be set at a time */
>>>> +		if (__ffs(range.flags) != __fls(range.flags))
>>>> +			return -EINVAL;
>>>> +
>>>> +		if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
>>>> +			unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>>>> +
>>>> +			mutex_lock(&iommu->lock);
>>>> +			iommu->dirty_page_tracking = true;
>>>> +			ret = vfio_dma_all_bitmap_alloc(iommu, iommu_pgsizes);
>>>
>>> So dirty page tracking is enabled even if we fail to allocate all the
>>> bitmaps?  Shouldn't this return an error if dirty tracking is already
>>> enabled?
>>>    
>>
>> Adding error handling here in next patch.
>>
>>>> +			mutex_unlock(&iommu->lock);
>>>> +			return ret;
>>>> +		} else if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
>>>> +			mutex_lock(&iommu->lock);
>>>> +			iommu->dirty_page_tracking = false;
>>>
>>> Shouldn't we only allow STOP if tracking is enabled?
>>>    
>>
>> Right,adding.
>>
>>>> +			vfio_dma_all_bitmap_free(iommu);
>>>
>>> Here's where that user induced double free enters the picture.
>>>    
>>
>> Error handling as mentioned above will prevent double free.
>>
>> Thanks,
>> Kirti
>>
>>>> +			vfio_remove_unpinned_from_dma_list(iommu);
>>>> +			mutex_unlock(&iommu->lock);
>>>> +			return 0;
>>>> +		} else if (range.flags &
>>>> +				 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
>>>> +			long bsize;
>>>> +			unsigned long pgshift = __ffs(range.pgsize);
>>>> +			uint64_t iommu_pgsizes = vfio_pgsize_bitmap(iommu);
>>>> +			uint64_t iommu_pgmask =
>>>> +				 ((uint64_t)1 << __ffs(iommu_pgsizes)) - 1;
>>>> +
>>>> +			if ((range.pgsize & iommu_pgsizes) != range.pgsize)
>>>> +				return -EINVAL;
>>>> +			if (range.iova & iommu_pgmask)
>>>> +				return -EINVAL;
>>>> +			if (!range.size || range.size & iommu_pgmask)
>>>> +				return -EINVAL;
>>>> +			if (range.iova + range.size < range.iova)
>>>> +				return -EINVAL;
>>>> +			if (!access_ok((void __user *)range.bitmap,
>>>> +				       range.bitmap_size))
>>>> +				return -EINVAL;
>>>> +
>>>> +			bsize = verify_bitmap_size(range.size >> pgshift,
>>>> +						   range.bitmap_size);
>>>> +			if (bsize < 0)
>>>> +				return bsize;
>>>> +
>>>> +			mutex_lock(&iommu->lock);
>>>> +			if (iommu->dirty_page_tracking)
>>>> +				ret = vfio_iova_dirty_bitmap(iommu, range.iova,
>>>> +					 range.size, range.pgsize,
>>>> +					 (unsigned char __user *)range.bitmap);
>>>> +			else
>>>> +				ret = -EINVAL;
>>>> +			mutex_unlock(&iommu->lock);
>>>> +
>>>> +			return ret;
>>>> +		}
>>>>    	}
>>>>    
>>>>    	return -ENOTTY;
>>>
>>> Thanks,
>>> Alex
>>>    
>>
>
Alex Williamson Feb. 13, 2020, 11:20 p.m. UTC | #10
On Fri, 14 Feb 2020 01:41:35 +0530
Kirti Wankhede <kwankhede@nvidia.com> wrote:

> <snip>
> 
> >>>>    
> >>>> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> >>>> +				  size_t size, uint64_t pgsize,
> >>>> +				  unsigned char __user *bitmap)
> >>>> +{
> >>>> +	struct vfio_dma *dma;
> >>>> +	dma_addr_t i = iova, iova_limit;
> >>>> +	unsigned int bsize, nbits = 0, l = 0;
> >>>> +	unsigned long pgshift = __ffs(pgsize);
> >>>> +
> >>>> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> >>>> +		int ret, j;
> >>>> +		unsigned int npages = 0, shift = 0;
> >>>> +		unsigned char temp = 0;
> >>>> +
> >>>> +		/* mark all pages dirty if all pages are pinned and mapped. */
> >>>> +		if (dma->iommu_mapped) {
> >>>> +			iova_limit = min(dma->iova + dma->size, iova + size);
> >>>> +			npages = iova_limit/pgsize;
> >>>> +			bitmap_set(dma->bitmap, 0, npages);  
> >>>
> >>> npages is derived from iova_limit, which is the number of bits to set
> >>> dirty relative to the first requested iova, not iova zero, ie. the set
> >>> of dirty bits is offset from those requested unless iova == dma->iova.
> >>>      
> >>
> >> Right, fixing.
> >>  
> >>> Also I hope dma->bitmap was actually allocated.  Not only does the
> >>> START error path potentially leave dirty tracking enabled without all
> >>> the bitmap allocated, when does the bitmap get allocated for a new
> >>> vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
> >>> vpfn gets marked dirty.
> >>>      
> >>
> >> Right.
> >>
> >> Fixing error paths.
> >>
> >>  
> >>>> +		} else if (dma->bitmap) {
> >>>> +			struct rb_node *n = rb_first(&dma->pfn_list);
> >>>> +			bool found = false;
> >>>> +
> >>>> +			for (; n; n = rb_next(n)) {
> >>>> +				struct vfio_pfn *vpfn = rb_entry(n,
> >>>> +						struct vfio_pfn, node);
> >>>> +				if (vpfn->iova >= i) {
> >>>> +					found = true;
> >>>> +					break;
> >>>> +				}
> >>>> +			}
> >>>> +
> >>>> +			if (!found) {
> >>>> +				i += dma->size;
> >>>> +				continue;
> >>>> +			}
> >>>> +
> >>>> +			for (; n; n = rb_next(n)) {
> >>>> +				unsigned int s;
> >>>> +				struct vfio_pfn *vpfn = rb_entry(n,
> >>>> +						struct vfio_pfn, node);
> >>>> +
> >>>> +				if (vpfn->iova >= iova + size)
> >>>> +					break;
> >>>> +
> >>>> +				s = (vpfn->iova - dma->iova) >> pgshift;
> >>>> +				bitmap_set(dma->bitmap, s, 1);
> >>>> +
> >>>> +				iova_limit = vpfn->iova + pgsize;
> >>>> +			}
> >>>> +			npages = iova_limit/pgsize;  
> >>>
> >>> Isn't iova_limit potentially uninitialized here?  For example, if our
> >>> vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
> >>> there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
> >>> (4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
> >>> 4096 and break, and npages = ????/pgsize.
> >>>      
> >>
> >> Right, Fixing it.
> >>  
> >>>> +		}
> >>>> +
> >>>> +		bsize = dirty_bitmap_bytes(npages);
> >>>> +		shift = nbits % BITS_PER_BYTE;
> >>>> +
> >>>> +		if (npages && shift) {
> >>>> +			l--;
> >>>> +			if (!access_ok((void __user *)bitmap + l,
> >>>> +					sizeof(unsigned char)))
> >>>> +				return -EINVAL;
> >>>> +
> >>>> +			ret = __get_user(temp, bitmap + l);  
> >>>
> >>> I don't understand why we care to get the user's bitmap, are we trying
> >>> to leave whatever garbage they might have set in it and only also set
> >>> the dirty bits?  That seems unnecessary.
> >>>      
> >>
> >> Suppose dma mapped ranges are {start, size}:
> >> {0, 0xa000}, {0xa000, 0x10000}
> >>
> >> Bitmap asked from 0 - 0x10000. Say suppose all pages are dirty.
> >> Then in first iteration for dma {0,0xa000} there are 10 pages, so 10
> >> bits are set, put_user() happens for 2 bytes, (00000011 11111111b).
> >> In second iteration for dma {0xa000, 0x10000} there are 6 pages and
> >> these bits should be appended to previous byte. So get_user() that byte,
> >> then shift-OR rest of the bitmap, result should be: (11111111 11111111b)
> >>
> >> Without get_user() and shift-OR, resulting bitmap would be
> >> 111111 00000011 11111111b which would be wrong.  
> > 
> > Seems like if we use a put_user() approach then we should look for
> > adjacent vfio_dmas within the same byte/word/dword before we push it to
> > the user to avoid this sort of inefficiency.
> >   
> 
> Won't that add more complication to logic?

I'm tempted to think it might be less complicated.
 
> >>> Also why do we need these access_ok() checks when we already checked
> >>> the range at the start of the ioctl?  
> >>
> >> Since pointer is updated runtime here, better to check that pointer
> >> before using that pointer.  
> > 
> > Sorry, I still don't understand this, we check access_ok() with a
> > pointer and a length, therefore as long as we're incrementing the
> > pointer within that length, why do we need to retest?
> >   
> 
> Ideally caller for put_user() and get_user() must check the pointer with 
> access_ok() which is used as argument to these functions before calling 
> this function. That makes sure that pointer is correct after pointer 
> arithematic. May be lets remove previous check of pointer and length, 
> but keep these checks.

So we don't trust that we can increment a pointer within a range that
we've already tested with access_ok() and expect it to still be ok?  I
think the point of having access_ok() and __put_user() is that we can
batch many __put_user() calls under a single access_ok() check.  I
don't see any justification here why if we already tested
access_ok(ptr, 2) that we still need to test access_ok(ptr + 0, 1) and
access_ok(ptr + 1, 1), and removing the initial test is clearly the
wrong optimization if we agree there is redundancy here.	

> >>>> +			if (ret)
> >>>> +				return ret;
> >>>> +		}
> >>>> +
> >>>> +		for (j = 0; j < bsize; j++, l++) {
> >>>> +			temp = temp |
> >>>> +			       (*((unsigned char *)dma->bitmap + j) << shift);  
> >>>
> >>> |=
> >>>      
> >>>> +			if (!access_ok((void __user *)bitmap + l,
> >>>> +					sizeof(unsigned char)))
> >>>> +				return -EINVAL;
> >>>> +
> >>>> +			ret = __put_user(temp, bitmap + l);
> >>>> +			if (ret)
> >>>> +				return ret;
> >>>> +			if (shift) {
> >>>> +				temp = *((unsigned char *)dma->bitmap + j) >>
> >>>> +					(BITS_PER_BYTE - shift);
> >>>> +			}  
> >>>
> >>> When shift == 0, temp just seems to accumulate bits that never get
> >>> cleared.
> >>>      
> >>
> >> Hope example above explains the shift logic.  
> > 
> > But that example is when shift is non-zero.  When shift is zero, each
> > iteration of the loop just ORs in new bits to temp without ever
> > clearing the bits for the previous iteration.
> > 
> >   
> 
> Oh right, fixing it.
> 
> >>>> +		}
> >>>> +
> >>>> +		nbits += npages;
> >>>> +
> >>>> +		i = min(dma->iova + dma->size, iova + size);
> >>>> +		if (i >= iova + size)
> >>>> +			break;  
> >>>
> >>> So whether we error or succeed, we leave cruft in dma->bitmap for the
> >>> next pass.  It doesn't seem to make any sense why we pre-allocated the
> >>> bitmap, we might as well just allocate it on demand here.  Actually, if
> >>> we're not going to do a copy_to_user() for some range of the bitmap,
> >>> I'm not sure what it's purpose is at all.  I think the big advantages
> >>> of the bitmap are that we can't amortize the cost across every pinned
> >>> page or DMA mapping, we don't need the overhead of tracking unmapped
> >>> vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
> >>> getting any of those advantages here.
> >>>      
> >>
> >> That would still not work if dma range size is not multiples of 8 pages.
> >> See example above.  
> > 
> > I don't understand this comment, what about the example above justifies
> > the bitmap?  
> 
> copy_to_user() could be used if dma range size is not multiple of 8 pages.

s/is not/is/ ?

And we expect that to be a far more common case, right?  I don't think
there are too many ranges for a guest that are only mapped in sub-32KB
chucks.
 
> >  As I understand the above algorithm, we find a vfio_dma
> > overlapping the request and populate the bitmap for that range.  Then
> > we go back and put_user() for each byte that we touched.  We could
> > instead simply work on a one byte buffer as we enumerate the requested
> > range and do a put_user() ever time we reach the end of it and have bits
> > set. That would greatly simplify the above example.  But I would expect
> > that we're a) more likely to get asked for ranges covering a single
> > vfio_dma   
> 
> QEMU ask for single vfio_dma during each iteration.
> 
> If we restrict this ABI to cover single vfio_dma only, then it 
> simplifies the logic here. That was my original suggestion. Should we 
> think about that again?

But we currently allow unmaps that overlap multiple vfio_dmas as long
as no vfio_dma is bisected, so I think that implies that an unmap while
asking for the dirty bitmap has even further restricted semantics.  I'm
also reluctant to design an ABI around what happens to be the current
QEMU implementation.

If we take your example above, ranges {0x0000,0xa000} and
{0xa000,0x10000} ({start,end}), I think you're working with the
following two bitmaps in this implementation:

00000011 11111111b
00111111b

And we need to combine those into:

11111111 11111111b

Right?

But it seems like that would be easier if the second bitmap was instead:

11111100b

Then we wouldn't need to worry about the entire bitmap being shifted by
the bit offset within the byte, which limits our fixes to the boundary
byte and allows us to use copy_to_user() directly for the bulk of the
copy.  So how do we get there?

I think we start with allocating the vfio_dma bitmap to account for
this initial offset, so we calculate bitmap_base_iova as:
  (iova & ~((PAGE_SIZE << 3) - 1))
We then use bitmap_base_iova in calculating which bits to set.

The user needs to follow the same rules, and maybe this adds some value
to the user providing the bitmap size rather than the kernel
calculating it.  For example, if the user wanted the dirty bitmap for
the range {0xa000,0x10000} above, they'd provide at least a 1 byte
bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.

Effectively the user can ask for any iova range, but the buffer will be
filled relative to the zeroth bit of the bitmap following the above
bitmap_base_iova formula (and replacing PAGE_SIZE with the user
requested pgsize).  I'm tempted to make this explicit in the user
interface (ie. only allow bitmaps starting on aligned pages), but a
user is able to map and unmap single pages and we need to support
returning a dirty bitmap with an unmap, so I don't think we can do that.

So now are we biting off more than we can chew trying to transpose the
bitmap between page sizes?  If asked for the previous range with an 8K
pgsize, we'd somehow need to translate 11111100b into 00001110b.
What's worse, the user could ask for just the 8K page at 0xa000 and we'd
need to return back 00000010b while leaving our internal bitmap a
11110000b after we mark the bits clean.  Seems like this is really
only tenable if we do multiples of PAGE_SIZE pages within a byte, so
for 4K we'd have 32K, 64K, 128K, 256K, etc.  I'm somewhat losing sight
on what this accomplishes though and whether we need this in the first
implementation.  Should we simplify by dropping this aspect of it,
supporting only the minimum iommu page size, and focus on actually
using the bitmaps effectively?
 
> > and b) we're going to spend far more time operating in the
> > middle of the range and limiting ourselves to one-byte operations there
> > seems absurd.  If we want to specify that the user provides 4-byte
> > aligned buffers and naturally aligned iova ranges to make our lives
> > easier in the kernel, now would be the time to do that.
> >   
> >>>> +	}
> >>>> +	return 0;
> >>>> +}
> >>>> +
> >>>> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
> >>>> +{
> >>>> +	long bsize;
> >>>> +
> >>>> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
> >>>> +		return -EINVAL;
> >>>> +
> >>>> +	bsize = dirty_bitmap_bytes(npages);
> >>>> +
> >>>> +	if (bitmap_size < bsize)
> >>>> +		return -EINVAL;
> >>>> +
> >>>> +	return bsize;
> >>>> +}  
> >>>
> >>> Seems like this could simply return int, -errno or zero for success.
> >>> The returned bsize is not used for anything else.
> >>>      
> >>
> >> ok.
> >>  
> >>>> +
> >>>>    static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
> >>>>    			     struct vfio_iommu_type1_dma_unmap *unmap)
> >>>>    {
> >>>> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
> >>>>    
> >>>>    		return copy_to_user((void __user *)arg, &unmap, minsz) ?
> >>>>    			-EFAULT : 0;
> >>>> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
> >>>> +		struct vfio_iommu_type1_dirty_bitmap range;
> >>>> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
> >>>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
> >>>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
> >>>> +		int ret;
> >>>> +
> >>>> +		if (!iommu->v2)
> >>>> +			return -EACCES;
> >>>> +
> >>>> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
> >>>> +				    bitmap);  
> >>>
> >>> We require the user to provide iova, size, pgsize, bitmap_size, and
> >>> bitmap fields to START/STOP?  Why?
> >>>     
> >>
> >> No. But those are part of structure.  
> > 
> > But we do require it, minsz here includes all those fields, which would
> > probably make a user scratch their head wondering why they need to pass
> > irrelevant data for START/STOP.  It almost implies that we support
> > starting and stopping dirty logging for specific ranges of the IOVA
> > space.  We could define the structure, for example:
> > 
> > struct vfio_iommu_type1_dirty_bitmap {
> > 	__u32	argsz;
> > 	__u32	flags;
> > 	__u8	data[];
> > };
> > 
> > struct vfio_iommu_type1_dirty_bitmap_get {
> > 	__u64	iova;
> > 	__u64	size;
> > 	__u64	pgsize;
> > 	__u64	bitmap_size;
> > 	void __user *bitmap;
> > };
> > 
> > Where data[] is defined as the latter structure when FLAG_GET_BITMAP is
> > specified.  
> 
> Ok. Changing as above.
> 
> >  BTW, don't we need to specify the trailing void* as __u64?
> > We could theoretically be talking to an ILP32 user process.  Thanks,
> >   
> 
> Even on ILP32, using void* pointer will reserve the size required to 
> save a pointer address. I don't think using void* should be problem.

I think you're still assuming sizeof(void *) is the same in kernel vs
userspace whereas I'm thinking about an ILP32 user running on an LP64
kernel.  Thanks,

Alex
Kirti Wankhede Feb. 17, 2020, 7:13 p.m. UTC | #11
On 2/14/2020 4:50 AM, Alex Williamson wrote:
> On Fri, 14 Feb 2020 01:41:35 +0530
> Kirti Wankhede <kwankhede@nvidia.com> wrote:
> 
>> <snip>
>>
>>>>>>     
>>>>>> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
>>>>>> +				  size_t size, uint64_t pgsize,
>>>>>> +				  unsigned char __user *bitmap)
>>>>>> +{
>>>>>> +	struct vfio_dma *dma;
>>>>>> +	dma_addr_t i = iova, iova_limit;
>>>>>> +	unsigned int bsize, nbits = 0, l = 0;
>>>>>> +	unsigned long pgshift = __ffs(pgsize);
>>>>>> +
>>>>>> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
>>>>>> +		int ret, j;
>>>>>> +		unsigned int npages = 0, shift = 0;
>>>>>> +		unsigned char temp = 0;
>>>>>> +
>>>>>> +		/* mark all pages dirty if all pages are pinned and mapped. */
>>>>>> +		if (dma->iommu_mapped) {
>>>>>> +			iova_limit = min(dma->iova + dma->size, iova + size);
>>>>>> +			npages = iova_limit/pgsize;
>>>>>> +			bitmap_set(dma->bitmap, 0, npages);
>>>>>
>>>>> npages is derived from iova_limit, which is the number of bits to set
>>>>> dirty relative to the first requested iova, not iova zero, ie. the set
>>>>> of dirty bits is offset from those requested unless iova == dma->iova.
>>>>>       
>>>>
>>>> Right, fixing.
>>>>   
>>>>> Also I hope dma->bitmap was actually allocated.  Not only does the
>>>>> START error path potentially leave dirty tracking enabled without all
>>>>> the bitmap allocated, when does the bitmap get allocated for a new
>>>>> vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
>>>>> vpfn gets marked dirty.
>>>>>       
>>>>
>>>> Right.
>>>>
>>>> Fixing error paths.
>>>>
>>>>   
>>>>>> +		} else if (dma->bitmap) {
>>>>>> +			struct rb_node *n = rb_first(&dma->pfn_list);
>>>>>> +			bool found = false;
>>>>>> +
>>>>>> +			for (; n; n = rb_next(n)) {
>>>>>> +				struct vfio_pfn *vpfn = rb_entry(n,
>>>>>> +						struct vfio_pfn, node);
>>>>>> +				if (vpfn->iova >= i) {
>>>>>> +					found = true;
>>>>>> +					break;
>>>>>> +				}
>>>>>> +			}
>>>>>> +
>>>>>> +			if (!found) {
>>>>>> +				i += dma->size;
>>>>>> +				continue;
>>>>>> +			}
>>>>>> +
>>>>>> +			for (; n; n = rb_next(n)) {
>>>>>> +				unsigned int s;
>>>>>> +				struct vfio_pfn *vpfn = rb_entry(n,
>>>>>> +						struct vfio_pfn, node);
>>>>>> +
>>>>>> +				if (vpfn->iova >= iova + size)
>>>>>> +					break;
>>>>>> +
>>>>>> +				s = (vpfn->iova - dma->iova) >> pgshift;
>>>>>> +				bitmap_set(dma->bitmap, s, 1);
>>>>>> +
>>>>>> +				iova_limit = vpfn->iova + pgsize;
>>>>>> +			}
>>>>>> +			npages = iova_limit/pgsize;
>>>>>
>>>>> Isn't iova_limit potentially uninitialized here?  For example, if our
>>>>> vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
>>>>> there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
>>>>> (4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
>>>>> 4096 and break, and npages = ????/pgsize.
>>>>>       
>>>>
>>>> Right, Fixing it.
>>>>   
>>>>>> +		}
>>>>>> +
>>>>>> +		bsize = dirty_bitmap_bytes(npages);
>>>>>> +		shift = nbits % BITS_PER_BYTE;
>>>>>> +
>>>>>> +		if (npages && shift) {
>>>>>> +			l--;
>>>>>> +			if (!access_ok((void __user *)bitmap + l,
>>>>>> +					sizeof(unsigned char)))
>>>>>> +				return -EINVAL;
>>>>>> +
>>>>>> +			ret = __get_user(temp, bitmap + l);
>>>>>
>>>>> I don't understand why we care to get the user's bitmap, are we trying
>>>>> to leave whatever garbage they might have set in it and only also set
>>>>> the dirty bits?  That seems unnecessary.
>>>>>       
>>>>
>>>> Suppose dma mapped ranges are {start, size}:
>>>> {0, 0xa000}, {0xa000, 0x10000}
>>>>
>>>> Bitmap asked from 0 - 0x10000. Say suppose all pages are dirty.
>>>> Then in first iteration for dma {0,0xa000} there are 10 pages, so 10
>>>> bits are set, put_user() happens for 2 bytes, (00000011 11111111b).
>>>> In second iteration for dma {0xa000, 0x10000} there are 6 pages and
>>>> these bits should be appended to previous byte. So get_user() that byte,
>>>> then shift-OR rest of the bitmap, result should be: (11111111 11111111b)
>>>>
>>>> Without get_user() and shift-OR, resulting bitmap would be
>>>> 111111 00000011 11111111b which would be wrong.
>>>
>>> Seems like if we use a put_user() approach then we should look for
>>> adjacent vfio_dmas within the same byte/word/dword before we push it to
>>> the user to avoid this sort of inefficiency.
>>>    
>>
>> Won't that add more complication to logic?
> 
> I'm tempted to think it might be less complicated.
>   
>>>>> Also why do we need these access_ok() checks when we already checked
>>>>> the range at the start of the ioctl?
>>>>
>>>> Since pointer is updated runtime here, better to check that pointer
>>>> before using that pointer.
>>>
>>> Sorry, I still don't understand this, we check access_ok() with a
>>> pointer and a length, therefore as long as we're incrementing the
>>> pointer within that length, why do we need to retest?
>>>    
>>
>> Ideally caller for put_user() and get_user() must check the pointer with
>> access_ok() which is used as argument to these functions before calling
>> this function. That makes sure that pointer is correct after pointer
>> arithematic. May be lets remove previous check of pointer and length,
>> but keep these checks.
> 
> So we don't trust that we can increment a pointer within a range that
> we've already tested with access_ok() and expect it to still be ok?  I
> think the point of having access_ok() and __put_user() is that we can
> batch many __put_user() calls under a single access_ok() check.  I
> don't see any justification here why if we already tested
> access_ok(ptr, 2) that we still need to test access_ok(ptr + 0, 1) and
> access_ok(ptr + 1, 1), and removing the initial test is clearly the
> wrong optimization if we agree there is redundancy here.	
> 

access_ok(ptr + x, 1), where x is variable, then x shouldn't be out of 
range. If we go with initial test, then there should be check for x, 
such that x is within range.

>>>>>> +			if (ret)
>>>>>> +				return ret;
>>>>>> +		}
>>>>>> +
>>>>>> +		for (j = 0; j < bsize; j++, l++) {
>>>>>> +			temp = temp |
>>>>>> +			       (*((unsigned char *)dma->bitmap + j) << shift);
>>>>>
>>>>> |=
>>>>>       
>>>>>> +			if (!access_ok((void __user *)bitmap + l,
>>>>>> +					sizeof(unsigned char)))
>>>>>> +				return -EINVAL;
>>>>>> +
>>>>>> +			ret = __put_user(temp, bitmap + l);
>>>>>> +			if (ret)
>>>>>> +				return ret;
>>>>>> +			if (shift) {
>>>>>> +				temp = *((unsigned char *)dma->bitmap + j) >>
>>>>>> +					(BITS_PER_BYTE - shift);
>>>>>> +			}
>>>>>
>>>>> When shift == 0, temp just seems to accumulate bits that never get
>>>>> cleared.
>>>>>       
>>>>
>>>> Hope example above explains the shift logic.
>>>
>>> But that example is when shift is non-zero.  When shift is zero, each
>>> iteration of the loop just ORs in new bits to temp without ever
>>> clearing the bits for the previous iteration.
>>>
>>>    
>>
>> Oh right, fixing it.
>>
>>>>>> +		}
>>>>>> +
>>>>>> +		nbits += npages;
>>>>>> +
>>>>>> +		i = min(dma->iova + dma->size, iova + size);
>>>>>> +		if (i >= iova + size)
>>>>>> +			break;
>>>>>
>>>>> So whether we error or succeed, we leave cruft in dma->bitmap for the
>>>>> next pass.  It doesn't seem to make any sense why we pre-allocated the
>>>>> bitmap, we might as well just allocate it on demand here.  Actually, if
>>>>> we're not going to do a copy_to_user() for some range of the bitmap,
>>>>> I'm not sure what it's purpose is at all.  I think the big advantages
>>>>> of the bitmap are that we can't amortize the cost across every pinned
>>>>> page or DMA mapping, we don't need the overhead of tracking unmapped
>>>>> vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
>>>>> getting any of those advantages here.
>>>>>       
>>>>
>>>> That would still not work if dma range size is not multiples of 8 pages.
>>>> See example above.
>>>
>>> I don't understand this comment, what about the example above justifies
>>> the bitmap?
>>
>> copy_to_user() could be used if dma range size is not multiple of 8 pages.
> 
> s/is not/is/ ?
> 

My bad, you're right.

> And we expect that to be a far more common case, right?  I don't think
> there are too many ranges for a guest that are only mapped in sub-32KB
> chucks.
>   
>>>   As I understand the above algorithm, we find a vfio_dma
>>> overlapping the request and populate the bitmap for that range.  Then
>>> we go back and put_user() for each byte that we touched.  We could
>>> instead simply work on a one byte buffer as we enumerate the requested
>>> range and do a put_user() ever time we reach the end of it and have bits
>>> set. That would greatly simplify the above example.  But I would expect
>>> that we're a) more likely to get asked for ranges covering a single
>>> vfio_dma
>>
>> QEMU ask for single vfio_dma during each iteration.
>>
>> If we restrict this ABI to cover single vfio_dma only, then it
>> simplifies the logic here. That was my original suggestion. Should we
>> think about that again?
> 
> But we currently allow unmaps that overlap multiple vfio_dmas as long
> as no vfio_dma is bisected, so I think that implies that an unmap while
> asking for the dirty bitmap has even further restricted semantics.  I'm
> also reluctant to design an ABI around what happens to be the current
> QEMU implementation.
> 
> If we take your example above, ranges {0x0000,0xa000} and
> {0xa000,0x10000} ({start,end}), I think you're working with the
> following two bitmaps in this implementation:
> 
> 00000011 11111111b
> 00111111b
> 
> And we need to combine those into:
> 
> 11111111 11111111b
> 
> Right?
> 
> But it seems like that would be easier if the second bitmap was instead:
> 
> 11111100b
> 
> Then we wouldn't need to worry about the entire bitmap being shifted by
> the bit offset within the byte, which limits our fixes to the boundary
> byte and allows us to use copy_to_user() directly for the bulk of the
> copy.  So how do we get there?
> 
> I think we start with allocating the vfio_dma bitmap to account for
> this initial offset, so we calculate bitmap_base_iova as:
>    (iova & ~((PAGE_SIZE << 3) - 1))
> We then use bitmap_base_iova in calculating which bits to set.
> 
> The user needs to follow the same rules, and maybe this adds some value
> to the user providing the bitmap size rather than the kernel
> calculating it.  For example, if the user wanted the dirty bitmap for
> the range {0xa000,0x10000} above, they'd provide at least a 1 byte
> bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.
> 
> Effectively the user can ask for any iova range, but the buffer will be
> filled relative to the zeroth bit of the bitmap following the above
> bitmap_base_iova formula (and replacing PAGE_SIZE with the user
> requested pgsize).  I'm tempted to make this explicit in the user
> interface (ie. only allow bitmaps starting on aligned pages), but a
> user is able to map and unmap single pages and we need to support
> returning a dirty bitmap with an unmap, so I don't think we can do that.
> 

Sigh, finding adjacent vfio_dmas within the same byte seems simpler than 
this.

> So now are we biting off more than we can chew trying to transpose the
> bitmap between page sizes?  If asked for the previous range with an 8K
> pgsize, we'd somehow need to translate 11111100b into 00001110b.
> What's worse, the user could ask for just the 8K page at 0xa000 and we'd
> need to return back 00000010b while leaving our internal bitmap a
> 11110000b after we mark the bits clean.  Seems like this is really
> only tenable if we do multiples of PAGE_SIZE pages within a byte, so
> for 4K we'd have 32K, 64K, 128K, 256K, etc.  I'm somewhat losing sight
> on what this accomplishes though and whether we need this in the first
> implementation.  Should we simplify by dropping this aspect of it,
> supporting only the minimum iommu page size, and focus on actually
> using the bitmaps effectively?
>   

Sure, this will help to push first implementation, we can add 
optimization later.

>>> and b) we're going to spend far more time operating in the
>>> middle of the range and limiting ourselves to one-byte operations there
>>> seems absurd.  If we want to specify that the user provides 4-byte
>>> aligned buffers and naturally aligned iova ranges to make our lives
>>> easier in the kernel, now would be the time to do that.
>>>    
>>>>>> +	}
>>>>>> +	return 0;
>>>>>> +}
>>>>>> +
>>>>>> +static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
>>>>>> +{
>>>>>> +	long bsize;
>>>>>> +
>>>>>> +	if (!bitmap_size || bitmap_size > SIZE_MAX)
>>>>>> +		return -EINVAL;
>>>>>> +
>>>>>> +	bsize = dirty_bitmap_bytes(npages);
>>>>>> +
>>>>>> +	if (bitmap_size < bsize)
>>>>>> +		return -EINVAL;
>>>>>> +
>>>>>> +	return bsize;
>>>>>> +}
>>>>>
>>>>> Seems like this could simply return int, -errno or zero for success.
>>>>> The returned bsize is not used for anything else.
>>>>>       
>>>>
>>>> ok.
>>>>   
>>>>>> +
>>>>>>     static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
>>>>>>     			     struct vfio_iommu_type1_dma_unmap *unmap)
>>>>>>     {
>>>>>> @@ -2277,6 +2478,80 @@ static long vfio_iommu_type1_ioctl(void *iommu_data,
>>>>>>     
>>>>>>     		return copy_to_user((void __user *)arg, &unmap, minsz) ?
>>>>>>     			-EFAULT : 0;
>>>>>> +	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
>>>>>> +		struct vfio_iommu_type1_dirty_bitmap range;
>>>>>> +		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
>>>>>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
>>>>>> +				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
>>>>>> +		int ret;
>>>>>> +
>>>>>> +		if (!iommu->v2)
>>>>>> +			return -EACCES;
>>>>>> +
>>>>>> +		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
>>>>>> +				    bitmap);
>>>>>
>>>>> We require the user to provide iova, size, pgsize, bitmap_size, and
>>>>> bitmap fields to START/STOP?  Why?
>>>>>      
>>>>
>>>> No. But those are part of structure.
>>>
>>> But we do require it, minsz here includes all those fields, which would
>>> probably make a user scratch their head wondering why they need to pass
>>> irrelevant data for START/STOP.  It almost implies that we support
>>> starting and stopping dirty logging for specific ranges of the IOVA
>>> space.  We could define the structure, for example:
>>>
>>> struct vfio_iommu_type1_dirty_bitmap {
>>> 	__u32	argsz;
>>> 	__u32	flags;
>>> 	__u8	data[];
>>> };
>>>
>>> struct vfio_iommu_type1_dirty_bitmap_get {
>>> 	__u64	iova;
>>> 	__u64	size;
>>> 	__u64	pgsize;
>>> 	__u64	bitmap_size;
>>> 	void __user *bitmap;
>>> };
>>>
>>> Where data[] is defined as the latter structure when FLAG_GET_BITMAP is
>>> specified.
>>
>> Ok. Changing as above.
>>
>>>   BTW, don't we need to specify the trailing void* as __u64?
>>> We could theoretically be talking to an ILP32 user process.  Thanks,
>>>    
>>
>> Even on ILP32, using void* pointer will reserve the size required to
>> save a pointer address. I don't think using void* should be problem.
> 
> I think you're still assuming sizeof(void *) is the same in kernel vs
> userspace whereas I'm thinking about an ILP32 user running on an LP64
> kernel.  Thanks,
> 
Ok. Changing it to __u64

Thanks,
Kirti
Alex Williamson Feb. 17, 2020, 8:55 p.m. UTC | #12
On Tue, 18 Feb 2020 00:43:48 +0530
Kirti Wankhede <kwankhede@nvidia.com> wrote:

> On 2/14/2020 4:50 AM, Alex Williamson wrote:
> > On Fri, 14 Feb 2020 01:41:35 +0530
> > Kirti Wankhede <kwankhede@nvidia.com> wrote:
> >   
> >> <snip>
> >>  
> >>>>>>     
> >>>>>> +static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
> >>>>>> +				  size_t size, uint64_t pgsize,
> >>>>>> +				  unsigned char __user *bitmap)
> >>>>>> +{
> >>>>>> +	struct vfio_dma *dma;
> >>>>>> +	dma_addr_t i = iova, iova_limit;
> >>>>>> +	unsigned int bsize, nbits = 0, l = 0;
> >>>>>> +	unsigned long pgshift = __ffs(pgsize);
> >>>>>> +
> >>>>>> +	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
> >>>>>> +		int ret, j;
> >>>>>> +		unsigned int npages = 0, shift = 0;
> >>>>>> +		unsigned char temp = 0;
> >>>>>> +
> >>>>>> +		/* mark all pages dirty if all pages are pinned and mapped. */
> >>>>>> +		if (dma->iommu_mapped) {
> >>>>>> +			iova_limit = min(dma->iova + dma->size, iova + size);
> >>>>>> +			npages = iova_limit/pgsize;
> >>>>>> +			bitmap_set(dma->bitmap, 0, npages);  
> >>>>>
> >>>>> npages is derived from iova_limit, which is the number of bits to set
> >>>>> dirty relative to the first requested iova, not iova zero, ie. the set
> >>>>> of dirty bits is offset from those requested unless iova == dma->iova.
> >>>>>         
> >>>>
> >>>> Right, fixing.
> >>>>     
> >>>>> Also I hope dma->bitmap was actually allocated.  Not only does the
> >>>>> START error path potentially leave dirty tracking enabled without all
> >>>>> the bitmap allocated, when does the bitmap get allocated for a new
> >>>>> vfio_dma when dirty tracking is enabled?  Seems it only occurs if a
> >>>>> vpfn gets marked dirty.
> >>>>>         
> >>>>
> >>>> Right.
> >>>>
> >>>> Fixing error paths.
> >>>>
> >>>>     
> >>>>>> +		} else if (dma->bitmap) {
> >>>>>> +			struct rb_node *n = rb_first(&dma->pfn_list);
> >>>>>> +			bool found = false;
> >>>>>> +
> >>>>>> +			for (; n; n = rb_next(n)) {
> >>>>>> +				struct vfio_pfn *vpfn = rb_entry(n,
> >>>>>> +						struct vfio_pfn, node);
> >>>>>> +				if (vpfn->iova >= i) {
> >>>>>> +					found = true;
> >>>>>> +					break;
> >>>>>> +				}
> >>>>>> +			}
> >>>>>> +
> >>>>>> +			if (!found) {
> >>>>>> +				i += dma->size;
> >>>>>> +				continue;
> >>>>>> +			}
> >>>>>> +
> >>>>>> +			for (; n; n = rb_next(n)) {
> >>>>>> +				unsigned int s;
> >>>>>> +				struct vfio_pfn *vpfn = rb_entry(n,
> >>>>>> +						struct vfio_pfn, node);
> >>>>>> +
> >>>>>> +				if (vpfn->iova >= iova + size)
> >>>>>> +					break;
> >>>>>> +
> >>>>>> +				s = (vpfn->iova - dma->iova) >> pgshift;
> >>>>>> +				bitmap_set(dma->bitmap, s, 1);
> >>>>>> +
> >>>>>> +				iova_limit = vpfn->iova + pgsize;
> >>>>>> +			}
> >>>>>> +			npages = iova_limit/pgsize;  
> >>>>>
> >>>>> Isn't iova_limit potentially uninitialized here?  For example, if our
> >>>>> vfio_dma covers {0,8192} and we ask for the bitmap of {0,4096} and
> >>>>> there's a vpfn at {4096,8192}.  I think that means vpfn->iova >= i
> >>>>> (4096 >= 0), so we break with found = true, then we test 4096 >= 0 +
> >>>>> 4096 and break, and npages = ????/pgsize.
> >>>>>         
> >>>>
> >>>> Right, Fixing it.
> >>>>     
> >>>>>> +		}
> >>>>>> +
> >>>>>> +		bsize = dirty_bitmap_bytes(npages);
> >>>>>> +		shift = nbits % BITS_PER_BYTE;
> >>>>>> +
> >>>>>> +		if (npages && shift) {
> >>>>>> +			l--;
> >>>>>> +			if (!access_ok((void __user *)bitmap + l,
> >>>>>> +					sizeof(unsigned char)))
> >>>>>> +				return -EINVAL;
> >>>>>> +
> >>>>>> +			ret = __get_user(temp, bitmap + l);  
> >>>>>
> >>>>> I don't understand why we care to get the user's bitmap, are we trying
> >>>>> to leave whatever garbage they might have set in it and only also set
> >>>>> the dirty bits?  That seems unnecessary.
> >>>>>         
> >>>>
> >>>> Suppose dma mapped ranges are {start, size}:
> >>>> {0, 0xa000}, {0xa000, 0x10000}
> >>>>
> >>>> Bitmap asked from 0 - 0x10000. Say suppose all pages are dirty.
> >>>> Then in first iteration for dma {0,0xa000} there are 10 pages, so 10
> >>>> bits are set, put_user() happens for 2 bytes, (00000011 11111111b).
> >>>> In second iteration for dma {0xa000, 0x10000} there are 6 pages and
> >>>> these bits should be appended to previous byte. So get_user() that byte,
> >>>> then shift-OR rest of the bitmap, result should be: (11111111 11111111b)
> >>>>
> >>>> Without get_user() and shift-OR, resulting bitmap would be
> >>>> 111111 00000011 11111111b which would be wrong.  
> >>>
> >>> Seems like if we use a put_user() approach then we should look for
> >>> adjacent vfio_dmas within the same byte/word/dword before we push it to
> >>> the user to avoid this sort of inefficiency.
> >>>      
> >>
> >> Won't that add more complication to logic?  
> > 
> > I'm tempted to think it might be less complicated.
> >     
> >>>>> Also why do we need these access_ok() checks when we already checked
> >>>>> the range at the start of the ioctl?  
> >>>>
> >>>> Since pointer is updated runtime here, better to check that pointer
> >>>> before using that pointer.  
> >>>
> >>> Sorry, I still don't understand this, we check access_ok() with a
> >>> pointer and a length, therefore as long as we're incrementing the
> >>> pointer within that length, why do we need to retest?
> >>>      
> >>
> >> Ideally caller for put_user() and get_user() must check the pointer with
> >> access_ok() which is used as argument to these functions before calling
> >> this function. That makes sure that pointer is correct after pointer
> >> arithematic. May be lets remove previous check of pointer and length,
> >> but keep these checks.  
> > 
> > So we don't trust that we can increment a pointer within a range that
> > we've already tested with access_ok() and expect it to still be ok?  I
> > think the point of having access_ok() and __put_user() is that we can
> > batch many __put_user() calls under a single access_ok() check.  I
> > don't see any justification here why if we already tested
> > access_ok(ptr, 2) that we still need to test access_ok(ptr + 0, 1) and
> > access_ok(ptr + 1, 1), and removing the initial test is clearly the
> > wrong optimization if we agree there is redundancy here.	
> >   
> 
> access_ok(ptr + x, 1), where x is variable, then x shouldn't be out of 
> range. If we go with initial test, then there should be check for x, 
> such that x is within range.

That logic should already exist though, we shouldn't be trying to fill
a bitmap beyond what the user requested and therefore what we've
already tested that it's sized for and we have access to.
 
> >>>>>> +			if (ret)
> >>>>>> +				return ret;
> >>>>>> +		}
> >>>>>> +
> >>>>>> +		for (j = 0; j < bsize; j++, l++) {
> >>>>>> +			temp = temp |
> >>>>>> +			       (*((unsigned char *)dma->bitmap + j) << shift);  
> >>>>>
> >>>>> |=
> >>>>>         
> >>>>>> +			if (!access_ok((void __user *)bitmap + l,
> >>>>>> +					sizeof(unsigned char)))
> >>>>>> +				return -EINVAL;
> >>>>>> +
> >>>>>> +			ret = __put_user(temp, bitmap + l);
> >>>>>> +			if (ret)
> >>>>>> +				return ret;
> >>>>>> +			if (shift) {
> >>>>>> +				temp = *((unsigned char *)dma->bitmap + j) >>
> >>>>>> +					(BITS_PER_BYTE - shift);
> >>>>>> +			}  
> >>>>>
> >>>>> When shift == 0, temp just seems to accumulate bits that never get
> >>>>> cleared.
> >>>>>         
> >>>>
> >>>> Hope example above explains the shift logic.  
> >>>
> >>> But that example is when shift is non-zero.  When shift is zero, each
> >>> iteration of the loop just ORs in new bits to temp without ever
> >>> clearing the bits for the previous iteration.
> >>>
> >>>      
> >>
> >> Oh right, fixing it.
> >>  
> >>>>>> +		}
> >>>>>> +
> >>>>>> +		nbits += npages;
> >>>>>> +
> >>>>>> +		i = min(dma->iova + dma->size, iova + size);
> >>>>>> +		if (i >= iova + size)
> >>>>>> +			break;  
> >>>>>
> >>>>> So whether we error or succeed, we leave cruft in dma->bitmap for the
> >>>>> next pass.  It doesn't seem to make any sense why we pre-allocated the
> >>>>> bitmap, we might as well just allocate it on demand here.  Actually, if
> >>>>> we're not going to do a copy_to_user() for some range of the bitmap,
> >>>>> I'm not sure what it's purpose is at all.  I think the big advantages
> >>>>> of the bitmap are that we can't amortize the cost across every pinned
> >>>>> page or DMA mapping, we don't need the overhead of tracking unmapped
> >>>>> vpfns, and we can use copy_to_user() to push the bitmap out.  We're not
> >>>>> getting any of those advantages here.
> >>>>>         
> >>>>
> >>>> That would still not work if dma range size is not multiples of 8 pages.
> >>>> See example above.  
> >>>
> >>> I don't understand this comment, what about the example above justifies
> >>> the bitmap?  
> >>
> >> copy_to_user() could be used if dma range size is not multiple of 8 pages.  
> > 
> > s/is not/is/ ?
> >   
> 
> My bad, you're right.
> 
> > And we expect that to be a far more common case, right?  I don't think
> > there are too many ranges for a guest that are only mapped in sub-32KB
> > chucks.
> >     
> >>>   As I understand the above algorithm, we find a vfio_dma
> >>> overlapping the request and populate the bitmap for that range.  Then
> >>> we go back and put_user() for each byte that we touched.  We could
> >>> instead simply work on a one byte buffer as we enumerate the requested
> >>> range and do a put_user() ever time we reach the end of it and have bits
> >>> set. That would greatly simplify the above example.  But I would expect
> >>> that we're a) more likely to get asked for ranges covering a single
> >>> vfio_dma  
> >>
> >> QEMU ask for single vfio_dma during each iteration.
> >>
> >> If we restrict this ABI to cover single vfio_dma only, then it
> >> simplifies the logic here. That was my original suggestion. Should we
> >> think about that again?  
> > 
> > But we currently allow unmaps that overlap multiple vfio_dmas as long
> > as no vfio_dma is bisected, so I think that implies that an unmap while
> > asking for the dirty bitmap has even further restricted semantics.  I'm
> > also reluctant to design an ABI around what happens to be the current
> > QEMU implementation.
> > 
> > If we take your example above, ranges {0x0000,0xa000} and
> > {0xa000,0x10000} ({start,end}), I think you're working with the
> > following two bitmaps in this implementation:
> > 
> > 00000011 11111111b
> > 00111111b
> > 
> > And we need to combine those into:
> > 
> > 11111111 11111111b
> > 
> > Right?
> > 
> > But it seems like that would be easier if the second bitmap was instead:
> > 
> > 11111100b
> > 
> > Then we wouldn't need to worry about the entire bitmap being shifted by
> > the bit offset within the byte, which limits our fixes to the boundary
> > byte and allows us to use copy_to_user() directly for the bulk of the
> > copy.  So how do we get there?
> > 
> > I think we start with allocating the vfio_dma bitmap to account for
> > this initial offset, so we calculate bitmap_base_iova as:
> >    (iova & ~((PAGE_SIZE << 3) - 1))
> > We then use bitmap_base_iova in calculating which bits to set.
> > 
> > The user needs to follow the same rules, and maybe this adds some value
> > to the user providing the bitmap size rather than the kernel
> > calculating it.  For example, if the user wanted the dirty bitmap for
> > the range {0xa000,0x10000} above, they'd provide at least a 1 byte
> > bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.
> > 
> > Effectively the user can ask for any iova range, but the buffer will be
> > filled relative to the zeroth bit of the bitmap following the above
> > bitmap_base_iova formula (and replacing PAGE_SIZE with the user
> > requested pgsize).  I'm tempted to make this explicit in the user
> > interface (ie. only allow bitmaps starting on aligned pages), but a
> > user is able to map and unmap single pages and we need to support
> > returning a dirty bitmap with an unmap, so I don't think we can do that.
> >   
> 
> Sigh, finding adjacent vfio_dmas within the same byte seems simpler than 
> this.

How does KVM do this?  My intent was that if all of our bitmaps share
the same alignment then we can merge the intersection and continue to
use copy_to_user() on either side.  However, if QEMU doesn't do the
same, it doesn't really help us.  Is QEMU stuck with an implementation
of only retrieving dirty bits per MemoryRegionSection exactly because
of this issue and therefore we can rely on it in our implementation as
well?  Thanks,

Alex
Kirti Wankhede Feb. 18, 2020, 5:58 a.m. UTC | #13
<snip>

>>>>>    As I understand the above algorithm, we find a vfio_dma
>>>>> overlapping the request and populate the bitmap for that range.  Then
>>>>> we go back and put_user() for each byte that we touched.  We could
>>>>> instead simply work on a one byte buffer as we enumerate the requested
>>>>> range and do a put_user() ever time we reach the end of it and have bits
>>>>> set. That would greatly simplify the above example.  But I would expect
>>>>> that we're a) more likely to get asked for ranges covering a single
>>>>> vfio_dma
>>>>
>>>> QEMU ask for single vfio_dma during each iteration.
>>>>
>>>> If we restrict this ABI to cover single vfio_dma only, then it
>>>> simplifies the logic here. That was my original suggestion. Should we
>>>> think about that again?
>>>
>>> But we currently allow unmaps that overlap multiple vfio_dmas as long
>>> as no vfio_dma is bisected, so I think that implies that an unmap while
>>> asking for the dirty bitmap has even further restricted semantics.  I'm
>>> also reluctant to design an ABI around what happens to be the current
>>> QEMU implementation.
>>>
>>> If we take your example above, ranges {0x0000,0xa000} and
>>> {0xa000,0x10000} ({start,end}), I think you're working with the
>>> following two bitmaps in this implementation:
>>>
>>> 00000011 11111111b
>>> 00111111b
>>>
>>> And we need to combine those into:
>>>
>>> 11111111 11111111b
>>>
>>> Right?
>>>
>>> But it seems like that would be easier if the second bitmap was instead:
>>>
>>> 11111100b
>>>
>>> Then we wouldn't need to worry about the entire bitmap being shifted by
>>> the bit offset within the byte, which limits our fixes to the boundary
>>> byte and allows us to use copy_to_user() directly for the bulk of the
>>> copy.  So how do we get there?
>>>
>>> I think we start with allocating the vfio_dma bitmap to account for
>>> this initial offset, so we calculate bitmap_base_iova as:
>>>     (iova & ~((PAGE_SIZE << 3) - 1))
>>> We then use bitmap_base_iova in calculating which bits to set.
>>>
>>> The user needs to follow the same rules, and maybe this adds some value
>>> to the user providing the bitmap size rather than the kernel
>>> calculating it.  For example, if the user wanted the dirty bitmap for
>>> the range {0xa000,0x10000} above, they'd provide at least a 1 byte
>>> bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.
>>>
>>> Effectively the user can ask for any iova range, but the buffer will be
>>> filled relative to the zeroth bit of the bitmap following the above
>>> bitmap_base_iova formula (and replacing PAGE_SIZE with the user
>>> requested pgsize).  I'm tempted to make this explicit in the user
>>> interface (ie. only allow bitmaps starting on aligned pages), but a
>>> user is able to map and unmap single pages and we need to support
>>> returning a dirty bitmap with an unmap, so I don't think we can do that.
>>>    
>>
>> Sigh, finding adjacent vfio_dmas within the same byte seems simpler than
>> this.
> 
> How does KVM do this?  My intent was that if all of our bitmaps share
> the same alignment then we can merge the intersection and continue to
> use copy_to_user() on either side.  However, if QEMU doesn't do the
> same, it doesn't really help us.  Is QEMU stuck with an implementation
> of only retrieving dirty bits per MemoryRegionSection exactly because
> of this issue and therefore we can rely on it in our implementation as
> well?  Thanks,
> 

QEMU sync dirty_bitmap per MemoryRegionSection. Within 
MemoryRegionSection there could be multiple KVMSlots. QEMU queries 
dirty_bitmap per KVMSlot and mark dirty for each KVMSlot.
On kernel side, KVM_GET_DIRTY_LOG ioctl calls 
kvm_get_dirty_log_protect(), where it uses copy_to_user() to copy bitmap 
of that memSlot.
vfio_dma is per MemoryRegionSection. We can reply on MemoryRegionSection 
in our implementation. But to get bitmap during unmap, we have to take 
care of concatenating bitmaps.

In QEMU, in function kvm_physical_sync_dirty_bitmap() there is a comment 
where bitmap size is calculated and bitmap is defined as 'void __user 
*dirty_bitmap' which is also the concern you raised and could be handled 
similarly as below.

         /* XXX bad kernel interface alert
          * For dirty bitmap, kernel allocates array of size aligned to
          * bits-per-long.  But for case when the kernel is 64bits and
          * the userspace is 32bits, userspace can't align to the same
          * bits-per-long, since sizeof(long) is different between kernel
          * and user space.  This way, userspace will provide buffer which
          * may be 4 bytes less than the kernel will use, resulting in
          * userspace memory corruption (which is not detectable by valgrind
          * too, in most cases).
          * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
          * a hope that sizeof(long) won't become >8 any time soon.
          */
         if (!mem->dirty_bmap) {
             hwaddr bitmap_size = ALIGN(((mem->memory_size) >> 
TARGET_PAGE_BITS),
                                         /*HOST_LONG_BITS*/ 64) / 8;
             /* Allocate on the first log_sync, once and for all */
             mem->dirty_bmap = g_malloc0(bitmap_size);
         }

Thanks,
Kirti
Alex Williamson Feb. 18, 2020, 9:41 p.m. UTC | #14
On Tue, 18 Feb 2020 11:28:53 +0530
Kirti Wankhede <kwankhede@nvidia.com> wrote:

> <snip>
> 
> >>>>>    As I understand the above algorithm, we find a vfio_dma
> >>>>> overlapping the request and populate the bitmap for that range.  Then
> >>>>> we go back and put_user() for each byte that we touched.  We could
> >>>>> instead simply work on a one byte buffer as we enumerate the requested
> >>>>> range and do a put_user() ever time we reach the end of it and have bits
> >>>>> set. That would greatly simplify the above example.  But I would expect
> >>>>> that we're a) more likely to get asked for ranges covering a single
> >>>>> vfio_dma  
> >>>>
> >>>> QEMU ask for single vfio_dma during each iteration.
> >>>>
> >>>> If we restrict this ABI to cover single vfio_dma only, then it
> >>>> simplifies the logic here. That was my original suggestion. Should we
> >>>> think about that again?  
> >>>
> >>> But we currently allow unmaps that overlap multiple vfio_dmas as long
> >>> as no vfio_dma is bisected, so I think that implies that an unmap while
> >>> asking for the dirty bitmap has even further restricted semantics.  I'm
> >>> also reluctant to design an ABI around what happens to be the current
> >>> QEMU implementation.
> >>>
> >>> If we take your example above, ranges {0x0000,0xa000} and
> >>> {0xa000,0x10000} ({start,end}), I think you're working with the
> >>> following two bitmaps in this implementation:
> >>>
> >>> 00000011 11111111b
> >>> 00111111b
> >>>
> >>> And we need to combine those into:
> >>>
> >>> 11111111 11111111b
> >>>
> >>> Right?
> >>>
> >>> But it seems like that would be easier if the second bitmap was instead:
> >>>
> >>> 11111100b
> >>>
> >>> Then we wouldn't need to worry about the entire bitmap being shifted by
> >>> the bit offset within the byte, which limits our fixes to the boundary
> >>> byte and allows us to use copy_to_user() directly for the bulk of the
> >>> copy.  So how do we get there?
> >>>
> >>> I think we start with allocating the vfio_dma bitmap to account for
> >>> this initial offset, so we calculate bitmap_base_iova as:
> >>>     (iova & ~((PAGE_SIZE << 3) - 1))
> >>> We then use bitmap_base_iova in calculating which bits to set.
> >>>
> >>> The user needs to follow the same rules, and maybe this adds some value
> >>> to the user providing the bitmap size rather than the kernel
> >>> calculating it.  For example, if the user wanted the dirty bitmap for
> >>> the range {0xa000,0x10000} above, they'd provide at least a 1 byte
> >>> bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.
> >>>
> >>> Effectively the user can ask for any iova range, but the buffer will be
> >>> filled relative to the zeroth bit of the bitmap following the above
> >>> bitmap_base_iova formula (and replacing PAGE_SIZE with the user
> >>> requested pgsize).  I'm tempted to make this explicit in the user
> >>> interface (ie. only allow bitmaps starting on aligned pages), but a
> >>> user is able to map and unmap single pages and we need to support
> >>> returning a dirty bitmap with an unmap, so I don't think we can do that.
> >>>      
> >>
> >> Sigh, finding adjacent vfio_dmas within the same byte seems simpler than
> >> this.  
> > 
> > How does KVM do this?  My intent was that if all of our bitmaps share
> > the same alignment then we can merge the intersection and continue to
> > use copy_to_user() on either side.  However, if QEMU doesn't do the
> > same, it doesn't really help us.  Is QEMU stuck with an implementation
> > of only retrieving dirty bits per MemoryRegionSection exactly because
> > of this issue and therefore we can rely on it in our implementation as
> > well?  Thanks,
> >   
> 
> QEMU sync dirty_bitmap per MemoryRegionSection. Within 
> MemoryRegionSection there could be multiple KVMSlots. QEMU queries 
> dirty_bitmap per KVMSlot and mark dirty for each KVMSlot.
> On kernel side, KVM_GET_DIRTY_LOG ioctl calls 
> kvm_get_dirty_log_protect(), where it uses copy_to_user() to copy bitmap 
> of that memSlot.
> vfio_dma is per MemoryRegionSection. We can reply on MemoryRegionSection 
> in our implementation. But to get bitmap during unmap, we have to take 
> care of concatenating bitmaps.

So KVM does not worry about bitmap alignment because the interface is
based on slots, a dirty bitmap can only be retrieved for a single,
entire slot.  We need VFIO_IOMMU_UNMAP_DMA to maintain its support for
spanning multiple vfio_dmas, but maybe we have some leeway that we
don't need to support both multiple vfio_dmas and dirty bitmap at the
same time.  It seems like it would be a massive simplification if we
required an unmap with dirty bitmap to span exactly one vfio_dma,
right?  I don't see that we'd break any existing users with that, it's
unfortunate that we can't have the flexibility of the existing calling
convention, but I think there's good reason for it here.  Our separate
dirty bitmap log reporting would follow the same semantics.  I think
this all aligns with how the MemoryListener works in QEMU right now,
correct?  For example we wouldn't need any extra per MAP_DMA tracking
in QEMU like KVM has for its slots.

> In QEMU, in function kvm_physical_sync_dirty_bitmap() there is a comment 
> where bitmap size is calculated and bitmap is defined as 'void __user 
> *dirty_bitmap' which is also the concern you raised and could be handled 
> similarly as below.
> 
>          /* XXX bad kernel interface alert
>           * For dirty bitmap, kernel allocates array of size aligned to
>           * bits-per-long.  But for case when the kernel is 64bits and
>           * the userspace is 32bits, userspace can't align to the same
>           * bits-per-long, since sizeof(long) is different between kernel
>           * and user space.  This way, userspace will provide buffer which
>           * may be 4 bytes less than the kernel will use, resulting in
>           * userspace memory corruption (which is not detectable by valgrind
>           * too, in most cases).
>           * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
>           * a hope that sizeof(long) won't become >8 any time soon.
>           */
>          if (!mem->dirty_bmap) {
>              hwaddr bitmap_size = ALIGN(((mem->memory_size) >> 
> TARGET_PAGE_BITS),
>                                          /*HOST_LONG_BITS*/ 64) / 8;
>              /* Allocate on the first log_sync, once and for all */
>              mem->dirty_bmap = g_malloc0(bitmap_size);
>          }

Sort of, the the KVM ioctl seems to just pass a slot number and user
dirty bitmap pointer, so the size of the bitmap is inferred by the size
of the slot, but if both kernel and user round up to a multiple of
longs they might come up with different lengths.  QEMU therefore decides
to always round up the size for an LP64 based long.  Since you've
specified bitmap_size in our ioctl, the size agreement is explicit.

The concern I had looks like it addressed in KVM by placing the void*
__user pointer in a union with a u64:

struct kvm_dirty_log {
        __u32 slot;
        __u32 padding1;
        union {
                void __user *dirty_bitmap; /* one bit per page */
                __u64 padding2;
        };
};

The the kvm_vm_compat_ioctl() ioctl handles this with it's own private
structure:

truct compat_kvm_dirty_log {
        __u32 slot;
        __u32 padding1;
        union {
                compat_uptr_t dirty_bitmap; /* one bit per page */
                __u64 padding2;
        };
};

Which gets extracted via:

	log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);

However, compat_ptr() has:

/*
 * A pointer passed in from user mode. This should not
 * be used for syscall parameters, just declare them
 * as pointers because the syscall entry code will have
 * appropriately converted them already.
 */
#ifndef compat_ptr
static inline void __user *compat_ptr(compat_uptr_t uptr)
{
        return (void __user *)(unsigned long)uptr;
}
#endif

So maybe we don't need to do anything special?  I'm tempted to think
the KVM handling is using legacy mechanism or the padding in the union
was assumed not to be for that purpose.  Thanks,

Alex
Kirti Wankhede Feb. 19, 2020, 4:21 a.m. UTC | #15
On 2/19/2020 3:11 AM, Alex Williamson wrote:
> On Tue, 18 Feb 2020 11:28:53 +0530
> Kirti Wankhede <kwankhede@nvidia.com> wrote:
> 
>> <snip>
>>
>>>>>>>     As I understand the above algorithm, we find a vfio_dma
>>>>>>> overlapping the request and populate the bitmap for that range.  Then
>>>>>>> we go back and put_user() for each byte that we touched.  We could
>>>>>>> instead simply work on a one byte buffer as we enumerate the requested
>>>>>>> range and do a put_user() ever time we reach the end of it and have bits
>>>>>>> set. That would greatly simplify the above example.  But I would expect
>>>>>>> that we're a) more likely to get asked for ranges covering a single
>>>>>>> vfio_dma
>>>>>>
>>>>>> QEMU ask for single vfio_dma during each iteration.
>>>>>>
>>>>>> If we restrict this ABI to cover single vfio_dma only, then it
>>>>>> simplifies the logic here. That was my original suggestion. Should we
>>>>>> think about that again?
>>>>>
>>>>> But we currently allow unmaps that overlap multiple vfio_dmas as long
>>>>> as no vfio_dma is bisected, so I think that implies that an unmap while
>>>>> asking for the dirty bitmap has even further restricted semantics.  I'm
>>>>> also reluctant to design an ABI around what happens to be the current
>>>>> QEMU implementation.
>>>>>
>>>>> If we take your example above, ranges {0x0000,0xa000} and
>>>>> {0xa000,0x10000} ({start,end}), I think you're working with the
>>>>> following two bitmaps in this implementation:
>>>>>
>>>>> 00000011 11111111b
>>>>> 00111111b
>>>>>
>>>>> And we need to combine those into:
>>>>>
>>>>> 11111111 11111111b
>>>>>
>>>>> Right?
>>>>>
>>>>> But it seems like that would be easier if the second bitmap was instead:
>>>>>
>>>>> 11111100b
>>>>>
>>>>> Then we wouldn't need to worry about the entire bitmap being shifted by
>>>>> the bit offset within the byte, which limits our fixes to the boundary
>>>>> byte and allows us to use copy_to_user() directly for the bulk of the
>>>>> copy.  So how do we get there?
>>>>>
>>>>> I think we start with allocating the vfio_dma bitmap to account for
>>>>> this initial offset, so we calculate bitmap_base_iova as:
>>>>>      (iova & ~((PAGE_SIZE << 3) - 1))
>>>>> We then use bitmap_base_iova in calculating which bits to set.
>>>>>
>>>>> The user needs to follow the same rules, and maybe this adds some value
>>>>> to the user providing the bitmap size rather than the kernel
>>>>> calculating it.  For example, if the user wanted the dirty bitmap for
>>>>> the range {0xa000,0x10000} above, they'd provide at least a 1 byte
>>>>> bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.
>>>>>
>>>>> Effectively the user can ask for any iova range, but the buffer will be
>>>>> filled relative to the zeroth bit of the bitmap following the above
>>>>> bitmap_base_iova formula (and replacing PAGE_SIZE with the user
>>>>> requested pgsize).  I'm tempted to make this explicit in the user
>>>>> interface (ie. only allow bitmaps starting on aligned pages), but a
>>>>> user is able to map and unmap single pages and we need to support
>>>>> returning a dirty bitmap with an unmap, so I don't think we can do that.
>>>>>       
>>>>
>>>> Sigh, finding adjacent vfio_dmas within the same byte seems simpler than
>>>> this.
>>>
>>> How does KVM do this?  My intent was that if all of our bitmaps share
>>> the same alignment then we can merge the intersection and continue to
>>> use copy_to_user() on either side.  However, if QEMU doesn't do the
>>> same, it doesn't really help us.  Is QEMU stuck with an implementation
>>> of only retrieving dirty bits per MemoryRegionSection exactly because
>>> of this issue and therefore we can rely on it in our implementation as
>>> well?  Thanks,
>>>    
>>
>> QEMU sync dirty_bitmap per MemoryRegionSection. Within
>> MemoryRegionSection there could be multiple KVMSlots. QEMU queries
>> dirty_bitmap per KVMSlot and mark dirty for each KVMSlot.
>> On kernel side, KVM_GET_DIRTY_LOG ioctl calls
>> kvm_get_dirty_log_protect(), where it uses copy_to_user() to copy bitmap
>> of that memSlot.
>> vfio_dma is per MemoryRegionSection. We can reply on MemoryRegionSection
>> in our implementation. But to get bitmap during unmap, we have to take
>> care of concatenating bitmaps.
> 
> So KVM does not worry about bitmap alignment because the interface is
> based on slots, a dirty bitmap can only be retrieved for a single,
> entire slot.  We need VFIO_IOMMU_UNMAP_DMA to maintain its support for
> spanning multiple vfio_dmas, but maybe we have some leeway that we
> don't need to support both multiple vfio_dmas and dirty bitmap at the
> same time.  It seems like it would be a massive simplification if we
> required an unmap with dirty bitmap to span exactly one vfio_dma,
> right? 

Yes.

> I don't see that we'd break any existing users with that, it's
> unfortunate that we can't have the flexibility of the existing calling
> convention, but I think there's good reason for it here.  Our separate
> dirty bitmap log reporting would follow the same semantics.  I think
> this all aligns with how the MemoryListener works in QEMU right now,
> correct?  For example we wouldn't need any extra per MAP_DMA tracking
> in QEMU like KVM has for its slots.
> 

That right.
Should we go ahead with the implementation to get dirty bitmap for one 
vfio_dma for GET_DIRTY ioctl and unmap with dirty ioctl? Accordingly we 
can have sanity checks in these ioctls.

Thanks,
Kirti

>> In QEMU, in function kvm_physical_sync_dirty_bitmap() there is a comment
>> where bitmap size is calculated and bitmap is defined as 'void __user
>> *dirty_bitmap' which is also the concern you raised and could be handled
>> similarly as below.
>>
>>           /* XXX bad kernel interface alert
>>            * For dirty bitmap, kernel allocates array of size aligned to
>>            * bits-per-long.  But for case when the kernel is 64bits and
>>            * the userspace is 32bits, userspace can't align to the same
>>            * bits-per-long, since sizeof(long) is different between kernel
>>            * and user space.  This way, userspace will provide buffer which
>>            * may be 4 bytes less than the kernel will use, resulting in
>>            * userspace memory corruption (which is not detectable by valgrind
>>            * too, in most cases).
>>            * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
>>            * a hope that sizeof(long) won't become >8 any time soon.
>>            */
>>           if (!mem->dirty_bmap) {
>>               hwaddr bitmap_size = ALIGN(((mem->memory_size) >>
>> TARGET_PAGE_BITS),
>>                                           /*HOST_LONG_BITS*/ 64) / 8;
>>               /* Allocate on the first log_sync, once and for all */
>>               mem->dirty_bmap = g_malloc0(bitmap_size);
>>           }
> 
> Sort of, the the KVM ioctl seems to just pass a slot number and user
> dirty bitmap pointer, so the size of the bitmap is inferred by the size
> of the slot, but if both kernel and user round up to a multiple of
> longs they might come up with different lengths.  QEMU therefore decides
> to always round up the size for an LP64 based long.  Since you've
> specified bitmap_size in our ioctl, the size agreement is explicit.
> 
> The concern I had looks like it addressed in KVM by placing the void*
> __user pointer in a union with a u64:
> 
> struct kvm_dirty_log {
>          __u32 slot;
>          __u32 padding1;
>          union {
>                  void __user *dirty_bitmap; /* one bit per page */
>                  __u64 padding2;
>          };
> };
> 
> The the kvm_vm_compat_ioctl() ioctl handles this with it's own private
> structure:
> 
> truct compat_kvm_dirty_log {
>          __u32 slot;
>          __u32 padding1;
>          union {
>                  compat_uptr_t dirty_bitmap; /* one bit per page */
>                  __u64 padding2;
>          };
> };
> 
> Which gets extracted via:
> 
> 	log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
> 
> However, compat_ptr() has:
> 
> /*
>   * A pointer passed in from user mode. This should not
>   * be used for syscall parameters, just declare them
>   * as pointers because the syscall entry code will have
>   * appropriately converted them already.
>   */
> #ifndef compat_ptr
> static inline void __user *compat_ptr(compat_uptr_t uptr)
> {
>          return (void __user *)(unsigned long)uptr;
> }
> #endif
> 
> So maybe we don't need to do anything special?  I'm tempted to think
> the KVM handling is using legacy mechanism or the padding in the union
> was assumed not to be for that purpose.  Thanks,
> 
> Alex
>
Alex Williamson Feb. 19, 2020, 4:53 a.m. UTC | #16
On Wed, 19 Feb 2020 09:51:32 +0530
Kirti Wankhede <kwankhede@nvidia.com> wrote:

> On 2/19/2020 3:11 AM, Alex Williamson wrote:
> > On Tue, 18 Feb 2020 11:28:53 +0530
> > Kirti Wankhede <kwankhede@nvidia.com> wrote:
> >   
> >> <snip>
> >>  
> >>>>>>>     As I understand the above algorithm, we find a vfio_dma
> >>>>>>> overlapping the request and populate the bitmap for that range.  Then
> >>>>>>> we go back and put_user() for each byte that we touched.  We could
> >>>>>>> instead simply work on a one byte buffer as we enumerate the requested
> >>>>>>> range and do a put_user() ever time we reach the end of it and have bits
> >>>>>>> set. That would greatly simplify the above example.  But I would expect
> >>>>>>> that we're a) more likely to get asked for ranges covering a single
> >>>>>>> vfio_dma  
> >>>>>>
> >>>>>> QEMU ask for single vfio_dma during each iteration.
> >>>>>>
> >>>>>> If we restrict this ABI to cover single vfio_dma only, then it
> >>>>>> simplifies the logic here. That was my original suggestion. Should we
> >>>>>> think about that again?  
> >>>>>
> >>>>> But we currently allow unmaps that overlap multiple vfio_dmas as long
> >>>>> as no vfio_dma is bisected, so I think that implies that an unmap while
> >>>>> asking for the dirty bitmap has even further restricted semantics.  I'm
> >>>>> also reluctant to design an ABI around what happens to be the current
> >>>>> QEMU implementation.
> >>>>>
> >>>>> If we take your example above, ranges {0x0000,0xa000} and
> >>>>> {0xa000,0x10000} ({start,end}), I think you're working with the
> >>>>> following two bitmaps in this implementation:
> >>>>>
> >>>>> 00000011 11111111b
> >>>>> 00111111b
> >>>>>
> >>>>> And we need to combine those into:
> >>>>>
> >>>>> 11111111 11111111b
> >>>>>
> >>>>> Right?
> >>>>>
> >>>>> But it seems like that would be easier if the second bitmap was instead:
> >>>>>
> >>>>> 11111100b
> >>>>>
> >>>>> Then we wouldn't need to worry about the entire bitmap being shifted by
> >>>>> the bit offset within the byte, which limits our fixes to the boundary
> >>>>> byte and allows us to use copy_to_user() directly for the bulk of the
> >>>>> copy.  So how do we get there?
> >>>>>
> >>>>> I think we start with allocating the vfio_dma bitmap to account for
> >>>>> this initial offset, so we calculate bitmap_base_iova as:
> >>>>>      (iova & ~((PAGE_SIZE << 3) - 1))
> >>>>> We then use bitmap_base_iova in calculating which bits to set.
> >>>>>
> >>>>> The user needs to follow the same rules, and maybe this adds some value
> >>>>> to the user providing the bitmap size rather than the kernel
> >>>>> calculating it.  For example, if the user wanted the dirty bitmap for
> >>>>> the range {0xa000,0x10000} above, they'd provide at least a 1 byte
> >>>>> bitmap, but we'd return bit #2 set to indicate 0xa000 is dirty.
> >>>>>
> >>>>> Effectively the user can ask for any iova range, but the buffer will be
> >>>>> filled relative to the zeroth bit of the bitmap following the above
> >>>>> bitmap_base_iova formula (and replacing PAGE_SIZE with the user
> >>>>> requested pgsize).  I'm tempted to make this explicit in the user
> >>>>> interface (ie. only allow bitmaps starting on aligned pages), but a
> >>>>> user is able to map and unmap single pages and we need to support
> >>>>> returning a dirty bitmap with an unmap, so I don't think we can do that.
> >>>>>         
> >>>>
> >>>> Sigh, finding adjacent vfio_dmas within the same byte seems simpler than
> >>>> this.  
> >>>
> >>> How does KVM do this?  My intent was that if all of our bitmaps share
> >>> the same alignment then we can merge the intersection and continue to
> >>> use copy_to_user() on either side.  However, if QEMU doesn't do the
> >>> same, it doesn't really help us.  Is QEMU stuck with an implementation
> >>> of only retrieving dirty bits per MemoryRegionSection exactly because
> >>> of this issue and therefore we can rely on it in our implementation as
> >>> well?  Thanks,
> >>>      
> >>
> >> QEMU sync dirty_bitmap per MemoryRegionSection. Within
> >> MemoryRegionSection there could be multiple KVMSlots. QEMU queries
> >> dirty_bitmap per KVMSlot and mark dirty for each KVMSlot.
> >> On kernel side, KVM_GET_DIRTY_LOG ioctl calls
> >> kvm_get_dirty_log_protect(), where it uses copy_to_user() to copy bitmap
> >> of that memSlot.
> >> vfio_dma is per MemoryRegionSection. We can reply on MemoryRegionSection
> >> in our implementation. But to get bitmap during unmap, we have to take
> >> care of concatenating bitmaps.  
> > 
> > So KVM does not worry about bitmap alignment because the interface is
> > based on slots, a dirty bitmap can only be retrieved for a single,
> > entire slot.  We need VFIO_IOMMU_UNMAP_DMA to maintain its support for
> > spanning multiple vfio_dmas, but maybe we have some leeway that we
> > don't need to support both multiple vfio_dmas and dirty bitmap at the
> > same time.  It seems like it would be a massive simplification if we
> > required an unmap with dirty bitmap to span exactly one vfio_dma,
> > right?   
> 
> Yes.
> 
> > I don't see that we'd break any existing users with that, it's
> > unfortunate that we can't have the flexibility of the existing calling
> > convention, but I think there's good reason for it here.  Our separate
> > dirty bitmap log reporting would follow the same semantics.  I think
> > this all aligns with how the MemoryListener works in QEMU right now,
> > correct?  For example we wouldn't need any extra per MAP_DMA tracking
> > in QEMU like KVM has for its slots.
> >   
> 
> That right.
> Should we go ahead with the implementation to get dirty bitmap for one 
> vfio_dma for GET_DIRTY ioctl and unmap with dirty ioctl? Accordingly we 
> can have sanity checks in these ioctls.

Yes, I'm convinced that bitmap alignment is sufficiently too difficult
and unnecessary to restrict the calling convention of UNMAP_DMA, when
using the dirty bitmap extension, to exactly unmap a single vfio_dma.
Thanks,

Alex
diff mbox series

Patch

diff --git a/drivers/vfio/vfio_iommu_type1.c b/drivers/vfio/vfio_iommu_type1.c
index d386461e5d11..df358dc1c85b 100644
--- a/drivers/vfio/vfio_iommu_type1.c
+++ b/drivers/vfio/vfio_iommu_type1.c
@@ -70,6 +70,7 @@  struct vfio_iommu {
 	unsigned int		dma_avail;
 	bool			v2;
 	bool			nesting;
+	bool			dirty_page_tracking;
 };
 
 struct vfio_domain {
@@ -90,6 +91,7 @@  struct vfio_dma {
 	bool			lock_cap;	/* capable(CAP_IPC_LOCK) */
 	struct task_struct	*task;
 	struct rb_root		pfn_list;	/* Ex-user pinned pfn list */
+	unsigned long		*bitmap;
 };
 
 struct vfio_group {
@@ -125,6 +127,7 @@  struct vfio_regions {
 					(!list_empty(&iommu->domain_list))
 
 static int put_pfn(unsigned long pfn, int prot);
+static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu);
 
 /*
  * This code handles mapping and unmapping of user data buffers
@@ -174,6 +177,57 @@  static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
 	rb_erase(&old->node, &iommu->dma_list);
 }
 
+static inline unsigned long dirty_bitmap_bytes(unsigned int npages)
+{
+	if (!npages)
+		return 0;
+
+	return ALIGN(npages, BITS_PER_LONG) / sizeof(unsigned long);
+}
+
+static int vfio_dma_bitmap_alloc(struct vfio_iommu *iommu,
+				 struct vfio_dma *dma, unsigned long pgsizes)
+{
+	unsigned long pgshift = __ffs(pgsizes);
+
+	if (!RB_EMPTY_ROOT(&dma->pfn_list) || dma->iommu_mapped) {
+		unsigned long npages = dma->size >> pgshift;
+		unsigned long bsize = dirty_bitmap_bytes(npages);
+
+		dma->bitmap = kvzalloc(bsize, GFP_KERNEL);
+		if (!dma->bitmap)
+			return -ENOMEM;
+	}
+	return 0;
+}
+
+static int vfio_dma_all_bitmap_alloc(struct vfio_iommu *iommu,
+				     unsigned long pgsizes)
+{
+	struct rb_node *n = rb_first(&iommu->dma_list);
+	int ret;
+
+	for (; n; n = rb_next(n)) {
+		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
+
+		ret = vfio_dma_bitmap_alloc(iommu, dma, pgsizes);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+
+static void vfio_dma_all_bitmap_free(struct vfio_iommu *iommu)
+{
+	struct rb_node *n = rb_first(&iommu->dma_list);
+
+	for (; n; n = rb_next(n)) {
+		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
+
+		kfree(dma->bitmap);
+	}
+}
+
 /*
  * Helper Functions for host iova-pfn list
  */
@@ -244,6 +298,29 @@  static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
 	kfree(vpfn);
 }
 
+static void vfio_remove_unpinned_from_pfn_list(struct vfio_dma *dma)
+{
+	struct rb_node *n = rb_first(&dma->pfn_list);
+
+	for (; n; n = rb_next(n)) {
+		struct vfio_pfn *vpfn = rb_entry(n, struct vfio_pfn, node);
+
+		if (!vpfn->ref_count)
+			vfio_remove_from_pfn_list(dma, vpfn);
+	}
+}
+
+static void vfio_remove_unpinned_from_dma_list(struct vfio_iommu *iommu)
+{
+	struct rb_node *n = rb_first(&iommu->dma_list);
+
+	for (; n; n = rb_next(n)) {
+		struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
+
+		vfio_remove_unpinned_from_pfn_list(dma);
+	}
+}
+
 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
 					       unsigned long iova)
 {
@@ -261,7 +338,8 @@  static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
 	vpfn->ref_count--;
 	if (!vpfn->ref_count) {
 		ret = put_pfn(vpfn->pfn, dma->prot);
-		vfio_remove_from_pfn_list(dma, vpfn);
+		if (!dma->bitmap)
+			vfio_remove_from_pfn_list(dma, vpfn);
 	}
 	return ret;
 }
@@ -483,13 +561,14 @@  static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
 	return ret;
 }
 
-static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
+static int vfio_unpin_page_external(struct vfio_iommu *iommu,
+				    struct vfio_dma *dma, dma_addr_t iova,
 				    bool do_accounting)
 {
 	int unlocked;
 	struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
 
-	if (!vpfn)
+	if (!vpfn || !vpfn->ref_count)
 		return 0;
 
 	unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
@@ -510,6 +589,7 @@  static int vfio_iommu_type1_pin_pages(void *iommu_data,
 	unsigned long remote_vaddr;
 	struct vfio_dma *dma;
 	bool do_accounting;
+	unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
 
 	if (!iommu || !user_pfn || !phys_pfn)
 		return -EINVAL;
@@ -551,8 +631,10 @@  static int vfio_iommu_type1_pin_pages(void *iommu_data,
 
 		vpfn = vfio_iova_get_vfio_pfn(dma, iova);
 		if (vpfn) {
-			phys_pfn[i] = vpfn->pfn;
-			continue;
+			if (vpfn->ref_count > 1) {
+				phys_pfn[i] = vpfn->pfn;
+				continue;
+			}
 		}
 
 		remote_vaddr = dma->vaddr + iova - dma->iova;
@@ -560,11 +642,23 @@  static int vfio_iommu_type1_pin_pages(void *iommu_data,
 					     do_accounting);
 		if (ret)
 			goto pin_unwind;
-
-		ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
-		if (ret) {
-			vfio_unpin_page_external(dma, iova, do_accounting);
-			goto pin_unwind;
+		if (!vpfn) {
+			ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
+			if (ret) {
+				vfio_unpin_page_external(iommu, dma, iova,
+							 do_accounting);
+				goto pin_unwind;
+			}
+		} else
+			vpfn->pfn = phys_pfn[i];
+
+		if (iommu->dirty_page_tracking && !dma->bitmap) {
+			ret = vfio_dma_bitmap_alloc(iommu, dma, iommu_pgsizes);
+			if (ret) {
+				vfio_unpin_page_external(iommu, dma, iova,
+							 do_accounting);
+				goto pin_unwind;
+			}
 		}
 	}
 
@@ -578,7 +672,7 @@  static int vfio_iommu_type1_pin_pages(void *iommu_data,
 
 		iova = user_pfn[j] << PAGE_SHIFT;
 		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
-		vfio_unpin_page_external(dma, iova, do_accounting);
+		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
 		phys_pfn[j] = 0;
 	}
 pin_done:
@@ -612,7 +706,7 @@  static int vfio_iommu_type1_unpin_pages(void *iommu_data,
 		dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
 		if (!dma)
 			goto unpin_exit;
-		vfio_unpin_page_external(dma, iova, do_accounting);
+		vfio_unpin_page_external(iommu, dma, iova, do_accounting);
 	}
 
 unpin_exit:
@@ -830,6 +924,113 @@  static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
 	return bitmap;
 }
 
+static int vfio_iova_dirty_bitmap(struct vfio_iommu *iommu, dma_addr_t iova,
+				  size_t size, uint64_t pgsize,
+				  unsigned char __user *bitmap)
+{
+	struct vfio_dma *dma;
+	dma_addr_t i = iova, iova_limit;
+	unsigned int bsize, nbits = 0, l = 0;
+	unsigned long pgshift = __ffs(pgsize);
+
+	while ((dma = vfio_find_dma(iommu, i, pgsize))) {
+		int ret, j;
+		unsigned int npages = 0, shift = 0;
+		unsigned char temp = 0;
+
+		/* mark all pages dirty if all pages are pinned and mapped. */
+		if (dma->iommu_mapped) {
+			iova_limit = min(dma->iova + dma->size, iova + size);
+			npages = iova_limit/pgsize;
+			bitmap_set(dma->bitmap, 0, npages);
+		} else if (dma->bitmap) {
+			struct rb_node *n = rb_first(&dma->pfn_list);
+			bool found = false;
+
+			for (; n; n = rb_next(n)) {
+				struct vfio_pfn *vpfn = rb_entry(n,
+						struct vfio_pfn, node);
+				if (vpfn->iova >= i) {
+					found = true;
+					break;
+				}
+			}
+
+			if (!found) {
+				i += dma->size;
+				continue;
+			}
+
+			for (; n; n = rb_next(n)) {
+				unsigned int s;
+				struct vfio_pfn *vpfn = rb_entry(n,
+						struct vfio_pfn, node);
+
+				if (vpfn->iova >= iova + size)
+					break;
+
+				s = (vpfn->iova - dma->iova) >> pgshift;
+				bitmap_set(dma->bitmap, s, 1);
+
+				iova_limit = vpfn->iova + pgsize;
+			}
+			npages = iova_limit/pgsize;
+		}
+
+		bsize = dirty_bitmap_bytes(npages);
+		shift = nbits % BITS_PER_BYTE;
+
+		if (npages && shift) {
+			l--;
+			if (!access_ok((void __user *)bitmap + l,
+					sizeof(unsigned char)))
+				return -EINVAL;
+
+			ret = __get_user(temp, bitmap + l);
+			if (ret)
+				return ret;
+		}
+
+		for (j = 0; j < bsize; j++, l++) {
+			temp = temp |
+			       (*((unsigned char *)dma->bitmap + j) << shift);
+			if (!access_ok((void __user *)bitmap + l,
+					sizeof(unsigned char)))
+				return -EINVAL;
+
+			ret = __put_user(temp, bitmap + l);
+			if (ret)
+				return ret;
+			if (shift) {
+				temp = *((unsigned char *)dma->bitmap + j) >>
+					(BITS_PER_BYTE - shift);
+			}
+		}
+
+		nbits += npages;
+
+		i = min(dma->iova + dma->size, iova + size);
+		if (i >= iova + size)
+			break;
+	}
+	return 0;
+}
+
+static long verify_bitmap_size(unsigned long npages, unsigned long bitmap_size)
+{
+	long bsize;
+
+	if (!bitmap_size || bitmap_size > SIZE_MAX)
+		return -EINVAL;
+
+	bsize = dirty_bitmap_bytes(npages);
+
+	if (bitmap_size < bsize)
+		return -EINVAL;
+
+	return bsize;
+}
+
 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
 			     struct vfio_iommu_type1_dma_unmap *unmap)
 {
@@ -2277,6 +2478,80 @@  static long vfio_iommu_type1_ioctl(void *iommu_data,
 
 		return copy_to_user((void __user *)arg, &unmap, minsz) ?
 			-EFAULT : 0;
+	} else if (cmd == VFIO_IOMMU_DIRTY_PAGES) {
+		struct vfio_iommu_type1_dirty_bitmap range;
+		uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
+				VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
+				VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
+		int ret;
+
+		if (!iommu->v2)
+			return -EACCES;
+
+		minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap,
+				    bitmap);
+
+		if (copy_from_user(&range, (void __user *)arg, minsz))
+			return -EFAULT;
+
+		if (range.argsz < minsz || range.flags & ~mask)
+			return -EINVAL;
+
+		/* only one flag should be set at a time */
+		if (__ffs(range.flags) != __fls(range.flags))
+			return -EINVAL;
+
+		if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
+			unsigned long iommu_pgsizes = vfio_pgsize_bitmap(iommu);
+
+			mutex_lock(&iommu->lock);
+			iommu->dirty_page_tracking = true;
+			ret = vfio_dma_all_bitmap_alloc(iommu, iommu_pgsizes);
+			mutex_unlock(&iommu->lock);
+			return ret;
+		} else if (range.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
+			mutex_lock(&iommu->lock);
+			iommu->dirty_page_tracking = false;
+			vfio_dma_all_bitmap_free(iommu);
+			vfio_remove_unpinned_from_dma_list(iommu);
+			mutex_unlock(&iommu->lock);
+			return 0;
+		} else if (range.flags &
+				 VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
+			long bsize;
+			unsigned long pgshift = __ffs(range.pgsize);
+			uint64_t iommu_pgsizes = vfio_pgsize_bitmap(iommu);
+			uint64_t iommu_pgmask =
+				 ((uint64_t)1 << __ffs(iommu_pgsizes)) - 1;
+
+			if ((range.pgsize & iommu_pgsizes) != range.pgsize)
+				return -EINVAL;
+			if (range.iova & iommu_pgmask)
+				return -EINVAL;
+			if (!range.size || range.size & iommu_pgmask)
+				return -EINVAL;
+			if (range.iova + range.size < range.iova)
+				return -EINVAL;
+			if (!access_ok((void __user *)range.bitmap,
+				       range.bitmap_size))
+				return -EINVAL;
+
+			bsize = verify_bitmap_size(range.size >> pgshift,
+						   range.bitmap_size);
+			if (bsize < 0)
+				return bsize;
+
+			mutex_lock(&iommu->lock);
+			if (iommu->dirty_page_tracking)
+				ret = vfio_iova_dirty_bitmap(iommu, range.iova,
+					 range.size, range.pgsize,
+					 (unsigned char __user *)range.bitmap);
+			else
+				ret = -EINVAL;
+			mutex_unlock(&iommu->lock);
+
+			return ret;
+		}
 	}
 
 	return -ENOTTY;