Skip to contentSkip to conversation

Emulated coherent graphics memory take 2

PATCH Superseded Thomas Hellström (VMware) 6 participants 26 messages Oct 2, 2019 – Oct 4, 2019

Subsystems (6)

v3 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v3 cover Emulated coherent graphics memory take 2

From: Thomas Hellström <[email protected]>

Graphics APIs like OpenGL 4.4 and Vulkan require the graphics driver to provide coherent graphics memory, meaning that the GPU sees any content written to the coherent memory on the next GPU operation that touches that memory, and the CPU sees any content written by the GPU to that memory immediately after any fence object trailing the GPU operation is signaled.

Paravirtual drivers that otherwise require explicit synchronization needs to do this by hooking up dirty tracking to pagefault handlers and buffer object validation.

Provide mm helpers needed for this and that also allow for huge pmd- and pud entries (patch 1-3), and the associated vmwgfx code (patch 4-7).

The code has been tested and exercised by a tailored version of mesa where we disable all explicit synchronization and assume graphics memory is coherent. The performance loss varies of course; a typical number is around 5%.

I would like to merge this code through the DRM tree, so an ack to include the new mm helpers in that merge would be greatly appreciated.

Changes since RFC:
- Merge conflict changes moved to the correct patch. Fixes intra-patchset compile errors.
- Be more aggressive when turning ttm vm code into helpers. This makes sure we can use a const qualifier on the vmwgfx vm_ops.
- Reinstate a lost comment an fix an error path that was broken when turning the ttm vm code into helpers.
- Remove explicit type-casts of struct vm_area_struct::vm_private_data
- Clarify the locking inversion that makes us not being able to use the mm pagewalk code.

Changes since v1:
- Removed the vmwgfx maintainer entry for as_dirty_helpers.c, updated commit message accordingly
- Removed the TTM patches from the series as they are merged separately through DRM.
Changes since v2:
- Split out the pagewalk code from as_dirty_helpers.c and document locking.
- Add pre_vma and post_vma callbacks to the pagewalk code.
- Remove huge pmd and -pud asserts that would trip when we protect vmas with struct address_space::i_mmap_rwsem rather than with
struct vm_area_struct::mmap_sem.
- Do some naming cleanup in as_dirty_helpers.c

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
#1 lore raw

PATCH v3 1/7 mm: Remove BUG_ON mmap_sem not held from xxx_trans_huge_lock()

From: Thomas Hellstrom <[email protected]>

The caller needs to make sure that the vma is not torn down during the lock operation and can also use the i_mmap_rwsem for file-backed vmas. Remove the BUG_ON. We could, as an alternative, add a test that either vma->vm_mm->mmap_sem or vma->vm_file->f_mapping->i_mmap_rwsem are held.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 include/linux/huge_mm.h | 2 --
 1 file changed, 2 deletions(-)
include/linux/huge_mm.h +0 -2
index 93d5cf0bc716..0b84e13e88e2 100644
@@ -216,7 +216,6 @@ static inline int is_swap_pmd(pmd_t pmd)
 static inline spinlock_t *pmd_trans_huge_lock(pmd_t *pmd,
 		struct vm_area_struct *vma)
 {
-	VM_BUG_ON_VMA(!rwsem_is_locked(&vma->vm_mm->mmap_sem), vma);
 	if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd))
 		return __pmd_trans_huge_lock(pmd, vma);
 	else
@@ -225,7 +224,6 @@ static inline spinlock_t *pmd_trans_huge_lock(pmd_t *pmd,
 static inline spinlock_t *pud_trans_huge_lock(pud_t *pud,
 		struct vm_area_struct *vma)
 {
-	VM_BUG_ON_VMA(!rwsem_is_locked(&vma->vm_mm->mmap_sem), vma);
 	if (pud_trans_huge(*pud) || pud_devmap(*pud))
 		return __pud_trans_huge_lock(pud, vma);
 	else
Signature · 1 line
2.20.1
Acked-by on v3 1/7
#2 lore raw

Re: [PATCH v3 1/7] mm: Remove BUG_ON mmap_sem not held from xxx_trans_huge_lock()

Quoted 7 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

The caller needs to make sure that the vma is not torn down during the lock operation and can also use the i_mmap_rwsem for file-backed vmas. Remove the BUG_ON. We could, as an alternative, add a test that either vma->vm_mm->mmap_sem or vma->vm_file->f_mapping->i_mmap_rwsem are held.

Quoted 11 lines
Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>

The patch looks good to me:

But I looked at usage at pagewalk.c and it is inconsitent. The walker takes ptl before calling ->pud_entry(), but not for ->pmd_entry().

It should be fixed: do not take the lock before ->pud_entry(). The callback must take care of it.

Looks like we have single ->pud_entry() implementation the whole kernel. It should be trivial to fix.

Could you do this?

Signature · 1 line
 Kirill A. Shutemov
#3 lore raw

Re: [PATCH v3 1/7] mm: Remove BUG_ON mmap_sem not held from xxx_trans_huge_lock()

Hi, Kirill,

Quoted 26 lines · Kirill A. Shutemov
Quoted 7 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

The caller needs to make sure that the vma is not torn down during the lock operation and can also use the i_mmap_rwsem for file-backed vmas. Remove the BUG_ON. We could, as an alternative, add a test that either vma->vm_mm->mmap_sem or vma->vm_file->f_mapping->i_mmap_rwsem are held.

Quoted 11 lines
Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>

The patch looks good to me:

But I looked at usage at pagewalk.c and it is inconsitent. The walker takes ptl before calling ->pud_entry(), but not for ->pmd_entry().

Quoted 8 lines

It should be fixed: do not take the lock before ->pud_entry(). The callback must take care of it.

Looks like we have single ->pud_entry() implementation the whole kernel. It should be trivial to fix.

Could you do this?

I could probably fix that. There are some comments in the patch introducing that code as to why it was done that way, though, but I don't remember offhand what the arguments were.

But there seems to be more races WRT puds. See my next email. Perhaps this should be fixed as part of a larger audit of the huge_pud code?

/Thomas

#4 lore raw

PATCH v3 2/7 mm: Add a walk_page_mapping() function to the pagewalk code

In reply to Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

For users that want to travers all page table entries pointing into a region of a struct address_space mapping, introduce a walk_page_mapping() function.

The walk_page_mapping() function will be initially be used for dirty- tracking in virtual graphics drivers.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 include/linux/pagewalk.h |  9 ++++
 mm/pagewalk.c            | 99 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 107 insertions(+), 1 deletion(-)
include/linux/pagewalk.h +9 -0
index bddd9759bab9..6ec82e92c87f 100644
@@ -24,6 +24,9 @@ struct mm_walk;
  *			"do page table walk over the current vma", returning
  *			a negative value means "abort current page table walk
  *			right now" and returning 1 means "skip the current vma"
+ * @pre_vma:            if set, called before starting walk on a non-null vma.
+ * @post_vma:           if set, called after a walk on a non-null vma, provided
+ *                      that @pre_vma and the vma walk succeeded.
  */
 struct mm_walk_ops {
 	int (*pud_entry)(pud_t *pud, unsigned long addr,
@@ -39,6 +42,9 @@ struct mm_walk_ops {
 			     struct mm_walk *walk);
 	int (*test_walk)(unsigned long addr, unsigned long next,
 			struct mm_walk *walk);
+	int (*pre_vma)(unsigned long start, unsigned long end,
+		       struct mm_walk *walk);
+	void (*post_vma)(struct mm_walk *walk);
 };
 
 /**
@@ -62,5 +68,8 @@ int walk_page_range(struct mm_struct *mm, unsigned long start,
 		void *private);
 int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops,
 		void *private);
+int walk_page_mapping(struct address_space *mapping, pgoff_t first_index,
+		      pgoff_t nr, const struct mm_walk_ops *ops,
+		      void *private);
 
 #endif /* _LINUX_PAGEWALK_H */
mm/pagewalk.c +98 -1

125 lines not on this page · raw message

Signature · 1 line
2.20.1
#5 lore raw

Re: [PATCH v3 2/7] mm: Add a walk_page_mapping() function to the pagewalk code

Quoted 6 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

For users that want to travers all page table entries pointing into a region of a struct address_space mapping, introduce a walk_page_mapping() function.

This looks non-offensive to me.

My main reaction was "oh, really good that we split up the walker ops from the mm_walk structure, this would have been much uglier before that" due to the added vma entry/exit ops.

Linus

#6 lore raw

Re: [PATCH v3 2/7] mm: Add a walk_page_mapping() function to the pagewalk code

In reply to Thomas Hellström (VMware)
Quoted 133 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

For users that want to travers all page table entries pointing into a region of a struct address_space mapping, introduce a walk_page_mapping() function.

The walk_page_mapping() function will be initially be used for dirty- tracking in virtual graphics drivers.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 include/linux/pagewalk.h |  9 ++++
 mm/pagewalk.c            | 99 +++++++++++++++++++++++++++++++++++++++-
 2 files changed, 107 insertions(+), 1 deletion(-)
include/linux/pagewalk.h +9 -0
index bddd9759bab9..6ec82e92c87f 100644
@@ -24,6 +24,9 @@ struct mm_walk;
  *			"do page table walk over the current vma", returning
  *			a negative value means "abort current page table walk
  *			right now" and returning 1 means "skip the current vma"
+ * @pre_vma:            if set, called before starting walk on a non-null vma.
+ * @post_vma:           if set, called after a walk on a non-null vma, provided
+ *                      that @pre_vma and the vma walk succeeded.
  */
 struct mm_walk_ops {
 	int (*pud_entry)(pud_t *pud, unsigned long addr,
@@ -39,6 +42,9 @@ struct mm_walk_ops {
 			     struct mm_walk *walk);
 	int (*test_walk)(unsigned long addr, unsigned long next,
 			struct mm_walk *walk);
+	int (*pre_vma)(unsigned long start, unsigned long end,
+		       struct mm_walk *walk);
+	void (*post_vma)(struct mm_walk *walk);
 };
 
 /**
@@ -62,5 +68,8 @@ int walk_page_range(struct mm_struct *mm, unsigned long start,
 		void *private);
 int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops,
 		void *private);
+int walk_page_mapping(struct address_space *mapping, pgoff_t first_index,
+		      pgoff_t nr, const struct mm_walk_ops *ops,
+		      void *private);
 
 #endif /* _LINUX_PAGEWALK_H */
mm/pagewalk.c +41 -1
index d48c2a986ea3..658d1e5ec428 100644
@@ -253,13 +253,23 @@ static int __walk_page_range(unsigned long start, unsigned long end,
 {
 	int err = 0;
 	struct vm_area_struct *vma = walk->vma;
+	const struct mm_walk_ops *ops = walk->ops;
+
+	if (vma && ops->pre_vma) {
+		err = ops->pre_vma(start, end, walk);
+		if (err)
+			return err;
+	}
 
 	if (vma && is_vm_hugetlb_page(vma)) {
-		if (walk->ops->hugetlb_entry)
+		if (ops->hugetlb_entry)
 			err = walk_hugetlb_range(start, end, walk);
 	} else
 		err = walk_pgd_range(start, end, walk);
 
+	if (vma && ops->post_vma)
+		ops->post_vma(walk);
+
 	return err;
 }
 
@@ -285,11 +295,17 @@ static int __walk_page_range(unsigned long start, unsigned long end,
  *  - <0 : failed to handle the current entry, and return to the caller
  *         with error code.
  *
+ *
  * Before starting to walk page table, some callers want to check whether
  * they really want to walk over the current vma, typically by checking
  * its vm_flags. walk_page_test() and @ops->test_walk() are used for this
  * purpose.
  *
+ * If operations need to be staged before and committed after a vma is walked,
+ * there are two callbacks, pre_vma() and post_vma(). Note that post_vma(),
+ * since it is intended to handle commit-type operations, can't return any
+ * errors.
+ *
  * struct mm_walk keeps current values of some common data like vma and pmd,
  * which are useful for the access from callbacks. If you want to pass some
  * caller-specific data to callbacks, @private should be helpful.
@@ -376,3 +392,84 @@ int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops,
 		return err;
 	return __walk_page_range(vma->vm_start, vma->vm_end, &walk);
 }
+
+/**
+ * walk_page_mapping - walk all memory areas mapped into a struct address_space.
+ * @mapping: Pointer to the struct address_space
+ * @first_index: First page offset in the address_space
+ * @nr: Number of incremental page offsets to cover
+ * @ops:	operation to call during the walk
+ * @private:	private data for callbacks' usage
+ *
+ * This function walks all memory areas mapped into a struct address_space.
+ * The walk is limited to only the given page-size index range, but if
+ * the index boundaries cross a huge page-table entry, that entry will be
+ * included.
+ *
+ * Also see walk_page_range() for additional information.
+ *
+ * Locking:
+ *   This function can't require that the struct mm_struct::mmap_sem is held,
+ *   since @mapping may be mapped by multiple processes. Instead
+ *   @mapping->i_mmap_rwsem must be held. This might have implications in the
+ *   callbacks, and it's up tho the caller to ensure that the
+ *   struct mm_struct::mmap_sem is not needed.
+ *
+ *   Also this means that a caller can't rely on the struct

mm/pagewalk.c int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops, · line 428

Quoted 10 lines
mm/pagewalk.c +10 -0
+ *   vm_area_struct::vm_flags to be constant across a call,
+ *   except for immutable flags. Callers requiring this shouldn't use
+ *   this function.
+ *
+ *   If @mapping allows faulting of huge pmds and puds, it is desirable
+ *   that its huge_fault() handler blocks while this function is running on
+ *   @mapping. Otherwise a race may occur where the huge entry is split when
+ *   it was intended to be handled in a huge entry callback. This requires an
+ *   external lock, for example that @mapping->i_mmap_rwsem is held in
+ *   write mode in the huge_fault() handlers.

Em. No. We have ptl for this. It's the only lock required (plus mmap_sem on read) to split PMD entry into PTE table. And it can happen not only from fault path.

If you care about splitting compound page under you, take a pin or lock a page. It will block split_huge_page().

Suggestion to block fault path is not viable (and it will not happen magically just because of this comment).

Quoted 50 lines
mm/pagewalk.c +47 -0
+ */
+int walk_page_mapping(struct address_space *mapping, pgoff_t first_index,
+		      pgoff_t nr, const struct mm_walk_ops *ops,
+		      void *private)
+{
+	struct mm_walk walk = {
+		.ops		= ops,
+		.private	= private,
+	};
+	struct vm_area_struct *vma;
+	pgoff_t vba, vea, cba, cea;
+	unsigned long start_addr, end_addr;
+	int err = 0;
+
+	lockdep_assert_held(&mapping->i_mmap_rwsem);
+	vma_interval_tree_foreach(vma, &mapping->i_mmap, first_index,
+				  first_index + nr - 1) {
+		/* Clip to the vma */
+		vba = vma->vm_pgoff;
+		vea = vba + vma_pages(vma);
+		cba = first_index;
+		cba = max(cba, vba);
+		cea = first_index + nr;
+		cea = min(cea, vea);
+
+		start_addr = ((cba - vba) << PAGE_SHIFT) + vma->vm_start;
+		end_addr = ((cea - vba) << PAGE_SHIFT) + vma->vm_start;
+		if (start_addr >= end_addr)
+			continue;
+
+		walk.vma = vma;
+		walk.mm = vma->vm_mm;
+
+		err = walk_page_test(vma->vm_start, vma->vm_end, &walk);
+		if (err > 0) {
+			err = 0;
+			break;
+		} else if (err < 0)
+			break;
+
+		err = __walk_page_range(start_addr, end_addr, &walk);
+		if (err)
+			break;
+	}
+
+	return err;
+}
Signature · 1 line
2.20.1
Signature · 1 line
 Kirill A. Shutemov
#7 lore raw

Re: [PATCH v3 2/7] mm: Add a walk_page_mapping() function to the pagewalk code

Quoted 148 lines · Kirill A. Shutemov
Quoted 133 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

For users that want to travers all page table entries pointing into a region of a struct address_space mapping, introduce a walk_page_mapping() function.

The walk_page_mapping() function will be initially be used for dirty- tracking in virtual graphics drivers.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
  include/linux/pagewalk.h |  9 ++++
  mm/pagewalk.c            | 99 +++++++++++++++++++++++++++++++++++++++-
  2 files changed, 107 insertions(+), 1 deletion(-)
include/linux/pagewalk.h +9 -0
index bddd9759bab9..6ec82e92c87f 100644
@@ -24,6 +24,9 @@ struct mm_walk;
   *			"do page table walk over the current vma", returning
   *			a negative value means "abort current page table walk
   *			right now" and returning 1 means "skip the current vma"
+ * @pre_vma:            if set, called before starting walk on a non-null vma.
+ * @post_vma:           if set, called after a walk on a non-null vma, provided
+ *                      that @pre_vma and the vma walk succeeded.
   */
  struct mm_walk_ops {
  	int (*pud_entry)(pud_t *pud, unsigned long addr,
@@ -39,6 +42,9 @@ struct mm_walk_ops {
  			     struct mm_walk *walk);
  	int (*test_walk)(unsigned long addr, unsigned long next,
  			struct mm_walk *walk);
+	int (*pre_vma)(unsigned long start, unsigned long end,
+		       struct mm_walk *walk);
+	void (*post_vma)(struct mm_walk *walk);
  };
 
  /**
@@ -62,5 +68,8 @@ int walk_page_range(struct mm_struct *mm, unsigned long start,
  		void *private);
  int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops,
  		void *private);
+int walk_page_mapping(struct address_space *mapping, pgoff_t first_index,
+		      pgoff_t nr, const struct mm_walk_ops *ops,
+		      void *private);
 
  #endif /* _LINUX_PAGEWALK_H */
mm/pagewalk.c +41 -1
index d48c2a986ea3..658d1e5ec428 100644
@@ -253,13 +253,23 @@ static int __walk_page_range(unsigned long start, unsigned long end,
  {
  	int err = 0;
  	struct vm_area_struct *vma = walk->vma;
+	const struct mm_walk_ops *ops = walk->ops;
+
+	if (vma && ops->pre_vma) {
+		err = ops->pre_vma(start, end, walk);
+		if (err)
+			return err;
+	}
 
  	if (vma && is_vm_hugetlb_page(vma)) {
-		if (walk->ops->hugetlb_entry)
+		if (ops->hugetlb_entry)
  			err = walk_hugetlb_range(start, end, walk);
  	} else
  		err = walk_pgd_range(start, end, walk);
 
+	if (vma && ops->post_vma)
+		ops->post_vma(walk);
+
  	return err;
  }
 
@@ -285,11 +295,17 @@ static int __walk_page_range(unsigned long start, unsigned long end,
   *  - <0 : failed to handle the current entry, and return to the caller
   *         with error code.
   *
+ *
   * Before starting to walk page table, some callers want to check whether
   * they really want to walk over the current vma, typically by checking
   * its vm_flags. walk_page_test() and @ops->test_walk() are used for this
   * purpose.
   *
+ * If operations need to be staged before and committed after a vma is walked,
+ * there are two callbacks, pre_vma() and post_vma(). Note that post_vma(),
+ * since it is intended to handle commit-type operations, can't return any
+ * errors.
+ *
   * struct mm_walk keeps current values of some common data like vma and pmd,
   * which are useful for the access from callbacks. If you want to pass some
   * caller-specific data to callbacks, @private should be helpful.
@@ -376,3 +392,84 @@ int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops,
  		return err;
  	return __walk_page_range(vma->vm_start, vma->vm_end, &walk);
  }
+
+/**
+ * walk_page_mapping - walk all memory areas mapped into a struct address_space.
+ * @mapping: Pointer to the struct address_space
+ * @first_index: First page offset in the address_space
+ * @nr: Number of incremental page offsets to cover
+ * @ops:	operation to call during the walk
+ * @private:	private data for callbacks' usage
+ *
+ * This function walks all memory areas mapped into a struct address_space.
+ * The walk is limited to only the given page-size index range, but if
+ * the index boundaries cross a huge page-table entry, that entry will be
+ * included.
+ *
+ * Also see walk_page_range() for additional information.
+ *
+ * Locking:
+ *   This function can't require that the struct mm_struct::mmap_sem is held,
+ *   since @mapping may be mapped by multiple processes. Instead
+ *   @mapping->i_mmap_rwsem must be held. This might have implications in the
+ *   callbacks, and it's up tho the caller to ensure that the
+ *   struct mm_struct::mmap_sem is not needed.
+ *
+ *   Also this means that a caller can't rely on the struct

mm/pagewalk.c int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops, · line 428

Quoted 10 lines
mm/pagewalk.c +10 -0
+ *   vm_area_struct::vm_flags to be constant across a call,
+ *   except for immutable flags. Callers requiring this shouldn't use
+ *   this function.
+ *
+ *   If @mapping allows faulting of huge pmds and puds, it is desirable
+ *   that its huge_fault() handler blocks while this function is running on
+ *   @mapping. Otherwise a race may occur where the huge entry is split when
+ *   it was intended to be handled in a huge entry callback. This requires an
+ *   external lock, for example that @mapping->i_mmap_rwsem is held in
+ *   write mode in the huge_fault() handlers.

Em. No. We have ptl for this. It's the only lock required (plus mmap_sem on read) to split PMD entry into PTE table. And it can happen not only from fault path.

Quoted 6 lines

If you care about splitting compound page under you, take a pin or lock a page. It will block split_huge_page().

Suggestion to block fault path is not viable (and it will not happen magically just because of this comment).

I was specifically thinking of this:

https://elixir.bootlin.com/linux/latest/source/mm/pagewalk.c#L103

If a huge pud is concurrently faulted in here, it will immediatly get split without getting processed in pud_entry(). An external lock would protect against that, but that's perhaps a bug in the pagewalk code?  For pmds the situation is not the same since when pte_entry is used, all pmds will unconditionally get split.

There's a similar more scary race in

https://elixir.bootlin.com/linux/latest/source/mm/memory.c#L3931

It looks like if a concurrent thread faults in a huge pud just after the test for pud_none in that pmd_alloc, things might go pretty bad.

/Thomas

#8 lore raw

Re: [PATCH v3 2/7] mm: Add a walk_page_mapping() function to the pagewalk code

Quoted 18 lines · Thomas Hellström (VMware)
Quoted 10 lines
Quoted 6 lines
+ *   If @mapping allows faulting of huge pmds and puds, it is desirable
+ *   that its huge_fault() handler blocks while this function is running on
+ *   @mapping. Otherwise a race may occur where the huge entry is split when
+ *   it was intended to be handled in a huge entry callback. This requires an
+ *   external lock, for example that @mapping->i_mmap_rwsem is held in
+ *   write mode in the huge_fault() handlers.

Em. No. We have ptl for this. It's the only lock required (plus mmap_sem on read) to split PMD entry into PTE table. And it can happen not only from fault path.

Quoted 6 lines

If you care about splitting compound page under you, take a pin or lock a page. It will block split_huge_page().

Suggestion to block fault path is not viable (and it will not happen magically just because of this comment).

I was specifically thinking of this:

Quoted 7 lines

https://elixir.bootlin.com/linux/latest/source/mm/pagewalk.c#L103

If a huge pud is concurrently faulted in here, it will immediatly get split without getting processed in pud_entry(). An external lock would protect against that, but that's perhaps a bug in the pagewalk code?  For pmds the situation is not the same since when pte_entry is used, all pmds will unconditionally get split.

I *think* it should be fixed with something like this (there's no pud_trans_unstable() yet):

mm/pagewalk.c +3 -2
index d48c2a986ea3..221a3b945f42 100644
@@ -102,10 +102,11 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
 					break;
 				continue;
 			}
+		} else {
+			split_huge_pud(walk->vma, pud, addr);
 		}
 
-		split_huge_pud(walk->vma, pud, addr);
-		if (pud_none(*pud))
+		if (pud_none(*pud) || pud_trans_unstable(*pud))
 			goto again;
 
 		if (ops->pmd_entry || ops->pte_entry)

Or better yet converted to what we do on pmd level.

Honestly, all the code around PUD THP missing a lot of ground work. Rushing it upstream for DAX was not a right move.

Quoted 6 lines

There's a similar more scary race in

https://elixir.bootlin.com/linux/latest/source/mm/memory.c#L3931

It looks like if a concurrent thread faults in a huge pud just after the test for pud_none in that pmd_alloc, things might go pretty bad.

Hm? It will fail the next pmd_none() check under ptl. Do you have a particular racing scenarion?

Signature · 1 line
 Kirill A. Shutemov
#9 lore raw

Re: [PATCH v3 2/7] mm: Add a walk_page_mapping() function to the pagewalk code

Quoted 37 lines · Kirill A. Shutemov
Quoted 18 lines · Thomas Hellström (VMware)
Quoted 10 lines
Quoted 6 lines
+ *   If @mapping allows faulting of huge pmds and puds, it is desirable
+ *   that its huge_fault() handler blocks while this function is running on
+ *   @mapping. Otherwise a race may occur where the huge entry is split when
+ *   it was intended to be handled in a huge entry callback. This requires an
+ *   external lock, for example that @mapping->i_mmap_rwsem is held in
+ *   write mode in the huge_fault() handlers.

Em. No. We have ptl for this. It's the only lock required (plus mmap_sem on read) to split PMD entry into PTE table. And it can happen not only from fault path.

Quoted 6 lines

If you care about splitting compound page under you, take a pin or lock a page. It will block split_huge_page().

Suggestion to block fault path is not viable (and it will not happen magically just because of this comment).

I was specifically thinking of this:

Quoted 7 lines

https://elixir.bootlin.com/linux/latest/source/mm/pagewalk.c#L103

If a huge pud is concurrently faulted in here, it will immediatly get split without getting processed in pud_entry(). An external lock would protect against that, but that's perhaps a bug in the pagewalk code?  For pmds the situation is not the same since when pte_entry is used, all pmds will unconditionally get split.

I *think* it should be fixed with something like this (there's no pud_trans_unstable() yet):

mm/pagewalk.c +0 -0
index d48c2a986ea3..221a3b945f42 100644
@@ -102,10 +102,11 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
  					break;
  				continue;
  			}

mm/pagewalk.c static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, · line 112

Quoted 10 lines
mm/pagewalk.c +3 -2
+		} else {
+			split_huge_pud(walk->vma, pud, addr);
  		}
 
-		split_huge_pud(walk->vma, pud, addr);
-		if (pud_none(*pud))
+		if (pud_none(*pud) || pud_trans_unstable(*pud))
  			goto again;
 
  		if (ops->pmd_entry || ops->pte_entry)

Yes, this seems better. I was looking at implementing a pud_trans_unstable() as a basis of fixing problems like this, but when I looked at pmd_trans_unstable I got a bit confused:

Why are devmap huge pmds considered stable? I mean, couldn't anybody just run madvise() to clear those just like transhuge pmds?

Quoted 6 lines

Or better yet converted to what we do on pmd level.

Honestly, all the code around PUD THP missing a lot of ground work. Rushing it upstream for DAX was not a right move.

Quoted 9 lines
Quoted 6 lines

There's a similar more scary race in

https://elixir.bootlin.com/linux/latest/source/mm/memory.c#L3931

It looks like if a concurrent thread faults in a huge pud just after the test for pud_none in that pmd_alloc, things might go pretty bad.

Hm? It will fail the next pmd_none() check under ptl. Do you have a particular racing scenarion?

Yes, I misinterpreted the code somewhat, but here's the scenario that looks racy:

Thread 1 Thread 2
huge_fault(pud) - Fell back, for example because of write fault on dirty-tracking.
huge_fault(pud) - Taken, read fault.
pmd_alloc() - Will fail pmd_none check and return a pmd_offset()
into thread 2's THP.

Thanks,

Thomas

#10 lore raw

Re: [PATCH v3 2/7] mm: Add a walk_page_mapping() function to the pagewalk code

Quoted 51 lines · Thomas Hellström (VMware)
Quoted 35 lines · Kirill A. Shutemov
Quoted 18 lines · Thomas Hellström (VMware)
Quoted 10 lines
Quoted 6 lines
+ *   If @mapping allows faulting of huge pmds and puds, it is desirable
+ *   that its huge_fault() handler blocks while this function is running on
+ *   @mapping. Otherwise a race may occur where the huge entry is split when
+ *   it was intended to be handled in a huge entry callback. This requires an
+ *   external lock, for example that @mapping->i_mmap_rwsem is held in
+ *   write mode in the huge_fault() handlers.

Em. No. We have ptl for this. It's the only lock required (plus mmap_sem on read) to split PMD entry into PTE table. And it can happen not only from fault path.

Quoted 6 lines

If you care about splitting compound page under you, take a pin or lock a page. It will block split_huge_page().

Suggestion to block fault path is not viable (and it will not happen magically just because of this comment).

I was specifically thinking of this:

Quoted 7 lines

https://elixir.bootlin.com/linux/latest/source/mm/pagewalk.c#L103

If a huge pud is concurrently faulted in here, it will immediatly get split without getting processed in pud_entry(). An external lock would protect against that, but that's perhaps a bug in the pagewalk code?  For pmds the situation is not the same since when pte_entry is used, all pmds will unconditionally get split.

I *think* it should be fixed with something like this (there's no pud_trans_unstable() yet):

mm/pagewalk.c +0 -0
index d48c2a986ea3..221a3b945f42 100644
@@ -102,10 +102,11 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
  					break;

mm/pagewalk.c static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, · line 110

Quoted 10 lines
mm/pagewalk.c +3 -2
  				continue;
  			}
+		} else {
+			split_huge_pud(walk->vma, pud, addr);
  		}
-		split_huge_pud(walk->vma, pud, addr);
-		if (pud_none(*pud))
+		if (pud_none(*pud) || pud_trans_unstable(*pud))
  			goto again;
  		if (ops->pmd_entry || ops->pte_entry)

Yes, this seems better. I was looking at implementing a pud_trans_unstable() as a basis of fixing problems like this, but when I looked at pmd_trans_unstable I got a bit confused:

Quoted 2 lines

Why are devmap huge pmds considered stable? I mean, couldn't anybody just run madvise() to clear those just like transhuge pmds?

Matthew, Dan, could you comment on this?

Quoted 14 lines
Quoted 5 lines

Or better yet converted to what we do on pmd level.

Honestly, all the code around PUD THP missing a lot of ground work. Rushing it upstream for DAX was not a right move.

Quoted 9 lines
Quoted 6 lines

There's a similar more scary race in

https://elixir.bootlin.com/linux/latest/source/mm/memory.c#L3931

It looks like if a concurrent thread faults in a huge pud just after the test for pud_none in that pmd_alloc, things might go pretty bad.

Hm? It will fail the next pmd_none() check under ptl. Do you have a particular racing scenarion?

Quoted 7 lines

Yes, I misinterpreted the code somewhat, but here's the scenario that looks racy:

Thread 1 Thread 2
huge_fault(pud) - Fell back, for example because of write fault on dirty-tracking.
huge_fault(pud) - Taken, read fault.
pmd_alloc() - Will fail pmd_none check and return a pmd_offset()

I see. It also misses pud_tans_unstable() check or its variant.

Signature · 1 line
 Kirill A. Shutemov
#11 lore raw

PATCH v3 3/7 mm: Add write-protect and clean utilities for address space ranges

In reply to Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

Add two utilities to a) write-protect and b) clean all ptes pointing into a range of an address space.
The utilities are intended to aid in tracking dirty pages (either driver-allocated system memory or pci device memory).
The write-protect utility should be used in conjunction with page_mkwrite() and pfn_mkwrite() to trigger write page-faults on page accesses. Typically one would want to use this on sparse accesses into large memory regions. The clean utility should be used to utilize hardware dirtying functionality and avoid the overhead of page-faults, typically on large accesses into small memory regions.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 include/linux/mm.h    |  13 +-
 mm/Kconfig            |   3 +
 mm/Makefile           |   1 +
 mm/as_dirty_helpers.c | 315 ++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 331 insertions(+), 1 deletion(-)
 create mode 100644 mm/as_dirty_helpers.c
include/linux/mm.h +12 -1
index cc292273e6ba..4a9b02f7f91c 100644
@@ -2637,7 +2637,6 @@ typedef int (*pte_fn_t)(pte_t *pte, unsigned long addr, void *data);
 extern int apply_to_page_range(struct mm_struct *mm, unsigned long address,
 			       unsigned long size, pte_fn_t fn, void *data);
 
-
 #ifdef CONFIG_PAGE_POISONING
 extern bool page_poisoning_enabled(void);
 extern void kernel_poison_pages(struct page *page, int numpages, int enable);
@@ -2878,5 +2877,17 @@ static inline int pages_identical(struct page *page1, struct page *page2)
 	return !memcmp_pages(page1, page2);
 }
 
+#ifdef CONFIG_AS_DIRTY_HELPERS
+unsigned long as_dirty_clean(struct address_space *mapping,
+			     pgoff_t first_index, pgoff_t nr,
+			     pgoff_t bitmap_pgoff,
+			     unsigned long *bitmap,
+			     pgoff_t *start,
+			     pgoff_t *end);
+
+unsigned long as_dirty_wrprotect(struct address_space *mapping,
+				 pgoff_t first_index, pgoff_t nr);
+#endif
+
 #endif /* __KERNEL__ */
 #endif /* _LINUX_MM_H */
mm/Kconfig +3 -0
index a5dae9a7eb51..7a0538fe507f 100644
@@ -736,4 +736,7 @@ config ARCH_HAS_PTE_SPECIAL
 config ARCH_HAS_HUGEPD
 	bool
 
+config AS_DIRTY_HELPERS
+        bool
+
 endmenu
mm/Makefile +1 -0
index d996846697ef..828bf4278c9d 100644
@@ -107,3 +107,4 @@ obj-$(CONFIG_PERCPU_STATS) += percpu-stats.o
 obj-$(CONFIG_ZONE_DEVICE) += memremap.o
 obj-$(CONFIG_HMM_MIRROR) += hmm.o
 obj-$(CONFIG_MEMFD_CREATE) += memfd.o
+obj-$(CONFIG_AS_DIRTY_HELPERS) += as_dirty_helpers.o
mm/as_dirty_helpers.c new file +315 -0

315 lines not on this page · raw message

Signature · 1 line
2.20.1
#12 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 5 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

Add two utilities to a) write-protect and b) clean all ptes pointing into a range of an address space.

This one I still don't exactly love.

I'm not entirely sure what rubs me the wrong way, but part of it is naming. We don't use the name "as", because it reads as (sic) an English word.

The name we use for address_space pointers is "mapping", both for variables and for existing functions.

See for example "pte_same_as_swp()" which uses "as" as the _word_ 'as'.

Contrast that with "unmap_mapping_range()" or "mapping_set_unevictable()" or "read_mapping_page()" or "invalidate_mapping_pages()", that all work on address spaces.

So please don't use 'as' as shorthand for that - eithe rin the function names or the filename.

I'm not sure if that's the _only_ thing that raises my heckles when I read this patch, but I think it might be. So I'm not saying "ack with naming change", but I suspect that if the naming was changed, it would look much better to me.

Yes, it's a bit more typing. But I really think "clean_mapping_dirty_pages()" is just not only more in line with the mm naming, I think it's a lot more legible and understandable than "as_dirty_clean()", which just makes me go "what the heck does that function do?"

And I really think it needs more than just "as" -> "mapping". "mapping_dirty_clean()" still makes me go "what?" in a way that "clean_mapping_dirty_pages()" does not. One name reads as a series or random words, the other reads as a "this is what the function does".

I know I sometimes get hung up about naming, but I do think naming matters. A descriptive name that just reads as what the function does makes it much easier to read the logic of code, imnsho.

Linus

#13 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 7 lines · Linus Torvalds
Quoted 5 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

Add two utilities to a) write-protect and b) clean all ptes pointing into a range of an address space.

[...]

Quoted 10 lines

Yes, it's a bit more typing. But I really think "clean_mapping_dirty_pages()" is just not only more in line with the mm naming, I think it's a lot more legible and understandable than "as_dirty_clean()", which just makes me go "what the heck does that function do?"

And I really think it needs more than just "as" -> "mapping". "mapping_dirty_clean()" still makes me go "what?" in a way that "clean_mapping_dirty_pages()" does not. One name reads as a series or random words, the other reads as a "this is what the function does".

I'd suggest clean_mapping_pages() -- a function which does that would naturally skip the non-dirty pages, and that doesn't need to be in the function name.

#14 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

In reply to Linus Torvalds
Quoted 40 lines · Linus Torvalds
Quoted 4 lines · Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

Add two utilities to a) write-protect and b) clean all ptes pointing into a range of an address space.

This one I still don't exactly love.

I'm not entirely sure what rubs me the wrong way, but part of it is naming. We don't use the name "as", because it reads as (sic) an English word.

The name we use for address_space pointers is "mapping", both for variables and for existing functions.

See for example "pte_same_as_swp()" which uses "as" as the _word_ 'as'.

Contrast that with "unmap_mapping_range()" or "mapping_set_unevictable()" or "read_mapping_page()" or "invalidate_mapping_pages()", that all work on address spaces.

So please don't use 'as' as shorthand for that - eithe rin the function names or the filename.

I'm not sure if that's the _only_ thing that raises my heckles when I read this patch, but I think it might be. So I'm not saying "ack with naming change", but I suspect that if the naming was changed, it would look much better to me.

Yes, it's a bit more typing. But I really think "clean_mapping_dirty_pages()" is just not only more in line with the mm naming, I think it's a lot more legible and understandable than "as_dirty_clean()", which just makes me go "what the heck does that function do?"

And I really think it needs more than just "as" -> "mapping". "mapping_dirty_clean()" still makes me go "what?" in a way that "clean_mapping_dirty_pages()" does not. One name reads as a series or random words, the other reads as a "this is what the function does".

Quoted 5 lines

I know I sometimes get hung up about naming, but I do think naming matters. A descriptive name that just reads as what the function does makes it much easier to read the logic of code, imnsho.

Linus

Yes I typically tend towards using a "namespace_object_operation" naming scheme, with "as_dirty" being the namespace here,

But I'll give it a shot to see if I can rename it more in line with the above.

Looking at Matthew's suggestion but lining up with "unmap_mapping_range()", perhaps we could use "clean_mapping_range" and "wp_mapping_range"?

Thanks,

Thomas

#15 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 3 lines · Thomas Hellström (VMware)

Yes I typically tend towards using a "namespace_object_operation" naming scheme, with "as_dirty" being the namespace here,

We discourage that kind of mindless namespacing for core stuff.

It makes sense in a driver or a filesystem: when there are 20+ different filesystems all implementing the same operation, you can't have descriptive and natural names that are unique. So having a namespace prefix for the filesystem or driver makes sense. But even then it tends ot be just a simple name, not the op it does.

Quoted 3 lines

Looking at Matthew's suggestion but lining up with "unmap_mapping_range()", perhaps we could use "clean_mapping_range" and "wp_mapping_range"?

Yes, I agree with Willy that "dirty" is kind of implicit when the operation is to clean something, so the above sounds sane to me.

The wp part I'm not entirely sure about: you're not actually write-protecting the range. You're doing something different. You're only doing it for shared writable mappings. And I'd rather see separate 'struct mm_walk_ops' than shared ones that then have a flag in a differfent structure to change behavior.

Yes, yes, some of the levels share the same logic, but that just means that you can use the same function pointer for that level in the different "clean" vs "wp" mm_walk_op.

Also, looking closer at this patch, this makes me go "Whaa?":

+ pte = (mm == &init_mm) ?
+ pte_offset_kernel(pmd, addr) :
+ pte_offset_map_lock(mm, pmd, addr, &ptl);

because I don't think that's sensible. When do you have a vma in kernel space?

Also, why do you loop inside the pmd_entry function, instead of just having a pte_entry function?

Linus

#16 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 11 lines · Linus Torvalds
Quoted 2 lines · Thomas Hellström (VMware)

Yes I typically tend towards using a "namespace_object_operation" naming scheme, with "as_dirty" being the namespace here,

We discourage that kind of mindless namespacing for core stuff.

It makes sense in a driver or a filesystem: when there are 20+ different filesystems all implementing the same operation, you can't have descriptive and natural names that are unique. So having a namespace prefix for the filesystem or driver makes sense. But even then it tends ot be just a simple name, not the op it does.

Understood.

Quoted 10 lines
Quoted 4 lines

Looking at Matthew's suggestion but lining up with "unmap_mapping_range()", perhaps we could use "clean_mapping_range" and "wp_mapping_range"?

Yes, I agree with Willy that "dirty" is kind of implicit when the operation is to clean something, so the above sounds sane to me.

The wp part I'm not entirely sure about: you're not actually write-protecting the range. You're doing something different. You're only doing it for shared writable mappings.

Both the cleaning operation and the wp operation operate on shared writable mappings, and since they are also both restricted to entries that may take part in dirty-tracking (they're ignoring pmds and puds), so perhaps a "dirty" may make sense anyway, and to point out the similarity:

clean_mapping_dirty_range() and wp_mapping_dirty_range()"?

Quoted 7 lines

And I'd rather see
separate 'struct mm_walk_ops' than shared ones that then have a flag in a differfent structure to change behavior.

Yes, yes, some of the levels share the same logic, but that just means that you can use the same function pointer for that level in the different "clean" vs "wp" mm_walk_op.

I think that this comment and this last one:

Quoted 2 lines

Also, why do you loop inside the pmd_entry function, instead of just having a pte_entry function?"

are tied together. The pagewalk code is kind of awkward since if you provide a pte_entry function,
then huge pmds are unconditionally split, even if handled in pmd_entry, forcing pmd-aware users to handle also ptes in pmd_entry(). I'm not entirely sure why, but it looks like it's to avoid a race where huge pmds could otherwise be unintentionally split if appearing *after* the pmd_entry() call. Other pagewalk users do the same here, see for example clear_refs_pte_range();

https://elixir.bootlin.com/linux/latest/source/fs/proc/task_mmu.c#L1040

Also the pagewalk walk_pte_range() for some reason doesn't take the page table lock, which means that a pte may well be cleared under us while we have it cached for modification.

For these reasons we can't use the pte_entry, even internally and this means we have three choices:

a) Selecting the pte function using a bool. Saves code and avoids extra indirect function call.
b) Duplicating the pmd_entry with a different pte function, also duplicating the ops. Avoids extra indirect function call but some extra code.
c) Instead of the bool, use another function pointer in yet another ops pointed to by the private structure. Saves some code.

I opted for a) here, but I can of course change that if needed?

Quoted 11 lines

Also, looking closer at this patch, this makes me go "Whaa?":

mm/as_dirty_helpers.c new file +3 -0
+       pte = (mm == &init_mm) ?
+               pte_offset_kernel(pmd, addr) :
+               pte_offset_map_lock(mm, pmd, addr, &ptl);

because I don't think that's sensible. When do you have a vma in kernel space?

Also, why do you loop inside the pmd_entry function, instead of just having a pte_entry function?

Yes, that was a blind copy from v1 of the code that used "apply_to_page_range()". I'll fix that up.

Thanks,

/Thomas

Quoted 3 lines

Linus

#17 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 7 lines · Thomas Hellstrom

Both the cleaning operation and the wp operation operate on shared writable mappings, and since they are also both restricted to entries that may take part in dirty-tracking (they're ignoring pmds and puds), so perhaps a "dirty" may make sense anyway, and to point out the similarity:

clean_mapping_dirty_range() and wp_mapping_dirty_range()"?

Hmm. Yeah, either that, or "shared", as in "clean_shared_mapping_range()"?

I don't know. Maybe this isn't a huge deal, and the "don't care about private dirty/write" is kind of implied by the fact that it's about the backing mapping rather than the vma.

But on the other hand we do have things like "unmap_mapping_range()" which will unmap all the private mappings too, so maybe it's a good idea to clarify that this is about shared mappings.

I suspect it's a bit of a bike shed, and I could go either way.

Quoted 8 lines
Quoted 7 lines

And I'd rather see
separate 'struct mm_walk_ops' than shared ones that then have a flag in a differfent structure to change behavior.

Yes, yes, some of the levels share the same logic, but that just means that you can use the same function pointer for that level in the different "clean" vs "wp" mm_walk_op.

Quoted 7 lines

I think that this comment and this last one:

Quoted 2 lines

Also, why do you loop inside the pmd_entry function, instead of just having a pte_entry function?"

are tied together. The pagewalk code is kind of awkward since if you provide a pte_entry function, then huge pmds are unconditionally split,

So I think that we could handle differently.

But even if you don't want to do the pte_entry function, the "use two different set of walker op structures" stands. Instead of havign a test for "am I walking for wp or not", just make it implicit.

Also, I do think that you're seeing what is a weakness in the pte walkers wrt splitting. I do think we shouldn't split unconditionally.

I suspect we should instead change the logic to split only if we didn't have a pmd_entry. Because looking at the existing cases, if you have a pmd_entry, you currently never have a pte_entry, so it wouldn't change semantics for current cases.

Quoted 5 lines

even if handled in pmd_entry,
forcing pmd-aware users to handle also ptes in pmd_entry(). I'm not entirely sure why, but it looks like it's to avoid a race where huge pmds could otherwise be unintentionally split if appearing *after* the pmd_entry() call.

See above: we never have both pmd_entry and pte_entry walkers as it is right now. So you can't have that race.

Quoted 8 lines

Other pagewalk users do the same here, see for
example clear_refs_pte_range();

https://elixir.bootlin.com/linux/latest/source/fs/proc/task_mmu.c#L1040

Also the pagewalk walk_pte_range() for some reason doesn't take the page table lock, which means that a pte may well be cleared under us while we have it cached for modification.

Ho humm. That looks really sketchy to me. We actually have very few pte_entry cases, perhaps exactly because it's all kinds of broken.

There's a couple of odd architectures, and then there is prot_none_walk_ops. And that one purely looks at the pte's, and does a special "can we do this" phase before doing the real modification. It's limited to special PFNMAP/MIXEDMAP things.

So it does look like the pte walking code is accidentally (or intentionally) ok in that case, but looking at the architecture users (s390, at least), I do get the feeling that the lack of locking is an actual and real bug.

It's probably impossible to hit in practice because it's limited to special ops and you'd have to race with swapout anbd even then it might not much matter. But it looks _wrong_.

And honestly, it looks like the clear_refs_pte_range() example you point at comes from this for _exactly_ the same reason your code does
this: the pte walker is buggy, and the pmd case doesn't want to split.

The pte walker code in question has been there since 2008. This is not a new thing. The clear_refs_pte_range() code partly goes all the way back to that, although it's been changed some since. But the actual pte_offset_map_lock() call in there predates the generic walker, so what I think happened is that the generic walker was done only partially, and intentionally didn't go all the way to the pte level exactly because the walker was made to split things up unconditionally if you did the pte case.

Quoted 10 lines

For these reasons we can't use the pte_entry, even internally and this means we have three choices:

a) Selecting the pte function using a bool. Saves code and avoids extra indirect function call.
b) Duplicating the pmd_entry with a different pte function, also duplicating the ops. Avoids extra indirect function call but some extra code.
c) Instead of the bool, use another function pointer in yet another ops pointed to by the private structure. Saves some code.

So considering that

- there is one current user of the pte code that doesn't care about
the proper pte lock, because what it does is a racy pre-check anyway

- that one user is also documented to not care too much about
performance (it's a crazy special case)

- the other users _do_ look like they are currently buggy and want a
stable pte with proper locking

- there are currently no cases of "I have a pmd walker _and_ a pte
walker" because that case was always broken due to splitting

I would say that the current walker code is simply buggy in this respect, and people have worked around it for over a decade.

End result: since you have an actual test-case that wants this, I'd like to at least try

d) Fix the pte walker to do the right thing, then just use separate
pte walkers in your code

The fix would be those two conceptual changes:

1) don't split if the walker asks for a pmd_entry (the walker itself
can then decide to split, of course, but right now no walkers want it since there are no pmd _and_ pte walkers, because people who want that do the pte walk themselves)

2) get the proper page table lock if you do walk the pte, since
otherwise it's racy

Then there won't be any code duplication, because all the duplication you now have at the pmd level is literally just workarounds for the fact that our current walker has this bug.

That "fix the pte walker" would be one preliminary patch that would look something like the attached TOTALLY UNTESTED garbage.

I call it "garbage" because I really hope people take it just as what it is: "something like this". It compiles for me, and I did try to think it through, but I might have missed some big piece of the picture when writing that patch.

And yes, this is a much bigger conceptual change for the VM layer, but I really think our pagewalk code is actively buggy right now, and is forcing users to do bad things because they work around the existing limitations.

Hmm? Could some of the core mm people look over that patch?

And yes, I was tempted to move the proper pmd locking into the walker too, and do

        ptl = pmd_trans_huge_lock(pmd, vma);
        if (ptl) {
                err = ops->pmd_entry(pmd, addr, next, walk);
                spin_unlock(ptl);
                ...

but while I think that's the correct thing to do in the long run, that would have to be done together with changing all the existing pmd_entry users. It would make the pmd_entry _solely_ handle the hugepage case, and then you'd have to remove the locking in the pmd_entry, and have to make the pte walking be a walker entry. But that would _really_ clean things up, and would make things like smaps_pte_range() much easier to read, and much more obvious (it would be split into a smaps_pmd_range and smaps_pte_range, and the callbacks wouldn't need to know about the complex locking).

So I think this is the right direction to move into, but I do want people to think about this, and think about that next phase of doing the pmd_trans_huge_lock too.

Comments?

Linus

 mm/pagewalk.c | 37 +++++++++++++++++++++----------------
 1 file changed, 21 insertions(+), 16 deletions(-)
mm/pagewalk.c +21 -16
index d48c2a986ea3..6ae95932e799 100644
@@ -7,11 +7,13 @@
 static int walk_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
 			  struct mm_walk *walk)
 {
-	pte_t *pte;
+	pte_t *pte, *start_pte;
 	int err = 0;
 	const struct mm_walk_ops *ops = walk->ops;
+	spinlock_t *ptl;
 
-	pte = pte_offset_map(pmd, addr);
+	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
+	start_pte = pte;
 	for (;;) {
 		err = ops->pte_entry(pte, addr, addr + PAGE_SIZE, walk);
 		if (err)
@@ -22,7 +24,7 @@ static int walk_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
 		pte++;
 	}
 
-	pte_unmap(pte);
+	pte_unmap_unlock(start_pte, ptl);
 	return err;
 }
 
@@ -49,21 +51,24 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
 		 * This implies that each ->pmd_entry() handler
 		 * needs to know about pmd_trans_huge() pmds
 		 */
-		if (ops->pmd_entry)
+		if (ops->pmd_entry) {
 			err = ops->pmd_entry(pmd, addr, next, walk);
-		if (err)
-			break;
-
-		/*
-		 * Check this here so we only break down trans_huge
-		 * pages when we _need_ to
-		 */
-		if (!ops->pte_entry)
-			continue;
+			if (err)
+				break;
+			/* No pte level walking? */
+			if (!ops->pte_entry)
+				continue;
+			/* No pte level at all? */
+			if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd))
+				continue;
+		} else {
+			if (!ops->pte_entry)
+				continue;
 
-		split_huge_pmd(walk->vma, pmd, addr);
-		if (pmd_trans_unstable(pmd))
-			goto again;
+			split_huge_pmd(walk->vma, pmd, addr);
+			if (pmd_trans_unstable(pmd))
+				goto again;
+		}
 		err = walk_pte_range(pmd, addr, next, walk);
 		if (err)
 			break;
#18 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 11 lines · Linus Torvalds

d) Fix the pte walker to do the right thing, then just use separate
pte walkers in your code

The fix would be those two conceptual changes:

1) don't split if the walker asks for a pmd_entry (the walker itself
can then decide to split, of course, but right now no walkers want it since there are no pmd _and_ pte walkers, because people who want that do the pte walk themselves)

Quoted 6 lines

2) get the proper page table lock if you do walk the pte, since
otherwise it's racy

Then there won't be any code duplication, because all the duplication you now have at the pmd level is literally just workarounds for the fact that our current walker has this bug.

I actually started on d) already when Kirill asked me to unify the pud_entry() and pmd_entry() callbacks.

Quoted 35 lines

That "fix the pte walker" would be one preliminary patch that would look something like the attached TOTALLY UNTESTED garbage.

I call it "garbage" because I really hope people take it just as what it is: "something like this". It compiles for me, and I did try to think it through, but I might have missed some big piece of the picture when writing that patch.

And yes, this is a much bigger conceptual change for the VM layer, but I really think our pagewalk code is actively buggy right now, and is forcing users to do bad things because they work around the existing limitations.

Hmm? Could some of the core mm people look over that patch?

And yes, I was tempted to move the proper pmd locking into the walker too, and do

         ptl = pmd_trans_huge_lock(pmd, vma);
         if (ptl) {
                 err = ops->pmd_entry(pmd, addr, next, walk);
                 spin_unlock(ptl);
                 ...

but while I think that's the correct thing to do in the long run, that would have to be done together with changing all the existing pmd_entry users. It would make the pmd_entry _solely_ handle the hugepage case, and then you'd have to remove the locking in the pmd_entry, and have to make the pte walking be a walker entry. But that would _really_ clean things up, and would make things like smaps_pte_range() much easier to read, and much more obvious (it would be split into a smaps_pmd_range and smaps_pte_range, and the callbacks wouldn't need to know about the complex locking).

Quoted 8 lines

So I think this is the right direction to move into, but I do want people to think about this, and think about that next phase of doing the pmd_trans_huge_lock too.

Comments?

Linus

I think if we take the ptl lock outside the callback, we'd need to allow the callback to unlock to do non-atomic things or to avoid recursive locking if it decides to split in the callback. FWIW The pud_entry call is being made locked, but the only current implementation appears to happily ignore that from what I can tell.

And if we allow unlocking or call the callback unlocked, the callback needs to tell us whether the entry was actually handled or if we need to fallback to the next level. Perhaps using a positive PAGE_WALK_FALLBACK return value? That would allow current implementations to be unmodified.

/Thomas

#19 lore raw

Re: [PATCH v3 3/7] mm: Add write-protect and clean utilities for address space ranges

Quoted 9 lines · Thomas Hellström (VMware)
Quoted 5 lines

So I think this is the right direction to move into, but I do want people to think about this, and think about that next phase of doing the pmd_trans_huge_lock too.

I think if we take the ptl lock outside the callback, we'd need to allow the callback to unlock to do non-atomic things or to avoid recursive locking if it decides to split in the callback.

Note that I think that the particular pmd locking case we should leave for later, simply because it's a separate issue, and it comes with more worries.

So I just wanted to mention it to see what people thought and keep it in mind for later, but I don't think it should be part of this series. Your use case doesn't need it (at least yet), and existing users already do their own locking.

The "change pte_entry" to do the proper locking I think is safe. Probably exactly *because* pte_entry is so broken, we literally have only five users of it in the whole kernel, and they are fairly simple and certainly don't block.

(Ok, the s390 has some funky hw locking, so maybe "simple" is the wrong word to use, but it doesn't seem to have any interaction with the locking).

End result: I absolutely agree that changing the pmd locking to be done by the walker would be a much bigger change. I don't think we need to do that part yet. It's not the current pain-point.

Linus

#20 lore raw

PATCH v3 4/7 drm/vmwgfx: Implement an infrastructure for write-coherent resources

In reply to Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

This infrastructure will, for coherent resources, make sure that from the user-space point of view, data written by the CPU is immediately automatically available to the GPU at resource validation time.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 drivers/gpu/drm/vmwgfx/Kconfig                |   1 +
 drivers/gpu/drm/vmwgfx/Makefile               |   2 +-
 drivers/gpu/drm/vmwgfx/vmwgfx_bo.c            |   5 +-
 drivers/gpu/drm/vmwgfx/vmwgfx_drv.h           |  23 +-
 drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c       |   1 -
 drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c    | 417 ++++++++++++++++++
 drivers/gpu/drm/vmwgfx/vmwgfx_resource.c      |  57 +++
 drivers/gpu/drm/vmwgfx/vmwgfx_resource_priv.h |  11 +
 drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c      |  15 +-
 drivers/gpu/drm/vmwgfx/vmwgfx_validation.c    |  71 +++
 drivers/gpu/drm/vmwgfx/vmwgfx_validation.h    |  16 +-
 11 files changed, 598 insertions(+), 21 deletions(-)
 create mode 100644 drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c
drivers/gpu/drm/vmwgfx/Kconfig +1 -0
index 6b28a326f8bb..d5fd81a521f6 100644
@@ -8,6 +8,7 @@ config DRM_VMWGFX
 	select FB_CFB_IMAGEBLIT
 	select DRM_TTM
 	select FB
+	select AS_DIRTY_HELPERS
 	# Only needed for the transitional use of drm_crtc_init - can be removed
 	# again once vmwgfx sets up the primary plane itself.
 	select DRM_KMS_HELPER
drivers/gpu/drm/vmwgfx/Makefile +1 -1
index 8841bd30e1e5..c877a21a0739 100644
@@ -8,7 +8,7 @@ vmwgfx-y := vmwgfx_execbuf.o vmwgfx_gmr.o vmwgfx_kms.o vmwgfx_drv.o \
 	    vmwgfx_cmdbuf_res.o vmwgfx_cmdbuf.o vmwgfx_stdu.o \
 	    vmwgfx_cotable.o vmwgfx_so.o vmwgfx_binding.o vmwgfx_msg.o \
 	    vmwgfx_simple_resource.o vmwgfx_va.o vmwgfx_blit.o \
-	    vmwgfx_validation.o \
+	    vmwgfx_validation.o vmwgfx_page_dirty.o \
 	    ttm_object.o ttm_lock.o
 
 obj-$(CONFIG_DRM_VMWGFX) := vmwgfx.o
drivers/gpu/drm/vmwgfx/vmwgfx_bo.c +4 -1
index aad8d8140259..869aeaec2f86 100644
@@ -462,6 +462,7 @@ void vmw_bo_bo_free(struct ttm_buffer_object *bo)
 {
 	struct vmw_buffer_object *vmw_bo = vmw_buffer_object(bo);
 
+	WARN_ON(vmw_bo->dirty);
 	vmw_bo_unmap(vmw_bo);
 	kfree(vmw_bo);
 }
@@ -475,8 +476,10 @@ void vmw_bo_bo_free(struct ttm_buffer_object *bo)
 static void vmw_user_bo_destroy(struct ttm_buffer_object *bo)
 {
 	struct vmw_user_buffer_object *vmw_user_bo = vmw_user_buffer_object(bo);
+	struct vmw_buffer_object *vbo = &vmw_user_bo->vbo;
 
-	vmw_bo_unmap(&vmw_user_bo->vbo);
+	WARN_ON(vbo->dirty);
+	vmw_bo_unmap(vbo);
 	ttm_prime_object_kfree(vmw_user_bo, prime);
 }
 
drivers/gpu/drm/vmwgfx/vmwgfx_drv.h +20 -3
index 5eb73ded8e07..7944dbbbdd72 100644
@@ -105,6 +105,7 @@ struct vmw_fpriv {
  * @dx_query_ctx: DX context if this buffer object is used as a DX query MOB
  * @map: Kmap object for semi-persistent mappings
  * @res_prios: Eviction priority counts for attached resources
+ * @dirty: structure for user-space dirty-tracking
  */
 struct vmw_buffer_object {
 	struct ttm_buffer_object base;
@@ -115,6 +116,7 @@ struct vmw_buffer_object {
 	/* Protected by reservation */
 	struct ttm_bo_kmap_obj map;
 	u32 res_prios[TTM_MAX_BO_PRIORITY];
+	struct vmw_bo_dirty *dirty;
 };
 
 /**
@@ -145,7 +147,8 @@ struct vmw_res_func;
  * @res_dirty: Resource contains data not yet in the backup buffer. Protected
  * by resource reserved.
  * @backup_dirty: Backup buffer contains data not yet in the HW resource.
- * Protecte by resource reserved.
+ * Protected by resource reserved.
+ * @coherent: Emulate coherency by tracking vm accesses.
  * @backup: The backup buffer if any. Protected by resource reserved.
  * @backup_offset: Offset into the backup buffer if any. Protected by resource
  * reserved. Note that only a few resource types can have a @backup_offset
@@ -162,14 +165,16 @@ struct vmw_res_func;
  * @hw_destroy: Callback to destroy the resource on the device, as part of
  * resource destruction.
  */
+struct vmw_resource_dirty;
 struct vmw_resource {
 	struct kref kref;
 	struct vmw_private *dev_priv;
 	int id;
 	u32 used_prio;
 	unsigned long backup_size;
-	bool res_dirty;
-	bool backup_dirty;
+	u32 res_dirty : 1;
+	u32 backup_dirty : 1;
+	u32 coherent : 1;
 	struct vmw_buffer_object *backup;
 	unsigned long backup_offset;
 	unsigned long pin_count;
@@ -177,6 +182,7 @@ struct vmw_resource {
 	struct list_head lru_head;
 	struct list_head mob_head;
 	struct list_head binding_head;
+	struct vmw_resource_dirty *dirty;
 	void (*res_free) (struct vmw_resource *res);
 	void (*hw_destroy) (struct vmw_resource *res);
 };
@@ -716,6 +722,8 @@ extern void vmw_resource_evict_all(struct vmw_private *dev_priv);
 extern void vmw_resource_unbind_list(struct vmw_buffer_object *vbo);
 void vmw_resource_mob_attach(struct vmw_resource *res);
 void vmw_resource_mob_detach(struct vmw_resource *res);
+void vmw_resource_dirty_update(struct vmw_resource *res, pgoff_t start,
+			       pgoff_t end);
 
 /**
  * vmw_resource_mob_attached - Whether a resource currently has a mob attached
@@ -1403,6 +1411,15 @@ int vmw_host_log(const char *log);
 #define VMW_DEBUG_USER(fmt, ...)                                              \
 	DRM_DEBUG_DRIVER(fmt, ##__VA_ARGS__)
 
+/* Resource dirtying - vmwgfx_page_dirty.c */
+void vmw_bo_dirty_scan(struct vmw_buffer_object *vbo);
+int vmw_bo_dirty_add(struct vmw_buffer_object *vbo);
+void vmw_bo_dirty_transfer_to_res(struct vmw_resource *res);
+void vmw_bo_dirty_clear_res(struct vmw_resource *res);
+void vmw_bo_dirty_release(struct vmw_buffer_object *vbo);
+vm_fault_t vmw_bo_vm_fault(struct vm_fault *vmf);
+vm_fault_t vmw_bo_vm_mkwrite(struct vm_fault *vmf);
+
 /**
  * VMW_DEBUG_KMS - Debug output for kernel mode-setting
  *
drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c +0 -1
index ff86d49dc5e8..934ad7c0c342 100644
@@ -2560,7 +2560,6 @@ static int vmw_cmd_dx_check_subresource(struct vmw_private *dev_priv,
 		     offsetof(typeof(*cmd), sid));
 
 	cmd = container_of(header, typeof(*cmd), header);
-
 	return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface,
 				 VMW_RES_DIRTY_NONE, user_surface_converter,
 				 &cmd->sid, NULL);
drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c new file +417 -0

417 lines not on this page · raw message

drivers/gpu/drm/vmwgfx/vmwgfx_resource.c +57 -0

95 lines not on this page · raw message

drivers/gpu/drm/vmwgfx/vmwgfx_resource_priv.h +11 -0
index 984e588c62ca..c85144286cfe 100644
@@ -71,6 +71,12 @@ struct vmw_user_resource_conv {
  * @commit_notify:     If the resource is a command buffer managed resource,
  *                     callback to notify that a define or remove command
  *                     has been committed to the device.
+ * @dirty_alloc:       Allocate a dirty tracker. NULL if dirty-tracking is not
+ *                     supported.
+ * @dirty_free:        Free the dirty tracker.
+ * @dirty_sync:        Upload the dirty mob contents to the resource.
+ * @dirty_add_range:   Add a sequential dirty range to the resource
+ *                     dirty tracker.
  */
 struct vmw_res_func {
 	enum vmw_res_type res_type;
@@ -90,6 +96,11 @@ struct vmw_res_func {
 		       struct ttm_validate_buffer *val_buf);
 	void (*commit_notify)(struct vmw_resource *res,
 			      enum vmw_cmdbuf_res_state state);
+	int (*dirty_alloc)(struct vmw_resource *res);
+	void (*dirty_free)(struct vmw_resource *res);
+	int (*dirty_sync)(struct vmw_resource *res);
+	void (*dirty_range_add)(struct vmw_resource *res, size_t start,
+				 size_t end);
 };
 
 /**
drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c +14 -1
index 5a7b8bb420de..ce288756531b 100644
@@ -29,10 +29,23 @@
 
 int vmw_mmap(struct file *filp, struct vm_area_struct *vma)
 {
+	static const struct vm_operations_struct vmw_vm_ops = {
+		.pfn_mkwrite = vmw_bo_vm_mkwrite,
+		.page_mkwrite = vmw_bo_vm_mkwrite,
+		.fault = vmw_bo_vm_fault,
+		.open = ttm_bo_vm_open,
+		.close = ttm_bo_vm_close
+	};
 	struct drm_file *file_priv = filp->private_data;
 	struct vmw_private *dev_priv = vmw_priv(file_priv->minor->dev);
+	int ret = ttm_bo_mmap(filp, vma, &dev_priv->bdev);
 
-	return ttm_bo_mmap(filp, vma, &dev_priv->bdev);
+	if (ret)
+		return ret;
+
+	vma->vm_ops = &vmw_vm_ops;
+
+	return 0;
 }
 
 /* struct vmw_validation_mem callback */
drivers/gpu/drm/vmwgfx/vmwgfx_validation.c +71 -0

104 lines not on this page · raw message

drivers/gpu/drm/vmwgfx/vmwgfx_validation.h +2 -14
index 0e063743dd86..4cee3f732588 100644
@@ -173,20 +173,6 @@ vmw_validation_bo_reserve(struct vmw_validation_context *ctx,
 				      NULL, true);
 }
 
-/**
- * vmw_validation_bo_backoff - Unreserve buffer objects registered with a
- * validation context
- * @ctx: The validation context
- *
- * This function unreserves the buffer objects previously reserved using
- * vmw_validation_bo_reserve. It's typically used as part of an error path
- */
-static inline void
-vmw_validation_bo_backoff(struct vmw_validation_context *ctx)
-{
-	ttm_eu_backoff_reservation(&ctx->ticket, &ctx->bo_list);
-}
-
 /**
  * vmw_validation_bo_fence - Unreserve and fence buffer objects registered
  * with a validation context
@@ -269,4 +255,6 @@ int vmw_validation_preload_res(struct vmw_validation_context *ctx,
 			       unsigned int size);
 void vmw_validation_res_set_dirty(struct vmw_validation_context *ctx,
 				  void *val_private, u32 dirty);
+void vmw_validation_bo_backoff(struct vmw_validation_context *ctx);
+
 #endif
Signature · 1 line
2.20.1
#21 lore raw

Re: [PATCH v3 4/7] drm/vmwgfx: Implement an infrastructure for write-coherent resources

I love your patch! Yet something to improve:

Hi "Thomas,

I love your patch! Yet something to improve:

[auto build test ERROR on linus/master]
[cannot apply to v5.4-rc1 next-20191002]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please see https://stackoverflow.com/a/37406982]

url: https://github.com/0day-ci/linux/commits/Thomas-Hellstr-m-VMware/Emulated-coherent-graphics-memory-take-2/20191003-022615
config: x86_64-randconfig-s0-201939 (attached as .config)
compiler: gcc-5 (Ubuntu 5.5.0-12ubuntu1) 5.5.0 20171010 reproduce:

        # save the attached .config to linux build tree
        make ARCH=x86_64 

If you fix the issue, kindly add following tag

All errors (new ones prefixed by >>):

drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c: In function 'vmw_mmap':

>> drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c:36:11: error: 'ttm_bo_vm_open' undeclared (first use in this function)
      .open = ttm_bo_vm_open,
              ^
   drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c:36:11: note: each undeclared identifier is reported only once for each function it appears in
>> drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c:37:12: error: 'ttm_bo_vm_close' undeclared (first use in this function)

.close = ttm_bo_vm_close
^
--
drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c: In function 'vmw_bo_vm_mkwrite':

>> drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:360:8: error: implicit declaration of function 'ttm_bo_vm_reserve' [-Werror=implicit-function-declaration]
     ret = ttm_bo_vm_reserve(bo, vmf);
           ^
   drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c: In function 'vmw_bo_vm_fault':
>> drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:410:3: error: 'TTM_BO_VM_NUM_PREFAULT' undeclared (first use in this function)
      TTM_BO_VM_NUM_PREFAULT;
      ^
   drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:410:3: note: each undeclared identifier is reported only once for each function it appears in
>> drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:411:8: error: implicit declaration of function 'ttm_bo_vm_fault_reserved' [-Werror=implicit-function-declaration]
     ret = ttm_bo_vm_fault_reserved(vmf, prot, num_prefault);
           ^

cc1: some warnings being treated as errors

vim +/ttm_bo_vm_open +36 drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c

    29	
    30	int vmw_mmap(struct file *filp, struct vm_area_struct *vma)
    31	{
    32		static const struct vm_operations_struct vmw_vm_ops = {
    33			.pfn_mkwrite = vmw_bo_vm_mkwrite,
    34			.page_mkwrite = vmw_bo_vm_mkwrite,
    35			.fault = vmw_bo_vm_fault,
  > 36			.open = ttm_bo_vm_open,
  > 37			.close = ttm_bo_vm_close
    38		};
    39		struct drm_file *file_priv = filp->private_data;
    40		struct vmw_private *dev_priv = vmw_priv(file_priv->minor->dev);
    41		int ret = ttm_bo_mmap(filp, vma, &dev_priv->bdev);
    42	
    43		if (ret)
    44			return ret;
    45	
    46		vma->vm_ops = &vmw_vm_ops;
    47	
    48		return 0;
    49	}
    50	

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#22 lore raw

Re: [PATCH v3 4/7] drm/vmwgfx: Implement an infrastructure for write-coherent resources

In reply to Thomas Hellström (VMware)
I love your patch! Yet something to improve:

Hi "Thomas,

I love your patch! Yet something to improve:

[auto build test ERROR on linus/master]
[cannot apply to v5.4-rc1 next-20191002]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please see https://stackoverflow.com/a/37406982]

url: https://github.com/0day-ci/linux/commits/Thomas-Hellstr-m-VMware/Emulated-coherent-graphics-memory-take-2/20191003-022615
config: i386-allyesconfig (attached as .config)
compiler: gcc-7 (Debian 7.4.0-13) 7.4.0
reproduce:

        # save the attached .config to linux build tree
        make ARCH=i386 

If you fix the issue, kindly add following tag

All errors (new ones prefixed by >>):

drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c: In function 'vmw_mmap':

>> drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c:36:11: error: 'ttm_bo_vm_open' undeclared (first use in this function); did you mean 'ttm_bo_mem_put'?
      .open = ttm_bo_vm_open,
              ^~~~~~~~~~~~~~
              ttm_bo_mem_put
   drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c:36:11: note: each undeclared identifier is reported only once for each function it appears in
>> drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c:37:12: error: 'ttm_bo_vm_close' undeclared (first use in this function); did you mean 'ttm_bo_vm_open'?

.close = ttm_bo_vm_close
^~~~~~~~~~~~~~~
ttm_bo_vm_open
--
drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c: In function 'vmw_bo_vm_mkwrite':

>> drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:360:8: error: implicit declaration of function 'ttm_bo_vm_reserve'; did you mean 'ttm_bo_unreserve'? [-Werror=implicit-function-declaration]
     ret = ttm_bo_vm_reserve(bo, vmf);
           ^~~~~~~~~~~~~~~~~
           ttm_bo_unreserve
   drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c: In function 'vmw_bo_vm_fault':
   drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:410:3: error: 'TTM_BO_VM_NUM_PREFAULT' undeclared (first use in this function)
      TTM_BO_VM_NUM_PREFAULT;
      ^~~~~~~~~~~~~~~~~~~~~~
   drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:410:3: note: each undeclared identifier is reported only once for each function it appears in
>> drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c:411:8: error: implicit declaration of function 'ttm_bo_vm_fault_reserved'; did you mean 'ttm_bo_init_reserved'? [-Werror=implicit-function-declaration]
     ret = ttm_bo_vm_fault_reserved(vmf, prot, num_prefault);
           ^~~~~~~~~~~~~~~~~~~~~~~~
           ttm_bo_init_reserved

cc1: some warnings being treated as errors

vim +36 drivers/gpu/drm/vmwgfx/vmwgfx_ttm_glue.c

    29	
    30	int vmw_mmap(struct file *filp, struct vm_area_struct *vma)
    31	{
    32		static const struct vm_operations_struct vmw_vm_ops = {
    33			.pfn_mkwrite = vmw_bo_vm_mkwrite,
    34			.page_mkwrite = vmw_bo_vm_mkwrite,
    35			.fault = vmw_bo_vm_fault,
  > 36			.open = ttm_bo_vm_open,
  > 37			.close = ttm_bo_vm_close
    38		};
    39		struct drm_file *file_priv = filp->private_data;
    40		struct vmw_private *dev_priv = vmw_priv(file_priv->minor->dev);
    41		int ret = ttm_bo_mmap(filp, vma, &dev_priv->bdev);
    42	
    43		if (ret)
    44			return ret;
    45	
    46		vma->vm_ops = &vmw_vm_ops;
    47	
    48		return 0;
    49	}
    50	

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#23 lore raw

PATCH v3 5/7 drm/vmwgfx: Use an RBtree instead of linked list for MOB resources

In reply to Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

With emulated coherent memory we need to be able to quickly look up a resource from the MOB offset. Instead of traversing a linked list with O(n) worst case, use an RBtree with O(log n) worst case complexity.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 drivers/gpu/drm/vmwgfx/vmwgfx_bo.c       |  5 ++--
 drivers/gpu/drm/vmwgfx/vmwgfx_drv.h      | 10 +++----
 drivers/gpu/drm/vmwgfx/vmwgfx_resource.c | 33 +++++++++++++++++-------
 3 files changed, 32 insertions(+), 16 deletions(-)
drivers/gpu/drm/vmwgfx/vmwgfx_bo.c +3 -2
index 869aeaec2f86..18e4b329e563 100644
@@ -463,6 +463,7 @@ void vmw_bo_bo_free(struct ttm_buffer_object *bo)
 	struct vmw_buffer_object *vmw_bo = vmw_buffer_object(bo);
 
 	WARN_ON(vmw_bo->dirty);
+	WARN_ON(!RB_EMPTY_ROOT(&vmw_bo->res_tree));
 	vmw_bo_unmap(vmw_bo);
 	kfree(vmw_bo);
 }
@@ -479,6 +480,7 @@ static void vmw_user_bo_destroy(struct ttm_buffer_object *bo)
 	struct vmw_buffer_object *vbo = &vmw_user_bo->vbo;
 
 	WARN_ON(vbo->dirty);
+	WARN_ON(!RB_EMPTY_ROOT(&vbo->res_tree));
 	vmw_bo_unmap(vbo);
 	ttm_prime_object_kfree(vmw_user_bo, prime);
 }
@@ -514,8 +516,7 @@ int vmw_bo_init(struct vmw_private *dev_priv,
 	memset(vmw_bo, 0, sizeof(*vmw_bo));
 	BUILD_BUG_ON(TTM_MAX_BO_PRIORITY <= 3);
 	vmw_bo->base.priority = 3;
-
-	INIT_LIST_HEAD(&vmw_bo->res_list);
+	vmw_bo->res_tree = RB_ROOT;
 
 	ret = ttm_bo_init(bdev, &vmw_bo->base, size,
 			  ttm_bo_type_device, placement,
drivers/gpu/drm/vmwgfx/vmwgfx_drv.h +5 -5
index 7944dbbbdd72..53f8522ae032 100644
@@ -100,7 +100,7 @@ struct vmw_fpriv {
 /**
  * struct vmw_buffer_object - TTM buffer object with vmwgfx additions
  * @base: The TTM buffer object
- * @res_list: List of resources using this buffer object as a backing MOB
+ * @res_tree: RB tree of resources using this buffer object as a backing MOB
  * @pin_count: pin depth
  * @dx_query_ctx: DX context if this buffer object is used as a DX query MOB
  * @map: Kmap object for semi-persistent mappings
@@ -109,7 +109,7 @@ struct vmw_fpriv {
  */
 struct vmw_buffer_object {
 	struct ttm_buffer_object base;
-	struct list_head res_list;
+	struct rb_root res_tree;
 	s32 pin_count;
 	/* Not ref-counted.  Protected by binding_mutex */
 	struct vmw_resource *dx_query_ctx;
@@ -157,8 +157,8 @@ struct vmw_res_func;
  * pin-count greater than zero. It is not on the resource LRU lists and its
  * backup buffer is pinned. Hence it can't be evicted.
  * @func: Method vtable for this resource. Immutable.
+ * @mob_node; Node for the MOB backup rbtree. Protected by @backup reserved.
  * @lru_head: List head for the LRU list. Protected by @dev_priv::resource_lock.
- * @mob_head: List head for the MOB backup list. Protected by @backup reserved.
  * @binding_head: List head for the context binding list. Protected by
  * the @dev_priv::binding_mutex
  * @res_free: The resource destructor.
@@ -179,8 +179,8 @@ struct vmw_resource {
 	unsigned long backup_offset;
 	unsigned long pin_count;
 	const struct vmw_res_func *func;
+	struct rb_node mob_node;
 	struct list_head lru_head;
-	struct list_head mob_head;
 	struct list_head binding_head;
 	struct vmw_resource_dirty *dirty;
 	void (*res_free) (struct vmw_resource *res);
@@ -733,7 +733,7 @@ void vmw_resource_dirty_update(struct vmw_resource *res, pgoff_t start,
  */
 static inline bool vmw_resource_mob_attached(const struct vmw_resource *res)
 {
-	return !list_empty(&res->mob_head);
+	return !RB_EMPTY_NODE(&res->mob_node);
 }
 
 /**
drivers/gpu/drm/vmwgfx/vmwgfx_resource.c +24 -9
index e4c97a4cf2ff..328ad46076ff 100644
@@ -40,11 +40,24 @@
 void vmw_resource_mob_attach(struct vmw_resource *res)
 {
 	struct vmw_buffer_object *backup = res->backup;
+	struct rb_node **new = &backup->res_tree.rb_node, *parent = NULL;
 
 	dma_resv_assert_held(res->backup->base.base.resv);
 	res->used_prio = (res->res_dirty) ? res->func->dirty_prio :
 		res->func->prio;
-	list_add_tail(&res->mob_head, &backup->res_list);
+
+	while (*new) {
+		struct vmw_resource *this =
+			container_of(*new, struct vmw_resource, mob_node);
+
+		parent = *new;
+		new = (res->backup_offset < this->backup_offset) ?
+			&((*new)->rb_left) : &((*new)->rb_right);
+	}
+
+	rb_link_node(&res->mob_node, parent, new);
+	rb_insert_color(&res->mob_node, &backup->res_tree);
+
 	vmw_bo_prio_add(backup, res->used_prio);
 }
 
@@ -58,7 +71,8 @@ void vmw_resource_mob_detach(struct vmw_resource *res)
 
 	dma_resv_assert_held(backup->base.base.resv);
 	if (vmw_resource_mob_attached(res)) {
-		list_del_init(&res->mob_head);
+		rb_erase(&res->mob_node, &backup->res_tree);
+		RB_CLEAR_NODE(&res->mob_node);
 		vmw_bo_prio_del(backup, res->used_prio);
 	}
 }
@@ -204,8 +218,8 @@ int vmw_resource_init(struct vmw_private *dev_priv, struct vmw_resource *res,
 	res->res_free = res_free;
 	res->dev_priv = dev_priv;
 	res->func = func;
+	RB_CLEAR_NODE(&res->mob_node);
 	INIT_LIST_HEAD(&res->lru_head);
-	INIT_LIST_HEAD(&res->mob_head);
 	INIT_LIST_HEAD(&res->binding_head);
 	res->id = -1;
 	res->backup = NULL;
@@ -754,19 +768,20 @@ int vmw_resource_validate(struct vmw_resource *res, bool intr)
  */
 void vmw_resource_unbind_list(struct vmw_buffer_object *vbo)
 {
-
-	struct vmw_resource *res, *next;
 	struct ttm_validate_buffer val_buf = {
 		.bo = &vbo->base,
 		.num_shared = 0
 	};
 
 	dma_resv_assert_held(vbo->base.base.resv);
-	list_for_each_entry_safe(res, next, &vbo->res_list, mob_head) {
-		if (!res->func->unbind)
-			continue;
+	while (!RB_EMPTY_ROOT(&vbo->res_tree)) {
+		struct rb_node *node = vbo->res_tree.rb_node;
+		struct vmw_resource *res =
+			container_of(node, struct vmw_resource, mob_node);
+
+		if (!WARN_ON_ONCE(!res->func->unbind))
+			(void) res->func->unbind(res, res->res_dirty, &val_buf);
 
-		(void) res->func->unbind(res, res->res_dirty, &val_buf);
 		res->backup_dirty = true;
 		res->res_dirty = false;
 		vmw_resource_mob_detach(res);
Signature · 1 line
2.20.1
#24 lore raw

PATCH v3 6/7 drm/vmwgfx: Implement an infrastructure for read-coherent resources

In reply to Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

Similar to write-coherent resources, make sure that from the user-space point of view, GPU rendered contents is automatically available for reading by the CPU.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 drivers/gpu/drm/vmwgfx/vmwgfx_drv.h           |   7 +-
 drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c    |  75 ++++++++++++-
 drivers/gpu/drm/vmwgfx/vmwgfx_resource.c      | 103 +++++++++++++++++-
 drivers/gpu/drm/vmwgfx/vmwgfx_resource_priv.h |   2 +
 drivers/gpu/drm/vmwgfx/vmwgfx_validation.c    |   3 +-
 5 files changed, 179 insertions(+), 11 deletions(-)
drivers/gpu/drm/vmwgfx/vmwgfx_drv.h +6 -1
index 53f8522ae032..729a2e93acf1 100644
@@ -680,7 +680,8 @@ extern void vmw_resource_unreference(struct vmw_resource **p_res);
 extern struct vmw_resource *vmw_resource_reference(struct vmw_resource *res);
 extern struct vmw_resource *
 vmw_resource_reference_unless_doomed(struct vmw_resource *res);
-extern int vmw_resource_validate(struct vmw_resource *res, bool intr);
+extern int vmw_resource_validate(struct vmw_resource *res, bool intr,
+				 bool dirtying);
 extern int vmw_resource_reserve(struct vmw_resource *res, bool interruptible,
 				bool no_backup);
 extern bool vmw_resource_needs_backup(const struct vmw_resource *res);
@@ -724,6 +725,8 @@ void vmw_resource_mob_attach(struct vmw_resource *res);
 void vmw_resource_mob_detach(struct vmw_resource *res);
 void vmw_resource_dirty_update(struct vmw_resource *res, pgoff_t start,
 			       pgoff_t end);
+int vmw_resources_clean(struct vmw_buffer_object *vbo, pgoff_t start,
+			pgoff_t end, pgoff_t *num_prefault);
 
 /**
  * vmw_resource_mob_attached - Whether a resource currently has a mob attached
@@ -1417,6 +1420,8 @@ int vmw_bo_dirty_add(struct vmw_buffer_object *vbo);
 void vmw_bo_dirty_transfer_to_res(struct vmw_resource *res);
 void vmw_bo_dirty_clear_res(struct vmw_resource *res);
 void vmw_bo_dirty_release(struct vmw_buffer_object *vbo);
+void vmw_bo_dirty_unmap(struct vmw_buffer_object *vbo,
+			pgoff_t start, pgoff_t end);
 vm_fault_t vmw_bo_vm_fault(struct vm_fault *vmf);
 vm_fault_t vmw_bo_vm_mkwrite(struct vm_fault *vmf);
 
drivers/gpu/drm/vmwgfx/vmwgfx_page_dirty.c +70 -5

104 lines not on this page · raw message

drivers/gpu/drm/vmwgfx/vmwgfx_resource.c +99 -4

142 lines not on this page · raw message

drivers/gpu/drm/vmwgfx/vmwgfx_resource_priv.h +2 -0
index c85144286cfe..3b7438b2d289 100644
@@ -77,6 +77,7 @@ struct vmw_user_resource_conv {
  * @dirty_sync:        Upload the dirty mob contents to the resource.
  * @dirty_add_range:   Add a sequential dirty range to the resource
  *                     dirty tracker.
+ * @clean:             Clean the resource.
  */
 struct vmw_res_func {
 	enum vmw_res_type res_type;
@@ -101,6 +102,7 @@ struct vmw_res_func {
 	int (*dirty_sync)(struct vmw_resource *res);
 	void (*dirty_range_add)(struct vmw_resource *res, size_t start,
 				 size_t end);
+	int (*clean)(struct vmw_resource *res);
 };
 
 /**
drivers/gpu/drm/vmwgfx/vmwgfx_validation.c +2 -1
index 71349a7bae90..9aaf807ed73c 100644
@@ -641,7 +641,8 @@ int vmw_validation_res_validate(struct vmw_validation_context *ctx, bool intr)
 		struct vmw_resource *res = val->res;
 		struct vmw_buffer_object *backup = res->backup;
 
-		ret = vmw_resource_validate(res, intr);
+		ret = vmw_resource_validate(res, intr, val->dirty_set &&
+					    val->dirty);
 		if (ret) {
 			if (ret != -ERESTARTSYS)
 				DRM_ERROR("Failed to validate resource.\n");
Signature · 1 line
2.20.1
#25 lore raw

PATCH v3 7/7 drm/vmwgfx: Add surface dirty-tracking callbacks

In reply to Thomas Hellström (VMware)

From: Thomas Hellstrom <[email protected]>

Add the callbacks necessary to implement emulated coherent memory for surfaces. Add a flag to the gb_surface_create ioctl to indicate that surface memory should be coherent.
Also bump the drm minor version to signal the availability of coherent surfaces.

Cc Andrew Morton <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Huang Ying <[email protected]>
Cc Jérôme Glisse <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
---
 .../device_include/svga3d_surfacedefs.h       | 233 ++++++++++-
 drivers/gpu/drm/vmwgfx/vmwgfx_drv.h           |   4 +-
 drivers/gpu/drm/vmwgfx/vmwgfx_surface.c       | 395 +++++++++++++++++-
 include/uapi/drm/vmwgfx_drm.h                 |   4 +-
 4 files changed, 629 insertions(+), 7 deletions(-)
drivers/gpu/drm/vmwgfx/device_include/svga3d_surfacedefs.h +232 -1
index f2bfd3d80598..61414f105c67 100644
@@ -1280,7 +1280,6 @@ svga3dsurface_get_pixel_offset(SVGA3dSurfaceFormat format,
 	return offset;
 }
 
-
 static inline u32
 svga3dsurface_get_image_offset(SVGA3dSurfaceFormat format,
 			       surf_size_struct baseLevelSize,
@@ -1375,4 +1374,236 @@ svga3dsurface_is_screen_target_format(SVGA3dSurfaceFormat format)
 	return svga3dsurface_is_dx_screen_target_format(format);
 }
 
+/**
+ * struct svga3dsurface_mip - Mimpmap level information
+ * @bytes: Bytes required in the backing store of this mipmap level.
+ * @img_stride: Byte stride per image.
+ * @row_stride: Byte stride per block row.
+ * @size: The size of the mipmap.
+ */
+struct svga3dsurface_mip {
+	size_t bytes;
+	size_t img_stride;
+	size_t row_stride;
+	struct drm_vmw_size size;
+
+};
+
+/**
+ * struct svga3dsurface_cache - Cached surface information
+ * @desc: Pointer to the surface descriptor
+ * @mip: Array of mipmap level information. Valid size is @num_mip_levels.
+ * @mip_chain_bytes: Bytes required in the backing store for the whole chain
+ * of mip levels.
+ * @sheet_bytes: Bytes required in the backing store for a sheet
+ * representing a single sample.
+ * @num_mip_levels: Valid size of the @mip array. Number of mipmap levels in
+ * a chain.
+ * @num_layers: Number of slices in an array texture or number of faces in
+ * a cubemap texture.
+ */
+struct svga3dsurface_cache {
+	const struct svga3d_surface_desc *desc;
+	struct svga3dsurface_mip mip[DRM_VMW_MAX_MIP_LEVELS];
+	size_t mip_chain_bytes;
+	size_t sheet_bytes;
+	u32 num_mip_levels;
+	u32 num_layers;
+};
+
+/**
+ * struct svga3dsurface_loc - Surface location
+ * @sub_resource: Surface subresource. Defined as layer * num_mip_levels +
+ * mip_level.
+ * @x: X coordinate.
+ * @y: Y coordinate.
+ * @z: Z coordinate.
+ */
+struct svga3dsurface_loc {
+	u32 sub_resource;
+	u32 x, y, z;
+};
+
+/**
+ * svga3dsurface_subres - Compute the subresource from layer and mipmap.
+ * @cache: Surface layout data.
+ * @mip_level: The mipmap level.
+ * @layer: The surface layer (face or array slice).
+ *
+ * Return: The subresource.
+ */
+static inline u32 svga3dsurface_subres(const struct svga3dsurface_cache *cache,
+				       u32 mip_level, u32 layer)
+{
+	return cache->num_mip_levels * layer + mip_level;
+}
+
+/**
+ * svga3dsurface_setup_cache - Build a surface cache entry
+ * @size: The surface base level dimensions.
+ * @format: The surface format.
+ * @num_mip_levels: Number of mipmap levels.
+ * @num_layers: Number of layers.
+ * @cache: Pointer to a struct svga3dsurface_cach object to be filled in.
+ *
+ * Return: Zero on success, -EINVAL on invalid surface layout.
+ */
+static inline int svga3dsurface_setup_cache(const struct drm_vmw_size *size,
+					    SVGA3dSurfaceFormat format,
+					    u32 num_mip_levels,
+					    u32 num_layers,
+					    u32 num_samples,
+					    struct svga3dsurface_cache *cache)
+{
+	const struct svga3d_surface_desc *desc;
+	u32 i;
+
+	memset(cache, 0, sizeof(*cache));
+	cache->desc = desc = svga3dsurface_get_desc(format);
+	cache->num_mip_levels = num_mip_levels;
+	cache->num_layers = num_layers;
+	for (i = 0; i < cache->num_mip_levels; i++) {
+		struct svga3dsurface_mip *mip = &cache->mip[i];
+
+		mip->size = svga3dsurface_get_mip_size(*size, i);
+		mip->bytes = svga3dsurface_get_image_buffer_size
+			(desc, &mip->size, 0);
+		mip->row_stride =
+			__KERNEL_DIV_ROUND_UP(mip->size.width,
+					      desc->block_size.width) *
+			desc->bytes_per_block * num_samples;
+		if (!mip->row_stride)
+			goto invalid_dim;
+
+		mip->img_stride =
+			__KERNEL_DIV_ROUND_UP(mip->size.height,
+					      desc->block_size.height) *
+			mip->row_stride;
+		if (!mip->img_stride)
+			goto invalid_dim;
+
+		cache->mip_chain_bytes += mip->bytes;
+	}
+	cache->sheet_bytes = cache->mip_chain_bytes * num_layers;
+	if (!cache->sheet_bytes)
+		goto invalid_dim;
+
+	return 0;
+
+invalid_dim:
+	VMW_DEBUG_USER("Invalid surface layout for dirty tracking.\n");
+	return -EINVAL;
+}
+
+/**
+ * svga3dsurface_get_loc - Get a surface location from an offset into the
+ * backing store
+ * @cache: Surface layout data.
+ * @loc: Pointer to a struct svga3dsurface_loc to be filled in.
+ * @offset: Offset into the surface backing store.
+ */
+static inline void
+svga3dsurface_get_loc(const struct svga3dsurface_cache *cache,
+		      struct svga3dsurface_loc *loc,
+		      size_t offset)
+{
+	const struct svga3dsurface_mip *mip = &cache->mip[0];
+	const struct svga3d_surface_desc *desc = cache->desc;
+	u32 layer;
+	int i;
+
+	if (offset >= cache->sheet_bytes)
+		offset %= cache->sheet_bytes;
+
+	layer = offset / cache->mip_chain_bytes;
+	offset -= layer * cache->mip_chain_bytes;
+	for (i = 0; i < cache->num_mip_levels; ++i, ++mip) {
+		if (mip->bytes > offset)
+			break;
+		offset -= mip->bytes;
+	}
+
+	loc->sub_resource = svga3dsurface_subres(cache, i, layer);
+	loc->z = offset / mip->img_stride;
+	offset -= loc->z * mip->img_stride;
+	loc->z *= desc->block_size.depth;
+	loc->y = offset / mip->row_stride;
+	offset -= loc->y * mip->row_stride;
+	loc->y *= desc->block_size.height;
+	loc->x = offset / desc->bytes_per_block;
+	loc->x *= desc->block_size.width;
+}
+
+/**
+ * svga3dsurface_inc_loc - Clamp increment a surface location with one block
+ * size
+ * in each dimension.
+ * @loc: Pointer to a struct svga3dsurface_loc to be incremented.
+ *
+ * When computing the size of a range as size = end - start, the range does not
+ * include the end element. However a location representing the last byte
+ * of a touched region in the backing store *is* included in the range.
+ * This function modifies such a location to match the end definition
+ * given as start + size which is the one used in a SVGA3dBox.
+ */
+static inline void
+svga3dsurface_inc_loc(const struct svga3dsurface_cache *cache,
+		      struct svga3dsurface_loc *loc)
+{
+	const struct svga3d_surface_desc *desc = cache->desc;
+	u32 mip = loc->sub_resource % cache->num_mip_levels;
+	const struct drm_vmw_size *size = &cache->mip[mip].size;
+
+	loc->sub_resource++;
+	loc->x += desc->block_size.width;
+	if (loc->x > size->width)
+		loc->x = size->width;
+	loc->y += desc->block_size.height;
+	if (loc->y > size->height)
+		loc->y = size->height;
+	loc->z += desc->block_size.depth;
+	if (loc->z > size->depth)
+		loc->z = size->depth;
+}
+
+/**
+ * svga3dsurface_min_loc - The start location in a subresource
+ * @cache: Surface layout data.
+ * @sub_resource: The subresource.
+ * @loc: Pointer to a struct svga3dsurface_loc to be filled in.
+ */
+static inline void
+svga3dsurface_min_loc(const struct svga3dsurface_cache *cache,
+		      u32 sub_resource,
+		      struct svga3dsurface_loc *loc)
+{
+	loc->sub_resource = sub_resource;
+	loc->x = loc->y = loc->z = 0;
+}
+
+/**
+ * svga3dsurface_min_loc - The end location in a subresource
+ * @cache: Surface layout data.
+ * @sub_resource: The subresource.
+ * @loc: Pointer to a struct svga3dsurface_loc to be filled in.
+ *
+ * Following the end definition given in svga3dsurface_inc_loc(),
+ * Compute the end location of a surface subresource.
+ */
+static inline void
+svga3dsurface_max_loc(const struct svga3dsurface_cache *cache,
+		      u32 sub_resource,
+		      struct svga3dsurface_loc *loc)
+{
+	const struct drm_vmw_size *size;
+	u32 mip;
+
+	loc->sub_resource = sub_resource + 1;
+	mip = sub_resource % cache->num_mip_levels;
+	size = &cache->mip[mip].size;
+	loc->x = size->width;
+	loc->y = size->height;
+	loc->z = size->depth;
+}
+
 #endif /* _SVGA3D_SURFACEDEFS_H_ */
drivers/gpu/drm/vmwgfx/vmwgfx_drv.h +2 -2
index 729a2e93acf1..f5261e1c96d7 100644
@@ -56,9 +56,9 @@
 
 
 #define VMWGFX_DRIVER_NAME "vmwgfx"
-#define VMWGFX_DRIVER_DATE "20180704"
+#define VMWGFX_DRIVER_DATE "20190328"
 #define VMWGFX_DRIVER_MAJOR 2
-#define VMWGFX_DRIVER_MINOR 15
+#define VMWGFX_DRIVER_MINOR 16
 #define VMWGFX_DRIVER_PATCHLEVEL 0
 #define VMWGFX_FIFO_STATIC_SIZE (1024*1024)
 #define VMWGFX_MAX_RELOCATIONS 2048
drivers/gpu/drm/vmwgfx/vmwgfx_surface.c +392 -3

443 lines not on this page · raw message

include/uapi/drm/vmwgfx_drm.h +3 -1
index 399f58317cff..02cab33f2f25 100644
@@ -891,11 +891,13 @@ struct drm_vmw_shader_arg {
  *                                      surface.
  * @drm_vmw_surface_flag_create_buffer: Create a backup buffer if none is
  *                                      given.
+ * @drm_vmw_surface_flag_coherent:      Back surface with coherent memory.
  */
 enum drm_vmw_surface_flags {
 	drm_vmw_surface_flag_shareable = (1 << 0),
 	drm_vmw_surface_flag_scanout = (1 << 1),
-	drm_vmw_surface_flag_create_buffer = (1 << 2)
+	drm_vmw_surface_flag_create_buffer = (1 << 2),
+	drm_vmw_surface_flag_coherent = (1 << 3),
 };
 
 /**
Signature · 1 line
2.20.1