Skip to contentSkip to conversation

drm/ttm, drm/xe: Minimize dma-resv hold times and defragment sub-optimally backed BOs

PATCH In review Matthew Brost 6 participants 145 messages Jul 11 – Nov 24 Page 2 of 3

Subsystems (7)
lore
Share & tools
lore
author maintainer
#49 lore raw

PATCH v3 12/33 drm/xe: Add debugfs stats for DMA-mapped pages per order

In reply to Matthew Brost

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

Expose per-page-order DMA mapping counts for the system memory that the xe driver maps for GPU access, split into two categories: TTM buffer objects, and the GPU SVM / userptr ranges (which share a single drm_gpusvm instance per VM).

The stats are visible at:

<debugfs>/dri/<N>/dma_mapped_pages

and are broken out into two rows (bo, svm/userptr), one column per page order, mirroring the layout of the TTM pool page_pool stat.

For TTM BOs the per-order counts are derived from the DMA scatter-gather
table: each mapped segment is physically contiguous, so its page count is split into the largest power-of-two runs (a segment of N pages contributes a 2^k chunk for the largest k with 2^k <= N, repeated for the remainder). Driving the accounting off the sg table rather than the pages[] array keeps it correct even when pages[] entries are cleared while still DMA-mapped, as happens on the defrag page-borrowing path.

For the SVM and userptr ranges the accounting is driven by the drm_gpusvm @dma_map_account callback, which fires once per dma_addr[] entry at the exact point the entry is DMA-mapped and unmapped. This makes the accounting symmetric by construction and avoids driver-side walks that could drift across migration, partial unmaps and the iova vs non-iova paths. Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted; device interconnect (VRAM, P2P) entries are skipped, so the counter reflects only system pages actually mapped through the DMA layer.

The callback is shared between the full SVM instance (fault mode) and the core drm_gpusvm_pages-only instance used for userptr, so userptr mappings are accounted in both the CONFIG_DRM_XE_GPUSVM=y and =n (but CONFIG_DRM_GPUSVM=y) configurations, into the same svm/userptr counter.

Since the counts are only ever consumed through debugfs, gate the counter storage and all accounting on CONFIG_DEBUG_FS so that builds without debugfs carry no extra atomic traffic or device state; the drm_gpusvm callback is simply left unregistered in that case.

On device teardown assert that every counter has returned to zero, to catch any unbalanced accounting (a leaked DMA mapping) during testing.

Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Fix drm_gpusvm_init() argument order, clamp DMA-page order to NR_PAGE_ORDERS - 1, and drain DMA-page accounting after xe_bo_dev_fini() (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c           | 46 ++++++++++++++++++++
 drivers/gpu/drm/xe/xe_debugfs.c      | 26 ++++++++++++
 drivers/gpu/drm/xe/xe_device.c       | 30 +++++++++++++
 drivers/gpu/drm/xe/xe_device_types.h | 17 ++++++++
 drivers/gpu/drm/xe/xe_svm.c          | 44 ++++++++++++++++++-
 drivers/gpu/drm/xe/xe_svm.h          |  4 +-
 drivers/gpu/drm/xe/xe_userptr.c      | 63 ++++++++++++++++++++++++++++
 drivers/gpu/drm/xe/xe_userptr.h      |  1 +
 8 files changed, 228 insertions(+), 3 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +46 -0
index 85e6d9a0f575..60e0e568aa31 100644
@@ -367,6 +367,50 @@ struct xe_ttm_tt {
 	bool purgeable;
 };
 
+/*
+ * xe_tt_account_dma_pages - account DMA-mapped tt pages per order
+ * @xe: the xe device
+ * @xe_tt: the xe_ttm_tt whose sg table to walk
+ * @sign: +1 to add, -1 to subtract
+ *
+ * Walk the tt's DMA scatter-gather table and split each (physically
+ * contiguous) segment into the largest power-of-two page runs: a segment of N
+ * pages contributes a 2^k chunk for the largest k with 2^k <= N, repeated for
+ * the remainder. Accumulate the count of 2^k pages into
+ * xe->mem.dma_mapped_pages[k]. Driving this off the sg table rather than
+ * tt->pages keeps the accounting correct even when pages[] entries are cleared
+ * while still DMA-mapped (e.g. the defrag page-borrowing path).
+ */
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+static void xe_tt_account_dma_pages(struct xe_device *xe,
+				    struct xe_ttm_tt *xe_tt, int sign)
+{
+	struct scatterlist *sg;
+	unsigned int i;
+
+	for_each_sgtable_sg(xe_tt->sg, sg, i) {
+		unsigned long nr_pages = sg->length >> PAGE_SHIFT;
+
+		while (nr_pages) {
+			unsigned int order = min_t(unsigned int,
+						   __fls(nr_pages),
+						   MAX_PAGE_ORDER);
+			unsigned long chunk = 1UL << order;
+
+			atomic_long_add((long)chunk * sign,
+					&xe->mem.dma_mapped_pages[order]);
+
+			nr_pages -= chunk;
+		}
+	}
+}
+#else
+static void xe_tt_account_dma_pages(struct xe_device *xe,
+				    struct xe_ttm_tt *xe_tt, int sign)
+{
+}
+#endif
+
 static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
 {
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
@@ -396,6 +440,7 @@ static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
 		return ret;
 	}
 
+	xe_tt_account_dma_pages(xe, xe_tt, 1);
 	return 0;
 }
 
@@ -404,6 +449,7 @@ static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt)
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
 
 	if (xe_tt->sg) {
+		xe_tt_account_dma_pages(xe, xe_tt, -1);
 		dma_unmap_sgtable(xe->drm.dev, xe_tt->sg,
 				  DMA_BIDIRECTIONAL, 0);
 		sg_free_table(xe_tt->sg);
drivers/gpu/drm/xe/xe_debugfs.c +26 -0
index 8c391c7b017a..97b47c5c4213 100644
@@ -6,6 +6,7 @@
 #include "xe_debugfs.h"
 
 #include <linux/debugfs.h>
+#include <linux/mmzone.h>
 #include <linux/fault-inject.h>
 #include <linux/string_helpers.h>
 
@@ -231,6 +232,28 @@ static int dgfx_pcie_link_residencies_show(struct seq_file *m, void *data)
 	return 0;
 }
 
+static int dma_mapped_pages_show(struct seq_file *m, void *data)
+{
+	struct xe_device *xe = m->private;
+	unsigned int i;
+
+	seq_printf(m, "%-11s ", "");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " ---%2u---", i);
+	seq_printf(m, "\n%-11s:", "bo");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " %8lu",
+			   atomic_long_read(&xe->mem.dma_mapped_pages[i]));
+	seq_printf(m, "\n%-11s:", "svm/userptr");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " %8lu",
+			   atomic_long_read(&xe->mem.dma_mapped_pages_svm[i]));
+	seq_puts(m, "\n");
+
+	return 0;
+}
+DEFINE_SHOW_ATTRIBUTE(dma_mapped_pages);
+
 static const struct drm_info_list debugfs_list[] = {
 	{"info", info, 0},
 	{ .name = "sriov_info", .show = sriov_info, },
@@ -632,6 +655,9 @@ void xe_debugfs_register(struct xe_device *xe)
 	if (man)
 		ttm_resource_manager_create_debugfs(man, root, "stolen_mm");
 
+	debugfs_create_file("dma_mapped_pages", 0444, root, xe,
+			    &dma_mapped_pages_fops);
+
 	for_each_tile(tile, xe, tile_id)
 		xe_tile_debugfs_register(tile);
 
drivers/gpu/drm/xe/xe_device.c +30 -0
index ad7f3e61d457..97cc2d185e45 100644
@@ -455,12 +455,42 @@ bool xe_device_is_admin_only(const struct xe_device *xe)
 }
 #endif
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+static void xe_device_assert_dma_pages_zero(struct xe_device *xe)
+{
+	unsigned int i;
+
+	/*
+	 * All BOs, userptr VMAs and SVM ranges must have been torn down by the
+	 * time the device is destroyed, so every DMA-mapped-pages counter must
+	 * have returned to zero. A non-zero value indicates unbalanced
+	 * accounting, i.e. a missing unmap-side decrement.
+	 */
+	for (i = 0; i < NR_PAGE_ORDERS; i++) {
+		xe_assert(xe, !atomic_long_read(&xe->mem.dma_mapped_pages[i]));
+		xe_assert(xe, !atomic_long_read(&xe->mem.dma_mapped_pages_svm[i]));
+	}
+}
+#else
+static void xe_device_assert_dma_pages_zero(struct xe_device *xe)
+{
+}
+#endif
+
 static void xe_device_destroy(struct drm_device *dev, void *dummy)
 {
 	struct xe_device *xe = to_xe_device(dev);
 
 	xe_bo_dev_fini(&xe->bo_device);
 
+	/*
+	 * Assert the DMA-mapped-pages accounting only after xe_bo_dev_fini()
+	 * has flushed the async BO-free worker: BOs pending async free still
+	 * hold their DMA mappings (and counts) until the worker runs, so
+	 * asserting before the flush could trip a false positive.
+	 */
+	xe_device_assert_dma_pages_zero(xe);
+
 	if (xe->preempt_fence_wq)
 		destroy_workqueue(xe->preempt_fence_wq);
 
drivers/gpu/drm/xe/xe_device_types.h +17 -0
index 022e08205897..95e7cea91cbf 100644
@@ -6,6 +6,7 @@
 #ifndef _XE_DEVICE_TYPES_H_
 #define _XE_DEVICE_TYPES_H_
 
+#include <linux/mmzone.h>
 #include <linux/pci.h>
 
 #include <drm/drm_device.h>
@@ -279,6 +280,22 @@ struct xe_device {
 		struct xe_shrinker *shrinker;
 		/** @mem.stolen_mgr: stolen memory manager. */
 		struct xe_ttm_stolen_mgr *stolen_mgr;
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+		/**
+		 * @mem.dma_mapped_pages: number of DMA-mapped pages per page
+		 * order currently live for this device, for TTM BOs. Only
+		 * accounted when CONFIG_DEBUG_FS is enabled, since it is solely
+		 * exposed through debugfs.
+		 */
+		atomic_long_t dma_mapped_pages[NR_PAGE_ORDERS];
+		/**
+		 * @mem.dma_mapped_pages_svm: number of DMA-mapped pages per
+		 * page order currently live for this device, for SVM ranges
+		 * and userptr VMAs (both share a single drm_gpusvm instance).
+		 * Only accounted when CONFIG_DEBUG_FS is enabled.
+		 */
+		atomic_long_t dma_mapped_pages_svm[NR_PAGE_ORDERS];
+#endif
 	} mem;
 
 	/** @sriov: device level virtualization data */
drivers/gpu/drm/xe/xe_svm.c +42 -2

60 lines not on this page · raw message

drivers/gpu/drm/xe/xe_svm.h +3 -1
index a921556d3466..8e347137a7a6 100644
@@ -194,6 +194,7 @@ struct drm_pagemap *xe_drm_pagemap_from_fd(int fd, u32 region_instance);
 
 #else
 #include <linux/interval_tree.h>
+#include "xe_userptr.h"
 #include "xe_vm.h"
 
 struct drm_pagemap_addr;
@@ -236,7 +237,8 @@ int xe_svm_init(struct xe_vm *vm)
 {
 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
 	return drm_gpusvm_init(&vm->svm.gpusvm, "Xe SVM (simple)",
-			       NULL, 0, 0, 0, NULL, NULL, 0);
+			       NULL, 0, 0, 0,
+			       xe_userptr_gpusvm_ops_get(), NULL, 0);
 #else
 	return 0;
 #endif
drivers/gpu/drm/xe/xe_userptr.c +63 -0

72 lines not on this page · raw message

drivers/gpu/drm/xe/xe_userptr.h +1 -0
index 2a3cd1b5efbb..1e9601be5713 100644
@@ -108,6 +108,7 @@ int __xe_vm_userptr_needs_repin(struct xe_vm *vm);
 int xe_vm_userptr_check_repin(struct xe_vm *vm);
 int xe_vma_userptr_pin_pages(struct xe_userptr_vma *uvma);
 int xe_vma_userptr_check_repin(struct xe_userptr_vma *uvma);
+const struct drm_gpusvm_ops *xe_userptr_gpusvm_ops_get(void);
 #else
 static inline void xe_userptr_remove(struct xe_userptr_vma *uvma) {}
 
Signature · 1 line
2.34.1
#50 lore raw

Re: [PATCH v3 12/33] drm/xe: Add debugfs stats for DMA-mapped pages per order

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

New issues:
- [Critical] Missing decrement of DMA mapped pages counter in xe_bo_dma_unmap_pinned() leads to leaked accounting and kernel assertion failure during device teardown.

Pre-existing issues:
- [High] xe_bo_dev_fini() is called before xe->destroy_wq is flushed, leading to Use-After-Free of the TTM device and false positive assertion failures on device teardown. --

--- Patch [12]: [PATCH v3 12/33] drm/xe: Add debugfs stats for DMA-mapped pages per order --- commit 670e42692f03a24b49683eec7ff3afb39e28a858
Author: Thomas Hellström <[email protected]>
Subject: drm/xe: Add debugfs stats for DMA-mapped pages per order

Expose per-page-order DMA mapping counts for the system memory that the xe driver maps for GPU access, split into two categories: TTM buffer objects, and the GPU SVM / userptr ranges.

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
index 85e6d9a0f575b..60e0e568aa31f 100644

[ ... ]

drivers/gpu/drm/xe/xe_bo.c static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt) · line 455

Quoted 8 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
@@ -404,6 +449,7 @@ static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt)
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
 
 	if (xe_tt->sg) {
+		xe_tt_account_dma_pages(xe, xe_tt, -1);
 		dma_unmap_sgtable(xe->drm.dev, xe_tt->sg,
 				  DMA_BIDIRECTIONAL, 0);
 		sg_free_table(xe_tt->sg);

[Severity: Critical]
Will this accounting leak if the scatter-gather table is unmapped elsewhere?

Looking at xe_bo_dma_unmap_pinned() in drivers/gpu/drm/xe/xe_bo.c, it unmaps and frees the sg table without updating the accounting:

	} else if (xe_tt->sg) {
		dma_unmap_sgtable(ttm_to_xe_device(ttm_bo->bdev)->drm.dev,
				  xe_tt->sg,
				  DMA_BIDIRECTIONAL, 0);
		sg_free_table(xe_tt->sg);
		xe_tt->sg = NULL;
	}

Because xe_bo_dma_unmap_pinned() clears xe_tt->sg, a later call to xe_tt_unmap_sg() will see xe_tt->sg as NULL and skip the decrement, leading to a permanent accounting leak and a guaranteed assertion failure on device teardown.

Quoted 4 lines
drivers/gpu/drm/xe/xe_device.c +0 -0
index ad7f3e61d4579..97cc2d185e45d 100644

[ ... ]

Quoted 6 lines

static void xe_device_destroy(struct drm_device *dev, void *dummy) {

drivers/gpu/drm/xe/xe_device.c +0 -0
 	struct xe_device *xe = to_xe_device(dev);
 
 	xe_bo_dev_fini(&xe->bo_device);
 

drivers/gpu/drm/xe/xe_device.c bool xe_device_is_admin_only(const struct xe_device *xe) · line 495

Quoted 10 lines
drivers/gpu/drm/xe/xe_device.c +8 -0
+	/*
+	 * Assert the DMA-mapped-pages accounting only after xe_bo_dev_fini()
+	 * has flushed the async BO-free worker: BOs pending async free still
+	 * hold their DMA mappings (and counts) until the worker runs, so
+	 * asserting before the flush could trip a false positive.
+	 */
+	xe_device_assert_dma_pages_zero(xe);
+
 	if (xe->preempt_fence_wq)
 		destroy_workqueue(xe->preempt_fence_wq);

[Severity: High]
This is a pre-existing issue, but will this new assertion falsely trip due to the teardown order?

Because xe->destroy_wq is destroyed after this assertion, and work items in xe->destroy_wq might still hold final references to BOs, those BOs won't be unmapped until the workqueue is drained.

Since the assertion now runs before the workqueues drop their BO references, it will incorrectly trigger because those BOs still have active DMA mappings.

Additionally, since xe_bo_dev_fini() flushes the async BO-free worker before the workqueues drop BOs, the worker can run concurrently with or after ttm_device_fini(), which is a pre-existing use-after-free risk exposed by this change.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#51 lore raw

Re: [PATCH v3 12/33] drm/xe: Add debugfs stats for DMA-mapped pages per order

In reply to Matthew Brost
Quoted 41 lines · Matthew Brost

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

Expose per-page-order DMA mapping counts for the system memory that the xe driver maps for GPU access, split into two categories: TTM buffer objects, and the GPU SVM / userptr ranges (which share a single drm_gpusvm instance per VM).

The stats are visible at:

<debugfs>/dri/<N>/dma_mapped_pages

and are broken out into two rows (bo, svm/userptr), one column per page order, mirroring the layout of the TTM pool page_pool stat.

For TTM BOs the per-order counts are derived from the DMA scatter-gather
table: each mapped segment is physically contiguous, so its page count is split into the largest power-of-two runs (a segment of N pages contributes a 2^k chunk for the largest k with 2^k <= N, repeated for the remainder). Driving the accounting off the sg table rather than the pages[] array keeps it correct even when pages[] entries are cleared while still DMA-mapped, as happens on the defrag page-borrowing path.

For the SVM and userptr ranges the accounting is driven by the drm_gpusvm @dma_map_account callback, which fires once per dma_addr[] entry at the exact point the entry is DMA-mapped and unmapped. This makes the accounting symmetric by construction and avoids driver-side walks that could drift across migration, partial unmaps and the iova vs non-iova paths. Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted; device interconnect (VRAM, P2P) entries are skipped, so the counter reflects only system pages actually mapped through the DMA layer.

The callback is shared between the full SVM instance (fault mode) and the core drm_gpusvm_pages-only instance used for userptr, so userptr mappings are accounted in both the CONFIG_DRM_XE_GPUSVM=y and =n (but CONFIG_DRM_GPUSVM=y) configurations, into the same svm/userptr counter.

Since the counts are only ever consumed through debugfs, gate the counter storage and all accounting on CONFIG_DEBUG_FS so that builds without debugfs carry no extra atomic traffic or device state; the drm_gpusvm callback is simply left unregistered in that case.

Quoted 6 lines

On device teardown assert that every counter has returned to zero, to catch any unbalanced accounting (a leaked DMA mapping) during testing.

Assisted-by GitHub_Copilot:claude-opus-4.8

Patches 11 and 12 can be spinned out as a separate patch series (for fast tracking).

Also, dma map/unmap of dmabuf imported BOs are skipped here (rightly so). But perhaps add a comments in commit message that either self-import returns the same BO and BOs of other device gets counted on exporter side when it gets first migrated to TT first.

Quoted 48 lines

---

v3:
- Fix drm_gpusvm_init() argument order, clamp DMA-page order to NR_PAGE_ORDERS - 1, and drain DMA-page accounting after xe_bo_dev_fini() (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c           | 46 ++++++++++++++++++++
drivers/gpu/drm/xe/xe_debugfs.c      | 26 ++++++++++++
drivers/gpu/drm/xe/xe_device.c       | 30 +++++++++++++
drivers/gpu/drm/xe/xe_device_types.h | 17 ++++++++
drivers/gpu/drm/xe/xe_svm.c          | 44 ++++++++++++++++++-
drivers/gpu/drm/xe/xe_svm.h          |  4 +-
drivers/gpu/drm/xe/xe_userptr.c      | 63 ++++++++++++++++++++++++++++
drivers/gpu/drm/xe/xe_userptr.h      |  1 +
8 files changed, 228 insertions(+), 3 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +23 -0
index 85e6d9a0f575..60e0e568aa31 100644
@@ -367,6 +367,50 @@ struct xe_ttm_tt {
 	bool purgeable;
 };
 
+/*
+ * xe_tt_account_dma_pages - account DMA-mapped tt pages per order
+ * @xe: the xe device
+ * @xe_tt: the xe_ttm_tt whose sg table to walk
+ * @sign: +1 to add, -1 to subtract
+ *
+ * Walk the tt's DMA scatter-gather table and split each (physically
+ * contiguous) segment into the largest power-of-two page runs: a segment of N
+ * pages contributes a 2^k chunk for the largest k with 2^k <= N, repeated for
+ * the remainder. Accumulate the count of 2^k pages into
+ * xe->mem.dma_mapped_pages[k]. Driving this off the sg table rather than
+ * tt->pages keeps the accounting correct even when pages[] entries are cleared
+ * while still DMA-mapped (e.g. the defrag page-borrowing path).
+ */
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+static void xe_tt_account_dma_pages(struct xe_device *xe,
+				    struct xe_ttm_tt *xe_tt, int sign)
+{
+	struct scatterlist *sg;
+	unsigned int i;
+
+	for_each_sgtable_sg(xe_tt->sg, sg, i) {
+		unsigned long nr_pages = sg->length >> PAGE_SHIFT;

drivers/gpu/drm/xe/xe_bo.c struct xe_ttm_tt { · line 402

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+
+		while (nr_pages) {
+			unsigned int order = min_t(unsigned int,
+						   __fls(nr_pages),
+						   MAX_PAGE_ORDER);
+			unsigned long chunk = 1UL << order;
+
+			atomic_long_add((long)chunk * sign,
+					&xe->mem.dma_mapped_pages[order]);
+

NIT: As there is an atomic operation involved, instead of doing it under CONFIG_DEBUG_FS, should we be doing it under a separate xe specific debug config?

Quoted 23 lines
drivers/gpu/drm/xe/xe_bo.c +12 -0
+			nr_pages -= chunk;
+		}
+	}
+}
+#else
+static void xe_tt_account_dma_pages(struct xe_device *xe,
+				    struct xe_ttm_tt *xe_tt, int sign)
+{
+}
+#endif
+
 static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
 {
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
@@ -396,6 +440,7 @@ static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
 		return ret;
 	}
 
+	xe_tt_account_dma_pages(xe, xe_tt, 1);
 	return 0;
 }
 

drivers/gpu/drm/xe/xe_bo.c static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt) · line 455

Quoted 7 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
@@ -404,6 +449,7 @@ static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt)
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
 
 	if (xe_tt->sg) {
+		xe_tt_account_dma_pages(xe, xe_tt, -1);
 		dma_unmap_sgtable(xe->drm.dev, xe_tt->sg,
 				  DMA_BIDIRECTIONAL, 0);
 		sg_free_table(xe_tt->sg);

There is another dma_unamp_sgtable() in xe_bo_dma_unmap_pinned(). I guess we should account for that unmap path also.
I am seeing sashiko reported this as well.

Quoted 24 lines
drivers/gpu/drm/xe/xe_debugfs.c +9 -0
index 8c391c7b017a..97b47c5c4213 100644
@@ -6,6 +6,7 @@
 #include "xe_debugfs.h"
 
 #include <linux/debugfs.h>
+#include <linux/mmzone.h>
 #include <linux/fault-inject.h>
 #include <linux/string_helpers.h>
 
@@ -231,6 +232,28 @@ static int dgfx_pcie_link_residencies_show(struct seq_file *m, void *data)
 	return 0;
 }
 
+static int dma_mapped_pages_show(struct seq_file *m, void *data)
+{
+	struct xe_device *xe = m->private;
+	unsigned int i;
+
+	seq_printf(m, "%-11s ", "");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " ---%2u---", i);

drivers/gpu/drm/xe/xe_debugfs.c static int dgfx_pcie_link_residencies_show(struct seq_file *m, void *data) · line 252

Quoted 10 lines
drivers/gpu/drm/xe/xe_debugfs.c +10 -0
+	seq_printf(m, "\n%-11s:", "bo");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " %8lu",
+			   atomic_long_read(&xe->mem.dma_mapped_pages[i]));
+	seq_printf(m, "\n%-11s:", "svm/userptr");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " %8lu",
+			   atomic_long_read(&xe->mem.dma_mapped_pages_svm[i]));
+	seq_puts(m, "\n");
+

NIT: As order-10 also prints higher order (1GB) pages, may be print it as '>=10'?

NIT: This is a rough snapshot as array elements could be changing as we print. I guess that is fine.

Quoted 29 lines
drivers/gpu/drm/xe/xe_debugfs.c +7 -0
+	return 0;
+}
+DEFINE_SHOW_ATTRIBUTE(dma_mapped_pages);
+
 static const struct drm_info_list debugfs_list[] = {
 	{"info", info, 0},
 	{ .name = "sriov_info", .show = sriov_info, },
@@ -632,6 +655,9 @@ void xe_debugfs_register(struct xe_device *xe)
 	if (man)
 		ttm_resource_manager_create_debugfs(man, root, "stolen_mm");
 
+	debugfs_create_file("dma_mapped_pages", 0444, root, xe,
+			    &dma_mapped_pages_fops);
+
 	for_each_tile(tile, xe, tile_id)
 		xe_tile_debugfs_register(tile);
 
drivers/gpu/drm/xe/xe_device.c +4 -0
index ad7f3e61d457..97cc2d185e45 100644
@@ -455,12 +455,42 @@ bool xe_device_is_admin_only(const struct xe_device *xe)
 }
 #endif
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+static void xe_device_assert_dma_pages_zero(struct xe_device *xe)
+{
+	unsigned int i;

drivers/gpu/drm/xe/xe_device.c bool xe_device_is_admin_only(const struct xe_device *xe) · line 471

Quoted 10 lines
drivers/gpu/drm/xe/xe_device.c +10 -0
+
+	/*
+	 * All BOs, userptr VMAs and SVM ranges must have been torn down by the
+	 * time the device is destroyed, so every DMA-mapped-pages counter must
+	 * have returned to zero. A non-zero value indicates unbalanced
+	 * accounting, i.e. a missing unmap-side decrement.
+	 */
+	for (i = 0; i < NR_PAGE_ORDERS; i++) {
+		xe_assert(xe, !atomic_long_read(&xe->mem.dma_mapped_pages[i]));
+		xe_assert(xe, !atomic_long_read(&xe->mem.dma_mapped_pages_svm[i]));

This also probably good to do it under a separate xe DEBUG config instead of CONFIG_DEBUG_FS.

Niranjana

Quoted 240 lines
drivers/gpu/drm/xe/xe_device.c +16 -0
+	}
+}
+#else
+static void xe_device_assert_dma_pages_zero(struct xe_device *xe)
+{
+}
+#endif
+
 static void xe_device_destroy(struct drm_device *dev, void *dummy)
 {
 	struct xe_device *xe = to_xe_device(dev);
 
 	xe_bo_dev_fini(&xe->bo_device);
 
+	/*
+	 * Assert the DMA-mapped-pages accounting only after xe_bo_dev_fini()
+	 * has flushed the async BO-free worker: BOs pending async free still
+	 * hold their DMA mappings (and counts) until the worker runs, so
+	 * asserting before the flush could trip a false positive.
+	 */
+	xe_device_assert_dma_pages_zero(xe);
+
 	if (xe->preempt_fence_wq)
 		destroy_workqueue(xe->preempt_fence_wq);
 
drivers/gpu/drm/xe/xe_device_types.h +17 -0
index 022e08205897..95e7cea91cbf 100644
@@ -6,6 +6,7 @@
 #ifndef _XE_DEVICE_TYPES_H_
 #define _XE_DEVICE_TYPES_H_
 
+#include <linux/mmzone.h>
 #include <linux/pci.h>
 
 #include <drm/drm_device.h>
@@ -279,6 +280,22 @@ struct xe_device {
 		struct xe_shrinker *shrinker;
 		/** @mem.stolen_mgr: stolen memory manager. */
 		struct xe_ttm_stolen_mgr *stolen_mgr;
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+		/**
+		 * @mem.dma_mapped_pages: number of DMA-mapped pages per page
+		 * order currently live for this device, for TTM BOs. Only
+		 * accounted when CONFIG_DEBUG_FS is enabled, since it is solely
+		 * exposed through debugfs.
+		 */
+		atomic_long_t dma_mapped_pages[NR_PAGE_ORDERS];
+		/**
+		 * @mem.dma_mapped_pages_svm: number of DMA-mapped pages per
+		 * page order currently live for this device, for SVM ranges
+		 * and userptr VMAs (both share a single drm_gpusvm instance).
+		 * Only accounted when CONFIG_DEBUG_FS is enabled.
+		 */
+		atomic_long_t dma_mapped_pages_svm[NR_PAGE_ORDERS];
+#endif
 	} mem;
 
 	/** @sriov: device level virtualization data */
drivers/gpu/drm/xe/xe_svm.c +42 -2
index b228a737cfd6..ebe48cb76ad9 100644
@@ -827,10 +827,50 @@ static int xe_svm_get_pagemaps(struct xe_vm *vm)
 }
 #endif
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+/*
+ * xe_svm_dma_map_account - drm_gpusvm DMA-mapping accounting callback
+ * @gpusvm: The GPU SVM the mapping belongs to
+ * @addr: The address descriptor of the chunk being (un)mapped
+ * @sign: +1 when @addr was DMA-mapped, -1 when it is being unmapped
+ *
+ * Maintain per-order counts of the system-memory pages that the full SVM
+ * instance (SVM ranges, and userptr VMAs in fault mode) has DMA-mapped for GPU
+ * access. Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted;
+ * device interconnect (VRAM, P2P) entries are skipped. The counts are solely
+ * exposed through debugfs, so the callback is only registered when
+ * CONFIG_DEBUG_FS is enabled.
+ */
+static void xe_svm_dma_map_account(struct drm_gpusvm *gpusvm,
+				   const struct drm_pagemap_addr *addr,
+				   int sign)
+{
+	struct xe_device *xe = gpusvm_to_vm(gpusvm)->xe;
+	unsigned int order = addr->order;
+
+	if (addr->proto != DRM_INTERCONNECT_SYSTEM)
+		return;
+
+	/*
+	 * The CPU-PTE map order reported by hmm can exceed MAX_PAGE_ORDER
+	 * (e.g. an order-18 1GB mapping), so clamp the array index to avoid an
+	 * out-of-bounds access. Clamping is symmetric across the +1/-1 calls,
+	 * so the per-order counters stay balanced.
+	 */
+	order = min(order, (unsigned int)NR_PAGE_ORDERS - 1);
+
+	atomic_long_add((long)(1UL << addr->order) * sign,
+			&xe->mem.dma_mapped_pages_svm[order]);
+}
+#endif
+
 static const struct drm_gpusvm_ops gpusvm_ops = {
 	.range_alloc = xe_svm_range_alloc,
 	.range_free = xe_svm_range_free,
 	.invalidate = xe_svm_invalidate,
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+	.dma_map_account = xe_svm_dma_map_account,
+#endif
 };
 
 static const unsigned long fault_chunk_sizes[] = {
@@ -925,8 +965,8 @@ int xe_svm_init(struct xe_vm *vm)
 		}
 	} else {
 		err = drm_gpusvm_init(&vm->svm.gpusvm, "Xe SVM (simple)",
-				      NULL, 0, 0, 0, NULL,
-				      NULL, 0);
+				      NULL, 0, 0, 0,
+				      xe_userptr_gpusvm_ops_get(), NULL, 0);
 	}
 
 	return err;
drivers/gpu/drm/xe/xe_svm.h +3 -1
index a921556d3466..8e347137a7a6 100644
@@ -194,6 +194,7 @@ struct drm_pagemap *xe_drm_pagemap_from_fd(int fd, u32 region_instance);
 
 #else
 #include <linux/interval_tree.h>
+#include "xe_userptr.h"
 #include "xe_vm.h"
 
 struct drm_pagemap_addr;
@@ -236,7 +237,8 @@ int xe_svm_init(struct xe_vm *vm)
 {
 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
 	return drm_gpusvm_init(&vm->svm.gpusvm, "Xe SVM (simple)",
-			       NULL, 0, 0, 0, NULL, NULL, 0);
+			       NULL, 0, 0, 0,
+			       xe_userptr_gpusvm_ops_get(), NULL, 0);
 #else
 	return 0;
 #endif
drivers/gpu/drm/xe/xe_userptr.c +63 -0
index 8b2d461ea0b2..6b9e1530ead4 100644
@@ -8,9 +8,72 @@
 
 #include <linux/mm.h>
 
+#include <drm/drm_pagemap.h>
+
 #include "xe_tlb_inval.h"
 #include "xe_trace_bo.h"
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+/*
+ * xe_userptr_dma_map_account - drm_gpusvm DMA-mapping accounting callback
+ * @gpusvm: The GPU SVM the mapping belongs to
+ * @addr: The address descriptor of the chunk being (un)mapped
+ * @sign: +1 when @addr was DMA-mapped, -1 when it is being unmapped
+ *
+ * Account, per page order, the system-memory pages DMA-mapped for GPU access
+ * through the drm_gpusvm_pages instance shared by userptr (and, in fault mode,
+ * SVM). Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted;
+ * device interconnect (VRAM, P2P) entries are skipped. The counts are solely
+ * exposed through debugfs, so the callback is only registered when
+ * CONFIG_DEBUG_FS is enabled.
+ */
+static void xe_userptr_dma_map_account(struct drm_gpusvm *gpusvm,
+				       const struct drm_pagemap_addr *addr,
+				       int sign)
+{
+	struct xe_vm *vm = container_of(gpusvm, struct xe_vm, svm.gpusvm);
+	unsigned int order = addr->order;
+
+	if (addr->proto != DRM_INTERCONNECT_SYSTEM)
+		return;
+
+	/*
+	 * The CPU-PTE map order reported by hmm can exceed MAX_PAGE_ORDER
+	 * (e.g. an order-18 1GB mapping), so clamp the array index to avoid an
+	 * out-of-bounds access. Clamping is symmetric across the +1/-1 calls,
+	 * so the per-order counters stay balanced.
+	 */
+	order = min(order, (unsigned int)NR_PAGE_ORDERS - 1);
+
+	atomic_long_add((long)(1UL << addr->order) * sign,
+			&vm->xe->mem.dma_mapped_pages_svm[order]);
+}
+
+static const struct drm_gpusvm_ops xe_userptr_gpusvm_ops = {
+	.dma_map_account = xe_userptr_dma_map_account,
+};
+#endif
+
+/**
+ * xe_userptr_gpusvm_ops_get() - Accounting ops for the simple gpusvm instance
+ *
+ * The core drm_gpusvm_pages-only instance used for userptr (and, in fault
+ * mode, shared with SVM) is initialised with these ops so that DMA-mapped
+ * system pages are accounted and exposed through debugfs. Returns NULL when
+ * CONFIG_DEBUG_FS is disabled, in which case no accounting is kept and the
+ * instance is initialised without ops.
+ *
+ * Return: Pointer to the restricted &drm_gpusvm_ops, or NULL.
+ */
+const struct drm_gpusvm_ops *xe_userptr_gpusvm_ops_get(void)
+{
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+	return &xe_userptr_gpusvm_ops;
+#else
+	return NULL;
+#endif
+}
+
 static void xe_userptr_assert_in_notifier(struct xe_vm *vm)
 {
 	lockdep_assert(lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 0) ||
drivers/gpu/drm/xe/xe_userptr.h +1 -0
index 2a3cd1b5efbb..1e9601be5713 100644
@@ -108,6 +108,7 @@ int __xe_vm_userptr_needs_repin(struct xe_vm *vm);
 int xe_vm_userptr_check_repin(struct xe_vm *vm);
 int xe_vma_userptr_pin_pages(struct xe_userptr_vma *uvma);
 int xe_vma_userptr_check_repin(struct xe_userptr_vma *uvma);
+const struct drm_gpusvm_ops *xe_userptr_gpusvm_ops_get(void);
 #else
 static inline void xe_userptr_remove(struct xe_userptr_vma *uvma) {}
 
Signature · 1 line
2.34.1
author maintainer
#52 lore raw

Re: [PATCH v3 12/33] drm/xe: Add debugfs stats for DMA-mapped pages per order

Quoted 45 lines · Niranjana Vishwanathapura
Quoted 44 lines · Matthew Brost

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

Expose per-page-order DMA mapping counts for the system memory that the xe driver maps for GPU access, split into two categories: TTM buffer objects, and the GPU SVM / userptr ranges (which share a single drm_gpusvm instance per VM).

The stats are visible at:

<debugfs>/dri/<N>/dma_mapped_pages

and are broken out into two rows (bo, svm/userptr), one column per page order, mirroring the layout of the TTM pool page_pool stat.

For TTM BOs the per-order counts are derived from the DMA scatter-gather
table: each mapped segment is physically contiguous, so its page count is split into the largest power-of-two runs (a segment of N pages contributes a 2^k chunk for the largest k with 2^k <= N, repeated for the remainder). Driving the accounting off the sg table rather than the pages[] array keeps it correct even when pages[] entries are cleared while still DMA-mapped, as happens on the defrag page-borrowing path.

For the SVM and userptr ranges the accounting is driven by the drm_gpusvm @dma_map_account callback, which fires once per dma_addr[] entry at the exact point the entry is DMA-mapped and unmapped. This makes the accounting symmetric by construction and avoids driver-side walks that could drift across migration, partial unmaps and the iova vs non-iova paths. Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted; device interconnect (VRAM, P2P) entries are skipped, so the counter reflects only system pages actually mapped through the DMA layer.

The callback is shared between the full SVM instance (fault mode) and the core drm_gpusvm_pages-only instance used for userptr, so userptr mappings are accounted in both the CONFIG_DRM_XE_GPUSVM=y and =n (but CONFIG_DRM_GPUSVM=y) configurations, into the same svm/userptr counter.

Since the counts are only ever consumed through debugfs, gate the counter storage and all accounting on CONFIG_DEBUG_FS so that builds without debugfs carry no extra atomic traffic or device state; the drm_gpusvm callback is simply left unregistered in that case.

On device teardown assert that every counter has returned to zero, to catch any unbalanced accounting (a leaked DMA mapping) during testing.

Quoted 7 lines
Quoted 3 lines
Assisted-by GitHub_Copilot:claude-opus-4.8

Patches 11 and 12 can be spinned out as a separate patch series (for fast tracking).

Yep, spliting these out now.

Quoted 5 lines

Also, dma map/unmap of dmabuf imported BOs are skipped here (rightly so). But perhaps add a comments in commit message that either self-import returns the same BO and BOs of other device gets counted on exporter side when it gets first migrated to TT first.

Sure.

Quoted 54 lines
Quoted 54 lines

---

v3:
- Fix drm_gpusvm_init() argument order, clamp DMA-page order to NR_PAGE_ORDERS - 1, and drain DMA-page accounting after xe_bo_dev_fini() (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c           | 46 ++++++++++++++++++++
drivers/gpu/drm/xe/xe_debugfs.c      | 26 ++++++++++++
drivers/gpu/drm/xe/xe_device.c       | 30 +++++++++++++
drivers/gpu/drm/xe/xe_device_types.h | 17 ++++++++
drivers/gpu/drm/xe/xe_svm.c          | 44 ++++++++++++++++++-
drivers/gpu/drm/xe/xe_svm.h          |  4 +-
drivers/gpu/drm/xe/xe_userptr.c      | 63 ++++++++++++++++++++++++++++
drivers/gpu/drm/xe/xe_userptr.h      |  1 +
8 files changed, 228 insertions(+), 3 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +29 -0
index 85e6d9a0f575..60e0e568aa31 100644
@@ -367,6 +367,50 @@ struct xe_ttm_tt {
 	bool purgeable;
 };
 
+/*
+ * xe_tt_account_dma_pages - account DMA-mapped tt pages per order
+ * @xe: the xe device
+ * @xe_tt: the xe_ttm_tt whose sg table to walk
+ * @sign: +1 to add, -1 to subtract
+ *
+ * Walk the tt's DMA scatter-gather table and split each (physically
+ * contiguous) segment into the largest power-of-two page runs: a segment of N
+ * pages contributes a 2^k chunk for the largest k with 2^k <= N, repeated for
+ * the remainder. Accumulate the count of 2^k pages into
+ * xe->mem.dma_mapped_pages[k]. Driving this off the sg table rather than
+ * tt->pages keeps the accounting correct even when pages[] entries are cleared
+ * while still DMA-mapped (e.g. the defrag page-borrowing path).
+ */
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+static void xe_tt_account_dma_pages(struct xe_device *xe,
+				    struct xe_ttm_tt *xe_tt, int sign)
+{
+	struct scatterlist *sg;
+	unsigned int i;
+
+	for_each_sgtable_sg(xe_tt->sg, sg, i) {
+		unsigned long nr_pages = sg->length >> PAGE_SHIFT;
+
+		while (nr_pages) {
+			unsigned int order = min_t(unsigned int,
+						   __fls(nr_pages),
+						   MAX_PAGE_ORDER);
+			unsigned long chunk = 1UL << order;
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c struct xe_ttm_tt { · line 402

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
+
+			atomic_long_add((long)chunk * sign,
+					&xe->mem.dma_mapped_pages[order]);
+

NIT: As there is an atomic operation involved, instead of doing it under CONFIG_DEBUG_FS, should we be doing it under a separate xe specific debug config?

I think GT stats are just gated by CONFIG_DEBUG_FS, I say this is roughly idea. If someone complains about perf we could change this per-cpu counter like GT stats or I guess add different Kconfig gate?

Quoted 25 lines
Quoted 25 lines
drivers/gpu/drm/xe/xe_bo.c +12 -0
+			nr_pages -= chunk;
+		}
+	}
+}
+#else
+static void xe_tt_account_dma_pages(struct xe_device *xe,
+				    struct xe_ttm_tt *xe_tt, int sign)
+{
+}
+#endif
+
 static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
 {
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
@@ -396,6 +440,7 @@ static int xe_tt_map_sg(struct xe_device *xe, struct ttm_tt *tt)
 		return ret;
 	}
 
+	xe_tt_account_dma_pages(xe, xe_tt, 1);
 	return 0;
 }
 
@@ -404,6 +449,7 @@ static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt)
 	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
 
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_tt_unmap_sg(struct xe_device *xe, struct ttm_tt *tt) · line 455

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
 	if (xe_tt->sg) {
+		xe_tt_account_dma_pages(xe, xe_tt, -1);
 		dma_unmap_sgtable(xe->drm.dev, xe_tt->sg,
 				  DMA_BIDIRECTIONAL, 0);
 		sg_free_table(xe_tt->sg);

There is another dma_unamp_sgtable() in xe_bo_dma_unmap_pinned(). I guess we should account for that unmap path also.
I am seeing sashiko reported this as well.

I see dma_buf_unmap_attachment and call to xe_tt_unmap_sg but I'm on drm-tip now, so at in what I'll post shortly this I don't think this is an issue.

Quoted 75 lines
Quoted 25 lines
drivers/gpu/drm/xe/xe_debugfs.c +9 -0
index 8c391c7b017a..97b47c5c4213 100644
@@ -6,6 +6,7 @@
 #include "xe_debugfs.h"
 
 #include <linux/debugfs.h>
+#include <linux/mmzone.h>
 #include <linux/fault-inject.h>
 #include <linux/string_helpers.h>
 
@@ -231,6 +232,28 @@ static int dgfx_pcie_link_residencies_show(struct seq_file *m, void *data)
 	return 0;
 }
 
+static int dma_mapped_pages_show(struct seq_file *m, void *data)
+{
+	struct xe_device *xe = m->private;
+	unsigned int i;
+
+	seq_printf(m, "%-11s ", "");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " ---%2u---", i);

drivers/gpu/drm/xe/xe_debugfs.c static int dgfx_pcie_link_residencies_show(struct seq_file *m, void *data) · line 252

Quoted 10 lines
drivers/gpu/drm/xe/xe_debugfs.c +10 -0
+	seq_printf(m, "\n%-11s:", "bo");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " %8lu",
+			   atomic_long_read(&xe->mem.dma_mapped_pages[i]));
+	seq_printf(m, "\n%-11s:", "svm/userptr");
+	for (i = 0; i < NR_PAGE_ORDERS; i++)
+		seq_printf(m, " %8lu",
+			   atomic_long_read(&xe->mem.dma_mapped_pages_svm[i]));
+	seq_puts(m, "\n");
+

NIT: As order-10 also prints higher order (1GB) pages, may be print it as '>=10'?

NIT: This is a rough snapshot as array elements could be changing as we print. I guess that is fine.

Quoted 34 lines
drivers/gpu/drm/xe/xe_debugfs.c +7 -0
+	return 0;
+}
+DEFINE_SHOW_ATTRIBUTE(dma_mapped_pages);
+
 static const struct drm_info_list debugfs_list[] = {
 	{"info", info, 0},
 	{ .name = "sriov_info", .show = sriov_info, },
@@ -632,6 +655,9 @@ void xe_debugfs_register(struct xe_device *xe)
 	if (man)
 		ttm_resource_manager_create_debugfs(man, root, "stolen_mm");
 
+	debugfs_create_file("dma_mapped_pages", 0444, root, xe,
+			    &dma_mapped_pages_fops);
+
 	for_each_tile(tile, xe, tile_id)
 		xe_tile_debugfs_register(tile);
 
drivers/gpu/drm/xe/xe_device.c +9 -0
index ad7f3e61d457..97cc2d185e45 100644
@@ -455,12 +455,42 @@ bool xe_device_is_admin_only(const struct xe_device *xe)
 }
 #endif
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+static void xe_device_assert_dma_pages_zero(struct xe_device *xe)
+{
+	unsigned int i;
+
+	/*
+	 * All BOs, userptr VMAs and SVM ranges must have been torn down by the
+	 * time the device is destroyed, so every DMA-mapped-pages counter must
+	 * have returned to zero. A non-zero value indicates unbalanced
Quoted 9 lines

drivers/gpu/drm/xe/xe_device.c bool xe_device_is_admin_only(const struct xe_device *xe) · line 471

Quoted 5 lines
drivers/gpu/drm/xe/xe_device.c +5 -0
+	 * accounting, i.e. a missing unmap-side decrement.
+	 */
+	for (i = 0; i < NR_PAGE_ORDERS; i++) {
+		xe_assert(xe, !atomic_long_read(&xe->mem.dma_mapped_pages[i]));
+		xe_assert(xe, !atomic_long_read(&xe->mem.dma_mapped_pages_svm[i]));

This also probably good to do it under a separate xe DEBUG config instead of CONFIG_DEBUG_FS.

I can make this change but IMO this is needed. I would think we'd want these stats on all production systems for debug, i.e., CONFIG_DEBUG_FS is likely the right Kconfig.

Matt

Quoted 242 lines

Niranjana

Quoted 240 lines
drivers/gpu/drm/xe/xe_device.c +16 -0
+	}
+}
+#else
+static void xe_device_assert_dma_pages_zero(struct xe_device *xe)
+{
+}
+#endif
+
 static void xe_device_destroy(struct drm_device *dev, void *dummy)
 {
 	struct xe_device *xe = to_xe_device(dev);
 
 	xe_bo_dev_fini(&xe->bo_device);
 
+	/*
+	 * Assert the DMA-mapped-pages accounting only after xe_bo_dev_fini()
+	 * has flushed the async BO-free worker: BOs pending async free still
+	 * hold their DMA mappings (and counts) until the worker runs, so
+	 * asserting before the flush could trip a false positive.
+	 */
+	xe_device_assert_dma_pages_zero(xe);
+
 	if (xe->preempt_fence_wq)
 		destroy_workqueue(xe->preempt_fence_wq);
 
drivers/gpu/drm/xe/xe_device_types.h +17 -0
index 022e08205897..95e7cea91cbf 100644
@@ -6,6 +6,7 @@
 #ifndef _XE_DEVICE_TYPES_H_
 #define _XE_DEVICE_TYPES_H_
 
+#include <linux/mmzone.h>
 #include <linux/pci.h>
 
 #include <drm/drm_device.h>
@@ -279,6 +280,22 @@ struct xe_device {
 		struct xe_shrinker *shrinker;
 		/** @mem.stolen_mgr: stolen memory manager. */
 		struct xe_ttm_stolen_mgr *stolen_mgr;
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+		/**
+		 * @mem.dma_mapped_pages: number of DMA-mapped pages per page
+		 * order currently live for this device, for TTM BOs. Only
+		 * accounted when CONFIG_DEBUG_FS is enabled, since it is solely
+		 * exposed through debugfs.
+		 */
+		atomic_long_t dma_mapped_pages[NR_PAGE_ORDERS];
+		/**
+		 * @mem.dma_mapped_pages_svm: number of DMA-mapped pages per
+		 * page order currently live for this device, for SVM ranges
+		 * and userptr VMAs (both share a single drm_gpusvm instance).
+		 * Only accounted when CONFIG_DEBUG_FS is enabled.
+		 */
+		atomic_long_t dma_mapped_pages_svm[NR_PAGE_ORDERS];
+#endif
 	} mem;
 
 	/** @sriov: device level virtualization data */
drivers/gpu/drm/xe/xe_svm.c +42 -2
index b228a737cfd6..ebe48cb76ad9 100644
@@ -827,10 +827,50 @@ static int xe_svm_get_pagemaps(struct xe_vm *vm)
 }
 #endif
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+/*
+ * xe_svm_dma_map_account - drm_gpusvm DMA-mapping accounting callback
+ * @gpusvm: The GPU SVM the mapping belongs to
+ * @addr: The address descriptor of the chunk being (un)mapped
+ * @sign: +1 when @addr was DMA-mapped, -1 when it is being unmapped
+ *
+ * Maintain per-order counts of the system-memory pages that the full SVM
+ * instance (SVM ranges, and userptr VMAs in fault mode) has DMA-mapped for GPU
+ * access. Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted;
+ * device interconnect (VRAM, P2P) entries are skipped. The counts are solely
+ * exposed through debugfs, so the callback is only registered when
+ * CONFIG_DEBUG_FS is enabled.
+ */
+static void xe_svm_dma_map_account(struct drm_gpusvm *gpusvm,
+				   const struct drm_pagemap_addr *addr,
+				   int sign)
+{
+	struct xe_device *xe = gpusvm_to_vm(gpusvm)->xe;
+	unsigned int order = addr->order;
+
+	if (addr->proto != DRM_INTERCONNECT_SYSTEM)
+		return;
+
+	/*
+	 * The CPU-PTE map order reported by hmm can exceed MAX_PAGE_ORDER
+	 * (e.g. an order-18 1GB mapping), so clamp the array index to avoid an
+	 * out-of-bounds access. Clamping is symmetric across the +1/-1 calls,
+	 * so the per-order counters stay balanced.
+	 */
+	order = min(order, (unsigned int)NR_PAGE_ORDERS - 1);
+
+	atomic_long_add((long)(1UL << addr->order) * sign,
+			&xe->mem.dma_mapped_pages_svm[order]);
+}
+#endif
+
 static const struct drm_gpusvm_ops gpusvm_ops = {
 	.range_alloc = xe_svm_range_alloc,
 	.range_free = xe_svm_range_free,
 	.invalidate = xe_svm_invalidate,
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+	.dma_map_account = xe_svm_dma_map_account,
+#endif
 };
 
 static const unsigned long fault_chunk_sizes[] = {
@@ -925,8 +965,8 @@ int xe_svm_init(struct xe_vm *vm)
 		}
 	} else {
 		err = drm_gpusvm_init(&vm->svm.gpusvm, "Xe SVM (simple)",
-				      NULL, 0, 0, 0, NULL,
-				      NULL, 0);
+				      NULL, 0, 0, 0,
+				      xe_userptr_gpusvm_ops_get(), NULL, 0);
 	}
 
 	return err;
drivers/gpu/drm/xe/xe_svm.h +3 -1
index a921556d3466..8e347137a7a6 100644
@@ -194,6 +194,7 @@ struct drm_pagemap *xe_drm_pagemap_from_fd(int fd, u32 region_instance);
 
 #else
 #include <linux/interval_tree.h>
+#include "xe_userptr.h"
 #include "xe_vm.h"
 
 struct drm_pagemap_addr;
@@ -236,7 +237,8 @@ int xe_svm_init(struct xe_vm *vm)
 {
 #if IS_ENABLED(CONFIG_DRM_GPUSVM)
 	return drm_gpusvm_init(&vm->svm.gpusvm, "Xe SVM (simple)",
-			       NULL, 0, 0, 0, NULL, NULL, 0);
+			       NULL, 0, 0, 0,
+			       xe_userptr_gpusvm_ops_get(), NULL, 0);
 #else
 	return 0;
 #endif
drivers/gpu/drm/xe/xe_userptr.c +63 -0
index 8b2d461ea0b2..6b9e1530ead4 100644
@@ -8,9 +8,72 @@
 
 #include <linux/mm.h>
 
+#include <drm/drm_pagemap.h>
+
 #include "xe_tlb_inval.h"
 #include "xe_trace_bo.h"
 
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+/*
+ * xe_userptr_dma_map_account - drm_gpusvm DMA-mapping accounting callback
+ * @gpusvm: The GPU SVM the mapping belongs to
+ * @addr: The address descriptor of the chunk being (un)mapped
+ * @sign: +1 when @addr was DMA-mapped, -1 when it is being unmapped
+ *
+ * Account, per page order, the system-memory pages DMA-mapped for GPU access
+ * through the drm_gpusvm_pages instance shared by userptr (and, in fault mode,
+ * SVM). Only DRM_INTERCONNECT_SYSTEM entries are real DMA maps and counted;
+ * device interconnect (VRAM, P2P) entries are skipped. The counts are solely
+ * exposed through debugfs, so the callback is only registered when
+ * CONFIG_DEBUG_FS is enabled.
+ */
+static void xe_userptr_dma_map_account(struct drm_gpusvm *gpusvm,
+				       const struct drm_pagemap_addr *addr,
+				       int sign)
+{
+	struct xe_vm *vm = container_of(gpusvm, struct xe_vm, svm.gpusvm);
+	unsigned int order = addr->order;
+
+	if (addr->proto != DRM_INTERCONNECT_SYSTEM)
+		return;
+
+	/*
+	 * The CPU-PTE map order reported by hmm can exceed MAX_PAGE_ORDER
+	 * (e.g. an order-18 1GB mapping), so clamp the array index to avoid an
+	 * out-of-bounds access. Clamping is symmetric across the +1/-1 calls,
+	 * so the per-order counters stay balanced.
+	 */
+	order = min(order, (unsigned int)NR_PAGE_ORDERS - 1);
+
+	atomic_long_add((long)(1UL << addr->order) * sign,
+			&vm->xe->mem.dma_mapped_pages_svm[order]);
+}
+
+static const struct drm_gpusvm_ops xe_userptr_gpusvm_ops = {
+	.dma_map_account = xe_userptr_dma_map_account,
+};
+#endif
+
+/**
+ * xe_userptr_gpusvm_ops_get() - Accounting ops for the simple gpusvm instance
+ *
+ * The core drm_gpusvm_pages-only instance used for userptr (and, in fault
+ * mode, shared with SVM) is initialised with these ops so that DMA-mapped
+ * system pages are accounted and exposed through debugfs. Returns NULL when
+ * CONFIG_DEBUG_FS is disabled, in which case no accounting is kept and the
+ * instance is initialised without ops.
+ *
+ * Return: Pointer to the restricted &drm_gpusvm_ops, or NULL.
+ */
+const struct drm_gpusvm_ops *xe_userptr_gpusvm_ops_get(void)
+{
+#if IS_ENABLED(CONFIG_DEBUG_FS)
+	return &xe_userptr_gpusvm_ops;
+#else
+	return NULL;
+#endif
+}
+
 static void xe_userptr_assert_in_notifier(struct xe_vm *vm)
 {
 	lockdep_assert(lockdep_is_held_type(&vm->svm.gpusvm.notifier_lock, 0) ||
drivers/gpu/drm/xe/xe_userptr.h +1 -0
index 2a3cd1b5efbb..1e9601be5713 100644
@@ -108,6 +108,7 @@ int __xe_vm_userptr_needs_repin(struct xe_vm *vm);
 int xe_vm_userptr_check_repin(struct xe_vm *vm);
 int xe_vma_userptr_pin_pages(struct xe_userptr_vma *uvma);
 int xe_vma_userptr_check_repin(struct xe_userptr_vma *uvma);
+const struct drm_gpusvm_ops *xe_userptr_gpusvm_ops_get(void);
 #else
 static inline void xe_userptr_remove(struct xe_userptr_vma *uvma) {}
 
Signature · 1 line
2.34.1
author maintainer
#53 lore raw

PATCH v3 13/33 drm/xe: Flush L2 asynchronously in xe_bo_trigger_rebind()

In reply to Matthew Brost

On L2-flush-optimized HW with a dma-resv (non-fault) VM, evicting a BO only needs to flush the L2 cache before the migration copy runs; the mappings themselves are torn down and rebuilt lazily via drm_gpuvm_bo_evict() and a subsequent rebind. Today this flush is done by waiting for the BO to go idle and then issuing a synchronous TLB invalidation per mapping VMA from inside xe_bo_trigger_rebind(). Both the idle wait and the synchronous invalidation stall the calling thread while holding the BO dma-resv lock, serializing the move behind all in-flight GPU work on the BO.

Replace this with an asynchronous flush. Add xe_vm_flush_vm_bo_tlb_async() which, for each VMA mapping the BO on each present tile, queues a TLB invalidation job on the tile migrate (kernel) exec queue. The jobs depend on the BO's in-flight GPU work, captured once as a singleton over DMA_RESV_USAGE_BOOKKEEP, so the flush only fires once the GPU is done with the current mapping. Each job's completion fence is installed into the BO's dma-resv as a DMA_RESV_USAGE_KERNEL fence, so the migration copy - which waits on the resv - waits on the flush without stalling this thread.

No PTEs are zapped and vma->tile_invalidated is left untouched: the mapping stays valid until the lazy rebind, and the only work performed here is the L2 flush. On any failure the caller falls back to the existing blocking wait-idle plus xe_vm_invalidate_vma() path.

Cc Thomas Hellström <[email protected]>
Cc Tejas Upadhyay <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Gate the asynchronous L2 flush on !ctx->no_wait_gpu (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c |  13 ++++
 drivers/gpu/drm/xe/xe_vm.c | 125 +++++++++++++++++++++++++++++++++++++
 drivers/gpu/drm/xe/xe_vm.h |   5 ++
 3 files changed, 143 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +13 -0
index 60e0e568aa31..4ee48cdc02ac 100644
@@ -732,6 +732,19 @@ static int xe_bo_trigger_rebind(struct xe_device *xe, struct xe_bo *bo,
 			 */
 			if (!xe_device_is_l2_flush_optimized(xe))
 				continue;
+
+			/*
+			 * Attempt to flush L2 async, fallback to sync flush on
+			 * failure. Skip the async attempt under no_wait_gpu
+			 * (e.g. the shrinker's reclaim pass): job creation
+			 * allocates with GFP_KERNEL, which must not run while
+			 * holding the dma-resv lock under fs_reclaim. The sync
+			 * fallback below honors no_wait_gpu (returns -EBUSY if
+			 * the BO is not idle).
+			 */
+			if (!ctx->no_wait_gpu &&
+			    !xe_vm_flush_vm_bo_tlb_async(vm, bo, vm_bo))
+				continue;
 		}
 
 		if (!idle) {
drivers/gpu/drm/xe/xe_vm.c +125 -0

137 lines not on this page · raw message

drivers/gpu/drm/xe/xe_vm.h +5 -0
index c5b900f38ded..dd5b070eaede 100644
@@ -26,6 +26,8 @@ struct ttm_buffer_object;
 
 struct dma_fence;
 
+struct xe_bo;
+struct drm_gpuvm_bo;
 struct xe_exec_queue;
 struct xe_file;
 struct xe_pagefault;
@@ -254,6 +256,9 @@ int xe_vm_invalidate_vma(struct xe_vma *vma);
 
 int xe_vm_invalidate_vma_submit(struct xe_vma *vma, struct xe_tlb_inval_batch *batch);
 
+int xe_vm_flush_vm_bo_tlb_async(struct xe_vm *vm, struct xe_bo *bo,
+				struct drm_gpuvm_bo *vm_bo);
+
 int xe_vm_validate_protected(struct xe_vm *vm);
 
 static inline void xe_vm_queue_rebind_worker(struct xe_vm *vm)
Signature · 1 line
2.34.1
reviewer
#54 lore raw

Re: [PATCH v3 13/33] drm/xe: Flush L2 asynchronously in xe_bo_trigger_rebind()

Quoted 24 lines · Matthew Brost

On L2-flush-optimized HW with a dma-resv (non-fault) VM, evicting a BO only needs to flush the L2 cache before the migration copy runs; the mappings themselves are torn down and rebuilt lazily via drm_gpuvm_bo_evict() and a subsequent rebind. Today this flush is done by waiting for the BO to go idle and then issuing a synchronous TLB invalidation per mapping VMA from inside xe_bo_trigger_rebind(). Both the idle wait and the synchronous invalidation stall the calling thread while holding the BO dma-resv lock, serializing the move behind all in-flight GPU work on the BO.

Replace this with an asynchronous flush. Add xe_vm_flush_vm_bo_tlb_async() which, for each VMA mapping the BO on each present tile, queues a TLB invalidation job on the tile migrate (kernel) exec queue. The jobs depend on the BO's in-flight GPU work, captured once as a singleton over DMA_RESV_USAGE_BOOKKEEP, so the flush only fires once the GPU is done with the current mapping. Each job's completion fence is installed into the BO's dma-resv as a DMA_RESV_USAGE_KERNEL fence, so the migration copy - which waits on the resv - waits on the flush without stalling this thread.

No PTEs are zapped and vma->tile_invalidated is left untouched: the mapping stays valid until the lazy rebind, and the only work performed here is the L2 flush. On any failure the caller falls back to the existing blocking wait-idle plus xe_vm_invalidate_vma() path.

Quoted 4 lines
Cc Thomas Hellström <[email protected]>
Cc Tejas Upadhyay <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

I think this one was split out right? But not merged yet?

author maintainer
#55 lore raw

Re: [PATCH v3 13/33] drm/xe: Flush L2 asynchronously in xe_bo_trigger_rebind()

Quoted 25 lines · Matthew Auld
Quoted 24 lines · Matthew Brost

On L2-flush-optimized HW with a dma-resv (non-fault) VM, evicting a BO only needs to flush the L2 cache before the migration copy runs; the mappings themselves are torn down and rebuilt lazily via drm_gpuvm_bo_evict() and a subsequent rebind. Today this flush is done by waiting for the BO to go idle and then issuing a synchronous TLB invalidation per mapping VMA from inside xe_bo_trigger_rebind(). Both the idle wait and the synchronous invalidation stall the calling thread while holding the BO dma-resv lock, serializing the move behind all in-flight GPU work on the BO.

Replace this with an asynchronous flush. Add xe_vm_flush_vm_bo_tlb_async() which, for each VMA mapping the BO on each present tile, queues a TLB invalidation job on the tile migrate (kernel) exec queue. The jobs depend on the BO's in-flight GPU work, captured once as a singleton over DMA_RESV_USAGE_BOOKKEEP, so the flush only fires once the GPU is done with the current mapping. Each job's completion fence is installed into the BO's dma-resv as a DMA_RESV_USAGE_KERNEL fence, so the migration copy - which waits on the resv - waits on the flush without stalling this thread.

No PTEs are zapped and vma->tile_invalidated is left untouched: the mapping stays valid until the lazy rebind, and the only work performed here is the L2 flush. On any failure the caller falls back to the existing blocking wait-idle plus xe_vm_invalidate_vma() path.

Quoted 6 lines
Quoted 4 lines
Cc Thomas Hellström <[email protected]>
Cc Tejas Upadhyay <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

I think this one was split out right? But not merged yet?

Yes, we can split this one out and in fact did earlier [1].

Let me respin this one as standalone patch today.

Matt

[1] https://patchwork.freedesktop.org/series/170046/

author maintainer
#56 lore raw

PATCH v3 14/33 drm/xe: Destroy page tables after unlinking all VMAs on VM close

In reply to Matthew Brost

xe_vm_close_and_put() freed the VM's page-table roots via xe_vm_pt_destroy() before destroying the "contested" VMAs - those backed by external (shared) BOs, which are deferred to xe_vma_destroy_unlocked() because unlinking them requires taking the external BO's dma-resv lock (via drm_exec), not vm->lock.

Until such a VMA is unlinked it remains reachable from its BO through drm_gem_for_each_gpuvm_bo(). A concurrent BO move that only holds the BO's dma-resv lock - TTM eviction, the shrinker, or the defrag worker - calls xe_bo_move_notify() -> xe_bo_trigger_rebind() -> xe_vm_invalidate_vma() -> xe_pt_zap_ptes(), which dereferences vm->pt_root[tile->id]. With the page tables already freed this is a use-after-free / NULL dereference, e.g.:

  Oops: general protection fault [...] kernel NULL pointer dereference
  RIP: xe_pt_zap_ptes+0x7c [xe]
  Call Trace:
   xe_vm_invalidate_vma_submit+0x64/0x130 [xe]
   xe_vm_invalidate_vma+0x27/0x60 [xe]
   xe_bo_move_notify+0x1e7/0x3d0 [xe]
   xe_bo_move+0x62d/0x1620 [xe]
   ttm_bo_handle_move_mem+0x243/0x330 [ttm]
   ttm_bo_validate+0xb4/0x1a0 [ttm]

The race is not closable with a flag or a NULL pt_root check in the invalidate path: the freeing side holds only vm->lock while the walker holds only the BO's resv, so there is no common lock to serialise on.

Fix the ordering instead: destroy the page tables only after every VMA - including the contested external-BO VMAs - has been unlinked. Once the contested loop completes no BO can reach a VMA of this VM, so freeing the page tables (under vm->lock, to satisfy xe_vm_assert_held()) is safe. xe_vm_free_scratch() still runs before the free as it reads pt_root[]->level.

Fixes dd08ebf6c352 ("drm/xe: Introduce a new DRM driver for Intel GPUs")
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_vm.c | 24 ++++++++++++++++--------
 1 file changed, 16 insertions(+), 8 deletions(-)
drivers/gpu/drm/xe/xe_vm.c +16 -8
index 4557a8a4d270..9f55d22cb985 100644
@@ -1934,15 +1934,7 @@ void xe_vm_close_and_put(struct xe_vm *vm)
 		vma->gpuva.flags |= XE_VMA_DESTROYED;
 	}
 
-	/*
-	 * All vm operations will add shared fences to resv.
-	 * The only exception is eviction for a shared object,
-	 * but even so, the unbind when evicted would still
-	 * install a fence to resv. Hence it's safe to
-	 * destroy the pagetables immediately.
-	 */
 	xe_vm_free_scratch(vm);
-	xe_vm_pt_destroy(vm);
 	xe_vm_unlock(vm);
 
 	/*
@@ -1956,6 +1948,22 @@ void xe_vm_close_and_put(struct xe_vm *vm)
 		xe_vma_destroy_unlocked(vma);
 	}
 
+	/*
+	 * Destroy the page tables only after every VMA has been unlinked. The
+	 * contested (external-BO) VMAs above are unlinked from their BO under
+	 * the BO's dma-resv lock, not vm->lock, so they can still be reached
+	 * via drm_gem_for_each_gpuvm_bo() by a concurrent BO move (eviction,
+	 * shrinker or the defrag worker) that only holds the BO's resv. Such a
+	 * move calls xe_vm_invalidate_vma() -> xe_pt_zap_ptes(), which
+	 * dereferences vm->pt_root[]; freeing the page tables while those VMAs
+	 * are still linked is a use-after-free. All vm operations add shared
+	 * fences to the resv (eviction of a shared object still installs an
+	 * unbind fence), so no GPU work outlives this point.
+	 */
+	xe_vm_lock(vm, false);
+	xe_vm_pt_destroy(vm);
+	xe_vm_unlock(vm);
+
 	xe_svm_fini(vm);
 
 	up_write(&vm->lock);
Signature · 1 line
2.34.1
#57 lore raw

Re: [PATCH v3 14/33] drm/xe: Destroy page tables after unlinking all VMAs on VM close

Quoted 35 lines · Matthew Brost

xe_vm_close_and_put() freed the VM's page-table roots via xe_vm_pt_destroy() before destroying the "contested" VMAs - those backed by external (shared) BOs, which are deferred to xe_vma_destroy_unlocked() because unlinking them requires taking the external BO's dma-resv lock (via drm_exec), not vm->lock.

Until such a VMA is unlinked it remains reachable from its BO through drm_gem_for_each_gpuvm_bo(). A concurrent BO move that only holds the BO's dma-resv lock - TTM eviction, the shrinker, or the defrag worker - calls xe_bo_move_notify() -> xe_bo_trigger_rebind() -> xe_vm_invalidate_vma() -> xe_pt_zap_ptes(), which dereferences vm->pt_root[tile->id]. With the page tables already freed this is a use-after-free / NULL dereference, e.g.:

 Oops: general protection fault [...] kernel NULL pointer dereference
 RIP: xe_pt_zap_ptes+0x7c [xe]
 Call Trace:
  xe_vm_invalidate_vma_submit+0x64/0x130 [xe]
  xe_vm_invalidate_vma+0x27/0x60 [xe]
  xe_bo_move_notify+0x1e7/0x3d0 [xe]
  xe_bo_move+0x62d/0x1620 [xe]
  ttm_bo_handle_move_mem+0x243/0x330 [ttm]
  ttm_bo_validate+0xb4/0x1a0 [ttm]

The race is not closable with a flag or a NULL pt_root check in the invalidate path: the freeing side holds only vm->lock while the walker holds only the BO's resv, so there is no common lock to serialise on.

Fix the ordering instead: destroy the page tables only after every VMA - including the contested external-BO VMAs - has been unlinked. Once the contested loop completes no BO can reach a VMA of this VM, so freeing the page tables (under vm->lock, to satisfy xe_vm_assert_held()) is safe. xe_vm_free_scratch() still runs before the free as it reads pt_root[]->level.

Quoted 3 lines
Fixes dd08ebf6c352 ("drm/xe: Introduce a new DRM driver for Intel GPUs")
Assisted-by GitHub_Copilot:claude-opus-4.8

Looks like this change is already merged with below commit "drm/xe/vm: nuke PTs only after unlinking contested VMAs"

So, needs to be dropped in this series.

Niranjana

Quoted 50 lines

---
drivers/gpu/drm/xe/xe_vm.c | 24 ++++++++++++++++--------

1 file changed, 16 insertions(+), 8 deletions(-)
drivers/gpu/drm/xe/xe_vm.c +16 -8
index 4557a8a4d270..9f55d22cb985 100644
@@ -1934,15 +1934,7 @@ void xe_vm_close_and_put(struct xe_vm *vm)
 		vma->gpuva.flags |= XE_VMA_DESTROYED;
 	}
 
-	/*
-	 * All vm operations will add shared fences to resv.
-	 * The only exception is eviction for a shared object,
-	 * but even so, the unbind when evicted would still
-	 * install a fence to resv. Hence it's safe to
-	 * destroy the pagetables immediately.
-	 */
 	xe_vm_free_scratch(vm);
-	xe_vm_pt_destroy(vm);
 	xe_vm_unlock(vm);
 
 	/*
@@ -1956,6 +1948,22 @@ void xe_vm_close_and_put(struct xe_vm *vm)
 		xe_vma_destroy_unlocked(vma);
 	}
 
+	/*
+	 * Destroy the page tables only after every VMA has been unlinked. The
+	 * contested (external-BO) VMAs above are unlinked from their BO under
+	 * the BO's dma-resv lock, not vm->lock, so they can still be reached
+	 * via drm_gem_for_each_gpuvm_bo() by a concurrent BO move (eviction,
+	 * shrinker or the defrag worker) that only holds the BO's resv. Such a
+	 * move calls xe_vm_invalidate_vma() -> xe_pt_zap_ptes(), which
+	 * dereferences vm->pt_root[]; freeing the page tables while those VMAs
+	 * are still linked is a use-after-free. All vm operations add shared
+	 * fences to the resv (eviction of a shared object still installs an
+	 * unbind fence), so no GPU work outlives this point.
+	 */
+	xe_vm_lock(vm, false);
+	xe_vm_pt_destroy(vm);
+	xe_vm_unlock(vm);
+
 	xe_svm_fini(vm);
 
 	up_write(&vm->lock);
Signature · 1 line
2.34.1
author maintainer
#58 lore raw

Re: [PATCH v3 14/33] drm/xe: Destroy page tables after unlinking all VMAs on VM close

Quoted 36 lines · Niranjana Vishwanathapura
Quoted 35 lines · Matthew Brost

xe_vm_close_and_put() freed the VM's page-table roots via xe_vm_pt_destroy() before destroying the "contested" VMAs - those backed by external (shared) BOs, which are deferred to xe_vma_destroy_unlocked() because unlinking them requires taking the external BO's dma-resv lock (via drm_exec), not vm->lock.

Until such a VMA is unlinked it remains reachable from its BO through drm_gem_for_each_gpuvm_bo(). A concurrent BO move that only holds the BO's dma-resv lock - TTM eviction, the shrinker, or the defrag worker - calls xe_bo_move_notify() -> xe_bo_trigger_rebind() -> xe_vm_invalidate_vma() -> xe_pt_zap_ptes(), which dereferences vm->pt_root[tile->id]. With the page tables already freed this is a use-after-free / NULL dereference, e.g.:

 Oops: general protection fault [...] kernel NULL pointer dereference
 RIP: xe_pt_zap_ptes+0x7c [xe]
 Call Trace:
  xe_vm_invalidate_vma_submit+0x64/0x130 [xe]
  xe_vm_invalidate_vma+0x27/0x60 [xe]
  xe_bo_move_notify+0x1e7/0x3d0 [xe]
  xe_bo_move+0x62d/0x1620 [xe]
  ttm_bo_handle_move_mem+0x243/0x330 [ttm]
  ttm_bo_validate+0xb4/0x1a0 [ttm]

The race is not closable with a flag or a NULL pt_root check in the invalidate path: the freeing side holds only vm->lock while the walker holds only the BO's resv, so there is no common lock to serialise on.

Fix the ordering instead: destroy the page tables only after every VMA - including the contested external-BO VMAs - has been unlinked. Once the contested loop completes no BO can reach a VMA of this VM, so freeing the page tables (under vm->lock, to satisfy xe_vm_assert_held()) is safe. xe_vm_free_scratch() still runs before the free as it reads pt_root[]->level.

Quoted 9 lines
Quoted 3 lines
Fixes dd08ebf6c352 ("drm/xe: Introduce a new DRM driver for Intel GPUs")
Assisted-by GitHub_Copilot:claude-opus-4.8

Looks like this change is already merged with below commit "drm/xe/vm: nuke PTs only after unlinking contested VMAs"

So, needs to be dropped in this series.

Yes, Auld got to this one so it can be droppped.

Matt

Quoted 52 lines

Niranjana

Quoted 50 lines

---
drivers/gpu/drm/xe/xe_vm.c | 24 ++++++++++++++++--------

1 file changed, 16 insertions(+), 8 deletions(-)
drivers/gpu/drm/xe/xe_vm.c +16 -8
index 4557a8a4d270..9f55d22cb985 100644
@@ -1934,15 +1934,7 @@ void xe_vm_close_and_put(struct xe_vm *vm)
 		vma->gpuva.flags |= XE_VMA_DESTROYED;
 	}
 
-	/*
-	 * All vm operations will add shared fences to resv.
-	 * The only exception is eviction for a shared object,
-	 * but even so, the unbind when evicted would still
-	 * install a fence to resv. Hence it's safe to
-	 * destroy the pagetables immediately.
-	 */
 	xe_vm_free_scratch(vm);
-	xe_vm_pt_destroy(vm);
 	xe_vm_unlock(vm);
 
 	/*
@@ -1956,6 +1948,22 @@ void xe_vm_close_and_put(struct xe_vm *vm)
 		xe_vma_destroy_unlocked(vma);
 	}
 
+	/*
+	 * Destroy the page tables only after every VMA has been unlinked. The
+	 * contested (external-BO) VMAs above are unlinked from their BO under
+	 * the BO's dma-resv lock, not vm->lock, so they can still be reached
+	 * via drm_gem_for_each_gpuvm_bo() by a concurrent BO move (eviction,
+	 * shrinker or the defrag worker) that only holds the BO's resv. Such a
+	 * move calls xe_vm_invalidate_vma() -> xe_pt_zap_ptes(), which
+	 * dereferences vm->pt_root[]; freeing the page tables while those VMAs
+	 * are still linked is a use-after-free. All vm operations add shared
+	 * fences to the resv (eviction of a shared object still installs an
+	 * unbind fence), so no GPU work outlives this point.
+	 */
+	xe_vm_lock(vm, false);
+	xe_vm_pt_destroy(vm);
+	xe_vm_unlock(vm);
+
 	xe_svm_fini(vm);
 
 	up_write(&vm->lock);
Signature · 1 line
2.34.1
author maintainer
#59 lore raw

PATCH v3 15/33 drm/xe: Track BOs backed at a sub-optimal page order

In reply to Matthew Brost

Add per-device tracking of BOs whose backing TT pages were allocated below the pool's beneficial order, as reported by the TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED tt page flag (read via ttm_tt_is_beneficial_order_failed()). These BOs are future candidates for a defragmentation pass that reallocates their pages at the beneficial order.

Add a mem.defrag sub-struct (lock, list, atomic count) to struct xe_device and a defrag_link to struct xe_bo, initialised at BO create and device init. Membership is updated from xe_bo_move() via xe_bo_defrag_update(): a BO is added when it is a populated, needed, non-pinned ttm_bo_type_device object flagged TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED, and removed otherwise. BOs are also removed on pin, on purge, moved to dontneed, and at destroy.

Only ttm_bo_type_device BOs are tracked.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_bo.c           | 115 +++++++++++++++++++++++++++
 drivers/gpu/drm/xe/xe_bo.h           |   1 +
 drivers/gpu/drm/xe/xe_bo_types.h     |   6 ++
 drivers/gpu/drm/xe/xe_device.c       |   2 +
 drivers/gpu/drm/xe/xe_device_types.h |  19 +++++
 5 files changed, 143 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +115 -0
index 4ee48cdc02ac..ff324caab6da 100644
@@ -926,6 +926,9 @@ static void xe_bo_set_purgeable_shrinker(struct xe_bo *bo,
 	}
 }
 
+static void xe_bo_defrag_update(struct xe_bo *bo);
+static void xe_bo_defrag_remove(struct xe_bo *bo);
+
 /**
  * xe_bo_set_purgeable_state() - Set BO purgeable state with validation
  * @bo: Buffer object
@@ -954,6 +957,7 @@ void xe_bo_set_purgeable_state(struct xe_bo *bo,
 
 	bo->purgeable.state = new_state;
 	xe_bo_set_purgeable_shrinker(bo, new_state);
+	xe_bo_defrag_update(bo);
 }
 
 /**
@@ -1003,9 +1007,100 @@ static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio
 	/* Commit the state transition only once invalidation was queued */
 	xe_bo_set_purgeable_state(bo, XE_MADV_PURGEABLE_PURGED);
 
+	/*
+	 * The backing store is gone, so the BO no longer needs defrag. Drop it
+	 * from the defrag list here so the count stays accurate even for purge
+	 * paths that don't pass through xe_bo_move() (e.g. swap_notify).
+	 */
+	xe_bo_defrag_remove(bo);
+
 	return 0;
 }
 
+/**
+ * xe_bo_defrag_init_early() - Initialize the device defrag BO tracking
+ * @xe: The xe device
+ *
+ * Initialize the list, lock and count used to track BOs whose backing TT
+ * pages were allocated at a sub-optimal order.
+ */
+void xe_bo_defrag_init_early(struct xe_device *xe)
+{
+	spin_lock_init(&xe->mem.defrag.lock);
+	INIT_LIST_HEAD(&xe->mem.defrag.list);
+	atomic_set(&xe->mem.defrag.count, 0);
+}
+
+static bool xe_bo_needs_defrag(struct xe_bo *bo)
+{
+	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_tt *tt = ttm_bo->ttm;
+
+	xe_bo_assert_held(bo);
+
+	return ttm_bo->type == ttm_bo_type_device && tt &&
+		!xe_bo_madv_is_dontneed(bo) &&
+		ttm_tt_is_populated(tt) &&
+		ttm_tt_is_beneficial_order_failed(tt) &&
+		ttm_bo->resource && ttm_bo->resource->mem_type == XE_PL_TT &&
+		!xe_bo_is_pinned(bo);
+}
+
+static void xe_bo_defrag_add(struct xe_bo *bo)
+{
+	struct xe_device *xe = xe_bo_device(bo);
+
+	xe_bo_assert_held(bo);
+	xe_assert(xe, xe_bo_needs_defrag(bo));
+
+	scoped_guard(spinlock, &xe->mem.defrag.lock) {
+		if (list_empty(&bo->defrag_link)) {
+			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
+			atomic_inc(&xe->mem.defrag.count);
+		}
+	}
+}
+
+static void __xe_bo_defrag_remove(struct xe_bo *bo)
+{
+	struct xe_device *xe = xe_bo_device(bo);
+
+	guard(spinlock)(&xe->mem.defrag.lock);
+	if (!list_empty(&bo->defrag_link)) {
+		list_del_init(&bo->defrag_link);
+		atomic_dec(&xe->mem.defrag.count);
+	}
+}
+
+static void xe_bo_defrag_remove(struct xe_bo *bo)
+{
+	xe_bo_assert_held(bo);
+
+	if (list_empty(&bo->defrag_link))
+		return;
+
+	__xe_bo_defrag_remove(bo);
+}
+
+/**
+ * xe_bo_defrag_update() - Update defrag list membership for a BO
+ * @bo: The buffer object
+ *
+ * Add @bo to the device defrag list when it is a ttm_bo_type_device BO resident
+ * in XE_PL_TT with a populated TT whose pages were allocated at a sub-optimal
+ * order (ttm_tt_is_beneficial_order_failed()) and it isn't pinned. Otherwise
+ * ensure it is removed from the list.
+ */
+static void xe_bo_defrag_update(struct xe_bo *bo)
+{
+	xe_bo_assert_held(bo);
+
+	if (xe_bo_needs_defrag(bo))
+		xe_bo_defrag_add(bo);
+	else
+		xe_bo_defrag_remove(bo);
+}
+
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		      struct ttm_operation_ctx *ctx,
 		      struct ttm_resource *new_mem,
@@ -1231,6 +1326,8 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		xe_tt_unmap_sg(xe, ttm_bo->ttm);
 	}
 
+	xe_bo_defrag_update(bo);
+
 	return ret;
 }
 
@@ -1267,6 +1364,15 @@ static long xe_bo_shrink_purge(struct ttm_operation_ctx *ctx,
 	if (lret > 0) {
 		xe_ttm_tt_account_subtract(xe, bo->ttm);
 		update_global_total_pages(bo->bdev, -(long)tt->num_pages);
+
+		/*
+		 * The pages are gone, so a tracked BO no longer needs defrag.
+		 * This shrinker purge path frees pages without going through
+		 * xe_bo_move(), so drop any stale defrag list entry here. Ghost
+		 * bos are never tracked, so guard for real xe bos.
+		 */
+		if (xe_bo_is_xe_bo(bo))
+			xe_bo_defrag_remove(ttm_to_xe_bo(bo));
 	}
 
 	return lret;
@@ -1909,6 +2015,8 @@ static void xe_ttm_bo_destroy(struct ttm_buffer_object *ttm_bo)
 		list_del(&bo->vram_userfault_link);
 	mutex_unlock(&xe->mem_access.vram_userfault.lock);
 
+	__xe_bo_defrag_remove(bo);
+
 	kfree(bo);
 }
 
@@ -2414,6 +2522,7 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 	bo->ttm.base.funcs = &xe_gem_object_funcs;
 	bo->ttm.priority = XE_BO_PRIORITY_NORMAL;
 	INIT_LIST_HEAD(&bo->pinned_link);
+	INIT_LIST_HEAD(&bo->defrag_link);
 #ifdef CONFIG_PROC_FS
 	INIT_LIST_HEAD(&bo->client_link);
 #endif
@@ -3020,6 +3129,8 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec)
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
 
+	xe_bo_defrag_remove(bo);
+
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
 	 * we do not need this.
@@ -3078,6 +3189,8 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec)
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
 
+	xe_bo_defrag_remove(bo);
+
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
 	 * we do not need this.
@@ -3113,6 +3226,7 @@ void xe_bo_unpin_external(struct xe_bo *bo)
 	ttm_bo_unpin(&bo->ttm);
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
+	xe_bo_defrag_update(bo);
 
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
@@ -3145,6 +3259,7 @@ void xe_bo_unpin(struct xe_bo *bo)
 	ttm_bo_unpin(&bo->ttm);
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
+	xe_bo_defrag_update(bo);
 }
 
 /**
drivers/gpu/drm/xe/xe_bo.h +1 -0
index 6340317f7d2e..4186cb51af87 100644
@@ -224,6 +224,7 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec);
 int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
 void xe_bo_unpin_external(struct xe_bo *bo);
 void xe_bo_unpin(struct xe_bo *bo);
+void xe_bo_defrag_init_early(struct xe_device *xe);
 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
 		   struct drm_exec *exec);
 
drivers/gpu/drm/xe/xe_bo_types.h +6 -0
index fcc63ae3f455..9eea9ab380e5 100644
@@ -54,6 +54,12 @@ struct xe_bo {
 	struct ttm_bo_kmap_obj kmap;
 	/** @pinned_link: link to present / evicted list of pinned BO */
 	struct list_head pinned_link;
+	/**
+	 * @defrag_link: link into @xe_device.mem.defrag.list for BOs whose
+	 * backing TT pages were allocated at a sub-optimal order. Protected by
+	 * @xe_device.mem.defrag.lock.
+	 */
+	struct list_head defrag_link;
 #ifdef CONFIG_PROC_FS
 	/**
 	 * @client: @xe_drm_client which created the bo
drivers/gpu/drm/xe/xe_device.c +2 -0
index 97cc2d185e45..bb93425a5c70 100644
@@ -607,6 +607,8 @@ int xe_device_init_early(struct xe_device *xe)
 	if (err)
 		return err;
 
+	xe_bo_defrag_init_early(xe);
+
 	xe->preempt_fence_wq = alloc_ordered_workqueue("xe-preempt-fence-wq",
 						       WQ_MEM_RECLAIM);
 	xe->ordered_wq = alloc_ordered_workqueue("xe-ordered-wq", 0);
drivers/gpu/drm/xe/xe_device_types.h +19 -0
index 95e7cea91cbf..9e6244d8f41b 100644
@@ -296,6 +296,25 @@ struct xe_device {
 		 */
 		atomic_long_t dma_mapped_pages_svm[NR_PAGE_ORDERS];
 #endif
+		/**
+		 * @mem.defrag: Tracking of BOs whose backing TT pages were
+		 * allocated at a sub-optimal (smaller than beneficial) order.
+		 *
+		 * Such BOs are candidates for a future defragmentation pass that
+		 * tries to reallocate their pages at the device's beneficial
+		 * order. Only ttm_bo_type_device BOs are tracked.
+		 */
+		struct {
+			/** @mem.defrag.lock: Protects @mem.defrag.list. */
+			spinlock_t lock;
+			/** @mem.defrag.list: List of struct xe_bo defrag_link. */
+			struct list_head list;
+			/**
+			 * @mem.defrag.count: Number of BOs currently on
+			 * @mem.defrag.list.
+			 */
+			atomic_t count;
+		} defrag;
 	} mem;
 
 	/** @sriov: device level virtualization data */
Signature · 1 line
2.34.1
#60 lore raw

Re: [PATCH v3 15/33] drm/xe: Track BOs backed at a sub-optimal page order

Quoted 120 lines · Matthew Brost

Add per-device tracking of BOs whose backing TT pages were allocated below the pool's beneficial order, as reported by the TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED tt page flag (read via ttm_tt_is_beneficial_order_failed()). These BOs are future candidates for a defragmentation pass that reallocates their pages at the beneficial order.

Add a mem.defrag sub-struct (lock, list, atomic count) to struct xe_device and a defrag_link to struct xe_bo, initialised at BO create and device init. Membership is updated from xe_bo_move() via xe_bo_defrag_update(): a BO is added when it is a populated, needed, non-pinned ttm_bo_type_device object flagged TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED, and removed otherwise. BOs are also removed on pin, on purge, moved to dontneed, and at destroy.

Only ttm_bo_type_device BOs are tracked.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

drivers/gpu/drm/xe/xe_bo.c           | 115 +++++++++++++++++++++++++++
drivers/gpu/drm/xe/xe_bo.h           |   1 +
drivers/gpu/drm/xe/xe_bo_types.h     |   6 ++
drivers/gpu/drm/xe/xe_device.c       |   2 +
drivers/gpu/drm/xe/xe_device_types.h |  19 +++++
5 files changed, 143 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +55 -0
index 4ee48cdc02ac..ff324caab6da 100644
@@ -926,6 +926,9 @@ static void xe_bo_set_purgeable_shrinker(struct xe_bo *bo,
 	}
 }
 
+static void xe_bo_defrag_update(struct xe_bo *bo);
+static void xe_bo_defrag_remove(struct xe_bo *bo);
+
 /**
 * xe_bo_set_purgeable_state() - Set BO purgeable state with validation
 * @bo: Buffer object
@@ -954,6 +957,7 @@ void xe_bo_set_purgeable_state(struct xe_bo *bo,
 
 	bo->purgeable.state = new_state;
 	xe_bo_set_purgeable_shrinker(bo, new_state);
+	xe_bo_defrag_update(bo);
 }
 
 /**
@@ -1003,9 +1007,100 @@ static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio
 	/* Commit the state transition only once invalidation was queued */
 	xe_bo_set_purgeable_state(bo, XE_MADV_PURGEABLE_PURGED);
 
+	/*
+	 * The backing store is gone, so the BO no longer needs defrag. Drop it
+	 * from the defrag list here so the count stays accurate even for purge
+	 * paths that don't pass through xe_bo_move() (e.g. swap_notify).
+	 */
+	xe_bo_defrag_remove(bo);
+
 	return 0;
 }
 
+/**
+ * xe_bo_defrag_init_early() - Initialize the device defrag BO tracking
+ * @xe: The xe device
+ *
+ * Initialize the list, lock and count used to track BOs whose backing TT
+ * pages were allocated at a sub-optimal order.
+ */
+void xe_bo_defrag_init_early(struct xe_device *xe)
+{
+	spin_lock_init(&xe->mem.defrag.lock);
+	INIT_LIST_HEAD(&xe->mem.defrag.list);
+	atomic_set(&xe->mem.defrag.count, 0);
+}
+
+static bool xe_bo_needs_defrag(struct xe_bo *bo)
+{
+	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_tt *tt = ttm_bo->ttm;
+
+	xe_bo_assert_held(bo);
+
+	return ttm_bo->type == ttm_bo_type_device && tt &&
+		!xe_bo_madv_is_dontneed(bo) &&
+		ttm_tt_is_populated(tt) &&
+		ttm_tt_is_beneficial_order_failed(tt) &&
+		ttm_bo->resource && ttm_bo->resource->mem_type == XE_PL_TT &&
+		!xe_bo_is_pinned(bo);
+}
+
+static void xe_bo_defrag_add(struct xe_bo *bo)
+{
+	struct xe_device *xe = xe_bo_device(bo);
+
+	xe_bo_assert_held(bo);
+	xe_assert(xe, xe_bo_needs_defrag(bo));
+
+	scoped_guard(spinlock, &xe->mem.defrag.lock) {
+		if (list_empty(&bo->defrag_link)) {
+			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
+			atomic_inc(&xe->mem.defrag.count);
+		}
+	}
+}
+

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio · line 1073

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+static void __xe_bo_defrag_remove(struct xe_bo *bo)
+{
+	struct xe_device *xe = xe_bo_device(bo);
+
+	guard(spinlock)(&xe->mem.defrag.lock);
+	if (!list_empty(&bo->defrag_link)) {
+		list_del_init(&bo->defrag_link);
+		atomic_dec(&xe->mem.defrag.count);
+	}
+}
Assisted-by LLM

NIT...probably worth adding a comment saying this version can be called without holding bo dma-resv lock?

Quoted 102 lines
drivers/gpu/drm/xe/xe_bo.c +49 -0
+
+static void xe_bo_defrag_remove(struct xe_bo *bo)
+{
+	xe_bo_assert_held(bo);
+
+	if (list_empty(&bo->defrag_link))
+		return;
+
+	__xe_bo_defrag_remove(bo);
+}
+
+/**
+ * xe_bo_defrag_update() - Update defrag list membership for a BO
+ * @bo: The buffer object
+ *
+ * Add @bo to the device defrag list when it is a ttm_bo_type_device BO resident
+ * in XE_PL_TT with a populated TT whose pages were allocated at a sub-optimal
+ * order (ttm_tt_is_beneficial_order_failed()) and it isn't pinned. Otherwise
+ * ensure it is removed from the list.
+ */
+static void xe_bo_defrag_update(struct xe_bo *bo)
+{
+	xe_bo_assert_held(bo);
+
+	if (xe_bo_needs_defrag(bo))
+		xe_bo_defrag_add(bo);
+	else
+		xe_bo_defrag_remove(bo);
+}
+
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		      struct ttm_operation_ctx *ctx,
 		      struct ttm_resource *new_mem,
@@ -1231,6 +1326,8 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		xe_tt_unmap_sg(xe, ttm_bo->ttm);
 	}
 
+	xe_bo_defrag_update(bo);
+
 	return ret;
 }
 
@@ -1267,6 +1364,15 @@ static long xe_bo_shrink_purge(struct ttm_operation_ctx *ctx,
 	if (lret > 0) {
 		xe_ttm_tt_account_subtract(xe, bo->ttm);
 		update_global_total_pages(bo->bdev, -(long)tt->num_pages);
+
+		/*
+		 * The pages are gone, so a tracked BO no longer needs defrag.
+		 * This shrinker purge path frees pages without going through
+		 * xe_bo_move(), so drop any stale defrag list entry here. Ghost
+		 * bos are never tracked, so guard for real xe bos.
+		 */
+		if (xe_bo_is_xe_bo(bo))
+			xe_bo_defrag_remove(ttm_to_xe_bo(bo));
 	}
 
 	return lret;
@@ -1909,6 +2015,8 @@ static void xe_ttm_bo_destroy(struct ttm_buffer_object *ttm_bo)
 		list_del(&bo->vram_userfault_link);
 	mutex_unlock(&xe->mem_access.vram_userfault.lock);
 
+	__xe_bo_defrag_remove(bo);
+
 	kfree(bo);
 }
 
@@ -2414,6 +2522,7 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 	bo->ttm.base.funcs = &xe_gem_object_funcs;
 	bo->ttm.priority = XE_BO_PRIORITY_NORMAL;
 	INIT_LIST_HEAD(&bo->pinned_link);
+	INIT_LIST_HEAD(&bo->defrag_link);
 #ifdef CONFIG_PROC_FS
 	INIT_LIST_HEAD(&bo->client_link);
 #endif
@@ -3020,6 +3129,8 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec)
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
 
+	xe_bo_defrag_remove(bo);
+
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
 	 * we do not need this.
@@ -3078,6 +3189,8 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec)
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
 
+	xe_bo_defrag_remove(bo);
+
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
 	 * we do not need this.
@@ -3113,6 +3226,7 @@ void xe_bo_unpin_external(struct xe_bo *bo)
 	ttm_bo_unpin(&bo->ttm);
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
+	xe_bo_defrag_update(bo);
 
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking

drivers/gpu/drm/xe/xe_bo.c void xe_bo_unpin(struct xe_bo *bo) · line 3263

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
@@ -3145,6 +3259,7 @@ void xe_bo_unpin(struct xe_bo *bo)
 	ttm_bo_unpin(&bo->ttm);
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
+	xe_bo_defrag_update(bo);
 }

Looks like list update needs to be called from 2 other places,

1. ttm_bo_populate() getting called from CPU fault path and from TTM fault never calls xe_bo_defrag_update().
2. In xe_bo_shrink() if ttm_bo_shrink() returns >0 value. This will inflate the defrag.count value.

Quoted 60 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 /**
drivers/gpu/drm/xe/xe_bo.h +1 -0
index 6340317f7d2e..4186cb51af87 100644
@@ -224,6 +224,7 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec);
 int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
 void xe_bo_unpin_external(struct xe_bo *bo);
 void xe_bo_unpin(struct xe_bo *bo);
+void xe_bo_defrag_init_early(struct xe_device *xe);
 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
 		   struct drm_exec *exec);
 
drivers/gpu/drm/xe/xe_bo_types.h +6 -0
index fcc63ae3f455..9eea9ab380e5 100644
@@ -54,6 +54,12 @@ struct xe_bo {
 	struct ttm_bo_kmap_obj kmap;
 	/** @pinned_link: link to present / evicted list of pinned BO */
 	struct list_head pinned_link;
+	/**
+	 * @defrag_link: link into @xe_device.mem.defrag.list for BOs whose
+	 * backing TT pages were allocated at a sub-optimal order. Protected by
+	 * @xe_device.mem.defrag.lock.
+	 */
+	struct list_head defrag_link;
 #ifdef CONFIG_PROC_FS
 	/**
 	 * @client: @xe_drm_client which created the bo
drivers/gpu/drm/xe/xe_device.c +2 -0
index 97cc2d185e45..bb93425a5c70 100644
@@ -607,6 +607,8 @@ int xe_device_init_early(struct xe_device *xe)
 	if (err)
 		return err;
 
+	xe_bo_defrag_init_early(xe);
+
 	xe->preempt_fence_wq = alloc_ordered_workqueue("xe-preempt-fence-wq",
 						       WQ_MEM_RECLAIM);
 	xe->ordered_wq = alloc_ordered_workqueue("xe-ordered-wq", 0);
drivers/gpu/drm/xe/xe_device_types.h +8 -0
index 95e7cea91cbf..9e6244d8f41b 100644
@@ -296,6 +296,25 @@ struct xe_device {
 		 */
 		atomic_long_t dma_mapped_pages_svm[NR_PAGE_ORDERS];
 #endif
+		/**
+		 * @mem.defrag: Tracking of BOs whose backing TT pages were
+		 * allocated at a sub-optimal (smaller than beneficial) order.
+		 *
+		 * Such BOs are candidates for a future defragmentation pass that
+		 * tries to reallocate their pages at the device's beneficial
+		 * order. Only ttm_bo_type_device BOs are tracked.
+		 */

drivers/gpu/drm/xe/xe_device_types.h struct xe_device { · line 316

Quoted 10 lines
drivers/gpu/drm/xe/xe_device_types.h +10 -0
+		struct {
+			/** @mem.defrag.lock: Protects @mem.defrag.list. */
+			spinlock_t lock;
+			/** @mem.defrag.list: List of struct xe_bo defrag_link. */
+			struct list_head list;
+			/**
+			 * @mem.defrag.count: Number of BOs currently on
+			 * @mem.defrag.list.
+			 */
+			atomic_t count;

NIT...Not sure if we need it to be atomic. Count is only used in patch 16 and usage is approximation anyhow (doesn't guarantee anything as list lenght can be changing).

Niranjana

Quoted 7 lines
drivers/gpu/drm/xe/xe_device_types.h +1 -0
+		} defrag;
 	} mem;
 
 	/** @sriov: device level virtualization data */
Signature · 1 line
2.34.1
author maintainer
#61 lore raw

Re: [PATCH v3 15/33] drm/xe: Track BOs backed at a sub-optimal page order

Quoted 125 lines · Niranjana Vishwanathapura
Quoted 124 lines · Matthew Brost

Add per-device tracking of BOs whose backing TT pages were allocated below the pool's beneficial order, as reported by the TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED tt page flag (read via ttm_tt_is_beneficial_order_failed()). These BOs are future candidates for a defragmentation pass that reallocates their pages at the beneficial order.

Add a mem.defrag sub-struct (lock, list, atomic count) to struct xe_device and a defrag_link to struct xe_bo, initialised at BO create and device init. Membership is updated from xe_bo_move() via xe_bo_defrag_update(): a BO is added when it is a populated, needed, non-pinned ttm_bo_type_device object flagged TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED, and removed otherwise. BOs are also removed on pin, on purge, moved to dontneed, and at destroy.

Only ttm_bo_type_device BOs are tracked.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

drivers/gpu/drm/xe/xe_bo.c           | 115 +++++++++++++++++++++++++++
drivers/gpu/drm/xe/xe_bo.h           |   1 +
drivers/gpu/drm/xe/xe_bo_types.h     |   6 ++
drivers/gpu/drm/xe/xe_device.c       |   2 +
drivers/gpu/drm/xe/xe_device_types.h |  19 +++++
5 files changed, 143 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +59 -0
index 4ee48cdc02ac..ff324caab6da 100644
@@ -926,6 +926,9 @@ static void xe_bo_set_purgeable_shrinker(struct xe_bo *bo,
 	}
 }
 
+static void xe_bo_defrag_update(struct xe_bo *bo);
+static void xe_bo_defrag_remove(struct xe_bo *bo);
+
 /**
 * xe_bo_set_purgeable_state() - Set BO purgeable state with validation
 * @bo: Buffer object
@@ -954,6 +957,7 @@ void xe_bo_set_purgeable_state(struct xe_bo *bo,
 
 	bo->purgeable.state = new_state;
 	xe_bo_set_purgeable_shrinker(bo, new_state);
+	xe_bo_defrag_update(bo);
 }
 
 /**
@@ -1003,9 +1007,100 @@ static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio
 	/* Commit the state transition only once invalidation was queued */
 	xe_bo_set_purgeable_state(bo, XE_MADV_PURGEABLE_PURGED);
 
+	/*
+	 * The backing store is gone, so the BO no longer needs defrag. Drop it
+	 * from the defrag list here so the count stays accurate even for purge
+	 * paths that don't pass through xe_bo_move() (e.g. swap_notify).
+	 */
+	xe_bo_defrag_remove(bo);
+
 	return 0;
 }
 
+/**
+ * xe_bo_defrag_init_early() - Initialize the device defrag BO tracking
+ * @xe: The xe device
+ *
+ * Initialize the list, lock and count used to track BOs whose backing TT
+ * pages were allocated at a sub-optimal order.
+ */
+void xe_bo_defrag_init_early(struct xe_device *xe)
+{
+	spin_lock_init(&xe->mem.defrag.lock);
+	INIT_LIST_HEAD(&xe->mem.defrag.list);
+	atomic_set(&xe->mem.defrag.count, 0);
+}
+
+static bool xe_bo_needs_defrag(struct xe_bo *bo)
+{
+	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_tt *tt = ttm_bo->ttm;
+
+	xe_bo_assert_held(bo);
+
+	return ttm_bo->type == ttm_bo_type_device && tt &&
+		!xe_bo_madv_is_dontneed(bo) &&
+		ttm_tt_is_populated(tt) &&
+		ttm_tt_is_beneficial_order_failed(tt) &&
+		ttm_bo->resource && ttm_bo->resource->mem_type == XE_PL_TT &&
+		!xe_bo_is_pinned(bo);
+}
+
+static void xe_bo_defrag_add(struct xe_bo *bo)
+{
+	struct xe_device *xe = xe_bo_device(bo);
+
+	xe_bo_assert_held(bo);
+	xe_assert(xe, xe_bo_needs_defrag(bo));
+
+	scoped_guard(spinlock, &xe->mem.defrag.lock) {
+		if (list_empty(&bo->defrag_link)) {
+			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
+			atomic_inc(&xe->mem.defrag.count);
+		}
+	}
+}
+
+static void __xe_bo_defrag_remove(struct xe_bo *bo)
+{
+	struct xe_device *xe = xe_bo_device(bo);
+
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio · line 1073

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+	guard(spinlock)(&xe->mem.defrag.lock);
+	if (!list_empty(&bo->defrag_link)) {
+		list_del_init(&bo->defrag_link);
+		atomic_dec(&xe->mem.defrag.count);
+	}
+}
Assisted-by LLM

Yes.

Quoted 3 lines

NIT...probably worth adding a comment saying this version can be called without holding bo dma-resv lock?

It should be self documenting with lockdep but can add this.

Quoted 110 lines
Quoted 102 lines
drivers/gpu/drm/xe/xe_bo.c +49 -0
+
+static void xe_bo_defrag_remove(struct xe_bo *bo)
+{
+	xe_bo_assert_held(bo);
+
+	if (list_empty(&bo->defrag_link))
+		return;
+
+	__xe_bo_defrag_remove(bo);
+}
+
+/**
+ * xe_bo_defrag_update() - Update defrag list membership for a BO
+ * @bo: The buffer object
+ *
+ * Add @bo to the device defrag list when it is a ttm_bo_type_device BO resident
+ * in XE_PL_TT with a populated TT whose pages were allocated at a sub-optimal
+ * order (ttm_tt_is_beneficial_order_failed()) and it isn't pinned. Otherwise
+ * ensure it is removed from the list.
+ */
+static void xe_bo_defrag_update(struct xe_bo *bo)
+{
+	xe_bo_assert_held(bo);
+
+	if (xe_bo_needs_defrag(bo))
+		xe_bo_defrag_add(bo);
+	else
+		xe_bo_defrag_remove(bo);
+}
+
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		      struct ttm_operation_ctx *ctx,
 		      struct ttm_resource *new_mem,
@@ -1231,6 +1326,8 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		xe_tt_unmap_sg(xe, ttm_bo->ttm);
 	}
 
+	xe_bo_defrag_update(bo);
+
 	return ret;
 }
 
@@ -1267,6 +1364,15 @@ static long xe_bo_shrink_purge(struct ttm_operation_ctx *ctx,
 	if (lret > 0) {
 		xe_ttm_tt_account_subtract(xe, bo->ttm);
 		update_global_total_pages(bo->bdev, -(long)tt->num_pages);
+
+		/*
+		 * The pages are gone, so a tracked BO no longer needs defrag.
+		 * This shrinker purge path frees pages without going through
+		 * xe_bo_move(), so drop any stale defrag list entry here. Ghost
+		 * bos are never tracked, so guard for real xe bos.
+		 */
+		if (xe_bo_is_xe_bo(bo))
+			xe_bo_defrag_remove(ttm_to_xe_bo(bo));
 	}
 
 	return lret;
@@ -1909,6 +2015,8 @@ static void xe_ttm_bo_destroy(struct ttm_buffer_object *ttm_bo)
 		list_del(&bo->vram_userfault_link);
 	mutex_unlock(&xe->mem_access.vram_userfault.lock);
 
+	__xe_bo_defrag_remove(bo);
+
 	kfree(bo);
 }
 
@@ -2414,6 +2522,7 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 	bo->ttm.base.funcs = &xe_gem_object_funcs;
 	bo->ttm.priority = XE_BO_PRIORITY_NORMAL;
 	INIT_LIST_HEAD(&bo->pinned_link);
+	INIT_LIST_HEAD(&bo->defrag_link);
 #ifdef CONFIG_PROC_FS
 	INIT_LIST_HEAD(&bo->client_link);
 #endif
@@ -3020,6 +3129,8 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec)
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
 
+	xe_bo_defrag_remove(bo);
+
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
 	 * we do not need this.
@@ -3078,6 +3189,8 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec)
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
 
+	xe_bo_defrag_remove(bo);
+
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking
 	 * we do not need this.
@@ -3113,6 +3226,7 @@ void xe_bo_unpin_external(struct xe_bo *bo)
 	ttm_bo_unpin(&bo->ttm);
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
+	xe_bo_defrag_update(bo);
 
 	/*
 	 * FIXME: If we always use the reserve / unreserve functions for locking

drivers/gpu/drm/xe/xe_bo.c void xe_bo_unpin(struct xe_bo *bo) · line 3263

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
@@ -3145,6 +3259,7 @@ void xe_bo_unpin(struct xe_bo *bo)
 	ttm_bo_unpin(&bo->ttm);
 	if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
 		xe_ttm_tt_account_add(xe, bo->ttm.ttm);
+	xe_bo_defrag_update(bo);
 }

Looks like list update needs to be called from 2 other places,

Quoted 2 lines

1. ttm_bo_populate() getting called from CPU fault path and from TTM fault never calls xe_bo_defrag_update().

Yes. We also need to strip out reclaim flags in CPU fault path as this a foreground op.

Quoted 3 lines

2. In xe_bo_shrink() if ttm_bo_shrink() returns >0 value. This will inflate the defrag.count value.

This routes through ttm_bo_validate which ends up in xe_bo_move so I think this case is covered.

Quoted 66 lines
Quoted 66 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 /**
drivers/gpu/drm/xe/xe_bo.h +1 -0
index 6340317f7d2e..4186cb51af87 100644
@@ -224,6 +224,7 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec);
 int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
 void xe_bo_unpin_external(struct xe_bo *bo);
 void xe_bo_unpin(struct xe_bo *bo);
+void xe_bo_defrag_init_early(struct xe_device *xe);
 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
 		   struct drm_exec *exec);
 
drivers/gpu/drm/xe/xe_bo_types.h +6 -0
index fcc63ae3f455..9eea9ab380e5 100644
@@ -54,6 +54,12 @@ struct xe_bo {
 	struct ttm_bo_kmap_obj kmap;
 	/** @pinned_link: link to present / evicted list of pinned BO */
 	struct list_head pinned_link;
+	/**
+	 * @defrag_link: link into @xe_device.mem.defrag.list for BOs whose
+	 * backing TT pages were allocated at a sub-optimal order. Protected by
+	 * @xe_device.mem.defrag.lock.
+	 */
+	struct list_head defrag_link;
 #ifdef CONFIG_PROC_FS
 	/**
 	 * @client: @xe_drm_client which created the bo
drivers/gpu/drm/xe/xe_device.c +2 -0
index 97cc2d185e45..bb93425a5c70 100644
@@ -607,6 +607,8 @@ int xe_device_init_early(struct xe_device *xe)
 	if (err)
 		return err;
 
+	xe_bo_defrag_init_early(xe);
+
 	xe->preempt_fence_wq = alloc_ordered_workqueue("xe-preempt-fence-wq",
 						       WQ_MEM_RECLAIM);
 	xe->ordered_wq = alloc_ordered_workqueue("xe-ordered-wq", 0);
drivers/gpu/drm/xe/xe_device_types.h +14 -0
index 95e7cea91cbf..9e6244d8f41b 100644
@@ -296,6 +296,25 @@ struct xe_device {
 		 */
 		atomic_long_t dma_mapped_pages_svm[NR_PAGE_ORDERS];
 #endif
+		/**
+		 * @mem.defrag: Tracking of BOs whose backing TT pages were
+		 * allocated at a sub-optimal (smaller than beneficial) order.
+		 *
+		 * Such BOs are candidates for a future defragmentation pass that
+		 * tries to reallocate their pages at the device's beneficial
+		 * order. Only ttm_bo_type_device BOs are tracked.
+		 */
+		struct {
+			/** @mem.defrag.lock: Protects @mem.defrag.list. */
+			spinlock_t lock;
+			/** @mem.defrag.list: List of struct xe_bo defrag_link. */
+			struct list_head list;
+			/**
Quoted 8 lines

drivers/gpu/drm/xe/xe_device_types.h struct xe_device { · line 316

Quoted 4 lines
drivers/gpu/drm/xe/xe_device_types.h +4 -0
+			 * @mem.defrag.count: Number of BOs currently on
+			 * @mem.defrag.list.
+			 */
+			atomic_t count;

NIT...Not sure if we need it to be atomic. Count is only used in patch 16 and usage is approximation anyhow (doesn't guarantee anything as list lenght can be changing).

Right - incr / decr are protected by the spin lock along with the list.

I think count might actually be able to be dropped as target has slighly moved - foreground just never does reclaim, thus XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD / count isn't needed.

Matt

Quoted 10 lines

Niranjana

Quoted 7 lines
drivers/gpu/drm/xe/xe_device_types.h +1 -0
+		} defrag;
 	} mem;
 
 	/** @sriov: device level virtualization data */
Signature · 1 line
2.34.1
author maintainer
#62 lore raw

PATCH v3 16/33 drm/xe: Back off beneficial-order reclaim under defrag pressure

In reply to Matthew Brost

Once a meaningful number of BOs are already tracked as being backed at a sub-optimal order, continuing to push hard for beneficial-order pages during populate mostly wastes time in reclaim/compaction.

In xe_ttm_tt_populate(), set ctx->beneficial_reclaim_backoff when the device defrag count reaches XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD (2) so the TTM pool backs off and allocations make forward progress. The deferred defrag pass is responsible for upgrading these objects to beneficial order later.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_bo.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +14 -0
index ff324caab6da..02395968d613 100644
@@ -41,6 +41,14 @@
 #include "xe_vm.h"
 #include "xe_vram_types.h"
 
+/*
+ * Once this many BOs are tracked on the device defrag list (i.e. were backed
+ * with a sub-optimal page order), request that the TTM pool backs off from
+ * aggressive reclaim at the beneficial order during populate, so that
+ * allocations make forward progress instead of stalling.
+ */
+#define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
+
 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
 	[XE_PL_SYSTEM] = "system",
 	[XE_PL_TT] = "gtt",
@@ -598,6 +606,12 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	if (ttm_tt_is_backed_up(tt) && !xe_tt->purgeable) {
 		err = ttm_tt_restore(ttm_dev, tt, ctx);
 	} else {
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		if (atomic_read(&xe->mem.defrag.count) >=
+		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+			ctx->beneficial_reclaim_backoff = true;
+
 		ttm_tt_clear_backed_up(tt);
 		err = ttm_pool_alloc(&ttm_dev->pool, tt, ctx);
 	}
Signature · 1 line
2.34.1
#63 lore raw

Re: [PATCH v3 16/33] drm/xe: Back off beneficial-order reclaim under defrag pressure

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The beneficial-order reclaim backoff optimization is inadvertently skipped when restoring…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The beneficial-order reclaim backoff optimization is inadvertently skipped when restoring backed-up buffer objects (swap-ins). --

--- Patch [16]: [PATCH v3 16/33] drm/xe: Back off beneficial-order reclaim under defrag pressure --- commit 2099c6d8da1f6677d9db38b2ffe92ba3eb96f8f0
Author: Matthew Brost <[email protected]>

drm/xe: Back off beneficial-order reclaim under defrag pressure

Once a meaningful number of BOs are tracked as being backed at a sub-optimal order, this commit configures the TTM pool to back off from aggressive reclaim during populate. This allows allocations to make forward progress, leaving upgrades to beneficial orders for a deferred defrag pass.

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0

[ ... ]

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt, · line 614

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
@@ -598,6 +606,12 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	if (ttm_tt_is_backed_up(tt) && !xe_tt->purgeable) {
 		err = ttm_tt_restore(ttm_dev, tt, ctx);
 	} else {
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		if (atomic_read(&xe->mem.defrag.count) >=
+		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+			ctx->beneficial_reclaim_backoff = true;
+

[Severity: Medium]
Does this unintentionally skip the backoff optimization for swap-ins?

Because the beneficial_reclaim_backoff flag is only set inside the else branch, any swapped-out buffer object being restored via ttm_tt_restore() under fragmentation pressure will miss this optimization.

Without the flag, ttm_tt_restore() will continue pushing hard for beneficial-order pages, potentially causing the exact reclaim and compaction stalls this commit intended to avoid.

Would it make sense to move the device defrag count check and flag evaluation above the ttm_tt_is_backed_up() check so both paths benefit from the optimization?

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 		ttm_tt_clear_backed_up(tt);
 		err = ttm_pool_alloc(&ttm_dev->pool, tt, ctx);
 	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#64 lore raw

Re: [PATCH v3 16/33] drm/xe: Back off beneficial-order reclaim under defrag pressure

In reply to Matthew Brost
Quoted 49 lines · Matthew Brost

Once a meaningful number of BOs are already tracked as being backed at a sub-optimal order, continuing to push hard for beneficial-order pages during populate mostly wastes time in reclaim/compaction.

In xe_ttm_tt_populate(), set ctx->beneficial_reclaim_backoff when the device defrag count reaches XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD (2) so the TTM pool backs off and allocations make forward progress. The deferred defrag pass is responsible for upgrading these objects to beneficial order later.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---
drivers/gpu/drm/xe/xe_bo.c | 14 ++++++++++++++

1 file changed, 14 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +8 -0
index ff324caab6da..02395968d613 100644
@@ -41,6 +41,14 @@
 #include "xe_vm.h"
 #include "xe_vram_types.h"
 
+/*
+ * Once this many BOs are tracked on the device defrag list (i.e. were backed
+ * with a sub-optimal page order), request that the TTM pool backs off from
+ * aggressive reclaim at the beneficial order during populate, so that
+ * allocations make forward progress instead of stalling.
+ */
+#define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
+
 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
 	[XE_PL_SYSTEM] = "system",
 	[XE_PL_TT] = "gtt",

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt, · line 607

Quoted 2 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
@@ -598,6 +606,12 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	if (ttm_tt_is_backed_up(tt) && !xe_tt->purgeable) {
 		err = ttm_tt_restore(ttm_dev, tt, ctx);
Assisted-by LLM

Don't we need to to backoff in restore path also? If it is intentional, probably add a comment?

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt, · line 614

Quoted 7 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
 	} else {
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		if (atomic_read(&xe->mem.defrag.count) >=
+		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+			ctx->beneficial_reclaim_backoff = true;
+

- beneficial_reclaim_backoff is not cleared if count comes below threshold. If the same ctx is used for multiple BOs, they all will backoff even when count has moved below threshold.

- Looks like self-reinforcing feedback loop causes spike in backoff.

count ≥ 2 → backoff on → new populates land sub-optimal → BENEFICIAL_ORDER_FAILED → added to defrag list → count stays ≥ 2 → backoff stays on → ...

Is it intentional? If so, may be a comment explaining it would be helpful?

- Will there be any value is heuristically adjusting threshold instead of using static value (2)?

Niranjana

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 		ttm_tt_clear_backed_up(tt);
 		err = ttm_pool_alloc(&ttm_dev->pool, tt, ctx);
 	}
Signature · 1 line
2.34.1
author maintainer
#65 lore raw

Re: [PATCH v3 16/33] drm/xe: Back off beneficial-order reclaim under defrag pressure

Quoted 55 lines · Niranjana Vishwanathapura
Quoted 49 lines · Matthew Brost

Once a meaningful number of BOs are already tracked as being backed at a sub-optimal order, continuing to push hard for beneficial-order pages during populate mostly wastes time in reclaim/compaction.

In xe_ttm_tt_populate(), set ctx->beneficial_reclaim_backoff when the device defrag count reaches XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD (2) so the TTM pool backs off and allocations make forward progress. The deferred defrag pass is responsible for upgrading these objects to beneficial order later.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---
drivers/gpu/drm/xe/xe_bo.c | 14 ++++++++++++++

1 file changed, 14 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +8 -0
index ff324caab6da..02395968d613 100644
@@ -41,6 +41,14 @@
 #include "xe_vm.h"
 #include "xe_vram_types.h"
 
+/*
+ * Once this many BOs are tracked on the device defrag list (i.e. were backed
+ * with a sub-optimal page order), request that the TTM pool backs off from
+ * aggressive reclaim at the beneficial order during populate, so that
+ * allocations make forward progress instead of stalling.
+ */
+#define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
+
 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
 	[XE_PL_SYSTEM] = "system",
 	[XE_PL_TT] = "gtt",

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt, · line 607

Quoted 2 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
@@ -598,6 +606,12 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	if (ttm_tt_is_backed_up(tt) && !xe_tt->purgeable) {
 		err = ttm_tt_restore(ttm_dev, tt, ctx);
Assisted-by LLM
Quoted 3 lines

Don't we need to to backoff in restore path also? If it is intentional, probably add a comment?

Yes, we do need backoff in the restore path. There a couple other places in this series that miss the backoff too (e.g., CPU fault) - the divide we want is anything the foreground no reclaim, and only reclaim in background outside of dma-resv (defragmenter).

Quoted 14 lines

drivers/gpu/drm/xe/xe_bo.c static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt, · line 614

Quoted 7 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
 	} else {
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		if (atomic_read(&xe->mem.defrag.count) >=
+		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+			ctx->beneficial_reclaim_backoff = true;
+

- beneficial_reclaim_backoff is not cleared if count comes below threshold. If the same ctx is used for multiple BOs, they all will backoff even when count has moved below threshold.

- Looks like self-reinforcing feedback loop causes spike in backoff.

Quoted 8 lines

count ≥ 2 → backoff on → new populates land sub-optimal → BENEFICIAL_ORDER_FAILED → added to defrag list → count stays ≥ 2 → backoff stays on → ...

Is it intentional? If so, may be a comment explaining it would be helpful?

- Will there be any value is heuristically adjusting threshold instead of using static value (2)?

As mentiond above / last patch - I'm just going rip this out have clear divide between foreground / background setting the reclaim flags correctly.

Matt

Quoted 8 lines

Niranjana

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 		ttm_tt_clear_backed_up(tt);
 		err = ttm_pool_alloc(&ttm_dev->pool, tt, ctx);
 	}
Signature · 1 line
2.34.1
author maintainer
#66 lore raw

PATCH v3 17/33 drm/xe: Add xe_migrate_copy_defrag() for on-GPU defrag copies

In reply to Matthew Brost

Add xe_migrate_copy_defrag(), a copy helper for the upcoming page defragmentation path where a single BO has its backing reallocated at a more beneficial page order and its contents must be relocated from the old pages to the new ones entirely on the GPU.

The contents are relocated in up to two passes:

- Data pass (always): copy the data pages verbatim. The pages are mapped without the compression PAT, so the (possibly compressed) bytes are copied as-is rather than being decompressed and recompressed, and no CCS aux copy is appended.

- CCS pass (need_ccs): copy the CCS aux (compression) state. Both the old and new data pages are mapped with the compression PAT so the copy engine accesses the aux state indirectly, issuing one indirect -> indirect XY_CTRL_SURF_COPY_BLT; the data blit is skipped.

The two passes are issued separately because they require opposite compression PAT settings on the data page mappings (cleared for the verbatim data copy, set for the indirect CCS access), which a single mapping cannot satisfy. Both passes run in order on the same migrate queue and are captured by the returned fence.

The source pages are passed explicitly via an sg_table argument (the old, still populated backing) since they no longer match the BO's current backing. The boolean arguments to __xe_migrate_copy() are folded into struct xe_migrate_copy_flags to keep the growing set of copy variants readable.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
 drivers/gpu/drm/xe/xe_migrate.h |   8 ++
 2 files changed, 128 insertions(+), 16 deletions(-)
drivers/gpu/drm/xe/xe_migrate.c +120 -16
index 92d5e81ceac2..305c6e1942fb 100644
@@ -858,13 +858,39 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
 	return flush_flags;
 }
 
+/**
+ * struct xe_migrate_copy_flags - Flags for __xe_migrate_copy()
+ * @copy_only_ccs: Only copy the CCS aux state, aliasing the destination data
+ * mapping to the source (used when the data pages are shared between src/dst).
+ * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
+ * compression PAT index for the data copy.
+ * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
+ * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * skipped (the data was copied by the @defrag_copy pass) and both the source
+ * and destination data pages are mapped with the compression PAT so the aux
+ * state is copied indirect -> indirect.
+ * @defrag_copy: Defrag move pass that copies the data pages between two
+ * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
+ * aux state. The data pages are mapped without the compression PAT so the
+ * (possibly compressed) bytes are copied verbatim rather than being
+ * decompressed and recompressed, and no CCS aux copy is appended; the aux
+ * state is migrated separately by the @defrag_ccs pass. The two passes need
+ * opposite compression PAT settings, which is why they cannot be combined.
+ */
+struct xe_migrate_copy_flags {
+	u32 copy_only_ccs : 1;
+	u32 is_vram_resolve : 1;
+	u32 defrag_ccs : 1;
+	u32 defrag_copy : 1;
+};
+
 static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 					   struct xe_bo *src_bo,
 					   struct xe_bo *dst_bo,
 					   struct ttm_resource *src,
 					   struct ttm_resource *dst,
-					   bool copy_only_ccs,
-					   bool is_vram_resolve)
+					   struct sg_table *src_sg,
+					   struct xe_migrate_copy_flags flags)
 {
 	struct xe_gt *gt = m->tile->primary_gt;
 	struct xe_device *xe = gt_to_xe(gt);
@@ -881,20 +907,29 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 	bool src_is_vram = mem_type_is_vram(src->mem_type);
 	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
 	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
-	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
+	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe) &&
+		!flags.defrag_copy;
 	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
-		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
-	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
+		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo) &&
+		!flags.defrag_copy;
+	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
+		!flags.defrag_ccs && !flags.defrag_copy;
 
 	/*
 	 * For decompression operation, always use the compression PAT index.
 	 * Otherwise, only use the compression PAT index for device memory
 	 * when copying from VRAM to system memory.
 	 */
-	bool use_comp_pat = is_vram_resolve || (type_device &&
+	bool use_comp_pat = flags.is_vram_resolve || (type_device &&
 			    xe_device_has_flat_ccs(xe) &&
 			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
 
+	/*
+	 * The defrag CCS pass migrates the aux state from the old pages
+	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
+	 */
+
 	/* Copying CCS between two different BOs is not supported yet. */
 	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
 		return ERR_PTR(-EINVAL);
@@ -903,7 +938,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(-EINVAL);
 
 	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 	if (!dst_is_vram)
@@ -912,7 +947,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		xe_res_first(dst, 0, size, &dst_it);
 
 	if (copy_system_ccs)
-		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+				xe_bo_ccs_pages_start(src_bo),
 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 				&ccs_it);
 
@@ -942,7 +978,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
 					      &src_L0_ofs, &src_L0_pt, 0, 0,
 					      avail_pts);
-		if (copy_only_ccs) {
+		if (flags.copy_only_ccs) {
 			dst_L0_ofs = src_L0_ofs;
 		} else {
 			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
@@ -963,7 +999,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		}
 
 		/* Add copy commands size here */
-		batch_size += ((copy_only_ccs) ? 0 : emit_copy_cmd_len(xe)) +
+		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
+			       emit_copy_cmd_len(xe)) +
 			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
 
 		bb = xe_bb_new(gt, batch_size, usm);
@@ -975,13 +1012,15 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
 			xe_res_next(&src_it, src_L0);
 		else
-			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
+			emit_pte(m, bb, src_L0_pt, src_is_vram,
+				 copy_system_ccs || use_comp_pat || flags.defrag_ccs,
 				 &src_it, src_L0, src);
 
 		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
 			xe_res_next(&dst_it, src_L0);
-		else if (!copy_only_ccs)
-			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
+		else if (!flags.copy_only_ccs)
+			emit_pte(m, bb, dst_L0_pt, dst_is_vram,
+				 copy_system_ccs || flags.defrag_ccs,
 				 &dst_it, src_L0, dst);
 
 		if (copy_system_ccs)
@@ -990,7 +1029,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
 		update_idx = bb->len;
 
-		if (!copy_only_ccs)
+		if (!flags.copy_only_ccs && !flags.defrag_ccs)
 			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
 
 		if (needs_ccs_emit)
@@ -1078,7 +1117,69 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 				  struct ttm_resource *dst,
 				  bool copy_only_ccs)
 {
-	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
+	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .copy_only_ccs = copy_only_ccs,
+				 });
+}
+
+/**
+ * xe_migrate_copy_defrag() - Migrate a BO's backing to a reallocated page set.
+ * @m: The migration context.
+ * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
+ * @src: The source TTM resource (the old backing).
+ * @dst: The dst TTM resource (the freshly reallocated backing).
+ * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
+ *
+ * Used by the defrag path where a single BO has its backing reallocated at a
+ * more beneficial page order. The contents are relocated from the old pages
+ * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * in up to two passes:
+ *
+ *  - Data pass (always): copy the data pages verbatim. The pages are mapped
+ *    without the compression PAT, so the (possibly compressed) bytes are copied
+ *    as-is rather than being decompressed and recompressed, and no CCS aux copy
+ *    is appended.
+ *
+ *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
+ *    and new data pages are mapped with the compression PAT so the copy engine
+ *    accesses the aux state indirectly, issuing one indirect -> indirect
+ *    XY_CTRL_SURF_COPY_BLT; the data blit is skipped.
+ *
+ * The two passes are issued separately because they require opposite
+ * compression PAT settings on the data page mappings (cleared for the verbatim
+ * data copy, set for the indirect CCS access), which a single mapping cannot
+ * satisfy. Both passes run in order on the same migrate queue.
+ *
+ * Return: Pointer to a dma_fence representing the last copy batch, or an error
+ * pointer on failure.
+ */
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs)
+{
+	struct dma_fence *fence2, *fence =
+		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				  (struct xe_migrate_copy_flags) {
+					 .defrag_copy = true,
+					 });
+
+	if (IS_ERR(fence) || !need_ccs)
+		return fence;
+
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				   (struct xe_migrate_copy_flags) {
+				   .defrag_ccs = true,
+				   });
+	if (IS_ERR(fence2))
+		dma_fence_wait(fence, false);
+	dma_fence_put(fence);
+
+	return fence2;
 }
 
 /**
@@ -1096,7 +1197,10 @@ struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
 				     struct xe_bo *bo,
 				     struct ttm_resource *res)
 {
-	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
+	return __xe_migrate_copy(m, bo, bo, res, res, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .is_vram_resolve = true,
+				 });
 }
 
 /**
drivers/gpu/drm/xe/xe_migrate.h +8 -0
index 965c45889c72..e4f996942a6d 100644
@@ -11,6 +11,7 @@
 struct dma_fence;
 struct drm_pagemap_addr;
 struct iosys_map;
+struct sg_table;
 struct ttm_resource;
 
 struct xe_bo;
@@ -132,6 +133,13 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 				  struct ttm_resource *dst,
 				  bool copy_only_ccs);
 
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs);
+
 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
 				     struct xe_bo *bo,
 				     struct ttm_resource *res);
Signature · 1 line
2.34.1
reviewer
#67 lore raw

Re: [PATCH v3 17/33] drm/xe: Add xe_migrate_copy_defrag() for on-GPU defrag copies

Quoted 12 lines · Matthew Brost

Add xe_migrate_copy_defrag(), a copy helper for the upcoming page defragmentation path where a single BO has its backing reallocated at a more beneficial page order and its contents must be relocated from the old pages to the new ones entirely on the GPU.

The contents are relocated in up to two passes:

- Data pass (always): copy the data pages verbatim. The pages are mapped without the compression PAT, so the (possibly compressed) bytes are copied as-is rather than being decompressed and recompressed, and no CCS aux copy is appended.

Quoted 4 lines

- CCS pass (need_ccs): copy the CCS aux (compression) state. Both the old and new data pages are mapped with the compression PAT so the copy engine accesses the aux state indirectly, issuing one indirect -> indirect XY_CTRL_SURF_COPY_BLT; the data blit is skipped.

Just to double check, there were no issues with this flow for a compressed surface? Not 100% sure if reading from the src with uncompressed PAT will zero out the CCS state (update to uncompressed status), such that when you do the CCS pass it is already gone. Quite sure it does that for a write, but I guess not for a read, so we are fine here?

Quoted 288 lines

The two passes are issued separately because they require opposite compression PAT settings on the data page mappings (cleared for the verbatim data copy, set for the indirect CCS access), which a single mapping cannot satisfy. Both passes run in order on the same migrate queue and are captured by the returned fence.

The source pages are passed explicitly via an sg_table argument (the old, still populated backing) since they no longer match the BO's current backing. The boolean arguments to __xe_migrate_copy() are folded into struct xe_migrate_copy_flags to keep the growing set of copy variants readable.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
  drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
  drivers/gpu/drm/xe/xe_migrate.h |   8 ++
  2 files changed, 128 insertions(+), 16 deletions(-)
drivers/gpu/drm/xe/xe_migrate.c +120 -16
index 92d5e81ceac2..305c6e1942fb 100644
@@ -858,13 +858,39 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
  	return flush_flags;
  }
 
+/**
+ * struct xe_migrate_copy_flags - Flags for __xe_migrate_copy()
+ * @copy_only_ccs: Only copy the CCS aux state, aliasing the destination data
+ * mapping to the source (used when the data pages are shared between src/dst).
+ * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
+ * compression PAT index for the data copy.
+ * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
+ * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * skipped (the data was copied by the @defrag_copy pass) and both the source
+ * and destination data pages are mapped with the compression PAT so the aux
+ * state is copied indirect -> indirect.
+ * @defrag_copy: Defrag move pass that copies the data pages between two
+ * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
+ * aux state. The data pages are mapped without the compression PAT so the
+ * (possibly compressed) bytes are copied verbatim rather than being
+ * decompressed and recompressed, and no CCS aux copy is appended; the aux
+ * state is migrated separately by the @defrag_ccs pass. The two passes need
+ * opposite compression PAT settings, which is why they cannot be combined.
+ */
+struct xe_migrate_copy_flags {
+	u32 copy_only_ccs : 1;
+	u32 is_vram_resolve : 1;
+	u32 defrag_ccs : 1;
+	u32 defrag_copy : 1;
+};
+
  static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  					   struct xe_bo *src_bo,
  					   struct xe_bo *dst_bo,
  					   struct ttm_resource *src,
  					   struct ttm_resource *dst,
-					   bool copy_only_ccs,
-					   bool is_vram_resolve)
+					   struct sg_table *src_sg,
+					   struct xe_migrate_copy_flags flags)
  {
  	struct xe_gt *gt = m->tile->primary_gt;
  	struct xe_device *xe = gt_to_xe(gt);
@@ -881,20 +907,29 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  	bool src_is_vram = mem_type_is_vram(src->mem_type);
  	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
  	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
-	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
+	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe) &&
+		!flags.defrag_copy;
  	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
-		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
-	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
+		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo) &&
+		!flags.defrag_copy;
+	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
+		!flags.defrag_ccs && !flags.defrag_copy;
 
  	/*
  	 * For decompression operation, always use the compression PAT index.
  	 * Otherwise, only use the compression PAT index for device memory
  	 * when copying from VRAM to system memory.
  	 */
-	bool use_comp_pat = is_vram_resolve || (type_device &&
+	bool use_comp_pat = flags.is_vram_resolve || (type_device &&
  			    xe_device_has_flat_ccs(xe) &&
  			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
 
+	/*
+	 * The defrag CCS pass migrates the aux state from the old pages
+	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
+	 */
+
  	/* Copying CCS between two different BOs is not supported yet. */
  	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
  		return ERR_PTR(-EINVAL);
@@ -903,7 +938,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		return ERR_PTR(-EINVAL);
 
  	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
  	else
  		xe_res_first(src, 0, size, &src_it);
  	if (!dst_is_vram)
@@ -912,7 +947,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		xe_res_first(dst, 0, size, &dst_it);
 
  	if (copy_system_ccs)
-		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+				xe_bo_ccs_pages_start(src_bo),
  				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
  				&ccs_it);
 
@@ -942,7 +978,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
  					      &src_L0_ofs, &src_L0_pt, 0, 0,
  					      avail_pts);
-		if (copy_only_ccs) {
+		if (flags.copy_only_ccs) {
  			dst_L0_ofs = src_L0_ofs;
  		} else {
  			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
@@ -963,7 +999,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		}
 
  		/* Add copy commands size here */
-		batch_size += ((copy_only_ccs) ? 0 : emit_copy_cmd_len(xe)) +
+		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
+			       emit_copy_cmd_len(xe)) +
  			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
 
  		bb = xe_bb_new(gt, batch_size, usm);
@@ -975,13 +1012,15 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
  			xe_res_next(&src_it, src_L0);
  		else
-			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
+			emit_pte(m, bb, src_L0_pt, src_is_vram,
+				 copy_system_ccs || use_comp_pat || flags.defrag_ccs,
  				 &src_it, src_L0, src);
 
  		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
  			xe_res_next(&dst_it, src_L0);
-		else if (!copy_only_ccs)
-			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
+		else if (!flags.copy_only_ccs)
+			emit_pte(m, bb, dst_L0_pt, dst_is_vram,
+				 copy_system_ccs || flags.defrag_ccs,
  				 &dst_it, src_L0, dst);
 
  		if (copy_system_ccs)
@@ -990,7 +1029,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
  		update_idx = bb->len;
 
-		if (!copy_only_ccs)
+		if (!flags.copy_only_ccs && !flags.defrag_ccs)
  			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
 
  		if (needs_ccs_emit)
@@ -1078,7 +1117,69 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
  				  struct ttm_resource *dst,
  				  bool copy_only_ccs)
  {
-	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
+	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .copy_only_ccs = copy_only_ccs,
+				 });
+}
+
+/**
+ * xe_migrate_copy_defrag() - Migrate a BO's backing to a reallocated page set.
+ * @m: The migration context.
+ * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
+ * @src: The source TTM resource (the old backing).
+ * @dst: The dst TTM resource (the freshly reallocated backing).
+ * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
+ *
+ * Used by the defrag path where a single BO has its backing reallocated at a
+ * more beneficial page order. The contents are relocated from the old pages
+ * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * in up to two passes:
+ *
+ *  - Data pass (always): copy the data pages verbatim. The pages are mapped
+ *    without the compression PAT, so the (possibly compressed) bytes are copied
+ *    as-is rather than being decompressed and recompressed, and no CCS aux copy
+ *    is appended.
+ *
+ *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
+ *    and new data pages are mapped with the compression PAT so the copy engine
+ *    accesses the aux state indirectly, issuing one indirect -> indirect
+ *    XY_CTRL_SURF_COPY_BLT; the data blit is skipped.
+ *
+ * The two passes are issued separately because they require opposite
+ * compression PAT settings on the data page mappings (cleared for the verbatim
+ * data copy, set for the indirect CCS access), which a single mapping cannot
+ * satisfy. Both passes run in order on the same migrate queue.
+ *
+ * Return: Pointer to a dma_fence representing the last copy batch, or an error
+ * pointer on failure.
+ */
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs)
+{
+	struct dma_fence *fence2, *fence =
+		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				  (struct xe_migrate_copy_flags) {
+					 .defrag_copy = true,
+					 });
+
+	if (IS_ERR(fence) || !need_ccs)
+		return fence;
+
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				   (struct xe_migrate_copy_flags) {
+				   .defrag_ccs = true,
+				   });
+	if (IS_ERR(fence2))
+		dma_fence_wait(fence, false);
+	dma_fence_put(fence);
+
+	return fence2;
  }
 
  /**
@@ -1096,7 +1197,10 @@ struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
  				     struct xe_bo *bo,
  				     struct ttm_resource *res)
  {
-	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
+	return __xe_migrate_copy(m, bo, bo, res, res, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .is_vram_resolve = true,
+				 });
  }
 
  /**
drivers/gpu/drm/xe/xe_migrate.h +8 -0
index 965c45889c72..e4f996942a6d 100644
@@ -11,6 +11,7 @@
  struct dma_fence;
  struct drm_pagemap_addr;
  struct iosys_map;
+struct sg_table;
  struct ttm_resource;
 
  struct xe_bo;
@@ -132,6 +133,13 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
  				  struct ttm_resource *dst,
  				  bool copy_only_ccs);
 
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs);
+
  struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
  				     struct xe_bo *bo,
  				     struct ttm_resource *res);
author maintainer
#68 lore raw

Re: [PATCH v3 17/33] drm/xe: Add xe_migrate_copy_defrag() for on-GPU defrag copies

Quoted 19 lines · Matthew Auld
Quoted 12 lines · Matthew Brost

Add xe_migrate_copy_defrag(), a copy helper for the upcoming page defragmentation path where a single BO has its backing reallocated at a more beneficial page order and its contents must be relocated from the old pages to the new ones entirely on the GPU.

The contents are relocated in up to two passes:

- Data pass (always): copy the data pages verbatim. The pages are mapped without the compression PAT, so the (possibly compressed) bytes are copied as-is rather than being decompressed and recompressed, and no CCS aux copy is appended.

Quoted 4 lines

- CCS pass (need_ccs): copy the CCS aux (compression) state. Both the old and new data pages are mapped with the compression PAT so the copy engine accesses the aux state indirectly, issuing one indirect -> indirect XY_CTRL_SURF_COPY_BLT; the data blit is skipped.

Quoted 6 lines

Just to double check, there were no issues with this flow for a compressed surface? Not 100% sure if reading from the src with uncompressed PAT will zero out the CCS state (update to uncompressed status), such that when you do the CCS pass it is already gone. Quite sure it does that for a write, but I guess not for a read, so we are fine here?

This isn't my area of expertise, but IIRC I spun on this patch several times before I finally got it right. In my first few attempts, when I ran something like 3DMark Wildlife Extreme or WebGL applications that would trigger the defragmenter, I could see visual corruption on the screen (i.e., the buffers were clearly being corrupted). I eventually landed on the approach detailed here and have not seen any visual issues since. So I think the reads without the compressed PAT are fine, at least on PTL.

I also have a local update to [1] where I use the compressed PAT, and the tests seem to pass. I can post an update to this test shortly.

Matt

[1] https://patchwork.freedesktop.org/patch/739244/?series=169723&rev=2

Quoted 273 lines
Quoted 272 lines

The two passes are issued separately because they require opposite compression PAT settings on the data page mappings (cleared for the verbatim data copy, set for the indirect CCS access), which a single mapping cannot satisfy. Both passes run in order on the same migrate queue and are captured by the returned fence.

The source pages are passed explicitly via an sg_table argument (the old, still populated backing) since they no longer match the BO's current backing. The boolean arguments to __xe_migrate_copy() are folded into struct xe_migrate_copy_flags to keep the growing set of copy variants readable.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
  drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
  drivers/gpu/drm/xe/xe_migrate.h |   8 ++
  2 files changed, 128 insertions(+), 16 deletions(-)
drivers/gpu/drm/xe/xe_migrate.c +120 -16
index 92d5e81ceac2..305c6e1942fb 100644
@@ -858,13 +858,39 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
  	return flush_flags;
  }
+/**
+ * struct xe_migrate_copy_flags - Flags for __xe_migrate_copy()
+ * @copy_only_ccs: Only copy the CCS aux state, aliasing the destination data
+ * mapping to the source (used when the data pages are shared between src/dst).
+ * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
+ * compression PAT index for the data copy.
+ * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
+ * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * skipped (the data was copied by the @defrag_copy pass) and both the source
+ * and destination data pages are mapped with the compression PAT so the aux
+ * state is copied indirect -> indirect.
+ * @defrag_copy: Defrag move pass that copies the data pages between two
+ * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
+ * aux state. The data pages are mapped without the compression PAT so the
+ * (possibly compressed) bytes are copied verbatim rather than being
+ * decompressed and recompressed, and no CCS aux copy is appended; the aux
+ * state is migrated separately by the @defrag_ccs pass. The two passes need
+ * opposite compression PAT settings, which is why they cannot be combined.
+ */
+struct xe_migrate_copy_flags {
+	u32 copy_only_ccs : 1;
+	u32 is_vram_resolve : 1;
+	u32 defrag_ccs : 1;
+	u32 defrag_copy : 1;
+};
+
  static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  					   struct xe_bo *src_bo,
  					   struct xe_bo *dst_bo,
  					   struct ttm_resource *src,
  					   struct ttm_resource *dst,
-					   bool copy_only_ccs,
-					   bool is_vram_resolve)
+					   struct sg_table *src_sg,
+					   struct xe_migrate_copy_flags flags)
  {
  	struct xe_gt *gt = m->tile->primary_gt;
  	struct xe_device *xe = gt_to_xe(gt);
@@ -881,20 +907,29 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  	bool src_is_vram = mem_type_is_vram(src->mem_type);
  	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
  	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
-	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
+	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe) &&
+		!flags.defrag_copy;
  	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
-		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
-	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
+		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo) &&
+		!flags.defrag_copy;
+	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
+		!flags.defrag_ccs && !flags.defrag_copy;
  	/*
  	 * For decompression operation, always use the compression PAT index.
  	 * Otherwise, only use the compression PAT index for device memory
  	 * when copying from VRAM to system memory.
  	 */
-	bool use_comp_pat = is_vram_resolve || (type_device &&
+	bool use_comp_pat = flags.is_vram_resolve || (type_device &&
  			    xe_device_has_flat_ccs(xe) &&
  			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
+	/*
+	 * The defrag CCS pass migrates the aux state from the old pages
+	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
+	 */
+
  	/* Copying CCS between two different BOs is not supported yet. */
  	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
  		return ERR_PTR(-EINVAL);
@@ -903,7 +938,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		return ERR_PTR(-EINVAL);
  	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
  	else
  		xe_res_first(src, 0, size, &src_it);
  	if (!dst_is_vram)
@@ -912,7 +947,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		xe_res_first(dst, 0, size, &dst_it);
  	if (copy_system_ccs)
-		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+				xe_bo_ccs_pages_start(src_bo),
  				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
  				&ccs_it);
@@ -942,7 +978,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
  					      &src_L0_ofs, &src_L0_pt, 0, 0,
  					      avail_pts);
-		if (copy_only_ccs) {
+		if (flags.copy_only_ccs) {
  			dst_L0_ofs = src_L0_ofs;
  		} else {
  			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
@@ -963,7 +999,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		}
  		/* Add copy commands size here */
-		batch_size += ((copy_only_ccs) ? 0 : emit_copy_cmd_len(xe)) +
+		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
+			       emit_copy_cmd_len(xe)) +
  			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
  		bb = xe_bb_new(gt, batch_size, usm);
@@ -975,13 +1012,15 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
  			xe_res_next(&src_it, src_L0);
  		else
-			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
+			emit_pte(m, bb, src_L0_pt, src_is_vram,
+				 copy_system_ccs || use_comp_pat || flags.defrag_ccs,
  				 &src_it, src_L0, src);
  		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
  			xe_res_next(&dst_it, src_L0);
-		else if (!copy_only_ccs)
-			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
+		else if (!flags.copy_only_ccs)
+			emit_pte(m, bb, dst_L0_pt, dst_is_vram,
+				 copy_system_ccs || flags.defrag_ccs,
  				 &dst_it, src_L0, dst);
  		if (copy_system_ccs)
@@ -990,7 +1029,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
  		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
  		update_idx = bb->len;
-		if (!copy_only_ccs)
+		if (!flags.copy_only_ccs && !flags.defrag_ccs)
  			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
  		if (needs_ccs_emit)
@@ -1078,7 +1117,69 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
  				  struct ttm_resource *dst,
  				  bool copy_only_ccs)
  {
-	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
+	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .copy_only_ccs = copy_only_ccs,
+				 });
+}
+
+/**
+ * xe_migrate_copy_defrag() - Migrate a BO's backing to a reallocated page set.
+ * @m: The migration context.
+ * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
+ * @src: The source TTM resource (the old backing).
+ * @dst: The dst TTM resource (the freshly reallocated backing).
+ * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
+ *
+ * Used by the defrag path where a single BO has its backing reallocated at a
+ * more beneficial page order. The contents are relocated from the old pages
+ * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * in up to two passes:
+ *
+ *  - Data pass (always): copy the data pages verbatim. The pages are mapped
+ *    without the compression PAT, so the (possibly compressed) bytes are copied
+ *    as-is rather than being decompressed and recompressed, and no CCS aux copy
+ *    is appended.
+ *
+ *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
+ *    and new data pages are mapped with the compression PAT so the copy engine
+ *    accesses the aux state indirectly, issuing one indirect -> indirect
+ *    XY_CTRL_SURF_COPY_BLT; the data blit is skipped.
+ *
+ * The two passes are issued separately because they require opposite
+ * compression PAT settings on the data page mappings (cleared for the verbatim
+ * data copy, set for the indirect CCS access), which a single mapping cannot
+ * satisfy. Both passes run in order on the same migrate queue.
+ *
+ * Return: Pointer to a dma_fence representing the last copy batch, or an error
+ * pointer on failure.
+ */
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs)
+{
+	struct dma_fence *fence2, *fence =
+		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				  (struct xe_migrate_copy_flags) {
+					 .defrag_copy = true,
+					 });
+
+	if (IS_ERR(fence) || !need_ccs)
+		return fence;
+
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				   (struct xe_migrate_copy_flags) {
+				   .defrag_ccs = true,
+				   });
+	if (IS_ERR(fence2))
+		dma_fence_wait(fence, false);
+	dma_fence_put(fence);
+
+	return fence2;
  }
  /**
@@ -1096,7 +1197,10 @@ struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
  				     struct xe_bo *bo,
  				     struct ttm_resource *res)
  {
-	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
+	return __xe_migrate_copy(m, bo, bo, res, res, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .is_vram_resolve = true,
+				 });
  }
  /**
drivers/gpu/drm/xe/xe_migrate.h +8 -0
index 965c45889c72..e4f996942a6d 100644
@@ -11,6 +11,7 @@
  struct dma_fence;
  struct drm_pagemap_addr;
  struct iosys_map;
+struct sg_table;
  struct ttm_resource;
  struct xe_bo;
@@ -132,6 +133,13 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
  				  struct ttm_resource *dst,
  				  bool copy_only_ccs);
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs);
+
  struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
  				     struct xe_bo *bo,
  				     struct ttm_resource *res);
reviewer
#69 lore raw

Re: [PATCH v3 17/33] drm/xe: Add xe_migrate_copy_defrag() for on-GPU defrag copies

Quoted 27 lines · Matthew Brost
Quoted 19 lines · Matthew Auld
Quoted 12 lines · Matthew Brost

Add xe_migrate_copy_defrag(), a copy helper for the upcoming page defragmentation path where a single BO has its backing reallocated at a more beneficial page order and its contents must be relocated from the old pages to the new ones entirely on the GPU.

The contents are relocated in up to two passes:

- Data pass (always): copy the data pages verbatim. The pages are mapped without the compression PAT, so the (possibly compressed) bytes are copied as-is rather than being decompressed and recompressed, and no CCS aux copy is appended.

Quoted 4 lines

- CCS pass (need_ccs): copy the CCS aux (compression) state. Both the old and new data pages are mapped with the compression PAT so the copy engine accesses the aux state indirectly, issuing one indirect -> indirect XY_CTRL_SURF_COPY_BLT; the data blit is skipped.

Quoted 6 lines

Just to double check, there were no issues with this flow for a compressed surface? Not 100% sure if reading from the src with uncompressed PAT will zero out the CCS state (update to uncompressed status), such that when you do the CCS pass it is already gone. Quite sure it does that for a write, but I guess not for a read, so we are fine here?

Quoted 8 lines

This isn't my area of expertise, but IIRC I spun on this patch several times before I finally got it right. In my first few attempts, when I ran something like 3DMark Wildlife Extreme or WebGL applications that would trigger the defragmenter, I could see visual corruption on the screen (i.e., the buffers were clearly being corrupted). I eventually landed on the approach detailed here and have not seen any visual issues since. So I think the reads without the compressed PAT are fine, at least on PTL.

Ok, also went and dug up the xe2+ memory compression SAS and under "verbatim copies" it matches up with how you do it here.

Quoted 281 lines

I also have a local update to [1] where I use the compressed PAT, and the tests seem to pass. I can post an update to this test shortly.

Matt

[1] https://patchwork.freedesktop.org/patch/739244/?series=169723&rev=2

Quoted 273 lines
Quoted 272 lines

The two passes are issued separately because they require opposite compression PAT settings on the data page mappings (cleared for the verbatim data copy, set for the indirect CCS access), which a single mapping cannot satisfy. Both passes run in order on the same migrate queue and are captured by the returned fence.

The source pages are passed explicitly via an sg_table argument (the old, still populated backing) since they no longer match the BO's current backing. The boolean arguments to __xe_migrate_copy() are folded into struct xe_migrate_copy_flags to keep the growing set of copy variants readable.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
   drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
   drivers/gpu/drm/xe/xe_migrate.h |   8 ++
   2 files changed, 128 insertions(+), 16 deletions(-)
drivers/gpu/drm/xe/xe_migrate.c +120 -16
index 92d5e81ceac2..305c6e1942fb 100644
@@ -858,13 +858,39 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
   	return flush_flags;
   }
+/**
+ * struct xe_migrate_copy_flags - Flags for __xe_migrate_copy()
+ * @copy_only_ccs: Only copy the CCS aux state, aliasing the destination data
+ * mapping to the source (used when the data pages are shared between src/dst).
+ * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
+ * compression PAT index for the data copy.
+ * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
+ * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * skipped (the data was copied by the @defrag_copy pass) and both the source
+ * and destination data pages are mapped with the compression PAT so the aux
+ * state is copied indirect -> indirect.
+ * @defrag_copy: Defrag move pass that copies the data pages between two
+ * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
+ * aux state. The data pages are mapped without the compression PAT so the
+ * (possibly compressed) bytes are copied verbatim rather than being
+ * decompressed and recompressed, and no CCS aux copy is appended; the aux
+ * state is migrated separately by the @defrag_ccs pass. The two passes need
+ * opposite compression PAT settings, which is why they cannot be combined.
+ */
+struct xe_migrate_copy_flags {
+	u32 copy_only_ccs : 1;
+	u32 is_vram_resolve : 1;
+	u32 defrag_ccs : 1;
+	u32 defrag_copy : 1;
+};
+
   static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   					   struct xe_bo *src_bo,
   					   struct xe_bo *dst_bo,
   					   struct ttm_resource *src,
   					   struct ttm_resource *dst,
-					   bool copy_only_ccs,
-					   bool is_vram_resolve)
+					   struct sg_table *src_sg,
+					   struct xe_migrate_copy_flags flags)
   {
   	struct xe_gt *gt = m->tile->primary_gt;
   	struct xe_device *xe = gt_to_xe(gt);
@@ -881,20 +907,29 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   	bool src_is_vram = mem_type_is_vram(src->mem_type);
   	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
   	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
-	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
+	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe) &&
+		!flags.defrag_copy;
   	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
-		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
-	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
+		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo) &&
+		!flags.defrag_copy;
+	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
+		!flags.defrag_ccs && !flags.defrag_copy;
   	/*
   	 * For decompression operation, always use the compression PAT index.
   	 * Otherwise, only use the compression PAT index for device memory
   	 * when copying from VRAM to system memory.
   	 */
-	bool use_comp_pat = is_vram_resolve || (type_device &&
+	bool use_comp_pat = flags.is_vram_resolve || (type_device &&
   			    xe_device_has_flat_ccs(xe) &&
   			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
+	/*
+	 * The defrag CCS pass migrates the aux state from the old pages
+	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
+	 */
+
   	/* Copying CCS between two different BOs is not supported yet. */
   	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
   		return ERR_PTR(-EINVAL);
@@ -903,7 +938,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		return ERR_PTR(-EINVAL);
   	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
   	else
   		xe_res_first(src, 0, size, &src_it);
   	if (!dst_is_vram)
@@ -912,7 +947,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		xe_res_first(dst, 0, size, &dst_it);
   	if (copy_system_ccs)
-		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+				xe_bo_ccs_pages_start(src_bo),
   				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
   				&ccs_it);
@@ -942,7 +978,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
   					      &src_L0_ofs, &src_L0_pt, 0, 0,
   					      avail_pts);
-		if (copy_only_ccs) {
+		if (flags.copy_only_ccs) {
   			dst_L0_ofs = src_L0_ofs;
   		} else {
   			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
@@ -963,7 +999,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		}
   		/* Add copy commands size here */
-		batch_size += ((copy_only_ccs) ? 0 : emit_copy_cmd_len(xe)) +
+		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
+			       emit_copy_cmd_len(xe)) +
   			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
   		bb = xe_bb_new(gt, batch_size, usm);
@@ -975,13 +1012,15 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
   			xe_res_next(&src_it, src_L0);
   		else
-			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
+			emit_pte(m, bb, src_L0_pt, src_is_vram,
+				 copy_system_ccs || use_comp_pat || flags.defrag_ccs,
   				 &src_it, src_L0, src);
   		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
   			xe_res_next(&dst_it, src_L0);
-		else if (!copy_only_ccs)
-			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
+		else if (!flags.copy_only_ccs)
+			emit_pte(m, bb, dst_L0_pt, dst_is_vram,
+				 copy_system_ccs || flags.defrag_ccs,
   				 &dst_it, src_L0, dst);
   		if (copy_system_ccs)
@@ -990,7 +1029,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
   		update_idx = bb->len;
-		if (!copy_only_ccs)
+		if (!flags.copy_only_ccs && !flags.defrag_ccs)
   			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
   		if (needs_ccs_emit)
@@ -1078,7 +1117,69 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
   				  struct ttm_resource *dst,
   				  bool copy_only_ccs)
   {
-	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
+	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .copy_only_ccs = copy_only_ccs,
+				 });
+}
+
+/**
+ * xe_migrate_copy_defrag() - Migrate a BO's backing to a reallocated page set.
+ * @m: The migration context.
+ * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
+ * @src: The source TTM resource (the old backing).
+ * @dst: The dst TTM resource (the freshly reallocated backing).
+ * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
+ *
+ * Used by the defrag path where a single BO has its backing reallocated at a
+ * more beneficial page order. The contents are relocated from the old pages
+ * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * in up to two passes:
+ *
+ *  - Data pass (always): copy the data pages verbatim. The pages are mapped
+ *    without the compression PAT, so the (possibly compressed) bytes are copied
+ *    as-is rather than being decompressed and recompressed, and no CCS aux copy
+ *    is appended.
+ *
+ *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
+ *    and new data pages are mapped with the compression PAT so the copy engine
+ *    accesses the aux state indirectly, issuing one indirect -> indirect
+ *    XY_CTRL_SURF_COPY_BLT; the data blit is skipped.
+ *
+ * The two passes are issued separately because they require opposite
+ * compression PAT settings on the data page mappings (cleared for the verbatim
+ * data copy, set for the indirect CCS access), which a single mapping cannot
+ * satisfy. Both passes run in order on the same migrate queue.
+ *
+ * Return: Pointer to a dma_fence representing the last copy batch, or an error
+ * pointer on failure.
+ */
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs)
+{
+	struct dma_fence *fence2, *fence =
+		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				  (struct xe_migrate_copy_flags) {
+					 .defrag_copy = true,
+					 });
+
+	if (IS_ERR(fence) || !need_ccs)
+		return fence;
+
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				   (struct xe_migrate_copy_flags) {
+				   .defrag_ccs = true,
+				   });
+	if (IS_ERR(fence2))
+		dma_fence_wait(fence, false);
+	dma_fence_put(fence);
+
+	return fence2;
   }
   /**
@@ -1096,7 +1197,10 @@ struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
   				     struct xe_bo *bo,
   				     struct ttm_resource *res)
   {
-	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
+	return __xe_migrate_copy(m, bo, bo, res, res, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .is_vram_resolve = true,
+				 });
   }
   /**
drivers/gpu/drm/xe/xe_migrate.h +8 -0
index 965c45889c72..e4f996942a6d 100644
@@ -11,6 +11,7 @@
   struct dma_fence;
   struct drm_pagemap_addr;
   struct iosys_map;
+struct sg_table;
   struct ttm_resource;
   struct xe_bo;
@@ -132,6 +133,13 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
   				  struct ttm_resource *dst,
   				  bool copy_only_ccs);
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs);
+
   struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
   				     struct xe_bo *bo,
   				     struct ttm_resource *res);
author maintainer
#70 lore raw

Re: [PATCH v3 17/33] drm/xe: Add xe_migrate_copy_defrag() for on-GPU defrag copies

Quoted 37 lines · Matthew Auld
Quoted 27 lines · Matthew Brost
Quoted 19 lines · Matthew Auld
Quoted 12 lines · Matthew Brost

Add xe_migrate_copy_defrag(), a copy helper for the upcoming page defragmentation path where a single BO has its backing reallocated at a more beneficial page order and its contents must be relocated from the old pages to the new ones entirely on the GPU.

The contents are relocated in up to two passes:

- Data pass (always): copy the data pages verbatim. The pages are mapped without the compression PAT, so the (possibly compressed) bytes are copied as-is rather than being decompressed and recompressed, and no CCS aux copy is appended.

Quoted 4 lines

- CCS pass (need_ccs): copy the CCS aux (compression) state. Both the old and new data pages are mapped with the compression PAT so the copy engine accesses the aux state indirectly, issuing one indirect -> indirect XY_CTRL_SURF_COPY_BLT; the data blit is skipped.

Quoted 6 lines

Just to double check, there were no issues with this flow for a compressed surface? Not 100% sure if reading from the src with uncompressed PAT will zero out the CCS state (update to uncompressed status), such that when you do the CCS pass it is already gone. Quite sure it does that for a write, but I guess not for a read, so we are fine here?

Quoted 8 lines

This isn't my area of expertise, but IIRC I spun on this patch several times before I finally got it right. In my first few attempts, when I ran something like 3DMark Wildlife Extreme or WebGL applications that would trigger the defragmenter, I could see visual corruption on the screen (i.e., the buffers were clearly being corrupted). I eventually landed on the approach detailed here and have not seen any visual issues since. So I think the reads without the compressed PAT are fine, at least on PTL.

Quoted 3 lines

Ok, also went and dug up the xe2+ memory compression SAS and under "verbatim copies" it matches up with how you do it here.

+1. Thanks for checking.

Matt

Quoted 282 lines
Quoted 281 lines

I also have a local update to [1] where I use the compressed PAT, and the tests seem to pass. I can post an update to this test shortly.

Matt

[1] https://patchwork.freedesktop.org/patch/739244/?series=169723&rev=2

Quoted 273 lines
Quoted 272 lines

The two passes are issued separately because they require opposite compression PAT settings on the data page mappings (cleared for the verbatim data copy, set for the indirect CCS access), which a single mapping cannot satisfy. Both passes run in order on the same migrate queue and are captured by the returned fence.

The source pages are passed explicitly via an sg_table argument (the old, still populated backing) since they no longer match the BO's current backing. The boolean arguments to __xe_migrate_copy() are folded into struct xe_migrate_copy_flags to keep the growing set of copy variants readable.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
   drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
   drivers/gpu/drm/xe/xe_migrate.h |   8 ++
   2 files changed, 128 insertions(+), 16 deletions(-)
drivers/gpu/drm/xe/xe_migrate.c +120 -16
index 92d5e81ceac2..305c6e1942fb 100644
@@ -858,13 +858,39 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
   	return flush_flags;
   }
+/**
+ * struct xe_migrate_copy_flags - Flags for __xe_migrate_copy()
+ * @copy_only_ccs: Only copy the CCS aux state, aliasing the destination data
+ * mapping to the source (used when the data pages are shared between src/dst).
+ * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
+ * compression PAT index for the data copy.
+ * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
+ * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * skipped (the data was copied by the @defrag_copy pass) and both the source
+ * and destination data pages are mapped with the compression PAT so the aux
+ * state is copied indirect -> indirect.
+ * @defrag_copy: Defrag move pass that copies the data pages between two
+ * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
+ * aux state. The data pages are mapped without the compression PAT so the
+ * (possibly compressed) bytes are copied verbatim rather than being
+ * decompressed and recompressed, and no CCS aux copy is appended; the aux
+ * state is migrated separately by the @defrag_ccs pass. The two passes need
+ * opposite compression PAT settings, which is why they cannot be combined.
+ */
+struct xe_migrate_copy_flags {
+	u32 copy_only_ccs : 1;
+	u32 is_vram_resolve : 1;
+	u32 defrag_ccs : 1;
+	u32 defrag_copy : 1;
+};
+
   static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   					   struct xe_bo *src_bo,
   					   struct xe_bo *dst_bo,
   					   struct ttm_resource *src,
   					   struct ttm_resource *dst,
-					   bool copy_only_ccs,
-					   bool is_vram_resolve)
+					   struct sg_table *src_sg,
+					   struct xe_migrate_copy_flags flags)
   {
   	struct xe_gt *gt = m->tile->primary_gt;
   	struct xe_device *xe = gt_to_xe(gt);
@@ -881,20 +907,29 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   	bool src_is_vram = mem_type_is_vram(src->mem_type);
   	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
   	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
-	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
+	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe) &&
+		!flags.defrag_copy;
   	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
-		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
-	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
+		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo) &&
+		!flags.defrag_copy;
+	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
+		!flags.defrag_ccs && !flags.defrag_copy;
   	/*
   	 * For decompression operation, always use the compression PAT index.
   	 * Otherwise, only use the compression PAT index for device memory
   	 * when copying from VRAM to system memory.
   	 */
-	bool use_comp_pat = is_vram_resolve || (type_device &&
+	bool use_comp_pat = flags.is_vram_resolve || (type_device &&
   			    xe_device_has_flat_ccs(xe) &&
   			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
+	/*
+	 * The defrag CCS pass migrates the aux state from the old pages
+	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
+	 */
+
   	/* Copying CCS between two different BOs is not supported yet. */
   	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
   		return ERR_PTR(-EINVAL);
@@ -903,7 +938,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		return ERR_PTR(-EINVAL);
   	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
   	else
   		xe_res_first(src, 0, size, &src_it);
   	if (!dst_is_vram)
@@ -912,7 +947,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		xe_res_first(dst, 0, size, &dst_it);
   	if (copy_system_ccs)
-		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+				xe_bo_ccs_pages_start(src_bo),
   				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
   				&ccs_it);
@@ -942,7 +978,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
   					      &src_L0_ofs, &src_L0_pt, 0, 0,
   					      avail_pts);
-		if (copy_only_ccs) {
+		if (flags.copy_only_ccs) {
   			dst_L0_ofs = src_L0_ofs;
   		} else {
   			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
@@ -963,7 +999,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		}
   		/* Add copy commands size here */
-		batch_size += ((copy_only_ccs) ? 0 : emit_copy_cmd_len(xe)) +
+		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
+			       emit_copy_cmd_len(xe)) +
   			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
   		bb = xe_bb_new(gt, batch_size, usm);
@@ -975,13 +1012,15 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
   			xe_res_next(&src_it, src_L0);
   		else
-			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
+			emit_pte(m, bb, src_L0_pt, src_is_vram,
+				 copy_system_ccs || use_comp_pat || flags.defrag_ccs,
   				 &src_it, src_L0, src);
   		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
   			xe_res_next(&dst_it, src_L0);
-		else if (!copy_only_ccs)
-			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
+		else if (!flags.copy_only_ccs)
+			emit_pte(m, bb, dst_L0_pt, dst_is_vram,
+				 copy_system_ccs || flags.defrag_ccs,
   				 &dst_it, src_L0, dst);
   		if (copy_system_ccs)
@@ -990,7 +1029,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
   		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
   		update_idx = bb->len;
-		if (!copy_only_ccs)
+		if (!flags.copy_only_ccs && !flags.defrag_ccs)
   			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
   		if (needs_ccs_emit)
@@ -1078,7 +1117,69 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
   				  struct ttm_resource *dst,
   				  bool copy_only_ccs)
   {
-	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
+	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .copy_only_ccs = copy_only_ccs,
+				 });
+}
+
+/**
+ * xe_migrate_copy_defrag() - Migrate a BO's backing to a reallocated page set.
+ * @m: The migration context.
+ * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
+ * @src: The source TTM resource (the old backing).
+ * @dst: The dst TTM resource (the freshly reallocated backing).
+ * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
+ *
+ * Used by the defrag path where a single BO has its backing reallocated at a
+ * more beneficial page order. The contents are relocated from the old pages
+ * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * in up to two passes:
+ *
+ *  - Data pass (always): copy the data pages verbatim. The pages are mapped
+ *    without the compression PAT, so the (possibly compressed) bytes are copied
+ *    as-is rather than being decompressed and recompressed, and no CCS aux copy
+ *    is appended.
+ *
+ *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
+ *    and new data pages are mapped with the compression PAT so the copy engine
+ *    accesses the aux state indirectly, issuing one indirect -> indirect
+ *    XY_CTRL_SURF_COPY_BLT; the data blit is skipped.
+ *
+ * The two passes are issued separately because they require opposite
+ * compression PAT settings on the data page mappings (cleared for the verbatim
+ * data copy, set for the indirect CCS access), which a single mapping cannot
+ * satisfy. Both passes run in order on the same migrate queue.
+ *
+ * Return: Pointer to a dma_fence representing the last copy batch, or an error
+ * pointer on failure.
+ */
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs)
+{
+	struct dma_fence *fence2, *fence =
+		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				  (struct xe_migrate_copy_flags) {
+					 .defrag_copy = true,
+					 });
+
+	if (IS_ERR(fence) || !need_ccs)
+		return fence;
+
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				   (struct xe_migrate_copy_flags) {
+				   .defrag_ccs = true,
+				   });
+	if (IS_ERR(fence2))
+		dma_fence_wait(fence, false);
+	dma_fence_put(fence);
+
+	return fence2;
   }
   /**
@@ -1096,7 +1197,10 @@ struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
   				     struct xe_bo *bo,
   				     struct ttm_resource *res)
   {
-	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
+	return __xe_migrate_copy(m, bo, bo, res, res, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .is_vram_resolve = true,
+				 });
   }
   /**
drivers/gpu/drm/xe/xe_migrate.h +8 -0
index 965c45889c72..e4f996942a6d 100644
@@ -11,6 +11,7 @@
   struct dma_fence;
   struct drm_pagemap_addr;
   struct iosys_map;
+struct sg_table;
   struct ttm_resource;
   struct xe_bo;
@@ -132,6 +133,13 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
   				  struct ttm_resource *dst,
   				  bool copy_only_ccs);
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs);
+
   struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
   				     struct xe_bo *bo,
   				     struct ttm_resource *res);
#71 lore raw

Re: [PATCH v3 17/33] drm/xe: Add xe_migrate_copy_defrag() for on-GPU defrag copies

In reply to Matthew Brost
Quoted 72 lines · Matthew Brost

Add xe_migrate_copy_defrag(), a copy helper for the upcoming page defragmentation path where a single BO has its backing reallocated at a more beneficial page order and its contents must be relocated from the old pages to the new ones entirely on the GPU.

The contents are relocated in up to two passes:

- Data pass (always): copy the data pages verbatim. The pages are mapped without the compression PAT, so the (possibly compressed) bytes are copied as-is rather than being decompressed and recompressed, and no CCS aux copy is appended.

- CCS pass (need_ccs): copy the CCS aux (compression) state. Both the old and new data pages are mapped with the compression PAT so the copy engine accesses the aux state indirectly, issuing one indirect -> indirect XY_CTRL_SURF_COPY_BLT; the data blit is skipped.

The two passes are issued separately because they require opposite compression PAT settings on the data page mappings (cleared for the verbatim data copy, set for the indirect CCS access), which a single mapping cannot satisfy. Both passes run in order on the same migrate queue and are captured by the returned fence.

The source pages are passed explicitly via an sg_table argument (the old, still populated backing) since they no longer match the BO's current backing. The boolean arguments to __xe_migrate_copy() are folded into struct xe_migrate_copy_flags to keep the growing set of copy variants readable.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---
drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
drivers/gpu/drm/xe/xe_migrate.h | 8 ++

2 files changed, 128 insertions(+), 16 deletions(-)
drivers/gpu/drm/xe/xe_migrate.c +15 -0
index 92d5e81ceac2..305c6e1942fb 100644
@@ -858,13 +858,39 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
 	return flush_flags;
 }
 
+/**
+ * struct xe_migrate_copy_flags - Flags for __xe_migrate_copy()
+ * @copy_only_ccs: Only copy the CCS aux state, aliasing the destination data
+ * mapping to the source (used when the data pages are shared between src/dst).
+ * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
+ * compression PAT index for the data copy.
+ * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
+ * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * skipped (the data was copied by the @defrag_copy pass) and both the source
+ * and destination data pages are mapped with the compression PAT so the aux
+ * state is copied indirect -> indirect.
+ * @defrag_copy: Defrag move pass that copies the data pages between two
+ * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
+ * aux state. The data pages are mapped without the compression PAT so the
+ * (possibly compressed) bytes are copied verbatim rather than being

drivers/gpu/drm/xe/xe_migrate.c static u32 xe_migrate_ccs_copy(struct xe_migrate *m, · line 885

Quoted 10 lines
drivers/gpu/drm/xe/xe_migrate.c +10 -0
+ * decompressed and recompressed, and no CCS aux copy is appended; the aux
+ * state is migrated separately by the @defrag_ccs pass. The two passes need
+ * opposite compression PAT settings, which is why they cannot be combined.
+ */
+struct xe_migrate_copy_flags {
+	u32 copy_only_ccs : 1;
+	u32 is_vram_resolve : 1;
+	u32 defrag_ccs : 1;
+	u32 defrag_copy : 1;
+};
Assisted-by LLM

These flags seems to be mutually exclusive. So, probably use an enum instead?

enum xe_migrate_copy_mode {
XE_MIGRATE_COPY_NORMAL,
XE_MIGRATE_COPY_CCS_ONLY, /* dst aliases src */
XE_MIGRATE_COPY_VRAM_RESOLVE, XE_MIGRATE_COPY_DEFRAG_DATA, /* distinct dst, verbatim data */
XE_MIGRATE_COPY_DEFRAG_CCS, /* distinct dst, indirect->indirect aux */
};

Niranjana

Quoted 225 lines
drivers/gpu/drm/xe/xe_migrate.c +95 -16
+
 static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 					   struct xe_bo *src_bo,
 					   struct xe_bo *dst_bo,
 					   struct ttm_resource *src,
 					   struct ttm_resource *dst,
-					   bool copy_only_ccs,
-					   bool is_vram_resolve)
+					   struct sg_table *src_sg,
+					   struct xe_migrate_copy_flags flags)
 {
 	struct xe_gt *gt = m->tile->primary_gt;
 	struct xe_device *xe = gt_to_xe(gt);
@@ -881,20 +907,29 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 	bool src_is_vram = mem_type_is_vram(src->mem_type);
 	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
 	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
-	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
+	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe) &&
+		!flags.defrag_copy;
 	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
-		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
-	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
+		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo) &&
+		!flags.defrag_copy;
+	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
+		!flags.defrag_ccs && !flags.defrag_copy;
 
 	/*
 	 * For decompression operation, always use the compression PAT index.
 	 * Otherwise, only use the compression PAT index for device memory
 	 * when copying from VRAM to system memory.
 	 */
-	bool use_comp_pat = is_vram_resolve || (type_device &&
+	bool use_comp_pat = flags.is_vram_resolve || (type_device &&
 			    xe_device_has_flat_ccs(xe) &&
 			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
 
+	/*
+	 * The defrag CCS pass migrates the aux state from the old pages
+	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
+	 */
+
 	/* Copying CCS between two different BOs is not supported yet. */
 	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
 		return ERR_PTR(-EINVAL);
@@ -903,7 +938,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(-EINVAL);
 
 	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 	if (!dst_is_vram)
@@ -912,7 +947,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		xe_res_first(dst, 0, size, &dst_it);
 
 	if (copy_system_ccs)
-		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+				xe_bo_ccs_pages_start(src_bo),
 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 				&ccs_it);
 
@@ -942,7 +978,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
 					      &src_L0_ofs, &src_L0_pt, 0, 0,
 					      avail_pts);
-		if (copy_only_ccs) {
+		if (flags.copy_only_ccs) {
 			dst_L0_ofs = src_L0_ofs;
 		} else {
 			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
@@ -963,7 +999,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		}
 
 		/* Add copy commands size here */
-		batch_size += ((copy_only_ccs) ? 0 : emit_copy_cmd_len(xe)) +
+		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
+			       emit_copy_cmd_len(xe)) +
 			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
 
 		bb = xe_bb_new(gt, batch_size, usm);
@@ -975,13 +1012,15 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
 			xe_res_next(&src_it, src_L0);
 		else
-			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
+			emit_pte(m, bb, src_L0_pt, src_is_vram,
+				 copy_system_ccs || use_comp_pat || flags.defrag_ccs,
 				 &src_it, src_L0, src);
 
 		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
 			xe_res_next(&dst_it, src_L0);
-		else if (!copy_only_ccs)
-			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
+		else if (!flags.copy_only_ccs)
+			emit_pte(m, bb, dst_L0_pt, dst_is_vram,
+				 copy_system_ccs || flags.defrag_ccs,
 				 &dst_it, src_L0, dst);
 
 		if (copy_system_ccs)
@@ -990,7 +1029,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
 		update_idx = bb->len;
 
-		if (!copy_only_ccs)
+		if (!flags.copy_only_ccs && !flags.defrag_ccs)
 			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
 
 		if (needs_ccs_emit)
@@ -1078,7 +1117,69 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 				  struct ttm_resource *dst,
 				  bool copy_only_ccs)
 {
-	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
+	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .copy_only_ccs = copy_only_ccs,
+				 });
+}
+
+/**
+ * xe_migrate_copy_defrag() - Migrate a BO's backing to a reallocated page set.
+ * @m: The migration context.
+ * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
+ * @src: The source TTM resource (the old backing).
+ * @dst: The dst TTM resource (the freshly reallocated backing).
+ * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
+ *
+ * Used by the defrag path where a single BO has its backing reallocated at a
+ * more beneficial page order. The contents are relocated from the old pages
+ * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * in up to two passes:
+ *
+ *  - Data pass (always): copy the data pages verbatim. The pages are mapped
+ *    without the compression PAT, so the (possibly compressed) bytes are copied
+ *    as-is rather than being decompressed and recompressed, and no CCS aux copy
+ *    is appended.
+ *
+ *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
+ *    and new data pages are mapped with the compression PAT so the copy engine
+ *    accesses the aux state indirectly, issuing one indirect -> indirect
+ *    XY_CTRL_SURF_COPY_BLT; the data blit is skipped.
+ *
+ * The two passes are issued separately because they require opposite
+ * compression PAT settings on the data page mappings (cleared for the verbatim
+ * data copy, set for the indirect CCS access), which a single mapping cannot
+ * satisfy. Both passes run in order on the same migrate queue.
+ *
+ * Return: Pointer to a dma_fence representing the last copy batch, or an error
+ * pointer on failure.
+ */
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs)
+{
+	struct dma_fence *fence2, *fence =
+		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				  (struct xe_migrate_copy_flags) {
+					 .defrag_copy = true,
+					 });
+
+	if (IS_ERR(fence) || !need_ccs)
+		return fence;
+
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+				   (struct xe_migrate_copy_flags) {
+				   .defrag_ccs = true,
+				   });
+	if (IS_ERR(fence2))
+		dma_fence_wait(fence, false);
+	dma_fence_put(fence);
+
+	return fence2;
 }
 
 /**
@@ -1096,7 +1197,10 @@ struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
 				     struct xe_bo *bo,
 				     struct ttm_resource *res)
 {
-	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
+	return __xe_migrate_copy(m, bo, bo, res, res, NULL,
+				 (struct xe_migrate_copy_flags) {
+					 .is_vram_resolve = true,
+				 });
 }
 
 /**
drivers/gpu/drm/xe/xe_migrate.h +8 -0
index 965c45889c72..e4f996942a6d 100644
@@ -11,6 +11,7 @@
 struct dma_fence;
 struct drm_pagemap_addr;
 struct iosys_map;
+struct sg_table;
 struct ttm_resource;
 
 struct xe_bo;
@@ -132,6 +133,13 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 				  struct ttm_resource *dst,
 				  bool copy_only_ccs);
 
+struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
+					 struct xe_bo *bo,
+					 struct ttm_resource *src,
+					 struct ttm_resource *dst,
+					 struct sg_table *src_sg,
+					 bool need_ccs);
+
 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
 				     struct xe_bo *bo,
 				     struct ttm_resource *res);
Signature · 1 line
2.34.1
author maintainer
#72 lore raw

PATCH v3 18/33 drm/xe: Handle defrag moves in xe_bo_move()

In reply to Matthew Brost

Teach xe_bo_move() to service a defrag move, where TTM reallocates a BO's backing at the device's beneficial order and hands the old, still populated tt to the move via the BO's defrag_old_tt.

A defrag move always has existing contents to copy, so force move_lacks_source false and fall through the XE_PL_TT -> XE_PL_TT no-op shortcut so the copy path runs. The relocation is performed entirely on the GPU via xe_migrate_copy_defrag(), reading the old pages from the stashed tt's sg table and writing the freshly reallocated backing.

Both copy passes run in order on the same migrate queue and are captured by the returned fence, so the teardown is pipelined via ttm_bo_move_accel_cleanup(): the old tt is handed to a ghost object and only unpopulated and freed once the fence signals, so the move need not block. The VF CCS attach/detach handling is extended to treat a defrag move (ctx->defrag) like the XE_PL_SYSTEM <-> XE_PL_TT transitions it mirrors.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_bo.c | 24 ++++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +20 -4
index 02395968d613..bdcc9bed5d36 100644
@@ -1170,6 +1170,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	move_lacks_source = !old_mem || (handle_system_ccs ? (!bo->ccs_cleared) :
 					 (!mem_type_is_vram(old_mem_type) && !tt_has_data));
 
+	/*
+	 * A defrag move always copies the existing contents from the stashed
+	 * old tt into the freshly (re)allocated backing.
+	 */
+	if (ttm_bo->defrag_old_tt)
+		move_lacks_source = false;
+
 	needs_clear = (ttm && ttm->page_flags & TTM_TT_FLAG_ZERO_ALLOC) ||
 		(!ttm && ttm_bo->type == ttm_bo_type_device);
 
@@ -1206,9 +1213,12 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	/*
 	 * Failed multi-hop where the old_mem is still marked as
 	 * TTM_PL_FLAG_TEMPORARY, should just be a dummy move.
+	 *
+	 * For a defrag move the old and new tt differ, so fallthrough to the
+	 * copy path instead of treating it as a no-op.
 	 */
 	if (old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_TT) {
+	    new_mem->mem_type == XE_PL_TT && !ttm_bo->defrag_old_tt) {
 		ttm_bo_move_null(ttm_bo, new_mem);
 		goto out;
 	}
@@ -1279,6 +1289,12 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 			flags |= XE_MIGRATE_CLEAR_FLAG_CCS_DATA;
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
+	} else if (ttm_bo->defrag_old_tt) {
+		struct xe_ttm_tt *old_xe_tt =
+			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
+
+		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
+					       old_xe_tt->sg, handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
@@ -1315,13 +1331,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	 * BBs from BO as it is no longer needed.
 	 */
 	if (IS_VF_CCS_READY(xe) && old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_SYSTEM)
+	    (new_mem->mem_type == XE_PL_SYSTEM || ctx->defrag))
 		xe_sriov_vf_ccs_detach_bo(bo);
 
 	if (IS_VF_CCS_READY(xe) &&
 	    ((move_lacks_source && new_mem->mem_type == XE_PL_TT) ||
-	     (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT)) &&
-	    handle_system_ccs)
+	     ((old_mem_type == XE_PL_SYSTEM || ctx->defrag) &&
+	      new_mem->mem_type == XE_PL_TT)) && handle_system_ccs)
 		ret = xe_sriov_vf_ccs_attach_bo(bo);
 
 out:
Signature · 1 line
2.34.1
#73 lore raw

Re: [PATCH v3 18/33] drm/xe: Handle defrag moves in xe_bo_move()

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

New issues:
- [High] Pipelined defrag move detaches VF CCS metadata before the GPU copy completes, risking CCS metadata corruption on VF migration.
- [Medium] Using ctx->defrag to identify a defrag move incorrectly applies defrag-specific VF CCS attach/detach logic to unrelated victim BOs evicted during a defrag operation.

Pre-existing issues:
- [Critical] Returning an error from xe_bo_move() after successfully committing the move causes TTM to free the new resource, leaving bo->resource as a dangling pointer. --

--- Patch [18]: [PATCH v3 18/33] drm/xe: Handle defrag moves in xe_bo_move() --- commit 22e925edd18b0faf0ff581a79813091d539553b8
Author: Matthew Brost <[email protected]>
Subject: drm/xe: Handle defrag moves in xe_bo_move()

This commit modifies xe_bo_move() to handle defragmentation moves, allowing TTM to reallocate a BO's backing at an optimal order while copying existing contents. It introduces a fast path for defrag moves via GPU relocation, pipelines the teardown asynchronously, and extends VF CCS attach/detach logic to cover defrag transitions.

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
index 02395968d613b..bdcc9bed5d36b 100644

[ ... ]

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict, · line 1335

Quoted 7 lines
drivers/gpu/drm/xe/xe_bo.c +1 -1
@@ -1315,13 +1331,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	 * BBs from BO as it is no longer needed.
 	 */
 	if (IS_VF_CCS_READY(xe) && old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_SYSTEM)
+	    (new_mem->mem_type == XE_PL_SYSTEM || ctx->defrag))
 		xe_sriov_vf_ccs_detach_bo(bo);

[Severity: High]
Does this code synchronously detach VF CCS metadata before the GPU copy completes?

Since a defrag move is pipelined asynchronously (evict is false, so ttm_bo_move_accel_cleanup() delegates to a ghost object without waiting for the fence), xe_bo_move() immediately calls xe_sriov_vf_ccs_detach_bo(bo).

This synchronously clears the GuC CCS save/restore batch buffers for the old TT. If a VF migration triggers while the async GPU copy job is still in flight, the GuC won't save the old TT's CCS state because its batch buffers were detached.

When the copy job resumes, can it copy uninitialized or garbage data from the old hardware CCS region into the new TT, leading to CCS metadata corruption?

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict, · line 1341

Quoted 7 lines
drivers/gpu/drm/xe/xe_bo.c +2 -2
 	if (IS_VF_CCS_READY(xe) &&
 	    ((move_lacks_source && new_mem->mem_type == XE_PL_TT) ||
-	     (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT)) &&
-	    handle_system_ccs)
+	     ((old_mem_type == XE_PL_SYSTEM || ctx->defrag) &&
+	      new_mem->mem_type == XE_PL_TT)) && handle_system_ccs)
 		ret = xe_sriov_vf_ccs_attach_bo(bo);

[Severity: Medium]
Does checking ctx->defrag instead of ttm_bo->defrag_old_tt misclassify victim BOs?

TTM passes the original ttm_operation_ctx down to all evictions triggered by an allocation, which means ctx->defrag is true for any victim BO evicted during a defrag pass.

If unrelated BOs (such as those evicted from STOLEN to TT) have VF CCS logic applied to them because ctx->defrag is true, will this modify their hardware CCS tracking unexpectedly and break standard eviction flows?

[Severity: Critical]
This is a pre-existing issue, but returning an error from xe_bo_move() after successfully committing the move causes TTM to free the new resource, leaving bo->resource as a dangling pointer.

In xe_bo_move(), the move is successfully committed via ttm_bo_move_accel_cleanup() which assigns the new resource to bo->resource. If a subsequent operation like xe_sriov_vf_ccs_attach_bo(bo) fails (e.g. returns -ENOMEM), xe_bo_move() propagates this error back to TTM.

TTM's error recovery in ttm_bo_validate() then unconditionally calls ttm_resource_free(bo, &res) for the new allocation. Since bo->resource already points to this new allocation, does this free the memory while leaving bo->resource as a dangling pointer, creating a use-after-free risk?

Quoted 2 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 out:
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
#74 lore raw

Re: [PATCH v3 18/33] drm/xe: Handle defrag moves in xe_bo_move()

In reply to Matthew Brost
Quoted 87 lines · Matthew Brost

Teach xe_bo_move() to service a defrag move, where TTM reallocates a BO's backing at the device's beneficial order and hands the old, still populated tt to the move via the BO's defrag_old_tt.

A defrag move always has existing contents to copy, so force move_lacks_source false and fall through the XE_PL_TT -> XE_PL_TT no-op shortcut so the copy path runs. The relocation is performed entirely on the GPU via xe_migrate_copy_defrag(), reading the old pages from the stashed tt's sg table and writing the freshly reallocated backing.

Both copy passes run in order on the same migrate queue and are captured by the returned fence, so the teardown is pipelined via ttm_bo_move_accel_cleanup(): the old tt is handed to a ghost object and only unpopulated and freed once the fence signals, so the move need not block. The VF CCS attach/detach handling is extended to treat a defrag move (ctx->defrag) like the XE_PL_SYSTEM <-> XE_PL_TT transitions it mirrors.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---
drivers/gpu/drm/xe/xe_bo.c | 24 ++++++++++++++++++++----

1 file changed, 20 insertions(+), 4 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +17 -2
index 02395968d613..bdcc9bed5d36 100644
@@ -1170,6 +1170,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	move_lacks_source = !old_mem || (handle_system_ccs ? (!bo->ccs_cleared) :
 					 (!mem_type_is_vram(old_mem_type) && !tt_has_data));
 
+	/*
+	 * A defrag move always copies the existing contents from the stashed
+	 * old tt into the freshly (re)allocated backing.
+	 */
+	if (ttm_bo->defrag_old_tt)
+		move_lacks_source = false;
+
 	needs_clear = (ttm && ttm->page_flags & TTM_TT_FLAG_ZERO_ALLOC) ||
 		(!ttm && ttm_bo->type == ttm_bo_type_device);
 
@@ -1206,9 +1213,12 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	/*
 	 * Failed multi-hop where the old_mem is still marked as
 	 * TTM_PL_FLAG_TEMPORARY, should just be a dummy move.
+	 *
+	 * For a defrag move the old and new tt differ, so fallthrough to the
+	 * copy path instead of treating it as a no-op.
 	 */
 	if (old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_TT) {
+	    new_mem->mem_type == XE_PL_TT && !ttm_bo->defrag_old_tt) {
 		ttm_bo_move_null(ttm_bo, new_mem);
 		goto out;
 	}
@@ -1279,6 +1289,12 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 			flags |= XE_MIGRATE_CLEAR_FLAG_CCS_DATA;
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
+	} else if (ttm_bo->defrag_old_tt) {
+		struct xe_ttm_tt *old_xe_tt =
+			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
+
+		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
+					       old_xe_tt->sg, handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
@@ -1315,13 +1331,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	 * BBs from BO as it is no longer needed.
 	 */
 	if (IS_VF_CCS_READY(xe) && old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_SYSTEM)

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict, · line 1341

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +3 -2
+	    (new_mem->mem_type == XE_PL_SYSTEM || ctx->defrag))
 		xe_sriov_vf_ccs_detach_bo(bo);
 
 	if (IS_VF_CCS_READY(xe) &&
 	    ((move_lacks_source && new_mem->mem_type == XE_PL_TT) ||
-	     (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT)) &&
-	    handle_system_ccs)
+	     ((old_mem_type == XE_PL_SYSTEM || ctx->defrag) &&
+	      new_mem->mem_type == XE_PL_TT)) && handle_system_ccs)
 		ret = xe_sriov_vf_ccs_attach_bo(bo);
Assisted-by LLM

Looks like code has changed in drm-tip and sriov_vf_ccs_attach/detach changes here needs to be rebased.

There are also some sashiko reported bugs around this sriov_vf_ccs_attach_bo which looks legitimate (like move() function returning earlier in error case while move is in progress).

Niranjana

Quoted 5 lines

out:

Signature · 1 line
2.34.1
author maintainer
#75 lore raw

Re: [PATCH v3 18/33] drm/xe: Handle defrag moves in xe_bo_move()

Quoted 101 lines · Niranjana Vishwanathapura
Quoted 87 lines · Matthew Brost

Teach xe_bo_move() to service a defrag move, where TTM reallocates a BO's backing at the device's beneficial order and hands the old, still populated tt to the move via the BO's defrag_old_tt.

A defrag move always has existing contents to copy, so force move_lacks_source false and fall through the XE_PL_TT -> XE_PL_TT no-op shortcut so the copy path runs. The relocation is performed entirely on the GPU via xe_migrate_copy_defrag(), reading the old pages from the stashed tt's sg table and writing the freshly reallocated backing.

Both copy passes run in order on the same migrate queue and are captured by the returned fence, so the teardown is pipelined via ttm_bo_move_accel_cleanup(): the old tt is handed to a ghost object and only unpopulated and freed once the fence signals, so the move need not block. The VF CCS attach/detach handling is extended to treat a defrag move (ctx->defrag) like the XE_PL_SYSTEM <-> XE_PL_TT transitions it mirrors.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---
drivers/gpu/drm/xe/xe_bo.c | 24 ++++++++++++++++++++----

1 file changed, 20 insertions(+), 4 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +17 -2
index 02395968d613..bdcc9bed5d36 100644
@@ -1170,6 +1170,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	move_lacks_source = !old_mem || (handle_system_ccs ? (!bo->ccs_cleared) :
 					 (!mem_type_is_vram(old_mem_type) && !tt_has_data));
 
+	/*
+	 * A defrag move always copies the existing contents from the stashed
+	 * old tt into the freshly (re)allocated backing.
+	 */
+	if (ttm_bo->defrag_old_tt)
+		move_lacks_source = false;
+
 	needs_clear = (ttm && ttm->page_flags & TTM_TT_FLAG_ZERO_ALLOC) ||
 		(!ttm && ttm_bo->type == ttm_bo_type_device);
 
@@ -1206,9 +1213,12 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	/*
 	 * Failed multi-hop where the old_mem is still marked as
 	 * TTM_PL_FLAG_TEMPORARY, should just be a dummy move.
+	 *
+	 * For a defrag move the old and new tt differ, so fallthrough to the
+	 * copy path instead of treating it as a no-op.
 	 */
 	if (old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_TT) {
+	    new_mem->mem_type == XE_PL_TT && !ttm_bo->defrag_old_tt) {
 		ttm_bo_move_null(ttm_bo, new_mem);
 		goto out;
 	}
@@ -1279,6 +1289,12 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 			flags |= XE_MIGRATE_CLEAR_FLAG_CCS_DATA;
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
+	} else if (ttm_bo->defrag_old_tt) {
+		struct xe_ttm_tt *old_xe_tt =
+			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
+
+		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
+					       old_xe_tt->sg, handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
@@ -1315,13 +1331,13 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 	 * BBs from BO as it is no longer needed.
 	 */
 	if (IS_VF_CCS_READY(xe) && old_mem_type == XE_PL_TT &&
-	    new_mem->mem_type == XE_PL_SYSTEM)

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict, · line 1341

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +3 -2
+	    (new_mem->mem_type == XE_PL_SYSTEM || ctx->defrag))
 		xe_sriov_vf_ccs_detach_bo(bo);
 
 	if (IS_VF_CCS_READY(xe) &&
 	    ((move_lacks_source && new_mem->mem_type == XE_PL_TT) ||
-	     (old_mem_type == XE_PL_SYSTEM && new_mem->mem_type == XE_PL_TT)) &&
-	    handle_system_ccs)
+	     ((old_mem_type == XE_PL_SYSTEM || ctx->defrag) &&
+	      new_mem->mem_type == XE_PL_TT)) && handle_system_ccs)
 		ret = xe_sriov_vf_ccs_attach_bo(bo);
Assisted-by LLM
Quoted 7 lines

Looks like code has changed in drm-tip and sriov_vf_ccs_attach/detach changes here needs to be rebased.

There are also some sashiko reported bugs around this sriov_vf_ccs_attach_bo which looks legitimate (like move() function returning earlier in error case while move is in progress).

Yea, I believe I fixed VF CCS issues here:

https://patchwork.freedesktop.org/series/170380/

Matt

Quoted 7 lines

Niranjana

Quoted 5 lines

out:

Signature · 1 line
2.34.1
author maintainer
#76 lore raw

PATCH v3 19/33 drm/xe: Skip self-copies for borrowed pages on defrag moves

In reply to Matthew Brost

A defrag move may harvest already beneficial-order chunks from the old tt, so the freshly reallocated backing borrows (references) some of the same physical pages. For those pages the source and destination GPU mappings alias the same memory, making the data blit a pointless self-copy.

Pass the source (old) tt into __xe_migrate_copy() instead of just its sg table, so the data pass can compare the src and dst tt page arrays at the matching offset and only blit runs of pages that actually differ. A new emit_copy_chunks() helper walks each L0 chunk, skips borrowed-page runs, and coalesces contiguous to-copy pages into a single emit_copy(). It runs twice per chunk: once with a NULL batch buffer to count the blits for batch sizing, then again to emit them.

When an entire L0 chunk turns out to be borrowed, skip it outright: no batch buffer is allocated and no GPU commands are issued, the cursors are just advanced past the chunk. If every chunk of the move is borrowed the copy is a complete no-op, so hand back a signaled stub fence.

The comparison is a cheap per-page pointer test (src page != dst page) that coalesces contiguous to-copy pages into a single blit. PTEs are still emitted for partially borrowed chunks, since that setup is cheap and only the data copies are worth skipping. Only the defrag data pass is affected; the separate CCS pass still migrates all aux state.

Since the Xe tt sg lives in the xe_ttm_tt subclass rather than the base ttm_tt, add an xe_tt_sg() helper to fetch it from a struct ttm_tt.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

----

v3:
- Fix start_page page-shift and blit pitch for src-natural to dst-packed copies (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c      |  22 +++++-
 drivers/gpu/drm/xe/xe_bo.h      |   2 +
 drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
 drivers/gpu/drm/xe/xe_migrate.h |   3 +-
 4 files changed, 142 insertions(+), 21 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +18 -4
index bdcc9bed5d36..7f6ee9b8d12e 100644
@@ -473,6 +473,22 @@ struct sg_table *xe_bo_sg(struct xe_bo *bo)
 	return xe_tt->sg;
 }
 
+/**
+ * xe_tt_sg() - Return the DMA scatter-gather table backing a ttm_tt.
+ * @tt: The ttm_tt to query.
+ *
+ * Like xe_bo_sg(), but takes the ttm_tt directly. Used by the defrag copy
+ * path which needs the old (source) tt's sg table without a backing xe_bo.
+ *
+ * Return: The sg table, or NULL if the tt is not currently mapped.
+ */
+struct sg_table *xe_tt_sg(struct ttm_tt *tt)
+{
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	return xe_tt->sg;
+}
+
 /*
  * Account ttm pages against the device shrinker's shrinkable and
  * purgeable counts.
@@ -1290,11 +1306,9 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
 	} else if (ttm_bo->defrag_old_tt) {
-		struct xe_ttm_tt *old_xe_tt =
-			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
-
 		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
-					       old_xe_tt->sg, handle_system_ccs);
+					       ttm_bo->defrag_old_tt,
+					       handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
drivers/gpu/drm/xe/xe_bo.h +2 -0
index 4186cb51af87..32211016a722 100644
@@ -110,6 +110,7 @@ enum xe_madv_purgeable_state {
 };
 
 struct sg_table;
+struct ttm_tt;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -547,6 +548,7 @@ void xe_bo_dev_init(struct xe_bo_dev *bo_device);
 void xe_bo_dev_fini(struct xe_bo_dev *bo_device);
 
 struct sg_table *xe_bo_sg(struct xe_bo *bo);
+struct sg_table *xe_tt_sg(struct ttm_tt *tt);
 
 /*
  * xe_sg_segment_size() - Provides upper limit for sg segment size.
drivers/gpu/drm/xe/xe_migrate.c +120 -16

237 lines not on this page · raw message

drivers/gpu/drm/xe/xe_migrate.h +2 -1
index e4f996942a6d..4094ea1c19c1 100644
@@ -13,6 +13,7 @@ struct drm_pagemap_addr;
 struct iosys_map;
 struct sg_table;
 struct ttm_resource;
+struct ttm_tt;
 
 struct xe_bo;
 struct xe_gt;
@@ -137,7 +138,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs);
 
 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
Signature · 1 line
2.34.1
#77 lore raw

Re: [PATCH v3 19/33] drm/xe: Skip self-copies for borrowed pages on defrag moves

Quoted 69 lines · Matthew Brost

A defrag move may harvest already beneficial-order chunks from the old tt, so the freshly reallocated backing borrows (references) some of the same physical pages. For those pages the source and destination GPU mappings alias the same memory, making the data blit a pointless self-copy.

Pass the source (old) tt into __xe_migrate_copy() instead of just its sg table, so the data pass can compare the src and dst tt page arrays at the matching offset and only blit runs of pages that actually differ. A new emit_copy_chunks() helper walks each L0 chunk, skips borrowed-page runs, and coalesces contiguous to-copy pages into a single emit_copy(). It runs twice per chunk: once with a NULL batch buffer to count the blits for batch sizing, then again to emit them.

When an entire L0 chunk turns out to be borrowed, skip it outright: no batch buffer is allocated and no GPU commands are issued, the cursors are just advanced past the chunk. If every chunk of the move is borrowed the copy is a complete no-op, so hand back a signaled stub fence.

The comparison is a cheap per-page pointer test (src page != dst page) that coalesces contiguous to-copy pages into a single blit. PTEs are still emitted for partially borrowed chunks, since that setup is cheap and only the data copies are worth skipping. Only the defrag data pass is affected; the separate CCS pass still migrates all aux state.

Since the Xe tt sg lives in the xe_ttm_tt subclass rather than the base ttm_tt, add an xe_tt_sg() helper to fetch it from a struct ttm_tt.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

----

v3:
- Fix start_page page-shift and blit pitch for src-natural to dst-packed copies (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c      |  22 +++++-
drivers/gpu/drm/xe/xe_bo.h      |   2 +
drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
drivers/gpu/drm/xe/xe_migrate.h |   3 +-
4 files changed, 142 insertions(+), 21 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +5 -0
index bdcc9bed5d36..7f6ee9b8d12e 100644
@@ -473,6 +473,22 @@ struct sg_table *xe_bo_sg(struct xe_bo *bo)
 	return xe_tt->sg;
 }
 
+/**
+ * xe_tt_sg() - Return the DMA scatter-gather table backing a ttm_tt.
+ * @tt: The ttm_tt to query.
+ *
+ * Like xe_bo_sg(), but takes the ttm_tt directly. Used by the defrag copy

drivers/gpu/drm/xe/xe_bo.c struct sg_table *xe_bo_sg(struct xe_bo *bo) · line 490

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+ * path which needs the old (source) tt's sg table without a backing xe_bo.
+ *
+ * Return: The sg table, or NULL if the tt is not currently mapped.
+ */
+struct sg_table *xe_tt_sg(struct ttm_tt *tt)
+{
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	return xe_tt->sg;
+}
Assisted-by LLM

xe_tt->sg can be potentially NULL (though probably not in current usecase). Probably an explicit assert better?

Quoted 63 lines
drivers/gpu/drm/xe/xe_bo.c +3 -4
+
 /*
 * Account ttm pages against the device shrinker's shrinkable and
 * purgeable counts.
@@ -1290,11 +1306,9 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
 	} else if (ttm_bo->defrag_old_tt) {
-		struct xe_ttm_tt *old_xe_tt =
-			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
-
 		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
-					       old_xe_tt->sg, handle_system_ccs);
+					       ttm_bo->defrag_old_tt,
+					       handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
drivers/gpu/drm/xe/xe_bo.h +2 -0
index 4186cb51af87..32211016a722 100644
@@ -110,6 +110,7 @@ enum xe_madv_purgeable_state {
 };
 
 struct sg_table;
+struct ttm_tt;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -547,6 +548,7 @@ void xe_bo_dev_init(struct xe_bo_dev *bo_device);
 void xe_bo_dev_fini(struct xe_bo_dev *bo_device);
 
 struct sg_table *xe_bo_sg(struct xe_bo *bo);
+struct sg_table *xe_tt_sg(struct ttm_tt *tt);
 
 /*
 * xe_sg_segment_size() - Provides upper limit for sg segment size.
drivers/gpu/drm/xe/xe_migrate.c +17 -0
index 305c6e1942fb..9990a7144a9f 100644
@@ -811,6 +811,63 @@ static void emit_copy(struct xe_gt *gt, struct xe_bb *bb,
 		emit_xy_fast_copy(gt, bb, src_ofs, dst_ofs, size, pitch);
 }
 
+/*
+ * emit_copy_chunks() - Emit the data blits for one defrag L0 chunk, skipping
+ * borrowed pages.
+ * @gt: The GT.
+ * @bb: The batch buffer to emit into, or NULL to only count the blits needed.
+ * @src_L0_ofs: GPU offset of the source pages mapped for this L0 chunk.
+ * @dst_L0_ofs: GPU offset of the destination pages mapped for this L0 chunk.
+ * @src_L0: Byte size of the L0 chunk (page aligned).
+ * @src_tt: Source (old) tt providing the page pointers.
+ * @dst_tt: Destination (new) tt providing the page pointers.
+ * @start_page: Page offset of this L0 chunk within the tt page arrays.
+ *
+ * A defragmentation move may harvest already beneficial-order chunks from the
+ * old tt, so the new tt references (borrows) some of the same physical pages.
+ * For those pages the source and destination GPU mappings alias the same
+ * memory and the data blit is a pointless self-copy. Walk the L0 chunk and
+ * only blit runs of pages that actually differ (src page != dst page),

drivers/gpu/drm/xe/xe_migrate.c static void emit_copy(struct xe_gt *gt, struct xe_bb *bb, · line 840

Quoted 10 lines
drivers/gpu/drm/xe/xe_migrate.c +10 -0
+ * coalescing contiguous to-copy pages into a single blit.
+ *
+ * Return: The number of blits emitted (or that would be emitted when @bb is
+ * NULL).
+ */
+static u32 emit_copy_chunks(struct xe_gt *gt, struct xe_bb *bb,
+			    u64 src_L0_ofs, u64 dst_L0_ofs, u32 src_L0,
+			    struct ttm_tt *src_tt, struct ttm_tt *dst_tt,
+			    pgoff_t start_page)
+{

emit_copy() doesn't have L0 in parameter names. Probably it is worth keeping it consistent here also?

Quoted 19 lines
drivers/gpu/drm/xe/xe_migrate.c +19 -0
+	u32 npages = src_L0 >> PAGE_SHIFT;
+	u32 i = 0, nblits = 0;
+
+	while (i < npages) {
+		u32 run = 0;
+
+		/* Skip a run of borrowed pages (src and dst alias). */
+		if (src_tt->pages[start_page + i] ==
+		    dst_tt->pages[start_page + i]) {
+			i++;
+			continue;
+		}
+
+		/* Coalesce a run of pages that actually need copying. */
+		while (i + run < npages &&
+		       src_tt->pages[start_page + i + run] !=
+		       dst_tt->pages[start_page + i + run])
+			run++;
+

drivers/gpu/drm/xe/xe_migrate.c static void emit_copy(struct xe_gt *gt, struct xe_bb *bb, · line 869

Quoted 10 lines
drivers/gpu/drm/xe/xe_migrate.c +10 -0
+		if (bb)
+			emit_copy(gt, bb, src_L0_ofs + (u64)i * PAGE_SIZE,
+				  dst_L0_ofs + (u64)i * PAGE_SIZE,
+				  run * PAGE_SIZE, XE_PAGE_SIZE);
+		nblits++;
+		i += run;
+	}
+
+	return nblits;
+}

Would it be good or possible to have similar counterpart for emit_copy_ccs()?

Quoted 34 lines
drivers/gpu/drm/xe/xe_migrate.c +7 -4
+
 static u64 xe_migrate_batch_base(struct xe_migrate *m, bool usm)
 {
 	return usm ? m->usm_batch_base_ofs : m->batch_base_ofs;
@@ -865,13 +922,15 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
 * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
 * compression PAT index for the data copy.
 * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
- * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * two distinct page sets (old @src_tt pages -> new pages). The data blit is
 * skipped (the data was copied by the @defrag_copy pass) and both the source
 * and destination data pages are mapped with the compression PAT so the aux
 * state is copied indirect -> indirect.
 * @defrag_copy: Defrag move pass that copies the data pages between two
- * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
- * aux state. The data pages are mapped without the compression PAT so the
+ * distinct page sets (old @src_tt pages -> new pages) without touching the CCS
+ * aux state. Pages the new tt borrowed from @src_tt (harvested already
+ * beneficial-order chunks) alias the same memory on both sides and are skipped.
+ * The data pages are mapped without the compression PAT so the
 * (possibly compressed) bytes are copied verbatim rather than being
 * decompressed and recompressed, and no CCS aux copy is appended; the aux
 * state is migrated separately by the @defrag_ccs pass. The two passes need
@@ -889,7 +948,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 					   struct xe_bo *dst_bo,
 					   struct ttm_resource *src,
 					   struct ttm_resource *dst,
-					   struct sg_table *src_sg,
+					   struct ttm_tt *src_tt,
 					   struct xe_migrate_copy_flags flags)
 {
 	struct xe_gt *gt = m->tile->primary_gt;
@@ -914,6 +973,14 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		!flags.defrag_copy;

drivers/gpu/drm/xe/xe_migrate.c static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m, · line 983

Quoted 10 lines
drivers/gpu/drm/xe/xe_migrate.c +8 -0
 	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
 		!flags.defrag_ccs && !flags.defrag_copy;
+	/*
+	 * On the defrag data pass the new (destination) tt may have borrowed
+	 * already beneficial-order pages from the old (source) tt, so skip the
+	 * self-copy for any page they share. Compare the tt page arrays at the
+	 * matching offset.
+	 */
+	struct ttm_tt *dst_tt = dst_bo->ttm.ttm;
+	bool skip_borrowed = flags.defrag_copy && src_tt && dst_tt;

I think for our case src_tt and and dst_tt check is redundant here as they will always be set for defrag_copy. May be add an assert instead of checking?

Niranjana

Quoted 171 lines
drivers/gpu/drm/xe/xe_migrate.c +49 -12
 	/*
 	 * For decompression operation, always use the compression PAT index.
@@ -926,7 +993,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 
 	/*
 	 * The defrag CCS pass migrates the aux state from the old pages
-	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * (@src_tt) to the new pages with both sides accessed indirectly, so
 	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
 	 */
 
@@ -938,7 +1005,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(-EINVAL);
 
 	if (!src_is_vram)
-		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo), 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 	if (!dst_is_vram)
@@ -947,7 +1014,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		xe_res_first(dst, 0, size, &dst_it);
 
 	if (copy_system_ccs)
-		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo),
 				xe_bo_ccs_pages_start(src_bo),
 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 				&ccs_it);
@@ -961,6 +1028,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		u64 ccs_ofs, ccs_size;
 		u32 ccs_pt;
 		u32 pte_flags;
+		pgoff_t start_page = (xe_bo_size(src_bo) - size) >> PAGE_SHIFT;
+		u32 ndata_blits = 1;
 
 		bool usm = xe->info.has_usm;
 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
@@ -998,9 +1067,30 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 			xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
 		}
 
-		/* Add copy commands size here */
+		/*
+		 * Add copy commands size here. On the defrag data pass the blit
+		 * is split into one command per run of non-borrowed pages, so
+		 * size for the number of runs actually needed.
+		 */
+		if (skip_borrowed)
+			ndata_blits = emit_copy_chunks(gt, NULL, 0, 0, src_L0,
+						       src_tt, dst_tt, start_page);
+
+		/*
+		 * If every page in this chunk was borrowed there is nothing to
+		 * copy: don't build a batch or issue any GPU commands, just
+		 * advance the cursors past the chunk. The non-vram tt cursors
+		 * would otherwise be advanced by emit_pte().
+		 */
+		if (skip_borrowed && !ndata_blits) {
+			xe_res_next(&src_it, src_L0);
+			xe_res_next(&dst_it, src_L0);
+			size -= src_L0;
+			continue;
+		}
+
 		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
-			       emit_copy_cmd_len(xe)) +
+			       ndata_blits * emit_copy_cmd_len(xe)) +
 			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
 
 		bb = xe_bb_new(gt, batch_size, usm);
@@ -1029,7 +1119,10 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
 		update_idx = bb->len;
 
-		if (!flags.copy_only_ccs && !flags.defrag_ccs)
+		if (skip_borrowed)
+			emit_copy_chunks(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0,
+					 src_tt, dst_tt, start_page);
+		else if (!flags.copy_only_ccs && !flags.defrag_ccs)
 			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
 
 		if (needs_ccs_emit)
@@ -1088,6 +1181,14 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(err);
 	}
 
+	/*
+	 * Every chunk of a defrag data pass may have been borrowed (nothing
+	 * copied), leaving no job and a NULL fence. Hand back a signaled stub
+	 * so callers always get a valid fence to wait on.
+	 */
+	if (!fence)
+		return dma_fence_get_stub();
+
 	return fence;
 }
 
@@ -1129,18 +1230,21 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
 * @src: The source TTM resource (the old backing).
 * @dst: The dst TTM resource (the freshly reallocated backing).
- * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @src_tt: The source (old) backing tt, providing both the scatter-gather
+ * table and page pointers of the old pages.
 * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
 *
 * Used by the defrag path where a single BO has its backing reallocated at a
 * more beneficial page order. The contents are relocated from the old pages
- * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * (@src_tt) to the new pages (the BO's current backing) entirely on the GPU,
 * in up to two passes:
 *
 *  - Data pass (always): copy the data pages verbatim. The pages are mapped
 *    without the compression PAT, so the (possibly compressed) bytes are copied
 *    as-is rather than being decompressed and recompressed, and no CCS aux copy
- *    is appended.
+ *    is appended. Pages the new backing borrowed from @src_tt (harvested
+ *    already beneficial-order chunks) alias the same memory on both sides and
+ *    are skipped.
 *
 *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
 *    and new data pages are mapped with the compression PAT so the copy engine
@@ -1159,11 +1263,11 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs)
 {
 	struct dma_fence *fence2, *fence =
-		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+		__xe_migrate_copy(m, bo, bo, src, dst, src_tt,
 				  (struct xe_migrate_copy_flags) {
 					 .defrag_copy = true,
 					 });
@@ -1171,7 +1275,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 	if (IS_ERR(fence) || !need_ccs)
 		return fence;
 
-	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_tt,
 				   (struct xe_migrate_copy_flags) {
 				   .defrag_ccs = true,
 				   });
drivers/gpu/drm/xe/xe_migrate.h +2 -1
index e4f996942a6d..4094ea1c19c1 100644
@@ -13,6 +13,7 @@ struct drm_pagemap_addr;
 struct iosys_map;
 struct sg_table;
 struct ttm_resource;
+struct ttm_tt;
 
 struct xe_bo;
 struct xe_gt;
@@ -137,7 +138,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs);
 
 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
Signature · 1 line
2.34.1
author maintainer
#78 lore raw

Re: [PATCH v3 19/33] drm/xe: Skip self-copies for borrowed pages on defrag moves

Quoted 74 lines · Niranjana Vishwanathapura
Quoted 73 lines · Matthew Brost

A defrag move may harvest already beneficial-order chunks from the old tt, so the freshly reallocated backing borrows (references) some of the same physical pages. For those pages the source and destination GPU mappings alias the same memory, making the data blit a pointless self-copy.

Pass the source (old) tt into __xe_migrate_copy() instead of just its sg table, so the data pass can compare the src and dst tt page arrays at the matching offset and only blit runs of pages that actually differ. A new emit_copy_chunks() helper walks each L0 chunk, skips borrowed-page runs, and coalesces contiguous to-copy pages into a single emit_copy(). It runs twice per chunk: once with a NULL batch buffer to count the blits for batch sizing, then again to emit them.

When an entire L0 chunk turns out to be borrowed, skip it outright: no batch buffer is allocated and no GPU commands are issued, the cursors are just advanced past the chunk. If every chunk of the move is borrowed the copy is a complete no-op, so hand back a signaled stub fence.

The comparison is a cheap per-page pointer test (src page != dst page) that coalesces contiguous to-copy pages into a single blit. PTEs are still emitted for partially borrowed chunks, since that setup is cheap and only the data copies are worth skipping. Only the defrag data pass is affected; the separate CCS pass still migrates all aux state.

Since the Xe tt sg lives in the xe_ttm_tt subclass rather than the base ttm_tt, add an xe_tt_sg() helper to fetch it from a struct ttm_tt.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

----

v3:
- Fix start_page page-shift and blit pitch for src-natural to dst-packed copies (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c      |  22 +++++-
drivers/gpu/drm/xe/xe_bo.h      |   2 +
drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
drivers/gpu/drm/xe/xe_migrate.h |   3 +-
4 files changed, 142 insertions(+), 21 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +9 -0
index bdcc9bed5d36..7f6ee9b8d12e 100644
@@ -473,6 +473,22 @@ struct sg_table *xe_bo_sg(struct xe_bo *bo)
 	return xe_tt->sg;
 }
 
+/**
+ * xe_tt_sg() - Return the DMA scatter-gather table backing a ttm_tt.
+ * @tt: The ttm_tt to query.
+ *
+ * Like xe_bo_sg(), but takes the ttm_tt directly. Used by the defrag copy
+ * path which needs the old (source) tt's sg table without a backing xe_bo.
+ *
+ * Return: The sg table, or NULL if the tt is not currently mapped.
+ */
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c struct sg_table *xe_bo_sg(struct xe_bo *bo) · line 490

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+struct sg_table *xe_tt_sg(struct ttm_tt *tt)
+{
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	return xe_tt->sg;
+}
Assisted-by LLM

Yes.

Quoted 3 lines

xe_tt->sg can be potentially NULL (though probably not in current usecase). Probably an explicit assert better?

Sashiko consisently tells asserts like that are useless and an assert pops and then you immediately NULL ptr deref. I tend to agree with that line of thinking.

Quoted 68 lines
Quoted 68 lines
drivers/gpu/drm/xe/xe_bo.c +3 -4
+
 /*
 * Account ttm pages against the device shrinker's shrinkable and
 * purgeable counts.
@@ -1290,11 +1306,9 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
 	} else if (ttm_bo->defrag_old_tt) {
-		struct xe_ttm_tt *old_xe_tt =
-			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
-
 		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
-					       old_xe_tt->sg, handle_system_ccs);
+					       ttm_bo->defrag_old_tt,
+					       handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
drivers/gpu/drm/xe/xe_bo.h +2 -0
index 4186cb51af87..32211016a722 100644
@@ -110,6 +110,7 @@ enum xe_madv_purgeable_state {
 };
 
 struct sg_table;
+struct ttm_tt;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -547,6 +548,7 @@ void xe_bo_dev_init(struct xe_bo_dev *bo_device);
 void xe_bo_dev_fini(struct xe_bo_dev *bo_device);
 
 struct sg_table *xe_bo_sg(struct xe_bo *bo);
+struct sg_table *xe_tt_sg(struct ttm_tt *tt);
 
 /*
 * xe_sg_segment_size() - Provides upper limit for sg segment size.
drivers/gpu/drm/xe/xe_migrate.c +22 -0
index 305c6e1942fb..9990a7144a9f 100644
@@ -811,6 +811,63 @@ static void emit_copy(struct xe_gt *gt, struct xe_bb *bb,
 		emit_xy_fast_copy(gt, bb, src_ofs, dst_ofs, size, pitch);
 }
 
+/*
+ * emit_copy_chunks() - Emit the data blits for one defrag L0 chunk, skipping
+ * borrowed pages.
+ * @gt: The GT.
+ * @bb: The batch buffer to emit into, or NULL to only count the blits needed.
+ * @src_L0_ofs: GPU offset of the source pages mapped for this L0 chunk.
+ * @dst_L0_ofs: GPU offset of the destination pages mapped for this L0 chunk.
+ * @src_L0: Byte size of the L0 chunk (page aligned).
+ * @src_tt: Source (old) tt providing the page pointers.
+ * @dst_tt: Destination (new) tt providing the page pointers.
+ * @start_page: Page offset of this L0 chunk within the tt page arrays.
+ *
+ * A defragmentation move may harvest already beneficial-order chunks from the
+ * old tt, so the new tt references (borrows) some of the same physical pages.
+ * For those pages the source and destination GPU mappings alias the same
+ * memory and the data blit is a pointless self-copy. Walk the L0 chunk and
+ * only blit runs of pages that actually differ (src page != dst page),
+ * coalescing contiguous to-copy pages into a single blit.
+ *
+ * Return: The number of blits emitted (or that would be emitted when @bb is
+ * NULL).
+ */
Quoted 9 lines

drivers/gpu/drm/xe/xe_migrate.c static void emit_copy(struct xe_gt *gt, struct xe_bb *bb, · line 840

Quoted 5 lines
drivers/gpu/drm/xe/xe_migrate.c +5 -0
+static u32 emit_copy_chunks(struct xe_gt *gt, struct xe_bb *bb,
+			    u64 src_L0_ofs, u64 dst_L0_ofs, u32 src_L0,
+			    struct ttm_tt *src_tt, struct ttm_tt *dst_tt,
+			    pgoff_t start_page)
+{

emit_copy() doesn't have L0 in parameter names. Probably it is worth keeping it consistent here also?

Sure.

Quoted 23 lines
Quoted 23 lines
drivers/gpu/drm/xe/xe_migrate.c +23 -0
+	u32 npages = src_L0 >> PAGE_SHIFT;
+	u32 i = 0, nblits = 0;
+
+	while (i < npages) {
+		u32 run = 0;
+
+		/* Skip a run of borrowed pages (src and dst alias). */
+		if (src_tt->pages[start_page + i] ==
+		    dst_tt->pages[start_page + i]) {
+			i++;
+			continue;
+		}
+
+		/* Coalesce a run of pages that actually need copying. */
+		while (i + run < npages &&
+		       src_tt->pages[start_page + i + run] !=
+		       dst_tt->pages[start_page + i + run])
+			run++;
+
+		if (bb)
+			emit_copy(gt, bb, src_L0_ofs + (u64)i * PAGE_SIZE,
+				  dst_L0_ofs + (u64)i * PAGE_SIZE,
+				  run * PAGE_SIZE, XE_PAGE_SIZE);
Quoted 9 lines

drivers/gpu/drm/xe/xe_migrate.c static void emit_copy(struct xe_gt *gt, struct xe_bb *bb, · line 869

Quoted 6 lines
drivers/gpu/drm/xe/xe_migrate.c +6 -0
+		nblits++;
+		i += run;
+	}
+
+	return nblits;
+}

Would it be good or possible to have similar counterpart for emit_copy_ccs()?

I didn't do that as CCS ratio is 1/512 (iirc) of BO size thus not time critical. e.g., 1G buffer with a 32M defrag is 32M + 2M CCS copy.

Quoted 39 lines
Quoted 39 lines
drivers/gpu/drm/xe/xe_migrate.c +10 -4
+
 static u64 xe_migrate_batch_base(struct xe_migrate *m, bool usm)
 {
 	return usm ? m->usm_batch_base_ofs : m->batch_base_ofs;
@@ -865,13 +922,15 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
 * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
 * compression PAT index for the data copy.
 * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
- * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * two distinct page sets (old @src_tt pages -> new pages). The data blit is
 * skipped (the data was copied by the @defrag_copy pass) and both the source
 * and destination data pages are mapped with the compression PAT so the aux
 * state is copied indirect -> indirect.
 * @defrag_copy: Defrag move pass that copies the data pages between two
- * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
- * aux state. The data pages are mapped without the compression PAT so the
+ * distinct page sets (old @src_tt pages -> new pages) without touching the CCS
+ * aux state. Pages the new tt borrowed from @src_tt (harvested already
+ * beneficial-order chunks) alias the same memory on both sides and are skipped.
+ * The data pages are mapped without the compression PAT so the
 * (possibly compressed) bytes are copied verbatim rather than being
 * decompressed and recompressed, and no CCS aux copy is appended; the aux
 * state is migrated separately by the @defrag_ccs pass. The two passes need
@@ -889,7 +948,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 					   struct xe_bo *dst_bo,
 					   struct ttm_resource *src,
 					   struct ttm_resource *dst,
-					   struct sg_table *src_sg,
+					   struct ttm_tt *src_tt,
 					   struct xe_migrate_copy_flags flags)
 {
 	struct xe_gt *gt = m->tile->primary_gt;
@@ -914,6 +973,14 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		!flags.defrag_copy;
 	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
 		!flags.defrag_ccs && !flags.defrag_copy;
+	/*
+	 * On the defrag data pass the new (destination) tt may have borrowed
+	 * already beneficial-order pages from the old (source) tt, so skip the
Quoted 9 lines

drivers/gpu/drm/xe/xe_migrate.c static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m, · line 983

Quoted 5 lines
drivers/gpu/drm/xe/xe_migrate.c +5 -0
+	 * self-copy for any page they share. Compare the tt page arrays at the
+	 * matching offset.
+	 */
+	struct ttm_tt *dst_tt = dst_bo->ttm.ttm;
+	bool skip_borrowed = flags.defrag_copy && src_tt && dst_tt;

I think for our case src_tt and and dst_tt check is redundant here as they will always be set for defrag_copy. May be add an assert instead of checking?

I think that right but will have to double check this true on HW.

Matt

Quoted 173 lines

Niranjana

Quoted 171 lines
drivers/gpu/drm/xe/xe_migrate.c +49 -12
 	/*
 	 * For decompression operation, always use the compression PAT index.
@@ -926,7 +993,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 
 	/*
 	 * The defrag CCS pass migrates the aux state from the old pages
-	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * (@src_tt) to the new pages with both sides accessed indirectly, so
 	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
 	 */
 
@@ -938,7 +1005,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(-EINVAL);
 
 	if (!src_is_vram)
-		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo), 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 	if (!dst_is_vram)
@@ -947,7 +1014,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		xe_res_first(dst, 0, size, &dst_it);
 
 	if (copy_system_ccs)
-		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo),
 				xe_bo_ccs_pages_start(src_bo),
 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 				&ccs_it);
@@ -961,6 +1028,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		u64 ccs_ofs, ccs_size;
 		u32 ccs_pt;
 		u32 pte_flags;
+		pgoff_t start_page = (xe_bo_size(src_bo) - size) >> PAGE_SHIFT;
+		u32 ndata_blits = 1;
 
 		bool usm = xe->info.has_usm;
 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
@@ -998,9 +1067,30 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 			xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
 		}
 
-		/* Add copy commands size here */
+		/*
+		 * Add copy commands size here. On the defrag data pass the blit
+		 * is split into one command per run of non-borrowed pages, so
+		 * size for the number of runs actually needed.
+		 */
+		if (skip_borrowed)
+			ndata_blits = emit_copy_chunks(gt, NULL, 0, 0, src_L0,
+						       src_tt, dst_tt, start_page);
+
+		/*
+		 * If every page in this chunk was borrowed there is nothing to
+		 * copy: don't build a batch or issue any GPU commands, just
+		 * advance the cursors past the chunk. The non-vram tt cursors
+		 * would otherwise be advanced by emit_pte().
+		 */
+		if (skip_borrowed && !ndata_blits) {
+			xe_res_next(&src_it, src_L0);
+			xe_res_next(&dst_it, src_L0);
+			size -= src_L0;
+			continue;
+		}
+
 		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
-			       emit_copy_cmd_len(xe)) +
+			       ndata_blits * emit_copy_cmd_len(xe)) +
 			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
 
 		bb = xe_bb_new(gt, batch_size, usm);
@@ -1029,7 +1119,10 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
 		update_idx = bb->len;
 
-		if (!flags.copy_only_ccs && !flags.defrag_ccs)
+		if (skip_borrowed)
+			emit_copy_chunks(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0,
+					 src_tt, dst_tt, start_page);
+		else if (!flags.copy_only_ccs && !flags.defrag_ccs)
 			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
 
 		if (needs_ccs_emit)
@@ -1088,6 +1181,14 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(err);
 	}
 
+	/*
+	 * Every chunk of a defrag data pass may have been borrowed (nothing
+	 * copied), leaving no job and a NULL fence. Hand back a signaled stub
+	 * so callers always get a valid fence to wait on.
+	 */
+	if (!fence)
+		return dma_fence_get_stub();
+
 	return fence;
 }
 
@@ -1129,18 +1230,21 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
 * @src: The source TTM resource (the old backing).
 * @dst: The dst TTM resource (the freshly reallocated backing).
- * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @src_tt: The source (old) backing tt, providing both the scatter-gather
+ * table and page pointers of the old pages.
 * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
 *
 * Used by the defrag path where a single BO has its backing reallocated at a
 * more beneficial page order. The contents are relocated from the old pages
- * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * (@src_tt) to the new pages (the BO's current backing) entirely on the GPU,
 * in up to two passes:
 *
 *  - Data pass (always): copy the data pages verbatim. The pages are mapped
 *    without the compression PAT, so the (possibly compressed) bytes are copied
 *    as-is rather than being decompressed and recompressed, and no CCS aux copy
- *    is appended.
+ *    is appended. Pages the new backing borrowed from @src_tt (harvested
+ *    already beneficial-order chunks) alias the same memory on both sides and
+ *    are skipped.
 *
 *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
 *    and new data pages are mapped with the compression PAT so the copy engine
@@ -1159,11 +1263,11 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs)
 {
 	struct dma_fence *fence2, *fence =
-		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+		__xe_migrate_copy(m, bo, bo, src, dst, src_tt,
 				  (struct xe_migrate_copy_flags) {
 					 .defrag_copy = true,
 					 });
@@ -1171,7 +1275,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 	if (IS_ERR(fence) || !need_ccs)
 		return fence;
 
-	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_tt,
 				   (struct xe_migrate_copy_flags) {
 				   .defrag_ccs = true,
 				   });
drivers/gpu/drm/xe/xe_migrate.h +2 -1
index e4f996942a6d..4094ea1c19c1 100644
@@ -13,6 +13,7 @@ struct drm_pagemap_addr;
 struct iosys_map;
 struct sg_table;
 struct ttm_resource;
+struct ttm_tt;
 
 struct xe_bo;
 struct xe_gt;
@@ -137,7 +138,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs);
 
 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
Signature · 1 line
2.34.1
author maintainer
#79 lore raw

Re: [PATCH v3 19/33] drm/xe: Skip self-copies for borrowed pages on defrag moves

Quoted 208 lines · Matthew Brost
Quoted 74 lines · Niranjana Vishwanathapura
Quoted 73 lines · Matthew Brost

A defrag move may harvest already beneficial-order chunks from the old tt, so the freshly reallocated backing borrows (references) some of the same physical pages. For those pages the source and destination GPU mappings alias the same memory, making the data blit a pointless self-copy.

Pass the source (old) tt into __xe_migrate_copy() instead of just its sg table, so the data pass can compare the src and dst tt page arrays at the matching offset and only blit runs of pages that actually differ. A new emit_copy_chunks() helper walks each L0 chunk, skips borrowed-page runs, and coalesces contiguous to-copy pages into a single emit_copy(). It runs twice per chunk: once with a NULL batch buffer to count the blits for batch sizing, then again to emit them.

When an entire L0 chunk turns out to be borrowed, skip it outright: no batch buffer is allocated and no GPU commands are issued, the cursors are just advanced past the chunk. If every chunk of the move is borrowed the copy is a complete no-op, so hand back a signaled stub fence.

The comparison is a cheap per-page pointer test (src page != dst page) that coalesces contiguous to-copy pages into a single blit. PTEs are still emitted for partially borrowed chunks, since that setup is cheap and only the data copies are worth skipping. Only the defrag data pass is affected; the separate CCS pass still migrates all aux state.

Since the Xe tt sg lives in the xe_ttm_tt subclass rather than the base ttm_tt, add an xe_tt_sg() helper to fetch it from a struct ttm_tt.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

----

v3:
- Fix start_page page-shift and blit pitch for src-natural to dst-packed copies (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c      |  22 +++++-
drivers/gpu/drm/xe/xe_bo.h      |   2 +
drivers/gpu/drm/xe/xe_migrate.c | 136 ++++++++++++++++++++++++++++----
drivers/gpu/drm/xe/xe_migrate.h |   3 +-
4 files changed, 142 insertions(+), 21 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +9 -0
index bdcc9bed5d36..7f6ee9b8d12e 100644
@@ -473,6 +473,22 @@ struct sg_table *xe_bo_sg(struct xe_bo *bo)
 	return xe_tt->sg;
 }
 
+/**
+ * xe_tt_sg() - Return the DMA scatter-gather table backing a ttm_tt.
+ * @tt: The ttm_tt to query.
+ *
+ * Like xe_bo_sg(), but takes the ttm_tt directly. Used by the defrag copy
+ * path which needs the old (source) tt's sg table without a backing xe_bo.
+ *
+ * Return: The sg table, or NULL if the tt is not currently mapped.
+ */
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c struct sg_table *xe_bo_sg(struct xe_bo *bo) · line 490

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+struct sg_table *xe_tt_sg(struct ttm_tt *tt)
+{
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	return xe_tt->sg;
+}
Assisted-by LLM

Yes.

Quoted 3 lines

xe_tt->sg can be potentially NULL (though probably not in current usecase). Probably an explicit assert better?

Sashiko consisently tells asserts like that are useless and an assert pops and then you immediately NULL ptr deref. I tend to agree with that line of thinking.

Quoted 68 lines
Quoted 68 lines
drivers/gpu/drm/xe/xe_bo.c +3 -4
+
 /*
 * Account ttm pages against the device shrinker's shrinkable and
 * purgeable counts.
@@ -1290,11 +1306,9 @@ static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 
 		fence = xe_migrate_clear(migrate, bo, new_mem, flags);
 	} else if (ttm_bo->defrag_old_tt) {
-		struct xe_ttm_tt *old_xe_tt =
-			container_of(ttm_bo->defrag_old_tt, struct xe_ttm_tt, ttm);
-
 		fence = xe_migrate_copy_defrag(migrate, bo, old_mem, new_mem,
-					       old_xe_tt->sg, handle_system_ccs);
+					       ttm_bo->defrag_old_tt,
+					       handle_system_ccs);
 	} else {
 		fence = xe_migrate_copy(migrate, bo, bo, old_mem, new_mem,
 					handle_system_ccs);
drivers/gpu/drm/xe/xe_bo.h +2 -0
index 4186cb51af87..32211016a722 100644
@@ -110,6 +110,7 @@ enum xe_madv_purgeable_state {
 };
 
 struct sg_table;
+struct ttm_tt;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -547,6 +548,7 @@ void xe_bo_dev_init(struct xe_bo_dev *bo_device);
 void xe_bo_dev_fini(struct xe_bo_dev *bo_device);
 
 struct sg_table *xe_bo_sg(struct xe_bo *bo);
+struct sg_table *xe_tt_sg(struct ttm_tt *tt);
 
 /*
 * xe_sg_segment_size() - Provides upper limit for sg segment size.
drivers/gpu/drm/xe/xe_migrate.c +22 -0
index 305c6e1942fb..9990a7144a9f 100644
@@ -811,6 +811,63 @@ static void emit_copy(struct xe_gt *gt, struct xe_bb *bb,
 		emit_xy_fast_copy(gt, bb, src_ofs, dst_ofs, size, pitch);
 }
 
+/*
+ * emit_copy_chunks() - Emit the data blits for one defrag L0 chunk, skipping
+ * borrowed pages.
+ * @gt: The GT.
+ * @bb: The batch buffer to emit into, or NULL to only count the blits needed.
+ * @src_L0_ofs: GPU offset of the source pages mapped for this L0 chunk.
+ * @dst_L0_ofs: GPU offset of the destination pages mapped for this L0 chunk.
+ * @src_L0: Byte size of the L0 chunk (page aligned).
+ * @src_tt: Source (old) tt providing the page pointers.
+ * @dst_tt: Destination (new) tt providing the page pointers.
+ * @start_page: Page offset of this L0 chunk within the tt page arrays.
+ *
+ * A defragmentation move may harvest already beneficial-order chunks from the
+ * old tt, so the new tt references (borrows) some of the same physical pages.
+ * For those pages the source and destination GPU mappings alias the same
+ * memory and the data blit is a pointless self-copy. Walk the L0 chunk and
+ * only blit runs of pages that actually differ (src page != dst page),
+ * coalescing contiguous to-copy pages into a single blit.
+ *
+ * Return: The number of blits emitted (or that would be emitted when @bb is
+ * NULL).
+ */
Quoted 9 lines

drivers/gpu/drm/xe/xe_migrate.c static void emit_copy(struct xe_gt *gt, struct xe_bb *bb, · line 840

Quoted 5 lines
drivers/gpu/drm/xe/xe_migrate.c +5 -0
+static u32 emit_copy_chunks(struct xe_gt *gt, struct xe_bb *bb,
+			    u64 src_L0_ofs, u64 dst_L0_ofs, u32 src_L0,
+			    struct ttm_tt *src_tt, struct ttm_tt *dst_tt,
+			    pgoff_t start_page)
+{

emit_copy() doesn't have L0 in parameter names. Probably it is worth keeping it consistent here also?

Sure.

Quoted 23 lines
Quoted 23 lines
drivers/gpu/drm/xe/xe_migrate.c +23 -0
+	u32 npages = src_L0 >> PAGE_SHIFT;
+	u32 i = 0, nblits = 0;
+
+	while (i < npages) {
+		u32 run = 0;
+
+		/* Skip a run of borrowed pages (src and dst alias). */
+		if (src_tt->pages[start_page + i] ==
+		    dst_tt->pages[start_page + i]) {
+			i++;
+			continue;
+		}
+
+		/* Coalesce a run of pages that actually need copying. */
+		while (i + run < npages &&
+		       src_tt->pages[start_page + i + run] !=
+		       dst_tt->pages[start_page + i + run])
+			run++;
+
+		if (bb)
+			emit_copy(gt, bb, src_L0_ofs + (u64)i * PAGE_SIZE,
+				  dst_L0_ofs + (u64)i * PAGE_SIZE,
+				  run * PAGE_SIZE, XE_PAGE_SIZE);
Quoted 9 lines

drivers/gpu/drm/xe/xe_migrate.c static void emit_copy(struct xe_gt *gt, struct xe_bb *bb, · line 869

Quoted 6 lines
drivers/gpu/drm/xe/xe_migrate.c +6 -0
+		nblits++;
+		i += run;
+	}
+
+	return nblits;
+}

Would it be good or possible to have similar counterpart for emit_copy_ccs()?

Quoted 3 lines

I didn't do that as CCS ratio is 1/512 (iirc) of BO size thus not time critical. e.g., 1G buffer with a 32M defrag is 32M + 2M CCS copy.

Actuaully I forgot a CCS version is required when the IOVA mapping is partial.

So this patch actually add this functionality but only flipped on when the IOVA mappin is partial:

https://patchwork.freedesktop.org/patch/739373/?series=170216&rev=2

Matt

Quoted 226 lines
Quoted 39 lines
Quoted 39 lines
drivers/gpu/drm/xe/xe_migrate.c +10 -4
+
 static u64 xe_migrate_batch_base(struct xe_migrate *m, bool usm)
 {
 	return usm ? m->usm_batch_base_ofs : m->batch_base_ofs;
@@ -865,13 +922,15 @@ static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
 * @is_vram_resolve: Decompression (VRAM -> system) resolve; always uses the
 * compression PAT index for the data copy.
 * @defrag_ccs: Defrag move pass that migrates only the CCS aux state between
- * two distinct page sets (old @src_sg pages -> new pages). The data blit is
+ * two distinct page sets (old @src_tt pages -> new pages). The data blit is
 * skipped (the data was copied by the @defrag_copy pass) and both the source
 * and destination data pages are mapped with the compression PAT so the aux
 * state is copied indirect -> indirect.
 * @defrag_copy: Defrag move pass that copies the data pages between two
- * distinct page sets (old @src_sg pages -> new pages) without touching the CCS
- * aux state. The data pages are mapped without the compression PAT so the
+ * distinct page sets (old @src_tt pages -> new pages) without touching the CCS
+ * aux state. Pages the new tt borrowed from @src_tt (harvested already
+ * beneficial-order chunks) alias the same memory on both sides and are skipped.
+ * The data pages are mapped without the compression PAT so the
 * (possibly compressed) bytes are copied verbatim rather than being
 * decompressed and recompressed, and no CCS aux copy is appended; the aux
 * state is migrated separately by the @defrag_ccs pass. The two passes need
@@ -889,7 +948,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 					   struct xe_bo *dst_bo,
 					   struct ttm_resource *src,
 					   struct ttm_resource *dst,
-					   struct sg_table *src_sg,
+					   struct ttm_tt *src_tt,
 					   struct xe_migrate_copy_flags flags)
 {
 	struct xe_gt *gt = m->tile->primary_gt;
@@ -914,6 +973,14 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		!flags.defrag_copy;
 	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram) &&
 		!flags.defrag_ccs && !flags.defrag_copy;
+	/*
+	 * On the defrag data pass the new (destination) tt may have borrowed
+	 * already beneficial-order pages from the old (source) tt, so skip the
Quoted 9 lines

drivers/gpu/drm/xe/xe_migrate.c static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m, · line 983

Quoted 5 lines
drivers/gpu/drm/xe/xe_migrate.c +5 -0
+	 * self-copy for any page they share. Compare the tt page arrays at the
+	 * matching offset.
+	 */
+	struct ttm_tt *dst_tt = dst_bo->ttm.ttm;
+	bool skip_borrowed = flags.defrag_copy && src_tt && dst_tt;

I think for our case src_tt and and dst_tt check is redundant here as they will always be set for defrag_copy. May be add an assert instead of checking?

I think that right but will have to double check this true on HW.

Matt

Quoted 173 lines

Niranjana

Quoted 171 lines
drivers/gpu/drm/xe/xe_migrate.c +49 -12
 	/*
 	 * For decompression operation, always use the compression PAT index.
@@ -926,7 +993,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 
 	/*
 	 * The defrag CCS pass migrates the aux state from the old pages
-	 * (@src_sg) to the new pages with both sides accessed indirectly, so
+	 * (@src_tt) to the new pages with both sides accessed indirectly, so
 	 * keep both src_is_pltt and dst_is_pltt set (no direct staging side).
 	 */
 
@@ -938,7 +1005,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(-EINVAL);
 
 	if (!src_is_vram)
-		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo), 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 	if (!dst_is_vram)
@@ -947,7 +1014,7 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		xe_res_first(dst, 0, size, &dst_it);
 
 	if (copy_system_ccs)
-		xe_res_first_sg(src_sg ? src_sg : xe_bo_sg(src_bo),
+		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo),
 				xe_bo_ccs_pages_start(src_bo),
 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 				&ccs_it);
@@ -961,6 +1028,8 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		u64 ccs_ofs, ccs_size;
 		u32 ccs_pt;
 		u32 pte_flags;
+		pgoff_t start_page = (xe_bo_size(src_bo) - size) >> PAGE_SHIFT;
+		u32 ndata_blits = 1;
 
 		bool usm = xe->info.has_usm;
 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
@@ -998,9 +1067,30 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 			xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
 		}
 
-		/* Add copy commands size here */
+		/*
+		 * Add copy commands size here. On the defrag data pass the blit
+		 * is split into one command per run of non-borrowed pages, so
+		 * size for the number of runs actually needed.
+		 */
+		if (skip_borrowed)
+			ndata_blits = emit_copy_chunks(gt, NULL, 0, 0, src_L0,
+						       src_tt, dst_tt, start_page);
+
+		/*
+		 * If every page in this chunk was borrowed there is nothing to
+		 * copy: don't build a batch or issue any GPU commands, just
+		 * advance the cursors past the chunk. The non-vram tt cursors
+		 * would otherwise be advanced by emit_pte().
+		 */
+		if (skip_borrowed && !ndata_blits) {
+			xe_res_next(&src_it, src_L0);
+			xe_res_next(&dst_it, src_L0);
+			size -= src_L0;
+			continue;
+		}
+
 		batch_size += ((flags.copy_only_ccs || flags.defrag_ccs) ? 0 :
-			       emit_copy_cmd_len(xe)) +
+			       ndata_blits * emit_copy_cmd_len(xe)) +
 			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
 
 		bb = xe_bb_new(gt, batch_size, usm);
@@ -1029,7 +1119,10 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
 		update_idx = bb->len;
 
-		if (!flags.copy_only_ccs && !flags.defrag_ccs)
+		if (skip_borrowed)
+			emit_copy_chunks(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0,
+					 src_tt, dst_tt, start_page);
+		else if (!flags.copy_only_ccs && !flags.defrag_ccs)
 			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
 
 		if (needs_ccs_emit)
@@ -1088,6 +1181,14 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(err);
 	}
 
+	/*
+	 * Every chunk of a defrag data pass may have been borrowed (nothing
+	 * copied), leaving no job and a NULL fence. Hand back a signaled stub
+	 * so callers always get a valid fence to wait on.
+	 */
+	if (!fence)
+		return dma_fence_get_stub();
+
 	return fence;
 }
 
@@ -1129,18 +1230,21 @@ struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
 * @bo: The buffer object being defragmented. Both @src and @dst belong to @bo.
 * @src: The source TTM resource (the old backing).
 * @dst: The dst TTM resource (the freshly reallocated backing).
- * @src_sg: Scatter-gather table of the source (old) backing pages.
+ * @src_tt: The source (old) backing tt, providing both the scatter-gather
+ * table and page pointers of the old pages.
 * @need_ccs: Whether the BO has CCS aux state that must be migrated too.
 *
 * Used by the defrag path where a single BO has its backing reallocated at a
 * more beneficial page order. The contents are relocated from the old pages
- * (@src_sg) to the new pages (the BO's current backing) entirely on the GPU,
+ * (@src_tt) to the new pages (the BO's current backing) entirely on the GPU,
 * in up to two passes:
 *
 *  - Data pass (always): copy the data pages verbatim. The pages are mapped
 *    without the compression PAT, so the (possibly compressed) bytes are copied
 *    as-is rather than being decompressed and recompressed, and no CCS aux copy
- *    is appended.
+ *    is appended. Pages the new backing borrowed from @src_tt (harvested
+ *    already beneficial-order chunks) alias the same memory on both sides and
+ *    are skipped.
 *
 *  - CCS pass (@need_ccs): copy the CCS aux (compression) state. Both the old
 *    and new data pages are mapped with the compression PAT so the copy engine
@@ -1159,11 +1263,11 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs)
 {
 	struct dma_fence *fence2, *fence =
-		__xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+		__xe_migrate_copy(m, bo, bo, src, dst, src_tt,
 				  (struct xe_migrate_copy_flags) {
 					 .defrag_copy = true,
 					 });
@@ -1171,7 +1275,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 	if (IS_ERR(fence) || !need_ccs)
 		return fence;
 
-	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_sg,
+	fence2 = __xe_migrate_copy(m, bo, bo, src, dst, src_tt,
 				   (struct xe_migrate_copy_flags) {
 				   .defrag_ccs = true,
 				   });
drivers/gpu/drm/xe/xe_migrate.h +2 -1
index e4f996942a6d..4094ea1c19c1 100644
@@ -13,6 +13,7 @@ struct drm_pagemap_addr;
 struct iosys_map;
 struct sg_table;
 struct ttm_resource;
+struct ttm_tt;
 
 struct xe_bo;
 struct xe_gt;
@@ -137,7 +138,7 @@ struct dma_fence *xe_migrate_copy_defrag(struct xe_migrate *m,
 					 struct xe_bo *bo,
 					 struct ttm_resource *src,
 					 struct ttm_resource *dst,
-					 struct sg_table *src_sg,
+					 struct ttm_tt *src_tt,
 					 bool need_ccs);
 
 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
Signature · 1 line
2.34.1
author maintainer
#80 lore raw

PATCH v3 20/33 drm/xe: Add a page defragmentation worker

In reply to Matthew Brost

BOs whose backing TT pages were allocated below the device's beneficial order (tracked via the TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED tt page flag) are added to a per-device defrag list. Add a delayed worker that periodically walks this list and attempts to re-back each BO with beneficial-order pages, improving TLB efficiency for long-lived objects that were initially allocated under memory pressure.

The worker is kicked when the list first transitions to non-empty and reschedules itself while work remains. On a failed pass it backs off exponentially (XE_BO_DEFRAG_INTERVAL_MS up to XE_BO_DEFRAG_INTERVAL_MAX_MS) and retries the whole list later; the interval is reset to the default on the next fresh enqueue. The worker stops scheduling once the list drains.

A defrag move synchronously reallocates and re-copies a BO's backing store, which is not free. To avoid stalling concurrent active work when many BOs (or one very large BO) become eligible at once (e.g. after a burst of memory pressure, which would otherwise manifest as a large FPS drop while the worker churns through the whole list), cap the number of newly (re)allocated bytes processed per run to XE_BO_DEFRAG_SIZE_LIMIT and reschedule. Only the pages a move actually reallocates are charged - pages harvested (borrowed) from the old backing are free and do not count
- so the budget tracks real defrag work and an object larger than the budget is upgraded in budget-sized slices across runs. This spreads the defrag effort over time, keeping it in the background and yielding to userspace progress.

Defragmenting a BO forces a TTM move (ctx.defrag) that reallocates the backing at the beneficial order and relocates the contents on the GPU (see xe_bo_move()). The per-BO move is bounded by the run's remaining byte budget via ctx.defrag_bytes_remaining; the pool allocator reports how much it spent so the worker can charge it accurately. When beneficial-order pages cannot be obtained the new allocation is discharged during populate and the BO keeps its original backing, staying on the list for a later retry.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Compute the needs-more state under the BO lock via an out-param instead of re-reading bo->ttm.ttm after unlock (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c           | 296 ++++++++++++++++++++++++++-
 drivers/gpu/drm/xe/xe_bo.h           |   1 +
 drivers/gpu/drm/xe/xe_device.c       |   9 +
 drivers/gpu/drm/xe/xe_device_types.h |  11 +
 4 files changed, 313 insertions(+), 4 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +292 -4
index 7f6ee9b8d12e..907cfa57481f 100644
@@ -31,6 +31,7 @@
 #include "xe_pat.h"
 #include "xe_pm.h"
 #include "xe_preempt_fence.h"
+#include "xe_printk.h"
 #include "xe_pxp.h"
 #include "xe_res_cursor.h"
 #include "xe_shrinker.h"
@@ -49,6 +50,35 @@
  */
 #define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
 
+/*
+ * Maximum number of bytes of newly (re)allocated backing the defrag worker will
+ * produce in a single run before yielding and rescheduling itself.
+ *
+ * A defrag move synchronously reallocates and re-copies a BO's backing store,
+ * which is not free. If a large number of BOs (or one very large BO) become
+ * eligible at once (e.g. after a burst of memory pressure), processing them all
+ * in one worker run would hold things up for a long, unbounded stretch and can
+ * visibly starve concurrent active work (e.g. a large FPS drop). Instead, cap
+ * the bytes actually upgraded per run and requeue, spreading the defrag effort
+ * out over time so it stays in the background and yields to userspace progress.
+ * Only pages a move truly reallocates are charged; pages harvested from the old
+ * backing are free, so an object larger than the budget is upgraded in
+ * budget-sized slices across runs.
+ */
+#define XE_BO_DEFRAG_SIZE_LIMIT			SZ_32M
+
+/* Default delay before (re)running the defrag worker, in milliseconds. */
+#define XE_BO_DEFRAG_INTERVAL_MS		25
+
+/*
+ * Upper bound for the (exponentially backed off) defrag worker interval, in
+ * milliseconds, so repeated failures don't push the retry arbitrarily far out.
+ */
+#define XE_BO_DEFRAG_INTERVAL_MAX_MS		15000	/* 15 seconds */
+
+static void xe_bo_defrag_worker(struct work_struct *w);
+static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place);
+
 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
 	[XE_PL_SYSTEM] = "system",
 	[XE_PL_TT] = "gtt",
@@ -624,8 +654,10 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	} else {
 		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
 
-		if (atomic_read(&xe->mem.defrag.count) >=
-		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+		if (ctx->defrag)
+			ctx->beneficial_reclaim_backoff = false;
+		else if (atomic_read(&xe->mem.defrag.count) >=
+			 XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
 			ctx->beneficial_reclaim_backoff = true;
 
 		ttm_tt_clear_backed_up(tt);
@@ -1047,18 +1079,54 @@ static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio
 	return 0;
 }
 
+static void xe_bo_defrag_fini(void *arg)
+{
+	struct xe_device *xe = arg;
+
+	disable_delayed_work_sync(&xe->mem.defrag.worker);
+}
+
 /**
  * xe_bo_defrag_init_early() - Initialize the device defrag BO tracking
  * @xe: The xe device
  *
- * Initialize the list, lock and count used to track BOs whose backing TT
- * pages were allocated at a sub-optimal order.
+ * Initialize the list, lock, count and delayed worker used to track and
+ * defragment BOs whose backing TT pages were allocated at a sub-optimal order.
+ *
+ * The devm action that cancels the worker on teardown is registered separately
+ * by xe_bo_defrag_init(), which must run after the migrate contexts the
+ * worker depends on have been initialized.
  */
 void xe_bo_defrag_init_early(struct xe_device *xe)
 {
 	spin_lock_init(&xe->mem.defrag.lock);
 	INIT_LIST_HEAD(&xe->mem.defrag.list);
 	atomic_set(&xe->mem.defrag.count, 0);
+	xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+	INIT_DELAYED_WORK(&xe->mem.defrag.worker, xe_bo_defrag_worker);
+}
+
+/**
+ * xe_bo_defrag_init() - Register defrag worker teardown
+ * @xe: The xe device
+ *
+ * Register the devm action that disables and drains the defrag worker on
+ * device teardown. This must be called after xe_migrate_init() so that, with
+ * devm's reverse-order cleanup, the worker is stopped before the migrate
+ * contexts it relies on (via xe_bo_defrag_one() -> ttm_bo_validate() ->
+ * xe_bo_move() -> xe_migrate_copy_defrag()) are torn down.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int xe_bo_defrag_init(struct xe_device *xe)
+{
+	return devm_add_action_or_reset(xe->drm.dev, xe_bo_defrag_fini, xe);
+}
+
+static void xe_bo_defrag_schedule(struct xe_device *xe)
+{
+	schedule_delayed_work(&xe->mem.defrag.worker,
+			      msecs_to_jiffies(xe->mem.defrag.interval_ms));
 }
 
 static bool xe_bo_needs_defrag(struct xe_bo *bo)
@@ -1079,16 +1147,24 @@ static bool xe_bo_needs_defrag(struct xe_bo *bo)
 static void xe_bo_defrag_add(struct xe_bo *bo)
 {
 	struct xe_device *xe = xe_bo_device(bo);
+	bool kick = false;
 
 	xe_bo_assert_held(bo);
 	xe_assert(xe, xe_bo_needs_defrag(bo));
 
 	scoped_guard(spinlock, &xe->mem.defrag.lock) {
 		if (list_empty(&bo->defrag_link)) {
+			/* Kick the worker when the list transitions to non-empty. */
+			kick = list_empty(&xe->mem.defrag.list);
+			if (kick)
+				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
 			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
 			atomic_inc(&xe->mem.defrag.count);
 		}
 	}
+
+	if (kick)
+		xe_bo_defrag_schedule(xe);
 }
 
 static void __xe_bo_defrag_remove(struct xe_bo *bo)
@@ -1131,6 +1207,218 @@ static void xe_bo_defrag_update(struct xe_bo *bo)
 		xe_bo_defrag_remove(bo);
 }
 
+/*
+ * Attempt to defragment a single BO by forcing a move that reallocates its
+ * backing at the device's beneficial order. @budget bounds how many bytes of
+ * new pages the move may (re)allocate; the remainder of the object is completed
+ * by harvesting the old backing, and the BO stays flagged for a later pass. On
+ * return *@consumed holds the bytes actually (re)allocated (0 on failure or
+ * when nothing needed reallocating). *@needs_more is set to true when the move
+ * succeeded but the BO still has sub-beneficial backing (partial upgrade) and
+ * should be revisited; it is computed under the BO lock so the caller does not
+ * need to re-inspect bo->ttm.ttm after the lock is dropped. Returns 0 if the BO
+ * no longer needs to be tracked (either defragmented or no longer eligible), or
+ * a negative error code if the attempt should be retried later.
+ */
+static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
+			    u64 budget, u64 *consumed, bool *needs_more)
+{
+	struct ttm_operation_ctx ctx = {
+		.gfp_retry_mayfail = true,
+		.defrag = true,
+		.defrag_bytes_remaining = budget,
+	};
+	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_placement placement;
+	struct ttm_place place;
+	int ret = 0;
+
+	*consumed = 0;
+	*needs_more = false;
+
+	xe_bo_lock(bo, false);
+
+	/* Re-check eligibility under the BO lock. */
+	if (!xe_bo_needs_defrag(bo)) {
+		xe_bo_defrag_remove(bo);
+		goto unlock;
+	}
+
+	xe_place_from_ttm_type(ttm_bo->resource->mem_type, &place);
+	place.flags |= TTM_PL_FLAG_TEMPORARY;
+	placement.num_placement = 1;
+	placement.placement = &place;
+
+	/*
+	 * On success the move reallocates the backing at beneficial order and
+	 * drops the BO from the defrag list. On failure the BO keeps its
+	 * original backing and stays on the list for a later retry.
+	 */
+	ret = ttm_bo_validate(ttm_bo, &placement, &ctx);
+
+	/*
+	 * The pool allocator decremented defrag_bytes_remaining as it
+	 * (re)allocated pages, so the unused budget tells us how much was spent.
+	 * Only meaningful when the move succeeded. A successful move may spend
+	 * nothing - e.g. when the object was already fully upgraded and every
+	 * chunk is harvested (borrowed) from the old backing for free - so a
+	 * zero spend is legitimate and must be charged as zero, not the whole
+	 * budget.
+	 */
+	if (!ret) {
+		s64 spent = (s64)budget - ctx.defrag_bytes_remaining;
+
+		*consumed = spent > 0 ? spent : 0;
+	}
+
+	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
+	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
+
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+		*needs_more = true;
+
+unlock:
+	xe_bo_unlock(bo);
+	return ret;
+}
+
+static void xe_bo_defrag_worker(struct work_struct *w)
+{
+	struct delayed_work *dwork = to_delayed_work(w);
+	struct xe_device *xe =
+		container_of(dwork, struct xe_device, mem.defrag.worker);
+	u64 defrag_bytes = 0;
+	bool requeue = false;
+	int idx;
+
+	if (!drm_dev_enter(&xe->drm, &idx))
+		return;
+
+	if (!xe_pm_runtime_get_if_in_use(xe)) {
+		/*
+		 * The device is (runtime) suspending/suspended. Reschedule so
+		 * the pass retries once it is active again: the enqueue-time
+		 * kick in xe_bo_defrag_add() only fires on an empty->non-empty
+		 * transition, so it will not re-arm the worker while the list
+		 * is still non-empty. Requeue here to avoid stranding tracked
+		 * BOs. The get attempt does not resume the device, so this is
+		 * just a lightweight CPU-side timer while suspended.
+		 */
+		if (atomic_read(&xe->mem.defrag.count))
+			xe_bo_defrag_schedule(xe);
+		drm_dev_exit(idx);
+		return;
+	}
+
+	/*
+	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated
+	 * backing per run rather than draining the whole list in one go. Only
+	 * the pages a move actually reallocates are charged - pages harvested
+	 * (borrowed) from the old backing are free and do not count - so the
+	 * budget tracks real defrag work. A single object larger than the
+	 * budget is upgraded in slices across successive runs. Each defrag is
+	 * synchronous and relatively expensive, so bounding the work per run
+	 * keeps the worker from monopolising resources and lets concurrent
+	 * active work make progress; any remaining work is handled by a
+	 * follow-up run scheduled below.
+	 */
+	while (defrag_bytes < XE_BO_DEFRAG_SIZE_LIMIT) {
+		struct xe_bo *first, *bo;
+		u64 consumed = 0;
+		bool needs_more = false;
+		int ret;
+
+		scoped_guard(spinlock, &xe->mem.defrag.lock) {
+			bool again;
+
+			/* Progress, reset interval */
+			if (defrag_bytes)
+				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+
+			do {
+				first = list_first_entry_or_null(&xe->mem.defrag.list,
+								 struct xe_bo,
+								 defrag_link);
+				bo = first ? xe_bo_get_unless_zero(first) : NULL;
+				again = first && !bo;
+				if (again) {
+					list_del_init(&first->defrag_link);
+					atomic_dec(&xe->mem.defrag.count);
+				}
+			} while (again);
+		}
+
+		if (!bo)
+			break;
+
+		/*
+		 * Bound the per-BO move to the run's remaining byte budget. A
+		 * large object is upgraded in budget-sized slices across runs;
+		 * the slices already upgraded come back as free already-
+		 * beneficial harvests, so each run only spends budget on new
+		 * forward progress.
+		 */
+		ret = xe_bo_defrag_one(xe, bo, XE_BO_DEFRAG_SIZE_LIMIT - defrag_bytes,
+				       &consumed, &needs_more);
+		defrag_bytes += consumed;
+
+		if (ret || needs_more) {
+			scoped_guard(spinlock, &xe->mem.defrag.lock) {
+				if (ret)
+					/*
+					 * Abort the pass and retry the whole
+					 * list later, backing off exponentially
+					 * on every failure.
+					 */
+					xe->mem.defrag.interval_ms =
+						min(xe->mem.defrag.interval_ms * 2,
+						    (unsigned int)XE_BO_DEFRAG_INTERVAL_MAX_MS);
+				else
+					/* Progress, reset interval */
+					xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+			}
+
+			xe_bo_put(bo);
+			requeue = true;
+			break;
+		}
+
+		xe_bo_put(bo);
+	}
+
+	/*
+	 * Decide whether to reschedule:
+	 *
+	 *  - The loop hit its per-run limit (defrag_bytes >=
+	 *    XE_BO_DEFRAG_SIZE_LIMIT): we stopped early to spread the work out,
+	 *    so requeue at the default interval (reset here since this run made
+	 *    progress) whenever the list still has entries.
+	 *
+	 *  - The loop aborted on a failed defrag (requeue): retry later at the
+	 *    backed-off interval computed above.
+	 *
+	 *  - The loop drained the list (broke on the empty list): nothing left to
+	 *    do, so stop scheduling. A fresh enqueue will kick the worker again.
+	 */
+	if (defrag_bytes >= XE_BO_DEFRAG_SIZE_LIMIT) {
+		struct xe_bo *bo;
+
+		scoped_guard(spinlock, &xe->mem.defrag.lock) {
+			bo = list_first_entry_or_null(&xe->mem.defrag.list,
+						      struct xe_bo, defrag_link);
+			xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+		}
+
+		if (bo)
+			xe_bo_defrag_schedule(xe);
+	} else if (requeue) {
+		xe_bo_defrag_schedule(xe);
+	}
+
+	xe_pm_runtime_put(xe);
+	drm_dev_exit(idx);
+}
+
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		      struct ttm_operation_ctx *ctx,
 		      struct ttm_resource *new_mem,
drivers/gpu/drm/xe/xe_bo.h +1 -0
index 32211016a722..38d50f8122cb 100644
@@ -226,6 +226,7 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
 void xe_bo_unpin_external(struct xe_bo *bo);
 void xe_bo_unpin(struct xe_bo *bo);
 void xe_bo_defrag_init_early(struct xe_device *xe);
+int xe_bo_defrag_init(struct xe_device *xe);
 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
 		   struct drm_exec *exec);
 
drivers/gpu/drm/xe/xe_device.c +9 -0
index bb93425a5c70..19d38e14c910 100644
@@ -1069,6 +1069,15 @@ int xe_device_probe(struct xe_device *xe)
 			return err;
 	}
 
+	/*
+	 * Register the defrag worker teardown now that the migrate contexts it
+	 * depends on are initialized, so devm's reverse-order cleanup stops the
+	 * worker before those contexts are torn down.
+	 */
+	err = xe_bo_defrag_init(xe);
+	if (err)
+		return err;
+
 	err = xe_pagefault_init(xe);
 	if (err)
 		return err;
drivers/gpu/drm/xe/xe_device_types.h +11 -0
index 9e6244d8f41b..6e68add4d652 100644
@@ -314,6 +314,17 @@ struct xe_device {
 			 * @mem.defrag.list.
 			 */
 			atomic_t count;
+			/**
+			 * @mem.defrag.worker: Delayed worker that walks
+			 * @mem.defrag.list trying to reallocate BO backing
+			 * store at the device's beneficial order.
+			 */
+			struct delayed_work worker;
+			/**
+			 * @mem.defrag.interval_ms: Reschedule interval for
+			 * @mem.defrag.worker, in milliseconds.
+			 */
+			unsigned int interval_ms;
 		} defrag;
 	} mem;
 
Signature · 1 line
2.34.1
#81 lore raw

Re: [PATCH v3 20/33] drm/xe: Add a page defragmentation worker

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Critical] The defrag worker can be scheduled during probe teardown but is never canceled if probe fails…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Critical] The defrag worker can be scheduled during probe teardown but is never canceled if probe fails early, leading to a UAF of the xe_device.
- [High] The defrag worker continuously polls at a high frequency (40Hz / 25ms) while the device is runtime-suspended or idle, causing significant power regression.
- [High] The defrag worker enters an infinite 40Hz retry loop on the same BO when memory is fragmented, bypassing exponential backoff.
--

--- Patch [20]: [PATCH v3 20/33] drm/xe: Add a page defragmentation worker --- commit 1f23cf5472cb7a98f4987467477a919155eb0dc0
Author: Matthew Brost <[email protected]>
Subject: drm/xe: Add a page defragmentation worker

This patch adds a delayed worker to the DRM XE driver to periodically defragment buffer objects whose backing TT pages were allocated below the optimal order. It bounds the work done per run and applies exponential backoff on failures.

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0

[ ... ]

Quoted 2 lines
drivers/gpu/drm/xe/xe_bo.c +2 -0
+static void xe_bo_defrag_worker(struct work_struct *w)
+{

[ ... ]

Quoted 8 lines
drivers/gpu/drm/xe/xe_bo.c +8 -0
+	if (!drm_dev_enter(&xe->drm, &idx))
+		return;
+
+	if (!xe_pm_runtime_get_if_in_use(xe)) {
+		/*
+		 * The device is (runtime) suspending/suspended. Reschedule so
+		 * the pass retries once it is active again: the enqueue-time
+		 * kick in xe_bo_defrag_add() only fires on an empty->non-empty

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1311

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+		 * transition, so it will not re-arm the worker while the list
+		 * is still non-empty. Requeue here to avoid stranding tracked
+		 * BOs. The get attempt does not resume the device, so this is
+		 * just a lightweight CPU-side timer while suspended.
+		 */
+		if (atomic_read(&xe->mem.defrag.count))
+			xe_bo_defrag_schedule(xe);
+		drm_dev_exit(idx);
+		return;
+	}

[Severity: High]
Will this cause the worker to endlessly poll at a high frequency while the device is suspended?

Looking at xe_bo_defrag_worker() in xe_bo.c, when the device is runtime suspended, xe_pm_runtime_get_if_in_use(xe) returns false. The worker then hits this early return path and schedules itself via xe_bo_defrag_schedule(xe) if the defrag count is non-zero.

Since this rescheduling uses the current interval_ms (which is typically 25ms) and applies no backoff, the worker will repeatedly wake up the CPU every 25ms (40Hz) endlessly while the device is suspended, preventing deep sleep C-states.

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +3 -0
+
+	/*
+	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated

[ ... ]

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+		if (ret || needs_more) {
+			scoped_guard(spinlock, &xe->mem.defrag.lock) {
+				if (ret)
+					/*
+					 * Abort the pass and retry the whole
+					 * list later, backing off exponentially
+					 * on every failure.
+					 */
+					xe->mem.defrag.interval_ms =
+						min(xe->mem.defrag.interval_ms * 2,

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1384

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+						    (unsigned int)XE_BO_DEFRAG_INTERVAL_MAX_MS);
+				else
+					/* Progress, reset interval */
+					xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+			}
+
+			xe_bo_put(bo);
+			requeue = true;
+			break;
+		}

[Severity: High]
Does this create an infinite 40Hz retry loop on the same BO when memory is fragmented, bypassing the exponential backoff?

When xe_bo_defrag_one() successfully satisfies an allocation using lower-order pages, ret is 0 but needs_more is true. In this block, because ret is 0, the else branch resets the interval_ms to 25ms, and the loop breaks with requeue set to true.

Since the BO is never moved to the back of the list or removed, it remains at the head. On the next run in 25ms, the worker attempts to defrag the exact same BO again, likely hitting the exact same fragmentation fallback, and reschedules at 25ms again.

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +3 -0
+
+		xe_bo_put(bo);
+	}

[ ... ]

Quoted 3 lines
drivers/gpu/drm/xe/xe_device.c +0 -0

[ ... ]

drivers/gpu/drm/xe/xe_device.c int xe_device_probe(struct xe_device *xe) · line 1079

Quoted 12 lines
drivers/gpu/drm/xe/xe_device.c +8 -0
@@ -1069,6 +1069,15 @@ int xe_device_probe(struct xe_device *xe)
 			return err;
 	}
 
+	/*
+	 * Register the defrag worker teardown now that the migrate contexts it
+	 * depends on are initialized, so devm's reverse-order cleanup stops the
+	 * worker before those contexts are torn down.
+	 */
+	err = xe_bo_defrag_init(xe);
+	if (err)
+		return err;

[Severity: Critical]
Is there a use-after-free risk if the device probe fails before this point?

The devm action to cleanly cancel the worker (xe_bo_defrag_init) is registered late in xe_device_probe(). If the probe fails before this registration (e.g., during xe_display_init_early() or xe_gt_init()), the devm teardown will unpin BOs.

Unpinning a BO calls xe_bo_unpin() -> xe_bo_defrag_update(), which can schedule the worker. Because the devm cleanup action was never registered, the worker won't be cancelled during teardown, leaving it active after the xe struct is freed.

Quoted 4 lines
drivers/gpu/drm/xe/xe_device.c +1 -0
+
 	err = xe_pagefault_init(xe);
 	if (err)
 		return err;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
#82 lore raw

Re: [PATCH v3 20/33] drm/xe: Add a page defragmentation worker

In reply to Matthew Brost
Quoted 231 lines · Matthew Brost

BOs whose backing TT pages were allocated below the device's beneficial order (tracked via the TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED tt page flag) are added to a per-device defrag list. Add a delayed worker that periodically walks this list and attempts to re-back each BO with beneficial-order pages, improving TLB efficiency for long-lived objects that were initially allocated under memory pressure.

The worker is kicked when the list first transitions to non-empty and reschedules itself while work remains. On a failed pass it backs off exponentially (XE_BO_DEFRAG_INTERVAL_MS up to XE_BO_DEFRAG_INTERVAL_MAX_MS) and retries the whole list later; the interval is reset to the default on the next fresh enqueue. The worker stops scheduling once the list drains.

A defrag move synchronously reallocates and re-copies a BO's backing store, which is not free. To avoid stalling concurrent active work when many BOs (or one very large BO) become eligible at once (e.g. after a burst of memory pressure, which would otherwise manifest as a large FPS drop while the worker churns through the whole list), cap the number of newly (re)allocated bytes processed per run to XE_BO_DEFRAG_SIZE_LIMIT and reschedule. Only the pages a move actually reallocates are charged - pages harvested (borrowed) from the old backing are free and do not count
- so the budget tracks real defrag work and an object larger than the budget is upgraded in budget-sized slices across runs. This spreads the defrag effort over time, keeping it in the background and yielding to userspace progress.

Defragmenting a BO forces a TTM move (ctx.defrag) that reallocates the backing at the beneficial order and relocates the contents on the GPU (see xe_bo_move()). The per-BO move is bounded by the run's remaining byte budget via ctx.defrag_bytes_remaining; the pool allocator reports how much it spent so the worker can charge it accurately. When beneficial-order pages cannot be obtained the new allocation is discharged during populate and the BO keeps its original backing, staying on the list for a later retry.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Compute the needs-more state under the BO lock via an out-param instead of re-reading bo->ttm.ttm after unlock (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c           | 296 ++++++++++++++++++++++++++-
drivers/gpu/drm/xe/xe_bo.h           |   1 +
drivers/gpu/drm/xe/xe_device.c       |   9 +
drivers/gpu/drm/xe/xe_device_types.h |  11 +
4 files changed, 313 insertions(+), 4 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +100 -4
index 7f6ee9b8d12e..907cfa57481f 100644
@@ -31,6 +31,7 @@
 #include "xe_pat.h"
 #include "xe_pm.h"
 #include "xe_preempt_fence.h"
+#include "xe_printk.h"
 #include "xe_pxp.h"
 #include "xe_res_cursor.h"
 #include "xe_shrinker.h"
@@ -49,6 +50,35 @@
 */
 #define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
 
+/*
+ * Maximum number of bytes of newly (re)allocated backing the defrag worker will
+ * produce in a single run before yielding and rescheduling itself.
+ *
+ * A defrag move synchronously reallocates and re-copies a BO's backing store,
+ * which is not free. If a large number of BOs (or one very large BO) become
+ * eligible at once (e.g. after a burst of memory pressure), processing them all
+ * in one worker run would hold things up for a long, unbounded stretch and can
+ * visibly starve concurrent active work (e.g. a large FPS drop). Instead, cap
+ * the bytes actually upgraded per run and requeue, spreading the defrag effort
+ * out over time so it stays in the background and yields to userspace progress.
+ * Only pages a move truly reallocates are charged; pages harvested from the old
+ * backing are free, so an object larger than the budget is upgraded in
+ * budget-sized slices across runs.
+ */
+#define XE_BO_DEFRAG_SIZE_LIMIT			SZ_32M
+
+/* Default delay before (re)running the defrag worker, in milliseconds. */
+#define XE_BO_DEFRAG_INTERVAL_MS		25
+
+/*
+ * Upper bound for the (exponentially backed off) defrag worker interval, in
+ * milliseconds, so repeated failures don't push the retry arbitrarily far out.
+ */
+#define XE_BO_DEFRAG_INTERVAL_MAX_MS		15000	/* 15 seconds */
+
+static void xe_bo_defrag_worker(struct work_struct *w);
+static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place);
+
 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
 	[XE_PL_SYSTEM] = "system",
 	[XE_PL_TT] = "gtt",
@@ -624,8 +654,10 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	} else {
 		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
 
-		if (atomic_read(&xe->mem.defrag.count) >=
-		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+		if (ctx->defrag)
+			ctx->beneficial_reclaim_backoff = false;
+		else if (atomic_read(&xe->mem.defrag.count) >=
+			 XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
 			ctx->beneficial_reclaim_backoff = true;
 
 		ttm_tt_clear_backed_up(tt);
@@ -1047,18 +1079,54 @@ static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio
 	return 0;
 }
 
+static void xe_bo_defrag_fini(void *arg)
+{
+	struct xe_device *xe = arg;
+
+	disable_delayed_work_sync(&xe->mem.defrag.worker);
+}
+
 /**
 * xe_bo_defrag_init_early() - Initialize the device defrag BO tracking
 * @xe: The xe device
 *
- * Initialize the list, lock and count used to track BOs whose backing TT
- * pages were allocated at a sub-optimal order.
+ * Initialize the list, lock, count and delayed worker used to track and
+ * defragment BOs whose backing TT pages were allocated at a sub-optimal order.
+ *
+ * The devm action that cancels the worker on teardown is registered separately
+ * by xe_bo_defrag_init(), which must run after the migrate contexts the
+ * worker depends on have been initialized.
 */
 void xe_bo_defrag_init_early(struct xe_device *xe)
 {
 	spin_lock_init(&xe->mem.defrag.lock);
 	INIT_LIST_HEAD(&xe->mem.defrag.list);
 	atomic_set(&xe->mem.defrag.count, 0);
+	xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+	INIT_DELAYED_WORK(&xe->mem.defrag.worker, xe_bo_defrag_worker);
+}
+
+/**
+ * xe_bo_defrag_init() - Register defrag worker teardown
+ * @xe: The xe device
+ *
+ * Register the devm action that disables and drains the defrag worker on
+ * device teardown. This must be called after xe_migrate_init() so that, with
+ * devm's reverse-order cleanup, the worker is stopped before the migrate
+ * contexts it relies on (via xe_bo_defrag_one() -> ttm_bo_validate() ->
+ * xe_bo_move() -> xe_migrate_copy_defrag()) are torn down.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int xe_bo_defrag_init(struct xe_device *xe)
+{
+	return devm_add_action_or_reset(xe->drm.dev, xe_bo_defrag_fini, xe);
+}
+
+static void xe_bo_defrag_schedule(struct xe_device *xe)
+{
+	schedule_delayed_work(&xe->mem.defrag.worker,
+			      msecs_to_jiffies(xe->mem.defrag.interval_ms));
 }
 
 static bool xe_bo_needs_defrag(struct xe_bo *bo)
@@ -1079,16 +1147,24 @@ static bool xe_bo_needs_defrag(struct xe_bo *bo)
 static void xe_bo_defrag_add(struct xe_bo *bo)
 {
 	struct xe_device *xe = xe_bo_device(bo);
+	bool kick = false;
 
 	xe_bo_assert_held(bo);
 	xe_assert(xe, xe_bo_needs_defrag(bo));
 
 	scoped_guard(spinlock, &xe->mem.defrag.lock) {
 		if (list_empty(&bo->defrag_link)) {
+			/* Kick the worker when the list transitions to non-empty. */
+			kick = list_empty(&xe->mem.defrag.list);
+			if (kick)
+				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
 			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
 			atomic_inc(&xe->mem.defrag.count);
 		}
 	}
+
+	if (kick)
+		xe_bo_defrag_schedule(xe);
 }
 
 static void __xe_bo_defrag_remove(struct xe_bo *bo)
@@ -1131,6 +1207,218 @@ static void xe_bo_defrag_update(struct xe_bo *bo)
 		xe_bo_defrag_remove(bo);
 }
 
+/*
+ * Attempt to defragment a single BO by forcing a move that reallocates its
+ * backing at the device's beneficial order. @budget bounds how many bytes of
+ * new pages the move may (re)allocate; the remainder of the object is completed
+ * by harvesting the old backing, and the BO stays flagged for a later pass. On
+ * return *@consumed holds the bytes actually (re)allocated (0 on failure or
+ * when nothing needed reallocating). *@needs_more is set to true when the move
+ * succeeded but the BO still has sub-beneficial backing (partial upgrade) and
+ * should be revisited; it is computed under the BO lock so the caller does not
+ * need to re-inspect bo->ttm.ttm after the lock is dropped. Returns 0 if the BO
+ * no longer needs to be tracked (either defragmented or no longer eligible), or
+ * a negative error code if the attempt should be retried later.
+ */
+static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
+			    u64 budget, u64 *consumed, bool *needs_more)
+{
+	struct ttm_operation_ctx ctx = {
+		.gfp_retry_mayfail = true,
+		.defrag = true,
+		.defrag_bytes_remaining = budget,

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1239

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+	};
+	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_placement placement;
+	struct ttm_place place;
+	int ret = 0;
+
+	*consumed = 0;
+	*needs_more = false;
+
+	xe_bo_lock(bo, false);
Assisted-by LLM

Instead of waiting for the lock here, would it be worth trylocking it and upon failure move to next bo?

Quoted 59 lines
drivers/gpu/drm/xe/xe_bo.c +59 -0
+
+	/* Re-check eligibility under the BO lock. */
+	if (!xe_bo_needs_defrag(bo)) {
+		xe_bo_defrag_remove(bo);
+		goto unlock;
+	}
+
+	xe_place_from_ttm_type(ttm_bo->resource->mem_type, &place);
+	place.flags |= TTM_PL_FLAG_TEMPORARY;
+	placement.num_placement = 1;
+	placement.placement = &place;
+
+	/*
+	 * On success the move reallocates the backing at beneficial order and
+	 * drops the BO from the defrag list. On failure the BO keeps its
+	 * original backing and stays on the list for a later retry.
+	 */
+	ret = ttm_bo_validate(ttm_bo, &placement, &ctx);
+
+	/*
+	 * The pool allocator decremented defrag_bytes_remaining as it
+	 * (re)allocated pages, so the unused budget tells us how much was spent.
+	 * Only meaningful when the move succeeded. A successful move may spend
+	 * nothing - e.g. when the object was already fully upgraded and every
+	 * chunk is harvested (borrowed) from the old backing for free - so a
+	 * zero spend is legitimate and must be charged as zero, not the whole
+	 * budget.
+	 */
+	if (!ret) {
+		s64 spent = (s64)budget - ctx.defrag_bytes_remaining;
+
+		*consumed = spent > 0 ? spent : 0;
+	}
+
+	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
+	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
+
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+		*needs_more = true;
+
+unlock:
+	xe_bo_unlock(bo);
+	return ret;
+}
+
+static void xe_bo_defrag_worker(struct work_struct *w)
+{
+	struct delayed_work *dwork = to_delayed_work(w);
+	struct xe_device *xe =
+		container_of(dwork, struct xe_device, mem.defrag.worker);
+	u64 defrag_bytes = 0;
+	bool requeue = false;
+	int idx;
+
+	if (!drm_dev_enter(&xe->drm, &idx))
+		return;
+
+	if (!xe_pm_runtime_get_if_in_use(xe)) {
+		/*

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1308

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+		 * The device is (runtime) suspending/suspended. Reschedule so
+		 * the pass retries once it is active again: the enqueue-time
+		 * kick in xe_bo_defrag_add() only fires on an empty->non-empty
+		 * transition, so it will not re-arm the worker while the list
+		 * is still non-empty. Requeue here to avoid stranding tracked
+		 * BOs. The get attempt does not resume the device, so this is
+		 * just a lightweight CPU-side timer while suspended.
+		 */
+		if (atomic_read(&xe->mem.defrag.count))
+			xe_bo_defrag_schedule(xe);

Instead of keep retrying with backoff during suspend, would be good to launch this worker from the resume handler?

Quoted 62 lines
drivers/gpu/drm/xe/xe_bo.c +62 -0
+		drm_dev_exit(idx);
+		return;
+	}
+
+	/*
+	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated
+	 * backing per run rather than draining the whole list in one go. Only
+	 * the pages a move actually reallocates are charged - pages harvested
+	 * (borrowed) from the old backing are free and do not count - so the
+	 * budget tracks real defrag work. A single object larger than the
+	 * budget is upgraded in slices across successive runs. Each defrag is
+	 * synchronous and relatively expensive, so bounding the work per run
+	 * keeps the worker from monopolising resources and lets concurrent
+	 * active work make progress; any remaining work is handled by a
+	 * follow-up run scheduled below.
+	 */
+	while (defrag_bytes < XE_BO_DEFRAG_SIZE_LIMIT) {
+		struct xe_bo *first, *bo;
+		u64 consumed = 0;
+		bool needs_more = false;
+		int ret;
+
+		scoped_guard(spinlock, &xe->mem.defrag.lock) {
+			bool again;
+
+			/* Progress, reset interval */
+			if (defrag_bytes)
+				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+
+			do {
+				first = list_first_entry_or_null(&xe->mem.defrag.list,
+								 struct xe_bo,
+								 defrag_link);
+				bo = first ? xe_bo_get_unless_zero(first) : NULL;
+				again = first && !bo;
+				if (again) {
+					list_del_init(&first->defrag_link);
+					atomic_dec(&xe->mem.defrag.count);
+				}
+			} while (again);
+		}
+
+		if (!bo)
+			break;
+
+		/*
+		 * Bound the per-BO move to the run's remaining byte budget. A
+		 * large object is upgraded in budget-sized slices across runs;
+		 * the slices already upgraded come back as free already-
+		 * beneficial harvests, so each run only spends budget on new
+		 * forward progress.
+		 */
+		ret = xe_bo_defrag_one(xe, bo, XE_BO_DEFRAG_SIZE_LIMIT - defrag_bytes,
+				       &consumed, &needs_more);
+		defrag_bytes += consumed;
+
+		if (ret || needs_more) {
+			scoped_guard(spinlock, &xe->mem.defrag.lock) {
+				if (ret)
+					/*
+					 * Abort the pass and retry the whole
+					 * list later, backing off exponentially

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1380

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+					 * on every failure.
+					 */
+					xe->mem.defrag.interval_ms =
+						min(xe->mem.defrag.interval_ms * 2,
+						    (unsigned int)XE_BO_DEFRAG_INTERVAL_MAX_MS);
+				else
+					/* Progress, reset interval */
+					xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+			}
+

If xe_bo_defrag_one() returns error, code does backoff and retry but with the same BO at the head of the list which can fail again (more so if that BO is a large BO). Not sure if that is fine or we should move the failing bo in the list.

Also, if the BO is large and returns needs_more, code backsoff and retries until that large BO is gets beneficial order. Would it be better instead to move on to other BOs without the backoff?

Quoted 63 lines
drivers/gpu/drm/xe/xe_bo.c +41 -0
+			xe_bo_put(bo);
+			requeue = true;
+			break;
+		}
+
+		xe_bo_put(bo);
+	}
+
+	/*
+	 * Decide whether to reschedule:
+	 *
+	 *  - The loop hit its per-run limit (defrag_bytes >=
+	 *    XE_BO_DEFRAG_SIZE_LIMIT): we stopped early to spread the work out,
+	 *    so requeue at the default interval (reset here since this run made
+	 *    progress) whenever the list still has entries.
+	 *
+	 *  - The loop aborted on a failed defrag (requeue): retry later at the
+	 *    backed-off interval computed above.
+	 *
+	 *  - The loop drained the list (broke on the empty list): nothing left to
+	 *    do, so stop scheduling. A fresh enqueue will kick the worker again.
+	 */
+	if (defrag_bytes >= XE_BO_DEFRAG_SIZE_LIMIT) {
+		struct xe_bo *bo;
+
+		scoped_guard(spinlock, &xe->mem.defrag.lock) {
+			bo = list_first_entry_or_null(&xe->mem.defrag.list,
+						      struct xe_bo, defrag_link);
+			xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+		}
+
+		if (bo)
+			xe_bo_defrag_schedule(xe);
+	} else if (requeue) {
+		xe_bo_defrag_schedule(xe);
+	}
+
+	xe_pm_runtime_put(xe);
+	drm_dev_exit(idx);
+}
+
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		      struct ttm_operation_ctx *ctx,
 		      struct ttm_resource *new_mem,
drivers/gpu/drm/xe/xe_bo.h +1 -0
index 32211016a722..38d50f8122cb 100644
@@ -226,6 +226,7 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
 void xe_bo_unpin_external(struct xe_bo *bo);
 void xe_bo_unpin(struct xe_bo *bo);
 void xe_bo_defrag_init_early(struct xe_device *xe);
+int xe_bo_defrag_init(struct xe_device *xe);
 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
 		   struct drm_exec *exec);
 
drivers/gpu/drm/xe/xe_device.c +0 -0
index bb93425a5c70..19d38e14c910 100644
@@ -1069,6 +1069,15 @@ int xe_device_probe(struct xe_device *xe)
 			return err;
 	}

drivers/gpu/drm/xe/xe_device.c int xe_device_probe(struct xe_device *xe) · line 1080

Quoted 10 lines
drivers/gpu/drm/xe/xe_device.c +9 -0
 
+	/*
+	 * Register the defrag worker teardown now that the migrate contexts it
+	 * depends on are initialized, so devm's reverse-order cleanup stops the
+	 * worker before those contexts are torn down.
+	 */
+	err = xe_bo_defrag_init(xe);
+	if (err)
+		return err;
+

There is a sashiko reported bug here regarding probe failing earlier than this teardown registration causing teardown not waiting for worker to finish. Not sure if there will be any defrag list at that time, but probably work a fix for completeness?

Niranjana

Quoted 28 lines
drivers/gpu/drm/xe/xe_device.c +0 -0
 	err = xe_pagefault_init(xe);
 	if (err)
 		return err;
drivers/gpu/drm/xe/xe_device_types.h +11 -0
index 9e6244d8f41b..6e68add4d652 100644
@@ -314,6 +314,17 @@ struct xe_device {
 			 * @mem.defrag.list.
 			 */
 			atomic_t count;
+			/**
+			 * @mem.defrag.worker: Delayed worker that walks
+			 * @mem.defrag.list trying to reallocate BO backing
+			 * store at the device's beneficial order.
+			 */
+			struct delayed_work worker;
+			/**
+			 * @mem.defrag.interval_ms: Reschedule interval for
+			 * @mem.defrag.worker, in milliseconds.
+			 */
+			unsigned int interval_ms;
 		} defrag;
 	} mem;
 
Signature · 1 line
2.34.1
author maintainer
#83 lore raw

Re: [PATCH v3 20/33] drm/xe: Add a page defragmentation worker

Quoted 236 lines · Niranjana Vishwanathapura
Quoted 235 lines · Matthew Brost

BOs whose backing TT pages were allocated below the device's beneficial order (tracked via the TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED tt page flag) are added to a per-device defrag list. Add a delayed worker that periodically walks this list and attempts to re-back each BO with beneficial-order pages, improving TLB efficiency for long-lived objects that were initially allocated under memory pressure.

The worker is kicked when the list first transitions to non-empty and reschedules itself while work remains. On a failed pass it backs off exponentially (XE_BO_DEFRAG_INTERVAL_MS up to XE_BO_DEFRAG_INTERVAL_MAX_MS) and retries the whole list later; the interval is reset to the default on the next fresh enqueue. The worker stops scheduling once the list drains.

A defrag move synchronously reallocates and re-copies a BO's backing store, which is not free. To avoid stalling concurrent active work when many BOs (or one very large BO) become eligible at once (e.g. after a burst of memory pressure, which would otherwise manifest as a large FPS drop while the worker churns through the whole list), cap the number of newly (re)allocated bytes processed per run to XE_BO_DEFRAG_SIZE_LIMIT and reschedule. Only the pages a move actually reallocates are charged - pages harvested (borrowed) from the old backing are free and do not count
- so the budget tracks real defrag work and an object larger than the budget is upgraded in budget-sized slices across runs. This spreads the defrag effort over time, keeping it in the background and yielding to userspace progress.

Defragmenting a BO forces a TTM move (ctx.defrag) that reallocates the backing at the beneficial order and relocates the contents on the GPU (see xe_bo_move()). The per-BO move is bounded by the run's remaining byte budget via ctx.defrag_bytes_remaining; the pool allocator reports how much it spent so the worker can charge it accurately. When beneficial-order pages cannot be obtained the new allocation is discharged during populate and the BO keeps its original backing, staying on the list for a later retry.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Compute the needs-more state under the BO lock via an out-param instead of re-reading bo->ttm.ttm after unlock (Sashiko)
---

drivers/gpu/drm/xe/xe_bo.c           | 296 ++++++++++++++++++++++++++-
drivers/gpu/drm/xe/xe_bo.h           |   1 +
drivers/gpu/drm/xe/xe_device.c       |   9 +
drivers/gpu/drm/xe/xe_device_types.h |  11 +
4 files changed, 313 insertions(+), 4 deletions(-)
drivers/gpu/drm/xe/xe_bo.c +104 -4
index 7f6ee9b8d12e..907cfa57481f 100644
@@ -31,6 +31,7 @@
 #include "xe_pat.h"
 #include "xe_pm.h"
 #include "xe_preempt_fence.h"
+#include "xe_printk.h"
 #include "xe_pxp.h"
 #include "xe_res_cursor.h"
 #include "xe_shrinker.h"
@@ -49,6 +50,35 @@
 */
 #define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
 
+/*
+ * Maximum number of bytes of newly (re)allocated backing the defrag worker will
+ * produce in a single run before yielding and rescheduling itself.
+ *
+ * A defrag move synchronously reallocates and re-copies a BO's backing store,
+ * which is not free. If a large number of BOs (or one very large BO) become
+ * eligible at once (e.g. after a burst of memory pressure), processing them all
+ * in one worker run would hold things up for a long, unbounded stretch and can
+ * visibly starve concurrent active work (e.g. a large FPS drop). Instead, cap
+ * the bytes actually upgraded per run and requeue, spreading the defrag effort
+ * out over time so it stays in the background and yields to userspace progress.
+ * Only pages a move truly reallocates are charged; pages harvested from the old
+ * backing are free, so an object larger than the budget is upgraded in
+ * budget-sized slices across runs.
+ */
+#define XE_BO_DEFRAG_SIZE_LIMIT			SZ_32M
+
+/* Default delay before (re)running the defrag worker, in milliseconds. */
+#define XE_BO_DEFRAG_INTERVAL_MS		25
+
+/*
+ * Upper bound for the (exponentially backed off) defrag worker interval, in
+ * milliseconds, so repeated failures don't push the retry arbitrarily far out.
+ */
+#define XE_BO_DEFRAG_INTERVAL_MAX_MS		15000	/* 15 seconds */
+
+static void xe_bo_defrag_worker(struct work_struct *w);
+static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place);
+
 const char *const xe_mem_type_to_name[TTM_NUM_MEM_TYPES]  = {
 	[XE_PL_SYSTEM] = "system",
 	[XE_PL_TT] = "gtt",
@@ -624,8 +654,10 @@ static int xe_ttm_tt_populate(struct ttm_device *ttm_dev, struct ttm_tt *tt,
 	} else {
 		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
 
-		if (atomic_read(&xe->mem.defrag.count) >=
-		    XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
+		if (ctx->defrag)
+			ctx->beneficial_reclaim_backoff = false;
+		else if (atomic_read(&xe->mem.defrag.count) >=
+			 XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD)
 			ctx->beneficial_reclaim_backoff = true;
 
 		ttm_tt_clear_backed_up(tt);
@@ -1047,18 +1079,54 @@ static int xe_ttm_bo_purge(struct ttm_buffer_object *ttm_bo, struct ttm_operatio
 	return 0;
 }
 
+static void xe_bo_defrag_fini(void *arg)
+{
+	struct xe_device *xe = arg;
+
+	disable_delayed_work_sync(&xe->mem.defrag.worker);
+}
+
 /**
 * xe_bo_defrag_init_early() - Initialize the device defrag BO tracking
 * @xe: The xe device
 *
- * Initialize the list, lock and count used to track BOs whose backing TT
- * pages were allocated at a sub-optimal order.
+ * Initialize the list, lock, count and delayed worker used to track and
+ * defragment BOs whose backing TT pages were allocated at a sub-optimal order.
+ *
+ * The devm action that cancels the worker on teardown is registered separately
+ * by xe_bo_defrag_init(), which must run after the migrate contexts the
+ * worker depends on have been initialized.
 */
 void xe_bo_defrag_init_early(struct xe_device *xe)
 {
 	spin_lock_init(&xe->mem.defrag.lock);
 	INIT_LIST_HEAD(&xe->mem.defrag.list);
 	atomic_set(&xe->mem.defrag.count, 0);
+	xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+	INIT_DELAYED_WORK(&xe->mem.defrag.worker, xe_bo_defrag_worker);
+}
+
+/**
+ * xe_bo_defrag_init() - Register defrag worker teardown
+ * @xe: The xe device
+ *
+ * Register the devm action that disables and drains the defrag worker on
+ * device teardown. This must be called after xe_migrate_init() so that, with
+ * devm's reverse-order cleanup, the worker is stopped before the migrate
+ * contexts it relies on (via xe_bo_defrag_one() -> ttm_bo_validate() ->
+ * xe_bo_move() -> xe_migrate_copy_defrag()) are torn down.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int xe_bo_defrag_init(struct xe_device *xe)
+{
+	return devm_add_action_or_reset(xe->drm.dev, xe_bo_defrag_fini, xe);
+}
+
+static void xe_bo_defrag_schedule(struct xe_device *xe)
+{
+	schedule_delayed_work(&xe->mem.defrag.worker,
+			      msecs_to_jiffies(xe->mem.defrag.interval_ms));
 }
 
 static bool xe_bo_needs_defrag(struct xe_bo *bo)
@@ -1079,16 +1147,24 @@ static bool xe_bo_needs_defrag(struct xe_bo *bo)
 static void xe_bo_defrag_add(struct xe_bo *bo)
 {
 	struct xe_device *xe = xe_bo_device(bo);
+	bool kick = false;
 
 	xe_bo_assert_held(bo);
 	xe_assert(xe, xe_bo_needs_defrag(bo));
 
 	scoped_guard(spinlock, &xe->mem.defrag.lock) {
 		if (list_empty(&bo->defrag_link)) {
+			/* Kick the worker when the list transitions to non-empty. */
+			kick = list_empty(&xe->mem.defrag.list);
+			if (kick)
+				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
 			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
 			atomic_inc(&xe->mem.defrag.count);
 		}
 	}
+
+	if (kick)
+		xe_bo_defrag_schedule(xe);
 }
 
 static void __xe_bo_defrag_remove(struct xe_bo *bo)
@@ -1131,6 +1207,218 @@ static void xe_bo_defrag_update(struct xe_bo *bo)
 		xe_bo_defrag_remove(bo);
 }
 
+/*
+ * Attempt to defragment a single BO by forcing a move that reallocates its
+ * backing at the device's beneficial order. @budget bounds how many bytes of
+ * new pages the move may (re)allocate; the remainder of the object is completed
+ * by harvesting the old backing, and the BO stays flagged for a later pass. On
+ * return *@consumed holds the bytes actually (re)allocated (0 on failure or
+ * when nothing needed reallocating). *@needs_more is set to true when the move
+ * succeeded but the BO still has sub-beneficial backing (partial upgrade) and
+ * should be revisited; it is computed under the BO lock so the caller does not
+ * need to re-inspect bo->ttm.ttm after the lock is dropped. Returns 0 if the BO
+ * no longer needs to be tracked (either defragmented or no longer eligible), or
+ * a negative error code if the attempt should be retried later.
+ */
+static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
+			    u64 budget, u64 *consumed, bool *needs_more)
+{
+	struct ttm_operation_ctx ctx = {
+		.gfp_retry_mayfail = true,
+		.defrag = true,
+		.defrag_bytes_remaining = budget,
+	};
+	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_placement placement;
+	struct ttm_place place;
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1239

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+	int ret = 0;
+
+	*consumed = 0;
+	*needs_more = false;
+
+	xe_bo_lock(bo, false);
Assisted-by LLM

Yes.

Quoted 3 lines

Instead of waiting for the lock here, would it be worth trylocking it and upon failure move to next bo?

I don't think, this is background worker so really no downside of blocking behind foreground work with the lock.

Also later in the series we pre-alloc pages outside of dma-resv and then just prune it in under dma-resv - a try lock would be quite weird as we'd have to throw away the memory we just tried hard to get.

Quoted 64 lines
Quoted 64 lines
drivers/gpu/drm/xe/xe_bo.c +64 -0
+
+	/* Re-check eligibility under the BO lock. */
+	if (!xe_bo_needs_defrag(bo)) {
+		xe_bo_defrag_remove(bo);
+		goto unlock;
+	}
+
+	xe_place_from_ttm_type(ttm_bo->resource->mem_type, &place);
+	place.flags |= TTM_PL_FLAG_TEMPORARY;
+	placement.num_placement = 1;
+	placement.placement = &place;
+
+	/*
+	 * On success the move reallocates the backing at beneficial order and
+	 * drops the BO from the defrag list. On failure the BO keeps its
+	 * original backing and stays on the list for a later retry.
+	 */
+	ret = ttm_bo_validate(ttm_bo, &placement, &ctx);
+
+	/*
+	 * The pool allocator decremented defrag_bytes_remaining as it
+	 * (re)allocated pages, so the unused budget tells us how much was spent.
+	 * Only meaningful when the move succeeded. A successful move may spend
+	 * nothing - e.g. when the object was already fully upgraded and every
+	 * chunk is harvested (borrowed) from the old backing for free - so a
+	 * zero spend is legitimate and must be charged as zero, not the whole
+	 * budget.
+	 */
+	if (!ret) {
+		s64 spent = (s64)budget - ctx.defrag_bytes_remaining;
+
+		*consumed = spent > 0 ? spent : 0;
+	}
+
+	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
+	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
+
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+		*needs_more = true;
+
+unlock:
+	xe_bo_unlock(bo);
+	return ret;
+}
+
+static void xe_bo_defrag_worker(struct work_struct *w)
+{
+	struct delayed_work *dwork = to_delayed_work(w);
+	struct xe_device *xe =
+		container_of(dwork, struct xe_device, mem.defrag.worker);
+	u64 defrag_bytes = 0;
+	bool requeue = false;
+	int idx;
+
+	if (!drm_dev_enter(&xe->drm, &idx))
+		return;
+
+	if (!xe_pm_runtime_get_if_in_use(xe)) {
+		/*
+		 * The device is (runtime) suspending/suspended. Reschedule so
+		 * the pass retries once it is active again: the enqueue-time
+		 * kick in xe_bo_defrag_add() only fires on an empty->non-empty
+		 * transition, so it will not re-arm the worker while the list
+		 * is still non-empty. Requeue here to avoid stranding tracked
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1308

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +5 -0
+		 * BOs. The get attempt does not resume the device, so this is
+		 * just a lightweight CPU-side timer while suspended.
+		 */
+		if (atomic_read(&xe->mem.defrag.count))
+			xe_bo_defrag_schedule(xe);

Instead of keep retrying with backoff during suspend, would be good to launch this worker from the resume handler?

Yes. I actually made this change locally on my own before this suggestion.

Quoted 68 lines
Quoted 68 lines
drivers/gpu/drm/xe/xe_bo.c +68 -0
+		drm_dev_exit(idx);
+		return;
+	}
+
+	/*
+	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated
+	 * backing per run rather than draining the whole list in one go. Only
+	 * the pages a move actually reallocates are charged - pages harvested
+	 * (borrowed) from the old backing are free and do not count - so the
+	 * budget tracks real defrag work. A single object larger than the
+	 * budget is upgraded in slices across successive runs. Each defrag is
+	 * synchronous and relatively expensive, so bounding the work per run
+	 * keeps the worker from monopolising resources and lets concurrent
+	 * active work make progress; any remaining work is handled by a
+	 * follow-up run scheduled below.
+	 */
+	while (defrag_bytes < XE_BO_DEFRAG_SIZE_LIMIT) {
+		struct xe_bo *first, *bo;
+		u64 consumed = 0;
+		bool needs_more = false;
+		int ret;
+
+		scoped_guard(spinlock, &xe->mem.defrag.lock) {
+			bool again;
+
+			/* Progress, reset interval */
+			if (defrag_bytes)
+				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+
+			do {
+				first = list_first_entry_or_null(&xe->mem.defrag.list,
+								 struct xe_bo,
+								 defrag_link);
+				bo = first ? xe_bo_get_unless_zero(first) : NULL;
+				again = first && !bo;
+				if (again) {
+					list_del_init(&first->defrag_link);
+					atomic_dec(&xe->mem.defrag.count);
+				}
+			} while (again);
+		}
+
+		if (!bo)
+			break;
+
+		/*
+		 * Bound the per-BO move to the run's remaining byte budget. A
+		 * large object is upgraded in budget-sized slices across runs;
+		 * the slices already upgraded come back as free already-
+		 * beneficial harvests, so each run only spends budget on new
+		 * forward progress.
+		 */
+		ret = xe_bo_defrag_one(xe, bo, XE_BO_DEFRAG_SIZE_LIMIT - defrag_bytes,
+				       &consumed, &needs_more);
+		defrag_bytes += consumed;
+
+		if (ret || needs_more) {
+			scoped_guard(spinlock, &xe->mem.defrag.lock) {
+				if (ret)
+					/*
+					 * Abort the pass and retry the whole
+					 * list later, backing off exponentially
+					 * on every failure.
+					 */
+					xe->mem.defrag.interval_ms =
+						min(xe->mem.defrag.interval_ms * 2,
+						    (unsigned int)XE_BO_DEFRAG_INTERVAL_MAX_MS);
+				else
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_update(struct xe_bo *bo) · line 1350

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
+					/* Progress, reset interval */
+					xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+			}
+

If xe_bo_defrag_one() returns error, code does backoff and retry but with the same BO at the head of the list which can fail again (more so if that BO is a large BO). Not sure if that is fine or we should move the failing bo in the list.

Yes, we retry the same BO which I think is fine. See below my next answer relates.

Quoted 3 lines

Also, if the BO is large and returns needs_more, code backsoff and retries until that large BO is gets beneficial order. Would it be better instead to move on to other BOs without the backoff?

Again I don't think so. The defrag worker grabs X amount of 2M pages per pass (default 32M). I don't think it matter which BO is grabs the pages for, the goal is just to drain the entire list eventually. I don't see value in rotating the BO which we grabbing pages for - either we will get pages or not; The BO actually has nothing to do with the memory acquire step.

Quoted 65 lines
Quoted 65 lines
drivers/gpu/drm/xe/xe_bo.c +41 -0
+			xe_bo_put(bo);
+			requeue = true;
+			break;
+		}
+
+		xe_bo_put(bo);
+	}
+
+	/*
+	 * Decide whether to reschedule:
+	 *
+	 *  - The loop hit its per-run limit (defrag_bytes >=
+	 *    XE_BO_DEFRAG_SIZE_LIMIT): we stopped early to spread the work out,
+	 *    so requeue at the default interval (reset here since this run made
+	 *    progress) whenever the list still has entries.
+	 *
+	 *  - The loop aborted on a failed defrag (requeue): retry later at the
+	 *    backed-off interval computed above.
+	 *
+	 *  - The loop drained the list (broke on the empty list): nothing left to
+	 *    do, so stop scheduling. A fresh enqueue will kick the worker again.
+	 */
+	if (defrag_bytes >= XE_BO_DEFRAG_SIZE_LIMIT) {
+		struct xe_bo *bo;
+
+		scoped_guard(spinlock, &xe->mem.defrag.lock) {
+			bo = list_first_entry_or_null(&xe->mem.defrag.list,
+						      struct xe_bo, defrag_link);
+			xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
+		}
+
+		if (bo)
+			xe_bo_defrag_schedule(xe);
+	} else if (requeue) {
+		xe_bo_defrag_schedule(xe);
+	}
+
+	xe_pm_runtime_put(xe);
+	drm_dev_exit(idx);
+}
+
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
 		      struct ttm_operation_ctx *ctx,
 		      struct ttm_resource *new_mem,
drivers/gpu/drm/xe/xe_bo.h +1 -0
index 32211016a722..38d50f8122cb 100644
@@ -226,6 +226,7 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
 void xe_bo_unpin_external(struct xe_bo *bo);
 void xe_bo_unpin(struct xe_bo *bo);
 void xe_bo_defrag_init_early(struct xe_device *xe);
+int xe_bo_defrag_init(struct xe_device *xe);
 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
 		   struct drm_exec *exec);
 
drivers/gpu/drm/xe/xe_device.c +0 -0
index bb93425a5c70..19d38e14c910 100644
@@ -1069,6 +1069,15 @@ int xe_device_probe(struct xe_device *xe)
 			return err;
 	}
 
Quoted 15 lines

drivers/gpu/drm/xe/xe_device.c int xe_device_probe(struct xe_device *xe) · line 1080

Quoted 9 lines
drivers/gpu/drm/xe/xe_device.c +9 -0
+	/*
+	 * Register the defrag worker teardown now that the migrate contexts it
+	 * depends on are initialized, so devm's reverse-order cleanup stops the
+	 * worker before those contexts are torn down.
+	 */
+	err = xe_bo_defrag_init(xe);
+	if (err)
+		return err;
+

There is a sashiko reported bug here regarding probe failing earlier than this teardown registration causing teardown not waiting for worker to finish. Not sure if there will be any defrag list at that time, but probably work a fix for completeness?

Yes, let me make sure that is fixed.

Matt

Quoted 30 lines

Niranjana

Quoted 28 lines
drivers/gpu/drm/xe/xe_device.c +0 -0
 	err = xe_pagefault_init(xe);
 	if (err)
 		return err;
drivers/gpu/drm/xe/xe_device_types.h +11 -0
index 9e6244d8f41b..6e68add4d652 100644
@@ -314,6 +314,17 @@ struct xe_device {
 			 * @mem.defrag.list.
 			 */
 			atomic_t count;
+			/**
+			 * @mem.defrag.worker: Delayed worker that walks
+			 * @mem.defrag.list trying to reallocate BO backing
+			 * store at the device's beneficial order.
+			 */
+			struct delayed_work worker;
+			/**
+			 * @mem.defrag.interval_ms: Reschedule interval for
+			 * @mem.defrag.worker, in milliseconds.
+			 */
+			unsigned int interval_ms;
 		} defrag;
 	} mem;
 
Signature · 1 line
2.34.1
author maintainer
#84 lore raw

PATCH v3 21/33 drm/xe: Add defrag GT stats

In reply to Matthew Brost

Add observability for the page defragmentation worker.

Introduce four primary-GT statistics counters: defrag_added_count (BOs queued onto the defrag list after being backed at a sub-optimal page order), defrag_success_count (BOs fully re-backed at the beneficial order), defrag_partial_success_count (BOs only partially re-backed at the beneficial order) defrag_failed_count (attempts that failed and left the BO on its original backing) and defrag_mb_moved. The ineligible/already-removed fast path is intentionally not counted as either success or failure.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_bo.c             | 18 +++++++++++++++++-
 drivers/gpu/drm/xe/xe_gt_stats.c       |  5 +++++
 drivers/gpu/drm/xe/xe_gt_stats_types.h | 17 +++++++++++++++++
 3 files changed, 39 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +17 -1
index 907cfa57481f..073d926ef9ac 100644
@@ -26,6 +26,7 @@
 #include "xe_dma_buf.h"
 #include "xe_drm_client.h"
 #include "xe_ggtt.h"
+#include "xe_gt_stats.h"
 #include "xe_map.h"
 #include "xe_migrate.h"
 #include "xe_pat.h"
@@ -1160,6 +1161,8 @@ static void xe_bo_defrag_add(struct xe_bo *bo)
 				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
 			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
 			atomic_inc(&xe->mem.defrag.count);
+			xe_gt_stats_incr(xe_root_mmio_gt(xe),
+					 XE_GT_STATS_ID_DEFRAG_ADDED_COUNT, 1);
 		}
 	}
 
@@ -1274,8 +1277,21 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
 	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
 
-	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm)) {
 		*needs_more = true;
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+				 1);
+	} else {
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 ret ? XE_GT_STATS_ID_DEFRAG_FAILED_COUNT :
+				       XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT, 1);
+	}
+
+	if (!ret)
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_MB_MOVED,
+				 *consumed >> 20);
 
 unlock:
 	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_gt_stats.c +5 -0
index 789397514f3e..68e60d9500c8 100644
@@ -154,6 +154,11 @@ static const char *const stat_description[__XE_GT_STATS_NUM_IDS] = {
 	DEF_STAT_STR(PRL_2M_ENTRY_COUNT, "prl_2m_entry_count"),
 	DEF_STAT_STR(PRL_ISSUED_COUNT, "prl_issued_count"),
 	DEF_STAT_STR(PRL_ABORTED_COUNT, "prl_aborted_count"),
+	DEF_STAT_STR(DEFRAG_ADDED_COUNT, "defrag_added_count"),
+	DEF_STAT_STR(DEFRAG_SUCCESS_COUNT, "defrag_success_count"),
+	DEF_STAT_STR(DEFRAG_PARTIAL_SUCCESS_COUNT, "defrag_partial_success_count"),
+	DEF_STAT_STR(DEFRAG_FAILED_COUNT, "defrag_failed_count"),
+	DEF_STAT_STR(DEFRAG_MB_MOVED, "defrag_mb_moved"),
 };
 
 /**
drivers/gpu/drm/xe/xe_gt_stats_types.h +17 -0
index 425491bed6c4..c42b494390f8 100644
@@ -122,6 +122,18 @@
  * @XE_GT_STATS_ID_PRL_ABORTED_COUNT: Times the page reclaim process was
  *   aborted.
  *
+ * @XE_GT_STATS_ID_DEFRAG_ADDED_COUNT: Times a buffer object was added to the
+ *   page defragmentation list after being backed at a sub-optimal page order.
+ * @XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT: Times the defrag worker successfully
+ *   re-backed a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT: Times the defrag worker
+ *   partially re-backed a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_FAILED_COUNT: Times the defrag worker failed to
+ *   re-back a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_MB_MOVED: Data (MiB) actually (re)allocated while
+ *   re-backing buffer objects at the beneficial page order. Chunks borrowed
+ *   from the old backing for free are not counted.
+ *
  * @__XE_GT_STATS_NUM_IDS: Number of valid IDs; not a real counter.
  *
  * See Documentation/gpu/xe/xe_gt_stats.rst.
@@ -181,6 +193,11 @@ enum xe_gt_stats_id {
 	XE_GT_STATS_ID_PRL_2M_ENTRY_COUNT,
 	XE_GT_STATS_ID_PRL_ISSUED_COUNT,
 	XE_GT_STATS_ID_PRL_ABORTED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_ADDED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT,
+	XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+	XE_GT_STATS_ID_DEFRAG_FAILED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_MB_MOVED,
 	/* must be the last entry */
 	__XE_GT_STATS_NUM_IDS,
 };
Signature · 1 line
2.34.1
#85 lore raw

Re: [PATCH v3 21/33] drm/xe: Add defrag GT stats

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The `defrag_mb_moved` counter loses precision and will significantly undercount the amount of…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The defrag_mb_moved counter loses precision and will significantly undercount the amount of data moved. --

--- Patch [21]: [PATCH v3 21/33] drm/xe: Add defrag GT stats --- commit 84ae24372375a8f7d60dca398232ca340eba4dd8
Author: Matthew Brost <[email protected]>
Subject: drm/xe: Add defrag GT stats

This commit introduces observability for the page defragmentation worker by adding GT statistics counters. It tracks counts for buffer objects added to the defrag list, successful defragmentations, partial successes, failures, and the amount of data moved in megabytes.

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
index 907cfa57481f4..073d926ef9ace 100644

[ ... ]

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +4 -1
@@ -1274,8 +1277,21 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
 	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
 
-	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm)) {
 		*needs_more = true;
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+				 1);

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1294

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+	} else {
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 ret ? XE_GT_STATS_ID_DEFRAG_FAILED_COUNT :
+				       XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT, 1);
+	}
+
+	if (!ret)
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_MB_MOVED,
+				 *consumed >> 20);

[Severity: Medium]
Does this right-shift truncate the accumulation of data moved? If *consumed is less than 1 MiB (for example, a 64 KiB chunk), *consumed >> 20 evaluates to 0, meaning it will not be counted at all.

Could this lead to significantly undercounting the actual data moved? Would it be better to accumulate raw bytes in the counter and only convert to megabytes when formatting the output for userspace?

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 unlock:
 	xe_bo_unlock(bo);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
#86 lore raw

Re: [PATCH v3 21/33] drm/xe: Add defrag GT stats

In reply to Matthew Brost
Quoted 45 lines · Matthew Brost

Add observability for the page defragmentation worker.

Introduce four primary-GT statistics counters: defrag_added_count (BOs queued onto the defrag list after being backed at a sub-optimal page order), defrag_success_count (BOs fully re-backed at the beneficial order), defrag_partial_success_count (BOs only partially re-backed at the beneficial order) defrag_failed_count (attempts that failed and left the BO on its original backing) and defrag_mb_moved. The ineligible/already-removed fast path is intentionally not counted as either success or failure.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

drivers/gpu/drm/xe/xe_bo.c             | 18 +++++++++++++++++-
drivers/gpu/drm/xe/xe_gt_stats.c       |  5 +++++
drivers/gpu/drm/xe/xe_gt_stats_types.h | 17 +++++++++++++++++
3 files changed, 39 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +1 -0
index 907cfa57481f..073d926ef9ac 100644
@@ -26,6 +26,7 @@
 #include "xe_dma_buf.h"
 #include "xe_drm_client.h"
 #include "xe_ggtt.h"
+#include "xe_gt_stats.h"
 #include "xe_map.h"
 #include "xe_migrate.h"
 #include "xe_pat.h"

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_add(struct xe_bo *bo) · line 1165

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +2 -0
@@ -1160,6 +1161,8 @@ static void xe_bo_defrag_add(struct xe_bo *bo)
 				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
 			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
 			atomic_inc(&xe->mem.defrag.count);
+			xe_gt_stats_incr(xe_root_mmio_gt(xe),
+					 XE_GT_STATS_ID_DEFRAG_ADDED_COUNT, 1);
Assisted-by LLM

I am not sure if ADDED_COUNT is much helpful here. But BOs added here can get silently dropped. Also, a silently dropped BO can get re-added.

Perhaps a better count would be a 'defrag_pending byte guage'? Also, probably make it not-resettable so that it gives the current state of fragmentation.

Quoted 13 lines
drivers/gpu/drm/xe/xe_bo.c +4 -1
 		}
 	}
 
@@ -1274,8 +1277,21 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
 	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
 
-	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm)) {
 		*needs_more = true;
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+				 1);

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1294

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+	} else {
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 ret ? XE_GT_STATS_ID_DEFRAG_FAILED_COUNT :
+				       XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT, 1);
+	}
+
+	if (!ret)
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_MB_MOVED,
+				 *consumed >> 20);

This will truncate the size which can accumulate over multiple BOs and the size here will be significantly off from real size that is moved.

Quoted 29 lines

unlock:

	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_gt_stats.c +5 -0
index 789397514f3e..68e60d9500c8 100644
@@ -154,6 +154,11 @@ static const char *const stat_description[__XE_GT_STATS_NUM_IDS] = {
 	DEF_STAT_STR(PRL_2M_ENTRY_COUNT, "prl_2m_entry_count"),
 	DEF_STAT_STR(PRL_ISSUED_COUNT, "prl_issued_count"),
 	DEF_STAT_STR(PRL_ABORTED_COUNT, "prl_aborted_count"),
+	DEF_STAT_STR(DEFRAG_ADDED_COUNT, "defrag_added_count"),
+	DEF_STAT_STR(DEFRAG_SUCCESS_COUNT, "defrag_success_count"),
+	DEF_STAT_STR(DEFRAG_PARTIAL_SUCCESS_COUNT, "defrag_partial_success_count"),
+	DEF_STAT_STR(DEFRAG_FAILED_COUNT, "defrag_failed_count"),
+	DEF_STAT_STR(DEFRAG_MB_MOVED, "defrag_mb_moved"),
 };
 
 /**
drivers/gpu/drm/xe/xe_gt_stats_types.h +2 -0
index 425491bed6c4..c42b494390f8 100644
@@ -122,6 +122,18 @@
 * @XE_GT_STATS_ID_PRL_ABORTED_COUNT: Times the page reclaim process was
 *   aborted.
 *
+ * @XE_GT_STATS_ID_DEFRAG_ADDED_COUNT: Times a buffer object was added to the
+ *   page defragmentation list after being backed at a sub-optimal page order.

drivers/gpu/drm/xe/xe_gt_stats_types.h line 136

Quoted 10 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +10 -0
+ * @XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT: Times the defrag worker successfully
+ *   re-backed a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT: Times the defrag worker
+ *   partially re-backed a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_FAILED_COUNT: Times the defrag worker failed to
+ *   re-back a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_MB_MOVED: Data (MiB) actually (re)allocated while
+ *   re-backing buffer objects at the beneficial page order. Chunks borrowed
+ *   from the old backing for free are not counted.
+ *

NIT...all GTs applied to root GT, which is fine, but probably update stats documentation?

drivers/gpu/drm/xe/xe_gt_stats_types.h enum xe_gt_stats_id { · line 200

Quoted 12 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +5 -0
 * @__XE_GT_STATS_NUM_IDS: Number of valid IDs; not a real counter.
 *
 * See Documentation/gpu/xe/xe_gt_stats.rst.
@@ -181,6 +193,11 @@ enum xe_gt_stats_id {
 	XE_GT_STATS_ID_PRL_2M_ENTRY_COUNT,
 	XE_GT_STATS_ID_PRL_ISSUED_COUNT,
 	XE_GT_STATS_ID_PRL_ABORTED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_ADDED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT,
+	XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+	XE_GT_STATS_ID_DEFRAG_FAILED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_MB_MOVED,

NIT...Few other counts that might be helpful are,
- defrag failure reason (DEFRAG_FAILED_BUSY/ENOMEM)
- time cost of defrag (DEFRAG_US)
- 'removed_without_defrag' so that 'MB_MOVED + removed_without_defrag + defrag_pending' is the total suboptimal size added to defrag list.

Niranjana

Quoted 6 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +0 -0
 	/* must be the last entry */
 	__XE_GT_STATS_NUM_IDS,
 };
Signature · 1 line
2.34.1
author maintainer
#87 lore raw

Re: [PATCH v3 21/33] drm/xe: Add defrag GT stats

Quoted 45 lines · Niranjana Vishwanathapura
Quoted 44 lines · Matthew Brost

Add observability for the page defragmentation worker.

Introduce four primary-GT statistics counters: defrag_added_count (BOs queued onto the defrag list after being backed at a sub-optimal page order), defrag_success_count (BOs fully re-backed at the beneficial order), defrag_partial_success_count (BOs only partially re-backed at the beneficial order) defrag_failed_count (attempts that failed and left the BO on its original backing) and defrag_mb_moved. The ineligible/already-removed fast path is intentionally not counted as either success or failure.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

drivers/gpu/drm/xe/xe_bo.c             | 18 +++++++++++++++++-
drivers/gpu/drm/xe/xe_gt_stats.c       |  5 +++++
drivers/gpu/drm/xe/xe_gt_stats_types.h | 17 +++++++++++++++++
3 files changed, 39 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +1 -0
index 907cfa57481f..073d926ef9ac 100644
@@ -26,6 +26,7 @@
 #include "xe_dma_buf.h"
 #include "xe_drm_client.h"
 #include "xe_ggtt.h"
+#include "xe_gt_stats.h"
 #include "xe_map.h"
 #include "xe_migrate.h"
 #include "xe_pat.h"
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_add(struct xe_bo *bo) · line 1165

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +2 -0
@@ -1160,6 +1161,8 @@ static void xe_bo_defrag_add(struct xe_bo *bo)
 				xe->mem.defrag.interval_ms = XE_BO_DEFRAG_INTERVAL_MS;
 			list_add_tail(&bo->defrag_link, &xe->mem.defrag.list);
 			atomic_inc(&xe->mem.defrag.count);
+			xe_gt_stats_incr(xe_root_mmio_gt(xe),
+					 XE_GT_STATS_ID_DEFRAG_ADDED_COUNT, 1);
Assisted-by LLM

Yes.

Quoted 3 lines

I am not sure if ADDED_COUNT is much helpful here. But BOs added here can get silently dropped. Also, a silently dropped BO can get re-added.

That is in fact true and if you run the xe_defrag IGT this happens a lot. I personally find this one useful and so has the ALOS team.

Quoted 3 lines

Perhaps a better count would be a 'defrag_pending byte guage'? Also, probably make it not-resettable so that it gives the current state of fragmentation.

I think for something like that debugfs would be the better choice rather than GT stats - e.g., Take spin_lock walk the defrag list and which shows the current state. This is a different patch though but probably worth adding.

Quoted 18 lines
Quoted 18 lines
drivers/gpu/drm/xe/xe_bo.c +9 -1
 		}
 	}
 
@@ -1274,8 +1277,21 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	xe_dbg(xe, "Defrag attempt on BO size=%zu: ret=%pe consumed=%llu\n",
 	       xe_bo_size(bo), ERR_PTR(ret), *consumed);
 
-	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm))
+	if (!ret && ttm_tt_is_beneficial_order_failed(bo->ttm.ttm)) {
 		*needs_more = true;
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+				 1);
+	} else {
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 ret ? XE_GT_STATS_ID_DEFRAG_FAILED_COUNT :
+				       XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT, 1);
+	}
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1294

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +5 -0
+
+	if (!ret)
+		xe_gt_stats_incr(xe_root_mmio_gt(xe),
+				 XE_GT_STATS_ID_DEFRAG_MB_MOVED,
+				 *consumed >> 20);

This will truncate the size which can accumulate over multiple BOs and the size here will be significantly off from real size that is moved.

I'm not following. Consumed is the number of newly pruned bytes, thus the total number of bytes copied on the migrate queue. A single BO can prune in anywhere from 2M to DRM_XE_BO_DEFRAG_SIZE_LIMIT per xe_bo_defrag_one call when !ret is true.

I use these stats all the time and they seem accurate.

Quoted 33 lines
Quoted 33 lines

unlock:

	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_gt_stats.c +5 -0
index 789397514f3e..68e60d9500c8 100644
@@ -154,6 +154,11 @@ static const char *const stat_description[__XE_GT_STATS_NUM_IDS] = {
 	DEF_STAT_STR(PRL_2M_ENTRY_COUNT, "prl_2m_entry_count"),
 	DEF_STAT_STR(PRL_ISSUED_COUNT, "prl_issued_count"),
 	DEF_STAT_STR(PRL_ABORTED_COUNT, "prl_aborted_count"),
+	DEF_STAT_STR(DEFRAG_ADDED_COUNT, "defrag_added_count"),
+	DEF_STAT_STR(DEFRAG_SUCCESS_COUNT, "defrag_success_count"),
+	DEF_STAT_STR(DEFRAG_PARTIAL_SUCCESS_COUNT, "defrag_partial_success_count"),
+	DEF_STAT_STR(DEFRAG_FAILED_COUNT, "defrag_failed_count"),
+	DEF_STAT_STR(DEFRAG_MB_MOVED, "defrag_mb_moved"),
 };
 
 /**
drivers/gpu/drm/xe/xe_gt_stats_types.h +6 -0
index 425491bed6c4..c42b494390f8 100644
@@ -122,6 +122,18 @@
 * @XE_GT_STATS_ID_PRL_ABORTED_COUNT: Times the page reclaim process was
 *   aborted.
 *
+ * @XE_GT_STATS_ID_DEFRAG_ADDED_COUNT: Times a buffer object was added to the
+ *   page defragmentation list after being backed at a sub-optimal page order.
+ * @XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT: Times the defrag worker successfully
+ *   re-backed a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT: Times the defrag worker
+ *   partially re-backed a buffer object at the beneficial page order.
Quoted 9 lines

drivers/gpu/drm/xe/xe_gt_stats_types.h line 136

Quoted 6 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +6 -0
+ * @XE_GT_STATS_ID_DEFRAG_FAILED_COUNT: Times the defrag worker failed to
+ *   re-back a buffer object at the beneficial page order.
+ * @XE_GT_STATS_ID_DEFRAG_MB_MOVED: Data (MiB) actually (re)allocated while
+ *   re-backing buffer objects at the beneficial page order. Chunks borrowed
+ *   from the old backing for free are not counted.
+ *

NIT...all GTs applied to root GT, which is fine, but probably update stats documentation?

Yes, let me add that.

Quoted 7 lines
Quoted 7 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +0 -0
 * @__XE_GT_STATS_NUM_IDS: Number of valid IDs; not a real counter.
 *
 * See Documentation/gpu/xe/xe_gt_stats.rst.
@@ -181,6 +193,11 @@ enum xe_gt_stats_id {
 	XE_GT_STATS_ID_PRL_2M_ENTRY_COUNT,
 	XE_GT_STATS_ID_PRL_ISSUED_COUNT,
 	XE_GT_STATS_ID_PRL_ABORTED_COUNT,
Quoted 8 lines

drivers/gpu/drm/xe/xe_gt_stats_types.h enum xe_gt_stats_id { · line 200

Quoted 5 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +5 -0
+	XE_GT_STATS_ID_DEFRAG_ADDED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_SUCCESS_COUNT,
+	XE_GT_STATS_ID_DEFRAG_PARTIAL_SUCCESS_COUNT,
+	XE_GT_STATS_ID_DEFRAG_FAILED_COUNT,
+	XE_GT_STATS_ID_DEFRAG_MB_MOVED,

NIT...Few other counts that might be helpful are,
- defrag failure reason (DEFRAG_FAILED_BUSY/ENOMEM)

I practice ENOMEM is really the way it can fail (e.g., we ask the core for 2M page with aggresive reclaim flags and it fails). So not sure if this is really useful.

Quoted 1 line

- time cost of defrag (DEFRAG_US)

This is tricky one. What would DEFRAG_US measure here? The time to allocate memory (e.g., reclaim time), the time to prune in memory under dma-resv, or the copy job time?

You can figure out all the above via ftrace and that how I profiled / tuned the implementation + how I believe the ALOS team if proving this works / tuning Kconfig options so we don't miss page flips on a defrag.

Quoted 2 lines

- 'removed_without_defrag' so that 'MB_MOVED + removed_without_defrag + defrag_pending' is the total suboptimal size added to defrag list.

Removed without a defrag is probably useful and perhaps a total of suboptimal bytes added could be helpful too. Let me add those.

Matt

Quoted 9 lines

Niranjana

Quoted 6 lines
drivers/gpu/drm/xe/xe_gt_stats_types.h +0 -0
 	/* must be the last entry */
 	__XE_GT_STATS_NUM_IDS,
 };
Signature · 1 line
2.34.1
author maintainer
#88 lore raw

PATCH v3 22/33 drm/xe: Add Kconfig.profile options for BO defrag configuration

In reply to Matthew Brost

Add Kconfig.profile options to make XE_BO_DEFRAG_* defines configurable:
- DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD: Threshold for TTM reclaim backoff
- DRM_XE_BO_DEFRAG_SIZE_LIMIT: Maximum number of bytes to defrag per work run
- DRM_XE_BO_DEFRAG_INTERVAL_MS: Default delay before defrag worker runs
- DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS: Upper bound for defrag worker interval

Update xe_bo.c to use these Kconfig options as defaults via #ifdef guards, maintaining backward compatibility with hardcoded values when not configured.

Additionally, disable defrag completely when XE_BO_DEFRAG_SIZE_LIMIT is set less than 2M by returning early from xe_bo_defrag_update() (and xe_bo_defrag_remove()) so BOs are never added to the defrag list or the worker kicked; xe_bo_defrag_add() and xe_bo_defrag_schedule() assert the limit is at least 2M.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-haiku-4.5
---
 drivers/gpu/drm/xe/Kconfig.profile | 40 ++++++++++++++++++++++++++++++
 drivers/gpu/drm/xe/xe_bo.c         | 26 +++++++++++++++++++
 2 files changed, 66 insertions(+)
drivers/gpu/drm/xe/Kconfig.profile +40 -0
index e07517d120e0..e0aade41f53e 100644
@@ -74,3 +74,43 @@ config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT
 	  to apply to applicable user. For elevated user, all above MIN
 	  and MAX values will apply when this configuration is enable to
 	  apply limitation. By default limitation is applied.
+
+config DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+	int "BO defrag reclaim backoff threshold"
+	default 2
+	range 1 1000
+	help
+	  Once this many BOs are tracked on the device defrag list (i.e. were
+	  backed with a sub-optimal page order), request that the TTM pool backs
+	  off from aggressive reclaim at the beneficial order during populate,
+	  so that allocations make forward progress instead of stalling.
+
+config DRM_XE_BO_DEFRAG_SIZE_LIMIT
+	int "Maximum bytes to defrag per work run"
+	default 33554432
+	range 0 1073741824
+	help
+	  Maximum number of bytes the defrag worker will process in a single run
+	  before yielding and rescheduling itself. Set to less than large page
+	  size (2M) to disable defrag. A defrag move synchronously reallocates
+	  and re-copies a BO's backing store, which is not free. If a large
+	  number of BOs become eligible at once, processing them all in one
+	  worker run would hold things up for a long, unbounded stretch.
+	  Instead, cap the work done per run and requeue, spreading the defrag
+	  effort out over time.
+
+config DRM_XE_BO_DEFRAG_INTERVAL_MS
+	int "Default delay before defrag worker run (ms)"
+	default 25
+	range 1 1000
+	help
+	  Default delay before (re)running the defrag worker, in milliseconds.
+
+config DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+	int "Upper bound for defrag worker interval (ms)"
+	default 15000
+	range 100 1000000
+	help
+	  Upper bound for the (exponentially backed off) defrag worker interval,
+	  in milliseconds, so repeated failures don't push the retry arbitrarily
+	  far out. 15000 ms = 15 seconds.
drivers/gpu/drm/xe/xe_bo.c +26 -0
index 073d926ef9ac..0bdd1c920404 100644
@@ -49,7 +49,11 @@
  * aggressive reclaim at the beneficial order during populate, so that
  * allocations make forward progress instead of stalling.
  */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+#define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	CONFIG_DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+#else
 #define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
+#endif
 
 /*
  * Maximum number of bytes of newly (re)allocated backing the defrag worker will
@@ -65,17 +69,31 @@
  * Only pages a move truly reallocates are charged; pages harvested from the old
  * backing are free, so an object larger than the budget is upgraded in
  * budget-sized slices across runs.
+ *
+ * Set to 0 to disable defrag completely.
  */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_SIZE_LIMIT
+#define XE_BO_DEFRAG_SIZE_LIMIT			CONFIG_DRM_XE_BO_DEFRAG_SIZE_LIMIT
+#else
 #define XE_BO_DEFRAG_SIZE_LIMIT			SZ_32M
+#endif
 
 /* Default delay before (re)running the defrag worker, in milliseconds. */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MS
+#define XE_BO_DEFRAG_INTERVAL_MS		CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MS
+#else
 #define XE_BO_DEFRAG_INTERVAL_MS		25
+#endif
 
 /*
  * Upper bound for the (exponentially backed off) defrag worker interval, in
  * milliseconds, so repeated failures don't push the retry arbitrarily far out.
  */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+#define XE_BO_DEFRAG_INTERVAL_MAX_MS		CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+#else
 #define XE_BO_DEFRAG_INTERVAL_MAX_MS		15000	/* 15 seconds */
+#endif
 
 static void xe_bo_defrag_worker(struct work_struct *w);
 static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place);
@@ -1126,6 +1144,7 @@ int xe_bo_defrag_init(struct xe_device *xe)
 
 static void xe_bo_defrag_schedule(struct xe_device *xe)
 {
+	xe_assert(xe, XE_BO_DEFRAG_SIZE_LIMIT >= SZ_2M);
 	schedule_delayed_work(&xe->mem.defrag.worker,
 			      msecs_to_jiffies(xe->mem.defrag.interval_ms));
 }
@@ -1152,6 +1171,7 @@ static void xe_bo_defrag_add(struct xe_bo *bo)
 
 	xe_bo_assert_held(bo);
 	xe_assert(xe, xe_bo_needs_defrag(bo));
+	xe_assert(xe, XE_BO_DEFRAG_SIZE_LIMIT >= SZ_2M);
 
 	scoped_guard(spinlock, &xe->mem.defrag.lock) {
 		if (list_empty(&bo->defrag_link)) {
@@ -1185,6 +1205,9 @@ static void xe_bo_defrag_remove(struct xe_bo *bo)
 {
 	xe_bo_assert_held(bo);
 
+	if (XE_BO_DEFRAG_SIZE_LIMIT < SZ_2M)
+		return;
+
 	if (list_empty(&bo->defrag_link))
 		return;
 
@@ -1204,6 +1227,9 @@ static void xe_bo_defrag_update(struct xe_bo *bo)
 {
 	xe_bo_assert_held(bo);
 
+	if (XE_BO_DEFRAG_SIZE_LIMIT < SZ_2M)
+		return;
+
 	if (xe_bo_needs_defrag(bo))
 		xe_bo_defrag_add(bo);
 	else
Signature · 1 line
2.34.1
#89 lore raw

Re: [PATCH v3 22/33] drm/xe: Add Kconfig.profile options for BO defrag configuration

Quoted 9 lines · Matthew Brost

Add Kconfig.profile options to make XE_BO_DEFRAG_* defines configurable:
- DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD: Threshold for TTM reclaim backoff
- DRM_XE_BO_DEFRAG_SIZE_LIMIT: Maximum number of bytes to defrag per work run
- DRM_XE_BO_DEFRAG_INTERVAL_MS: Default delay before defrag worker runs
- DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS: Upper bound for defrag worker interval

Assisted-by LLM

NIT...Would runtime knobs be useful than these compile time knobs?

Quoted 35 lines

Update xe_bo.c to use these Kconfig options as defaults via #ifdef guards, maintaining backward compatibility with hardcoded values when not configured.

Additionally, disable defrag completely when XE_BO_DEFRAG_SIZE_LIMIT is set less than 2M by returning early from xe_bo_defrag_update() (and xe_bo_defrag_remove()) so BOs are never added to the defrag list or the worker kicked; xe_bo_defrag_add() and xe_bo_defrag_schedule() assert the limit is at least 2M.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-haiku-4.5

---
drivers/gpu/drm/xe/Kconfig.profile | 40 ++++++++++++++++++++++++++++++
drivers/gpu/drm/xe/xe_bo.c | 26 +++++++++++++++++++

2 files changed, 66 insertions(+)
drivers/gpu/drm/xe/Kconfig.profile +0 -0
index e07517d120e0..e0aade41f53e 100644

drivers/gpu/drm/xe/Kconfig.profile config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT · line 81

Quoted 8 lines
drivers/gpu/drm/xe/Kconfig.profile +5 -0
@@ -74,3 +74,43 @@ config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT
 	  to apply to applicable user. For elevated user, all above MIN
 	  and MAX values will apply when this configuration is enable to
 	  apply limitation. By default limitation is applied.
+
+config DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+	int "BO defrag reclaim backoff threshold"
+	default 2
+	range 1 1000

Is the value of 1 intended here? As mentioned in patch 16, this will reinforce the self backoff loop.

NIT...Also the max value of the range here and below seems too higher than the default value. Not sure if that is intended.

Quoted 10 lines
drivers/gpu/drm/xe/Kconfig.profile +10 -0
+	help
+	  Once this many BOs are tracked on the device defrag list (i.e. were
+	  backed with a sub-optimal page order), request that the TTM pool backs
+	  off from aggressive reclaim at the beneficial order during populate,
+	  so that allocations make forward progress instead of stalling.
+
+config DRM_XE_BO_DEFRAG_SIZE_LIMIT
+	int "Maximum bytes to defrag per work run"
+	default 33554432
+	range 0 1073741824

drivers/gpu/drm/xe/Kconfig.profile config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT · line 101

Quoted 10 lines
drivers/gpu/drm/xe/Kconfig.profile +10 -0
+	help
+	  Maximum number of bytes the defrag worker will process in a single run
+	  before yielding and rescheduling itself. Set to less than large page
+	  size (2M) to disable defrag. A defrag move synchronously reallocates
+	  and re-copies a BO's backing store, which is not free. If a large
+	  number of BOs become eligible at once, processing them all in one
+	  worker run would hold things up for a long, unbounded stretch.
+	  Instead, cap the work done per run and requeue, spreading the defrag
+	  effort out over time.
+

The disable mechanism is confusing (0 to 2MB). May be add a separate runtime knob for enable/disable and change the range here to start from 2MB?

drivers/gpu/drm/xe/Kconfig.profile config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT · line 112

Quoted 11 lines
drivers/gpu/drm/xe/Kconfig.profile +11 -0
+config DRM_XE_BO_DEFRAG_INTERVAL_MS
+	int "Default delay before defrag worker run (ms)"
+	default 25
+	range 1 1000
+	help
+	  Default delay before (re)running the defrag worker, in milliseconds.
+
+config DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+	int "Upper bound for defrag worker interval (ms)"
+	default 15000
+	range 100 1000000

The range here overlaps with that of DRM_XE_BO_DEFRAG_INTERVAL_MS and it accepts value lower than that of DRM_XE_BO_DEFRAG_INTERVAL_MS.

Quoted 9 lines
drivers/gpu/drm/xe/Kconfig.profile +4 -0
+	help
+	  Upper bound for the (exponentially backed off) defrag worker interval,
+	  in milliseconds, so repeated failures don't push the retry arbitrarily
+	  far out. 15000 ms = 15 seconds.
drivers/gpu/drm/xe/xe_bo.c +0 -0
index 073d926ef9ac..0bdd1c920404 100644

drivers/gpu/drm/xe/xe_bo.c line 57

Quoted 9 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
@@ -49,7 +49,11 @@
 * aggressive reclaim at the beneficial order during populate, so that
 * allocations make forward progress instead of stalling.
 */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+#define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	CONFIG_DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+#else
 #define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
+#endif
 

Looks like The 'ifdef's are redundent here as the config params without any dependency take the default value and hence will always turn out to be true.

Quoted 43 lines
drivers/gpu/drm/xe/xe_bo.c +15 -0
 /*
 * Maximum number of bytes of newly (re)allocated backing the defrag worker will
@@ -65,17 +69,31 @@
 * Only pages a move truly reallocates are charged; pages harvested from the old
 * backing are free, so an object larger than the budget is upgraded in
 * budget-sized slices across runs.
+ *
+ * Set to 0 to disable defrag completely.
 */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_SIZE_LIMIT
+#define XE_BO_DEFRAG_SIZE_LIMIT			CONFIG_DRM_XE_BO_DEFRAG_SIZE_LIMIT
+#else
 #define XE_BO_DEFRAG_SIZE_LIMIT			SZ_32M
+#endif
 
 /* Default delay before (re)running the defrag worker, in milliseconds. */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MS
+#define XE_BO_DEFRAG_INTERVAL_MS		CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MS
+#else
 #define XE_BO_DEFRAG_INTERVAL_MS		25
+#endif
 
 /*
 * Upper bound for the (exponentially backed off) defrag worker interval, in
 * milliseconds, so repeated failures don't push the retry arbitrarily far out.
 */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+#define XE_BO_DEFRAG_INTERVAL_MAX_MS		CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+#else
 #define XE_BO_DEFRAG_INTERVAL_MAX_MS		15000	/* 15 seconds */
+#endif
 
 static void xe_bo_defrag_worker(struct work_struct *w);
 static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place);
@@ -1126,6 +1144,7 @@ int xe_bo_defrag_init(struct xe_device *xe)
 
 static void xe_bo_defrag_schedule(struct xe_device *xe)
 {
+	xe_assert(xe, XE_BO_DEFRAG_SIZE_LIMIT >= SZ_2M);
 	schedule_delayed_work(&xe->mem.defrag.worker,
 			      msecs_to_jiffies(xe->mem.defrag.interval_ms));
 }

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_add(struct xe_bo *bo) · line 1174

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
@@ -1152,6 +1171,7 @@ static void xe_bo_defrag_add(struct xe_bo *bo)
 
 	xe_bo_assert_held(bo);
 	xe_assert(xe, xe_bo_needs_defrag(bo));
+	xe_assert(xe, XE_BO_DEFRAG_SIZE_LIMIT >= SZ_2M);

xe_bo_defrag_init_early and xe_bo_defrag_init still runs if defrag is disabled which can be avoided.

Niranjana

Quoted 26 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
 	scoped_guard(spinlock, &xe->mem.defrag.lock) {
 		if (list_empty(&bo->defrag_link)) {
@@ -1185,6 +1205,9 @@ static void xe_bo_defrag_remove(struct xe_bo *bo)
 {
 	xe_bo_assert_held(bo);
 
+	if (XE_BO_DEFRAG_SIZE_LIMIT < SZ_2M)
+		return;
+
 	if (list_empty(&bo->defrag_link))
 		return;
 
@@ -1204,6 +1227,9 @@ static void xe_bo_defrag_update(struct xe_bo *bo)
 {
 	xe_bo_assert_held(bo);
 
+	if (XE_BO_DEFRAG_SIZE_LIMIT < SZ_2M)
+		return;
+
 	if (xe_bo_needs_defrag(bo))
 		xe_bo_defrag_add(bo);
 	else
Signature · 1 line
2.34.1
author maintainer
#90 lore raw

Re: [PATCH v3 22/33] drm/xe: Add Kconfig.profile options for BO defrag configuration

Quoted 11 lines · Niranjana Vishwanathapura
Quoted 9 lines · Matthew Brost

Add Kconfig.profile options to make XE_BO_DEFRAG_* defines configurable:
- DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD: Threshold for TTM reclaim backoff
- DRM_XE_BO_DEFRAG_SIZE_LIMIT: Maximum number of bytes to defrag per work run
- DRM_XE_BO_DEFRAG_INTERVAL_MS: Default delay before defrag worker runs
- DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS: Upper bound for defrag worker interval

Quoted 4 lines
Assisted-by LLM

NIT...Would runtime knobs be useful than these compile time knobs?

Yes, I think these will need to be made into runtime knobs. We'd still have Kconfig for default though.

Quoted 47 lines
Quoted 35 lines

Update xe_bo.c to use these Kconfig options as defaults via #ifdef guards, maintaining backward compatibility with hardcoded values when not configured.

Additionally, disable defrag completely when XE_BO_DEFRAG_SIZE_LIMIT is set less than 2M by returning early from xe_bo_defrag_update() (and xe_bo_defrag_remove()) so BOs are never added to the defrag list or the worker kicked; xe_bo_defrag_add() and xe_bo_defrag_schedule() assert the limit is at least 2M.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-haiku-4.5

---
drivers/gpu/drm/xe/Kconfig.profile | 40 ++++++++++++++++++++++++++++++
drivers/gpu/drm/xe/xe_bo.c | 26 +++++++++++++++++++

2 files changed, 66 insertions(+)
drivers/gpu/drm/xe/Kconfig.profile +0 -0
index e07517d120e0..e0aade41f53e 100644

drivers/gpu/drm/xe/Kconfig.profile config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT · line 81

Quoted 8 lines
drivers/gpu/drm/xe/Kconfig.profile +5 -0
@@ -74,3 +74,43 @@ config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT
 	  to apply to applicable user. For elevated user, all above MIN
 	  and MAX values will apply when this configuration is enable to
 	  apply limitation. By default limitation is applied.
+
+config DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+	int "BO defrag reclaim backoff threshold"
+	default 2
+	range 1 1000

Is the value of 1 intended here? As mentioned in patch 16, this will reinforce the self backoff loop.

Quoted 3 lines

NIT...Also the max value of the range here and below seems too higher than the default value. Not sure if that is intended.

This is getting dropped. As I mentioned in other patches I'm changing this blindly turn off reclaim for all foreground allocations and only allow the defragmenter to flip on reclaim. This is the desired behavior for all client systems to avoid missing page flips at all costs.

Quoted 15 lines
Quoted 15 lines
drivers/gpu/drm/xe/Kconfig.profile +15 -0
+	help
+	  Once this many BOs are tracked on the device defrag list (i.e. were
+	  backed with a sub-optimal page order), request that the TTM pool backs
+	  off from aggressive reclaim at the beneficial order during populate,
+	  so that allocations make forward progress instead of stalling.
+
+config DRM_XE_BO_DEFRAG_SIZE_LIMIT
+	int "Maximum bytes to defrag per work run"
+	default 33554432
+	range 0 1073741824
+	help
+	  Maximum number of bytes the defrag worker will process in a single run
+	  before yielding and rescheduling itself. Set to less than large page
+	  size (2M) to disable defrag. A defrag move synchronously reallocates
+	  and re-copies a BO's backing store, which is not free. If a large
Quoted 9 lines

drivers/gpu/drm/xe/Kconfig.profile config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT · line 101

Quoted 5 lines
drivers/gpu/drm/xe/Kconfig.profile +5 -0
+	  number of BOs become eligible at once, processing them all in one
+	  worker run would hold things up for a long, unbounded stretch.
+	  Instead, cap the work done per run and requeue, spreading the defrag
+	  effort out over time.
+

The disable mechanism is confusing (0 to 2MB). May be add a separate runtime knob for enable/disable and change the range here to start from 2MB?

Ok.

Quoted 6 lines
Quoted 6 lines
drivers/gpu/drm/xe/Kconfig.profile +6 -0
+config DRM_XE_BO_DEFRAG_INTERVAL_MS
+	int "Default delay before defrag worker run (ms)"
+	default 25
+	range 1 1000
+	help
+	  Default delay before (re)running the defrag worker, in milliseconds.
Quoted 9 lines

drivers/gpu/drm/xe/Kconfig.profile config DRM_XE_ENABLE_SCHEDTIMEOUT_LIMIT · line 112

Quoted 5 lines
drivers/gpu/drm/xe/Kconfig.profile +5 -0
+
+config DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+	int "Upper bound for defrag worker interval (ms)"
+	default 15000
+	range 100 1000000

The range here overlaps with that of DRM_XE_BO_DEFRAG_INTERVAL_MS and it accepts value lower than that of DRM_XE_BO_DEFRAG_INTERVAL_MS.

It does but there isn't a way Kconfig to enforce this. If someone really wants to compile with a broken Kconfig, IMO that is a user problem.

Quoted 13 lines
Quoted 13 lines
drivers/gpu/drm/xe/Kconfig.profile +4 -0
+	help
+	  Upper bound for the (exponentially backed off) defrag worker interval,
+	  in milliseconds, so repeated failures don't push the retry arbitrarily
+	  far out. 15000 ms = 15 seconds.
drivers/gpu/drm/xe/xe_bo.c +1 -0
index 073d926ef9ac..0bdd1c920404 100644
@@ -49,7 +49,11 @@
 * aggressive reclaim at the beneficial order during populate, so that
 * allocations make forward progress instead of stalling.
 */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c line 57

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +3 -0
+#define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	CONFIG_DRM_XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD
+#else
 #define XE_BO_DEFRAG_RECLAIM_BACKOFF_THRESHOLD	2
+#endif
 

Looks like The 'ifdef's are redundent here as the config params without any dependency take the default value and hence will always turn out to be true.

This is existing style for everything in Kconfig.profile

e.g. Look at xe_hw_engine.h

Quoted 44 lines
Quoted 44 lines
drivers/gpu/drm/xe/xe_bo.c +15 -0
 /*
 * Maximum number of bytes of newly (re)allocated backing the defrag worker will
@@ -65,17 +69,31 @@
 * Only pages a move truly reallocates are charged; pages harvested from the old
 * backing are free, so an object larger than the budget is upgraded in
 * budget-sized slices across runs.
+ *
+ * Set to 0 to disable defrag completely.
 */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_SIZE_LIMIT
+#define XE_BO_DEFRAG_SIZE_LIMIT			CONFIG_DRM_XE_BO_DEFRAG_SIZE_LIMIT
+#else
 #define XE_BO_DEFRAG_SIZE_LIMIT			SZ_32M
+#endif
 
 /* Default delay before (re)running the defrag worker, in milliseconds. */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MS
+#define XE_BO_DEFRAG_INTERVAL_MS		CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MS
+#else
 #define XE_BO_DEFRAG_INTERVAL_MS		25
+#endif
 
 /*
 * Upper bound for the (exponentially backed off) defrag worker interval, in
 * milliseconds, so repeated failures don't push the retry arbitrarily far out.
 */
+#ifdef CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+#define XE_BO_DEFRAG_INTERVAL_MAX_MS		CONFIG_DRM_XE_BO_DEFRAG_INTERVAL_MAX_MS
+#else
 #define XE_BO_DEFRAG_INTERVAL_MAX_MS		15000	/* 15 seconds */
+#endif
 
 static void xe_bo_defrag_worker(struct work_struct *w);
 static void xe_place_from_ttm_type(u32 mem_type, struct ttm_place *place);
@@ -1126,6 +1144,7 @@ int xe_bo_defrag_init(struct xe_device *xe)
 
 static void xe_bo_defrag_schedule(struct xe_device *xe)
 {
+	xe_assert(xe, XE_BO_DEFRAG_SIZE_LIMIT >= SZ_2M);
 	schedule_delayed_work(&xe->mem.defrag.worker,
 			      msecs_to_jiffies(xe->mem.defrag.interval_ms));
 }
@@ -1152,6 +1171,7 @@ static void xe_bo_defrag_add(struct xe_bo *bo)
 
Quoted 7 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_bo_defrag_add(struct xe_bo *bo) · line 1174

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +1 -0
 	xe_bo_assert_held(bo);
 	xe_assert(xe, xe_bo_needs_defrag(bo));
+	xe_assert(xe, XE_BO_DEFRAG_SIZE_LIMIT >= SZ_2M);

xe_bo_defrag_init_early and xe_bo_defrag_init still runs if defrag is disabled which can be avoided.

I'd rather not special case the init functions as they are harmless to run. Also if we switch runtime control of the defragmenter, you'd always have to call the init.

Matt

Quoted 28 lines

Niranjana

Quoted 26 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
 	scoped_guard(spinlock, &xe->mem.defrag.lock) {
 		if (list_empty(&bo->defrag_link)) {
@@ -1185,6 +1205,9 @@ static void xe_bo_defrag_remove(struct xe_bo *bo)
 {
 	xe_bo_assert_held(bo);
 
+	if (XE_BO_DEFRAG_SIZE_LIMIT < SZ_2M)
+		return;
+
 	if (list_empty(&bo->defrag_link))
 		return;
 
@@ -1204,6 +1227,9 @@ static void xe_bo_defrag_update(struct xe_bo *bo)
 {
 	xe_bo_assert_held(bo);
 
+	if (XE_BO_DEFRAG_SIZE_LIMIT < SZ_2M)
+		return;
+
 	if (xe_bo_needs_defrag(bo))
 		xe_bo_defrag_add(bo);
 	else
Signature · 1 line
2.34.1
author maintainer
#91 lore raw

PATCH v3 23/33 drm/xe: Defrag using out-of-lock page preallocation

In reply to Matthew Brost

Convert xe_bo_defrag_one() to a three-phase scheme that moves the expensive beneficial-order allocations out of the BO dma-resv lock:

1. Under the lock, re-check eligibility, capture the tt cpu-caching and read the exact sub-optimal page count (ttm_tt_suboptimal_pages()), bounded by the run budget.
2. Drop the lock and preallocate that many beneficial-order chunks via ttm_pool_prealloc_fill(); reclaim/compaction stalls and the cpu cache mode change both happen here, outside the lock.
3. Re-take the lock, re-check, and validate consuming the prealloc bag. Any shortfall harvests the old backing instead of reclaiming, so the move never stalls under the lock; the BO re-queues for a later pass.

With both allocation and caching hoisted out, the BO-lock held time drops to copy-bound (median ~0.27ms, p95 ~2ms); the remaining tail is lock-wait behind active rendering, as intended.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Use DIV_ROUND_UP_ULL() for the 64-bit preallocation chunk count (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c | 46 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 45 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +45 -1
index 0bdd1c920404..8b89d34f37d4 100644
@@ -1258,16 +1258,56 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 		.defrag_bytes_remaining = budget,
 	};
 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_pool *pool = &ttm_bo->bdev->pool;
+	struct ttm_pool_prealloc pp = {};
 	struct ttm_placement placement;
 	struct ttm_place place;
+	enum ttm_caching tt_caching;
+	unsigned int order, want = 0;
 	int ret = 0;
 
 	*consumed = 0;
 	*needs_more = false;
 
+	/*
+	 * Phase 1: under the BO lock, re-check eligibility and estimate how
+	 * many beneficial-order chunks the move will (re)allocate, bounded by
+	 * the run's byte budget. Then drop the lock so the high-order, possibly
+	 * reclaim/compaction stalling allocations happen unlocked.
+	 */
+	xe_bo_lock(bo, false);
+	if (!xe_bo_needs_defrag(bo)) {
+		xe_bo_defrag_remove(bo);
+		xe_bo_unlock(bo);
+		goto out;
+	}
+	tt_caching = bo->ttm.ttm->caching;
+	order = ttm_pool_prealloc_order(pool);
+	if (order && ttm_bo->ttm) {
+		u32 suboptimal = ttm_tt_suboptimal_pages(ttm_bo->ttm);
+		u64 cap = min_t(u64, budget, xe_bo_size(bo)) >> PAGE_SHIFT;
+
+		/* Prealloc only the beneficial-order chunks the move replaces. */
+		want = DIV_ROUND_UP_ULL(min_t(u64, suboptimal, cap), 1UL << order);
+	}
+	xe_bo_unlock(bo);
+
+	/* Phase 2: preallocate outside the lock; */
+	if (want) {
+		ret = ttm_pool_prealloc_fill(pool, tt_caching, &pp, want);
+		if (ret || !pp.count) {
+			ret = ret ?: -ENOMEM;
+			xe_gt_stats_incr(xe_root_mmio_gt(xe),
+					 XE_GT_STATS_ID_DEFRAG_FAILED_COUNT, 1);
+			goto out_err;
+		}
+	}
+
+	/*
+	 * Phase 3: re-take the lock, re-check, and validate using the prealloc.
+	 */
 	xe_bo_lock(bo, false);
 
-	/* Re-check eligibility under the BO lock. */
 	if (!xe_bo_needs_defrag(bo)) {
 		xe_bo_defrag_remove(bo);
 		goto unlock;
@@ -1277,6 +1317,7 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	place.flags |= TTM_PL_FLAG_TEMPORARY;
 	placement.num_placement = 1;
 	placement.placement = &place;
+	ctx.prealloc = &pp;
 
 	/*
 	 * On success the move reallocates the backing at beneficial order and
@@ -1321,6 +1362,9 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 
 unlock:
 	xe_bo_unlock(bo);
+out_err:
+	ttm_pool_prealloc_fini(pool, &pp);
+out:
 	return ret;
 }
 
Signature · 1 line
2.34.1
#92 lore raw

Re: [PATCH v3 23/33] drm/xe: Defrag using out-of-lock page preallocation

Quoted 13 lines · Matthew Brost

Convert xe_bo_defrag_one() to a three-phase scheme that moves the expensive beneficial-order allocations out of the BO dma-resv lock:

1. Under the lock, re-check eligibility, capture the tt cpu-caching and read the exact sub-optimal page count (ttm_tt_suboptimal_pages()), bounded by the run budget.
2. Drop the lock and preallocate that many beneficial-order chunks via ttm_pool_prealloc_fill(); reclaim/compaction stalls and the cpu cache mode change both happen here, outside the lock.
3. Re-take the lock, re-check, and validate consuming the prealloc bag. Any shortfall harvests the old backing instead of reclaiming, so the move never stalls under the lock; the BO re-queues for a later pass.

Assisted-by LLM

But as lock is released between phase 1 and 3, there can be BO mismatch between phase-3 and phase-1. More below.

Quoted 60 lines

With both allocation and caching hoisted out, the BO-lock held time drops to copy-bound (median ~0.27ms, p95 ~2ms); the remaining tail is lock-wait behind active rendering, as intended.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Use DIV_ROUND_UP_ULL() for the 64-bit preallocation chunk count (Sashiko)
---
drivers/gpu/drm/xe/xe_bo.c | 46 +++++++++++++++++++++++++++++++++++++-

1 file changed, 45 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +16 -0
index 0bdd1c920404..8b89d34f37d4 100644
@@ -1258,16 +1258,56 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 		.defrag_bytes_remaining = budget,
 	};
 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_pool *pool = &ttm_bo->bdev->pool;
+	struct ttm_pool_prealloc pp = {};
 	struct ttm_placement placement;
 	struct ttm_place place;
+	enum ttm_caching tt_caching;
+	unsigned int order, want = 0;
 	int ret = 0;
 
 	*consumed = 0;
 	*needs_more = false;
 
+	/*
+	 * Phase 1: under the BO lock, re-check eligibility and estimate how
+	 * many beneficial-order chunks the move will (re)allocate, bounded by
+	 * the run's byte budget. Then drop the lock so the high-order, possibly
+	 * reclaim/compaction stalling allocations happen unlocked.
+	 */
+	xe_bo_lock(bo, false);
+	if (!xe_bo_needs_defrag(bo)) {
+		xe_bo_defrag_remove(bo);
+		xe_bo_unlock(bo);
+		goto out;
+	}

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1293

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+	tt_caching = bo->ttm.ttm->caching;
+	order = ttm_pool_prealloc_order(pool);
+	if (order && ttm_bo->ttm) {
+		u32 suboptimal = ttm_tt_suboptimal_pages(ttm_bo->ttm);
+		u64 cap = min_t(u64, budget, xe_bo_size(bo)) >> PAGE_SHIFT;
+
+		/* Prealloc only the beneficial-order chunks the move replaces. */
+		want = DIV_ROUND_UP_ULL(min_t(u64, suboptimal, cap), 1UL << order);
+	}
+	xe_bo_unlock(bo);

As mentioned above, BO can change after we release the lock here. So, 'want' can be less than what BO needs. This is probably ok, as if fetching from prealloc fails, TTM will fall back to fresh alloc.
But if tt_caching changes after releaseing the lock here, it is never checked in phase-3 and page cache setting will be different than that of the BO.

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1298

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +5 -0
+
+	/* Phase 2: preallocate outside the lock; */
+	if (want) {
+		ret = ttm_pool_prealloc_fill(pool, tt_caching, &pp, want);
+		if (ret || !pp.count) {

'!pp.count' is treated as error but 'pp.count < want' is not. Should we?

Niranjana

Quoted 37 lines
drivers/gpu/drm/xe/xe_bo.c +11 -1
+			ret = ret ?: -ENOMEM;
+			xe_gt_stats_incr(xe_root_mmio_gt(xe),
+					 XE_GT_STATS_ID_DEFRAG_FAILED_COUNT, 1);
+			goto out_err;
+		}
+	}
+
+	/*
+	 * Phase 3: re-take the lock, re-check, and validate using the prealloc.
+	 */
 	xe_bo_lock(bo, false);
 
-	/* Re-check eligibility under the BO lock. */
 	if (!xe_bo_needs_defrag(bo)) {
 		xe_bo_defrag_remove(bo);
 		goto unlock;
@@ -1277,6 +1317,7 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	place.flags |= TTM_PL_FLAG_TEMPORARY;
 	placement.num_placement = 1;
 	placement.placement = &place;
+	ctx.prealloc = &pp;
 
 	/*
 	 * On success the move reallocates the backing at beneficial order and
@@ -1321,6 +1362,9 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 

unlock:

	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_bo.c +3 -0
+out_err:
+	ttm_pool_prealloc_fini(pool, &pp);
+out:
	return ret;
}
Signature · 1 line
2.34.1
author maintainer
#93 lore raw

Re: [PATCH v3 23/33] drm/xe: Defrag using out-of-lock page preallocation

Quoted 84 lines · Niranjana Vishwanathapura
Quoted 13 lines · Matthew Brost

Convert xe_bo_defrag_one() to a three-phase scheme that moves the expensive beneficial-order allocations out of the BO dma-resv lock:

1. Under the lock, re-check eligibility, capture the tt cpu-caching and read the exact sub-optimal page count (ttm_tt_suboptimal_pages()), bounded by the run budget.
2. Drop the lock and preallocate that many beneficial-order chunks via ttm_pool_prealloc_fill(); reclaim/compaction stalls and the cpu cache mode change both happen here, outside the lock.
3. Re-take the lock, re-check, and validate consuming the prealloc bag. Any shortfall harvests the old backing instead of reclaiming, so the move never stalls under the lock; the BO re-queues for a later pass.

Assisted-by LLM

But as lock is released between phase 1 and 3, there can be BO mismatch between phase-3 and phase-1. More below.

Quoted 64 lines

With both allocation and caching hoisted out, the BO-lock held time drops to copy-bound (median ~0.27ms, p95 ~2ms); the remaining tail is lock-wait behind active rendering, as intended.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Use DIV_ROUND_UP_ULL() for the 64-bit preallocation chunk count (Sashiko)
---
drivers/gpu/drm/xe/xe_bo.c | 46 +++++++++++++++++++++++++++++++++++++-

1 file changed, 45 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +20 -0
index 0bdd1c920404..8b89d34f37d4 100644
@@ -1258,16 +1258,56 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 		.defrag_bytes_remaining = budget,
 	};
 	struct ttm_buffer_object *ttm_bo = &bo->ttm;
+	struct ttm_pool *pool = &ttm_bo->bdev->pool;
+	struct ttm_pool_prealloc pp = {};
 	struct ttm_placement placement;
 	struct ttm_place place;
+	enum ttm_caching tt_caching;
+	unsigned int order, want = 0;
 	int ret = 0;
 
 	*consumed = 0;
 	*needs_more = false;
 
+	/*
+	 * Phase 1: under the BO lock, re-check eligibility and estimate how
+	 * many beneficial-order chunks the move will (re)allocate, bounded by
+	 * the run's byte budget. Then drop the lock so the high-order, possibly
+	 * reclaim/compaction stalling allocations happen unlocked.
+	 */
+	xe_bo_lock(bo, false);
+	if (!xe_bo_needs_defrag(bo)) {
+		xe_bo_defrag_remove(bo);
+		xe_bo_unlock(bo);
+		goto out;
+	}
+	tt_caching = bo->ttm.ttm->caching;
+	order = ttm_pool_prealloc_order(pool);
+	if (order && ttm_bo->ttm) {
+		u32 suboptimal = ttm_tt_suboptimal_pages(ttm_bo->ttm);
Quoted 8 lines

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1293

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+		u64 cap = min_t(u64, budget, xe_bo_size(bo)) >> PAGE_SHIFT;
+
+		/* Prealloc only the beneficial-order chunks the move replaces. */
+		want = DIV_ROUND_UP_ULL(min_t(u64, suboptimal, cap), 1UL << order);
+	}
+	xe_bo_unlock(bo);

As mentioned above, BO can change after we release the lock here.

Sure, but that is why we recheck the BO in phase 3. If it has changed (e.g., a user closed the BO, it got evicted to SYS, etc...) we just throw away the prealloc and move onto the next BO.

Quoted 5 lines

So, 'want' can be less than what BO needs. This is probably ok, as if fetching from prealloc fails, TTM will fall back to fresh alloc.
But if tt_caching changes after releaseing the lock here, it is never checked in phase-3 and page cache setting will be different than that of the BO.

Caching is a static value for the lifetime of the BO.

So I'm failing to see what the problem is here.

Quoted 8 lines

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1298

Quoted 5 lines
drivers/gpu/drm/xe/xe_bo.c +5 -0
+
+	/* Phase 2: preallocate outside the lock; */
+	if (want) {
+		ret = ttm_pool_prealloc_fill(pool, tt_caching, &pp, want);
+		if (ret || !pp.count) {

'!pp.count' is treated as error but 'pp.count < want' is not. Should we?

'pp.count < want' is not an error.

e.g. We want 32M but only get 2M from the core MM, this is still forward progress and will prune in that 2M into the BO.

!pp.count is core MM gave us no 2M pages, we have nothing to do and backoff the defragmenter.

Matt

Quoted 39 lines

Niranjana

Quoted 37 lines
drivers/gpu/drm/xe/xe_bo.c +11 -1
+			ret = ret ?: -ENOMEM;
+			xe_gt_stats_incr(xe_root_mmio_gt(xe),
+					 XE_GT_STATS_ID_DEFRAG_FAILED_COUNT, 1);
+			goto out_err;
+		}
+	}
+
+	/*
+	 * Phase 3: re-take the lock, re-check, and validate using the prealloc.
+	 */
 	xe_bo_lock(bo, false);
 
-	/* Re-check eligibility under the BO lock. */
 	if (!xe_bo_needs_defrag(bo)) {
 		xe_bo_defrag_remove(bo);
 		goto unlock;
@@ -1277,6 +1317,7 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	place.flags |= TTM_PL_FLAG_TEMPORARY;
 	placement.num_placement = 1;
 	placement.placement = &place;
+	ctx.prealloc = &pp;
 
 	/*
 	 * On success the move reallocates the backing at beneficial order and
@@ -1321,6 +1362,9 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 

unlock:

	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_bo.c +3 -0
+out_err:
+	ttm_pool_prealloc_fini(pool, &pp);
+out:
	return ret;
}
Signature · 1 line
2.34.1
author maintainer
#94 lore raw

PATCH v3 24/33 drm/xe: Add defrag profiling tracepoints

In reply to Matthew Brost

Add two tracepoints to profile the page defragmentation worker:

- xe_bo_defrag_worker: emitted on worker entry and exit with the current defrag list count and the bytes processed in the run.
- xe_bo_defrag_one: emitted per BO with the run budget, the prealloc fill ratio (got/want) and the lock-held, lock-wait and prealloc durations, plus the bytes consumed and the result.

These break down the cost of a defrag attempt into its locked vs unlocked phases, making it possible to confirm that the expensive beneficial-order allocation and cpu cache mode change happen outside the BO dma-resv lock and that the residual lock-held time is copy-bound (with the tail dominated by lock-wait behind active rendering).

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Move the ns-to-us division into TP_fast_assign() to avoid a 64-bit divide in TP_printk() (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c       | 18 +++++++++-
 drivers/gpu/drm/xe/xe_trace_bo.h | 59 ++++++++++++++++++++++++++++++++
 2 files changed, 76 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +17 -1
index 8b89d34f37d4..25e5b72f870c 100644
@@ -1263,7 +1263,9 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	struct ttm_placement placement;
 	struct ttm_place place;
 	enum ttm_caching tt_caching;
-	unsigned int order, want = 0;
+	unsigned int order, want = 0, got = 0;
+	u64 lock_ns = 0, prealloc_ns = 0, lockwait_ns = 0;
+	ktime_t t0;
 	int ret = 0;
 
 	*consumed = 0;
@@ -1294,6 +1296,7 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 
 	/* Phase 2: preallocate outside the lock; */
 	if (want) {
+		t0 = ktime_get();
 		ret = ttm_pool_prealloc_fill(pool, tt_caching, &pp, want);
 		if (ret || !pp.count) {
 			ret = ret ?: -ENOMEM;
@@ -1301,12 +1304,16 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 					 XE_GT_STATS_ID_DEFRAG_FAILED_COUNT, 1);
 			goto out_err;
 		}
+		prealloc_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
 	}
 
 	/*
 	 * Phase 3: re-take the lock, re-check, and validate using the prealloc.
 	 */
+	t0 = ktime_get();
 	xe_bo_lock(bo, false);
+	lockwait_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
+	t0 = ktime_get();
 
 	if (!xe_bo_needs_defrag(bo)) {
 		xe_bo_defrag_remove(bo);
@@ -1362,9 +1369,13 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 
 unlock:
 	xe_bo_unlock(bo);
+	lock_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
+	got = pp.used;
 out_err:
 	ttm_pool_prealloc_fini(pool, &pp);
 out:
+	trace_xe_bo_defrag_one(bo, budget, want, got, lock_ns, prealloc_ns,
+			       lockwait_ns, *consumed, ret);
 	return ret;
 }
 
@@ -1396,6 +1407,9 @@ static void xe_bo_defrag_worker(struct work_struct *w)
 		return;
 	}
 
+	trace_xe_bo_defrag_worker(xe, 0, atomic_read(&xe->mem.defrag.count),
+				  true);
+
 	/*
 	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated
 	 * backing per run rather than draining the whole list in one go. Only
@@ -1503,6 +1517,8 @@ static void xe_bo_defrag_worker(struct work_struct *w)
 
 	xe_pm_runtime_put(xe);
 	drm_dev_exit(idx);
+	trace_xe_bo_defrag_worker(xe, defrag_bytes,
+				  atomic_read(&xe->mem.defrag.count), false);
 }
 
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
drivers/gpu/drm/xe/xe_trace_bo.h +59 -0

65 lines not on this page · raw message

Signature · 1 line
2.34.1
#95 lore raw

Re: [PATCH v3 24/33] drm/xe: Add defrag profiling tracepoints

Quoted 67 lines · Matthew Brost

Add two tracepoints to profile the page defragmentation worker:

- xe_bo_defrag_worker: emitted on worker entry and exit with the current defrag list count and the bytes processed in the run.
- xe_bo_defrag_one: emitted per BO with the run budget, the prealloc fill ratio (got/want) and the lock-held, lock-wait and prealloc durations, plus the bytes consumed and the result.

These break down the cost of a defrag attempt into its locked vs unlocked phases, making it possible to confirm that the expensive beneficial-order allocation and cpu cache mode change happen outside the BO dma-resv lock and that the residual lock-held time is copy-bound (with the tail dominated by lock-wait behind active rendering).

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Move the ns-to-us division into TP_fast_assign() to avoid a 64-bit divide in TP_printk() (Sashiko)
---
drivers/gpu/drm/xe/xe_bo.c | 18 +++++++++-
drivers/gpu/drm/xe/xe_trace_bo.h | 59 ++++++++++++++++++++++++++++++++

2 files changed, 76 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +4 -1
index 8b89d34f37d4..25e5b72f870c 100644
@@ -1263,7 +1263,9 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	struct ttm_placement placement;
 	struct ttm_place place;
 	enum ttm_caching tt_caching;
-	unsigned int order, want = 0;
+	unsigned int order, want = 0, got = 0;
+	u64 lock_ns = 0, prealloc_ns = 0, lockwait_ns = 0;
+	ktime_t t0;
 	int ret = 0;
 
 	*consumed = 0;
@@ -1294,6 +1296,7 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 
 	/* Phase 2: preallocate outside the lock; */
 	if (want) {
+		t0 = ktime_get();
 		ret = ttm_pool_prealloc_fill(pool, tt_caching, &pp, want);
 		if (ret || !pp.count) {
 			ret = ret ?: -ENOMEM;
@@ -1301,12 +1304,16 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 					 XE_GT_STATS_ID_DEFRAG_FAILED_COUNT, 1);
 			goto out_err;
 		}

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1316

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
+		prealloc_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
 	}
 
 	/*
 	 * Phase 3: re-take the lock, re-check, and validate using the prealloc.
 	 */
+	t0 = ktime_get();
 	xe_bo_lock(bo, false);
+	lockwait_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
+	t0 = ktime_get();

Here only phase 3 locking is profiled. What about phase 1 locking?

Niranjana

Quoted 109 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 	if (!xe_bo_needs_defrag(bo)) {
 		xe_bo_defrag_remove(bo);
@@ -1362,9 +1369,13 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 

unlock:

	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_bo.c +2 -0
+	lock_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
+	got = pp.used;

out_err:

	ttm_pool_prealloc_fini(pool, &pp);

out:

drivers/gpu/drm/xe/xe_bo.c +2 -0
+	trace_xe_bo_defrag_one(bo, budget, want, got, lock_ns, prealloc_ns,
+			       lockwait_ns, *consumed, ret);
	return ret;
}
drivers/gpu/drm/xe/xe_bo.c +5 -0
@@ -1396,6 +1407,9 @@ static void xe_bo_defrag_worker(struct work_struct *w)
 		return;
 	}
 
+	trace_xe_bo_defrag_worker(xe, 0, atomic_read(&xe->mem.defrag.count),
+				  true);
+
 	/*
 	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated
 	 * backing per run rather than draining the whole list in one go. Only
@@ -1503,6 +1517,8 @@ static void xe_bo_defrag_worker(struct work_struct *w)
 
 	xe_pm_runtime_put(xe);
 	drm_dev_exit(idx);
+	trace_xe_bo_defrag_worker(xe, defrag_bytes,
+				  atomic_read(&xe->mem.defrag.count), false);
 }
 
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
drivers/gpu/drm/xe/xe_trace_bo.h +59 -0
index 86323cf3be2c..b159d37d39a1 100644
@@ -85,6 +85,65 @@ TRACE_EVENT(xe_bo_move,
 		      __get_str(new_placement_name), __get_str(device_id))
 );
 
+TRACE_EVENT(xe_bo_defrag_worker,
+	    TP_PROTO(struct xe_device *xe, u64 defrag_bytes, int count,
+		     bool enter),
+	    TP_ARGS(xe, defrag_bytes, count, enter),
+	    TP_STRUCT__entry(
+		     __string(dev, dev_name(xe->drm.dev))
+		     __field(u64, defrag_bytes)
+		     __field(int, count)
+		     __field(bool, enter)
+		     ),
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->defrag_bytes = defrag_bytes;
+		   __entry->count = count;
+		   __entry->enter = enter;
+		   ),
+	    TP_printk("dev=%s %s defrag_bytes=%llu count=%d",
+		      __get_str(dev), __entry->enter ? "enter" : "exit",
+		      __entry->defrag_bytes, __entry->count)
+);
+
+TRACE_EVENT(xe_bo_defrag_one,
+	    TP_PROTO(struct xe_bo *bo, u64 budget, unsigned int prealloc_want,
+		     unsigned int prealloc_got, u64 lock_ns, u64 prealloc_ns,
+		     u64 lockwait_ns, u64 consumed, int ret),
+	    TP_ARGS(bo, budget, prealloc_want, prealloc_got, lock_ns,
+		    prealloc_ns, lockwait_ns, consumed, ret),
+	    TP_STRUCT__entry(
+		     __string(dev, __dev_name_bo(bo))
+		     __field(size_t, size)
+		     __field(u64, budget)
+		     __field(unsigned int, prealloc_want)
+		     __field(unsigned int, prealloc_got)
+		     __field(u64, lock_us)
+		     __field(u64, prealloc_us)
+		     __field(u64, lockwait_us)
+		     __field(u64, consumed)
+		     __field(int, ret)
+		     ),
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->size = xe_bo_size(bo);
+		   __entry->budget = budget;
+		   __entry->prealloc_want = prealloc_want;
+		   __entry->prealloc_got = prealloc_got;
+		   __entry->lock_us = div_u64(lock_ns, 1000);
+		   __entry->prealloc_us = div_u64(prealloc_ns, 1000);
+		   __entry->lockwait_us = div_u64(lockwait_ns, 1000);
+		   __entry->consumed = consumed;
+		   __entry->ret = ret;
+		   ),
+	    TP_printk("dev=%s size=%zu budget=%llu prealloc=%u/%u lock_us=%llu lockwait_us=%llu prealloc_us=%llu consumed=%llu ret=%d",
+		      __get_str(dev), __entry->size, __entry->budget,
+		      __entry->prealloc_got, __entry->prealloc_want,
+		      __entry->lock_us, __entry->lockwait_us,
+		      __entry->prealloc_us, __entry->consumed,
+		      __entry->ret)
+);
+
 DECLARE_EVENT_CLASS(xe_vma,
 		    TP_PROTO(struct xe_vma *vma),
 		    TP_ARGS(vma),
Signature · 1 line
2.34.1
author maintainer
#96 lore raw

Re: [PATCH v3 24/33] drm/xe: Add defrag profiling tracepoints

Quoted 71 lines · Niranjana Vishwanathapura
Quoted 70 lines · Matthew Brost

Add two tracepoints to profile the page defragmentation worker:

- xe_bo_defrag_worker: emitted on worker entry and exit with the current defrag list count and the bytes processed in the run.
- xe_bo_defrag_one: emitted per BO with the run budget, the prealloc fill ratio (got/want) and the lock-held, lock-wait and prealloc durations, plus the bytes consumed and the result.

These break down the cost of a defrag attempt into its locked vs unlocked phases, making it possible to confirm that the expensive beneficial-order allocation and cpu cache mode change happen outside the BO dma-resv lock and that the residual lock-held time is copy-bound (with the tail dominated by lock-wait behind active rendering).

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Move the ns-to-us division into TP_fast_assign() to avoid a 64-bit divide in TP_printk() (Sashiko)
---
drivers/gpu/drm/xe/xe_bo.c | 18 +++++++++-
drivers/gpu/drm/xe/xe_trace_bo.h | 59 ++++++++++++++++++++++++++++++++

2 files changed, 76 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_bo.c +5 -1
index 8b89d34f37d4..25e5b72f870c 100644
@@ -1263,7 +1263,9 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 	struct ttm_placement placement;
 	struct ttm_place place;
 	enum ttm_caching tt_caching;
-	unsigned int order, want = 0;
+	unsigned int order, want = 0, got = 0;
+	u64 lock_ns = 0, prealloc_ns = 0, lockwait_ns = 0;
+	ktime_t t0;
 	int ret = 0;
 
 	*consumed = 0;
@@ -1294,6 +1296,7 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 
 	/* Phase 2: preallocate outside the lock; */
 	if (want) {
+		t0 = ktime_get();
 		ret = ttm_pool_prealloc_fill(pool, tt_caching, &pp, want);
 		if (ret || !pp.count) {
 			ret = ret ?: -ENOMEM;
@@ -1301,12 +1304,16 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 					 XE_GT_STATS_ID_DEFRAG_FAILED_COUNT, 1);
 			goto out_err;
 		}
+		prealloc_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
 	}
 
Quoted 10 lines

drivers/gpu/drm/xe/xe_bo.c static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo, · line 1316

Quoted 7 lines
drivers/gpu/drm/xe/xe_bo.c +3 -0
 	/*
 	 * Phase 3: re-take the lock, re-check, and validate using the prealloc.
 	 */
+	t0 = ktime_get();
 	xe_bo_lock(bo, false);
+	lockwait_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
+	t0 = ktime_get();

Here only phase 3 locking is profiled. What about phase 1 locking?

Phase 1 consists of a series of very small, time bounded checks performed under lock for stability, which should be extremely fast.

Phase 3 is interesting part as we perform dma mapping, formulate a copy job, and internally update the TTM bookkeeping. If this part takes too long (several ms) we could risk missing page flips as compositor could be waiting on the same lock. Fortunately iirc for most BOs the lock is held for less than 100us. So this is part we really need ftrace points for profiling.

Matt

Quoted 111 lines

Niranjana

Quoted 109 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 	if (!xe_bo_needs_defrag(bo)) {
 		xe_bo_defrag_remove(bo);
@@ -1362,9 +1369,13 @@ static int xe_bo_defrag_one(struct xe_device *xe, struct xe_bo *bo,
 

unlock:

	xe_bo_unlock(bo);
drivers/gpu/drm/xe/xe_bo.c +2 -0
+	lock_ns = ktime_to_ns(ktime_sub(ktime_get(), t0));
+	got = pp.used;

out_err:

	ttm_pool_prealloc_fini(pool, &pp);

out:

drivers/gpu/drm/xe/xe_bo.c +2 -0
+	trace_xe_bo_defrag_one(bo, budget, want, got, lock_ns, prealloc_ns,
+			       lockwait_ns, *consumed, ret);
	return ret;
}
drivers/gpu/drm/xe/xe_bo.c +5 -0
@@ -1396,6 +1407,9 @@ static void xe_bo_defrag_worker(struct work_struct *w)
 		return;
 	}
 
+	trace_xe_bo_defrag_worker(xe, 0, atomic_read(&xe->mem.defrag.count),
+				  true);
+
 	/*
 	 * Process at most XE_BO_DEFRAG_SIZE_LIMIT bytes of newly (re)allocated
 	 * backing per run rather than draining the whole list in one go. Only
@@ -1503,6 +1517,8 @@ static void xe_bo_defrag_worker(struct work_struct *w)
 
 	xe_pm_runtime_put(xe);
 	drm_dev_exit(idx);
+	trace_xe_bo_defrag_worker(xe, defrag_bytes,
+				  atomic_read(&xe->mem.defrag.count), false);
 }
 
 static int xe_bo_move(struct ttm_buffer_object *ttm_bo, bool evict,
drivers/gpu/drm/xe/xe_trace_bo.h +59 -0
index 86323cf3be2c..b159d37d39a1 100644
@@ -85,6 +85,65 @@ TRACE_EVENT(xe_bo_move,
 		      __get_str(new_placement_name), __get_str(device_id))
 );
 
+TRACE_EVENT(xe_bo_defrag_worker,
+	    TP_PROTO(struct xe_device *xe, u64 defrag_bytes, int count,
+		     bool enter),
+	    TP_ARGS(xe, defrag_bytes, count, enter),
+	    TP_STRUCT__entry(
+		     __string(dev, dev_name(xe->drm.dev))
+		     __field(u64, defrag_bytes)
+		     __field(int, count)
+		     __field(bool, enter)
+		     ),
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->defrag_bytes = defrag_bytes;
+		   __entry->count = count;
+		   __entry->enter = enter;
+		   ),
+	    TP_printk("dev=%s %s defrag_bytes=%llu count=%d",
+		      __get_str(dev), __entry->enter ? "enter" : "exit",
+		      __entry->defrag_bytes, __entry->count)
+);
+
+TRACE_EVENT(xe_bo_defrag_one,
+	    TP_PROTO(struct xe_bo *bo, u64 budget, unsigned int prealloc_want,
+		     unsigned int prealloc_got, u64 lock_ns, u64 prealloc_ns,
+		     u64 lockwait_ns, u64 consumed, int ret),
+	    TP_ARGS(bo, budget, prealloc_want, prealloc_got, lock_ns,
+		    prealloc_ns, lockwait_ns, consumed, ret),
+	    TP_STRUCT__entry(
+		     __string(dev, __dev_name_bo(bo))
+		     __field(size_t, size)
+		     __field(u64, budget)
+		     __field(unsigned int, prealloc_want)
+		     __field(unsigned int, prealloc_got)
+		     __field(u64, lock_us)
+		     __field(u64, prealloc_us)
+		     __field(u64, lockwait_us)
+		     __field(u64, consumed)
+		     __field(int, ret)
+		     ),
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->size = xe_bo_size(bo);
+		   __entry->budget = budget;
+		   __entry->prealloc_want = prealloc_want;
+		   __entry->prealloc_got = prealloc_got;
+		   __entry->lock_us = div_u64(lock_ns, 1000);
+		   __entry->prealloc_us = div_u64(prealloc_ns, 1000);
+		   __entry->lockwait_us = div_u64(lockwait_ns, 1000);
+		   __entry->consumed = consumed;
+		   __entry->ret = ret;
+		   ),
+	    TP_printk("dev=%s size=%zu budget=%llu prealloc=%u/%u lock_us=%llu lockwait_us=%llu prealloc_us=%llu consumed=%llu ret=%d",
+		      __get_str(dev), __entry->size, __entry->budget,
+		      __entry->prealloc_got, __entry->prealloc_want,
+		      __entry->lock_us, __entry->lockwait_us,
+		      __entry->prealloc_us, __entry->consumed,
+		      __entry->ret)
+);
+
 DECLARE_EVENT_CLASS(xe_vma,
 		    TP_PROTO(struct xe_vma *vma),
 		    TP_ARGS(vma),
Signature · 1 line
2.34.1
author maintainer
#97 lore raw

PATCH v3 25/33 drm/xe: Preallocate system BO backing outside the dma-resv lock

In reply to Matthew Brost

xe_gem_create_ioctl() populates a buffer object's backing store inside xe_validation_guard(), i.e. under the dma-resv lock. For a system-memory buffer that means the whole page allocation - potentially stalling in reclaim or compaction - happens in the critical section, holding the reservation and blocking anything that contends on it.

Use the TTM full-preallocation mechanism to move that work out of the lock. For a system-only, non-deferred user BO, allocate the entire tt backing up front, before entering the validation guard, and hand the bag down to the populate so it merely installs the pages:

- Thread an optional struct ttm_pool_prealloc through xe_bo_create_user() -> __xe_bo_create_locked() -> xe_bo_init_locked(), which stashes it in ttm_operation_ctx::prealloc. All other callers pass NULL.

- In xe_gem_create_ioctl(), for XE_BO_FLAG_SYSTEM BOs that are not VRAM, stolen or deferred-backing, call ttm_pool_prealloc_fill_full() before the guard and ttm_pool_prealloc_fini() after it. The bag size covers both the data pages and the appended CCS backup pages, matching the tt layout in xe_ttm_tt_create(), and the caching mirrors the same path.

The fill is best-effort: on a short fill (or if it is skipped) the pool allocates the remainder in-line as before, so this is purely an optimisation with no behavioural change to the created BO. fini() only releases the unconsumed tail, so it is safe on every success, error and OOM-retry path (consumed pages are owned by the tt).

The fill requests reclaim backoff for higher-order chunks (@beneficial_reclaim_backoff): Xe runs a background defragmenter that upgrades suboptimal pages to beneficial order in place, so there is no need to stall this user context reclaiming/compacting for contiguity.

To size the preallocation before the xe_bo exists, factor the CCS-pages decision in xe_bo_needs_ccs_pages() into a parameterised helper, __xe_bo_needs_ccs_pages(), and query it directly from the ioctl.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Preallocate only when the backing fits the available TT space (Sashiko)

---
 drivers/gpu/drm/xe/tests/xe_bo.c      |   8 +-
 drivers/gpu/drm/xe/tests/xe_dma_buf.c |   2 +-
 drivers/gpu/drm/xe/tests/xe_migrate.c |   6 +-
 drivers/gpu/drm/xe/xe_bo.c            | 139 +++++++++++++++++++++-----
 drivers/gpu/drm/xe/xe_bo.h            |   8 +-
 drivers/gpu/drm/xe/xe_dma_buf.c       |   2 +-
 6 files changed, 128 insertions(+), 37 deletions(-)
drivers/gpu/drm/xe/tests/xe_bo.c +4 -4
index 49c95ed67d7e..78781317b420 100644
@@ -141,7 +141,7 @@ static void ccs_test_run_tile(struct xe_device *xe, struct xe_tile *tile,
 		kunit_info(test, "Testing system memory\n");
 
 	bo = xe_bo_create_user(xe, NULL, SZ_1M, DRM_XE_GEM_CPU_CACHING_WC,
-			       bo_flags, exec);
+			       bo_flags, NULL, exec);
 	if (IS_ERR(bo)) {
 		KUNIT_FAIL(test, "Failed to create bo.\n");
 		return;
@@ -220,7 +220,7 @@ static int evict_test_run_tile(struct xe_device *xe, struct xe_tile *tile, struc
 		xe_vm_lock(vm, false);
 		bo = xe_bo_create_user(xe, vm, 0x10000,
 				       DRM_XE_GEM_CPU_CACHING_WC,
-				       bo_flags, exec);
+				       bo_flags, NULL, exec);
 		xe_vm_unlock(vm);
 		if (IS_ERR(bo)) {
 			KUNIT_FAIL(test, "bo create err=%pe\n", bo);
@@ -229,7 +229,7 @@ static int evict_test_run_tile(struct xe_device *xe, struct xe_tile *tile, struc
 
 		external = xe_bo_create_user(xe, NULL, 0x10000,
 					     DRM_XE_GEM_CPU_CACHING_WC,
-					     bo_flags, NULL);
+					     bo_flags, NULL, NULL);
 		if (IS_ERR(external)) {
 			KUNIT_FAIL(test, "external bo create err=%pe\n", external);
 			goto cleanup_bo;
@@ -494,7 +494,7 @@ static int shrink_test_run_device(struct xe_device *xe)
 		/* We can create bos using WC caching here. But it is slower. */
 		bo = xe_bo_create_user(xe, NULL, XE_BO_SHRINK_SIZE,
 				       DRM_XE_GEM_CPU_CACHING_WB,
-				       XE_BO_FLAG_SYSTEM, NULL);
+				       XE_BO_FLAG_SYSTEM, NULL, NULL);
 		if (IS_ERR(bo)) {
 			if (bo != ERR_PTR(-ENOMEM) && bo != ERR_PTR(-ENOSPC) &&
 			    bo != ERR_PTR(-EINTR) && bo != ERR_PTR(-ERESTARTSYS))
drivers/gpu/drm/xe/tests/xe_dma_buf.c +1 -1
index 0be8440b3976..e4fdc247c0c7 100644
@@ -127,7 +127,7 @@ static void xe_test_dmabuf_import_same_driver(struct xe_device *xe)
 
 	kunit_info(test, "running %s\n", __func__);
 	bo = xe_bo_create_user(xe, NULL, size, DRM_XE_GEM_CPU_CACHING_WC,
-			       params->mem_mask, NULL);
+			       params->mem_mask, NULL, NULL);
 	if (IS_ERR(bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
 			   PTR_ERR(bo));
drivers/gpu/drm/xe/tests/xe_migrate.c +3 -3
index 3c1be809be82..41de648b2c86 100644
@@ -647,7 +647,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 				   DRM_XE_GEM_CPU_CACHING_WC,
 				   XE_BO_FLAG_SYSTEM |
 				   XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				   XE_BO_FLAG_PINNED, NULL);
+				   XE_BO_FLAG_PINNED, NULL, NULL);
 
 	if (IS_ERR(sys_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
@@ -673,7 +673,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 	ccs_bo = xe_bo_create_user(xe, NULL, SZ_4M,
 				   DRM_XE_GEM_CPU_CACHING_WC,
 				   bo_flags | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				   XE_BO_FLAG_PINNED, NULL);
+				   XE_BO_FLAG_PINNED, NULL, NULL);
 
 	if (IS_ERR(ccs_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
@@ -698,7 +698,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 	vram_bo = xe_bo_create_user(xe, NULL, SZ_4M,
 				    DRM_XE_GEM_CPU_CACHING_WC,
 				    bo_flags | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				    XE_BO_FLAG_PINNED, NULL);
+				    XE_BO_FLAG_PINNED, NULL, NULL);
 	if (IS_ERR(vram_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
 			   PTR_ERR(vram_bo));
drivers/gpu/drm/xe/xe_bo.c +113 -26

290 lines not on this page · raw message

drivers/gpu/drm/xe/xe_bo.h +6 -2
index 38d50f8122cb..18fcccd082b7 100644
@@ -111,6 +111,7 @@ enum xe_madv_purgeable_state {
 
 struct sg_table;
 struct ttm_tt;
+struct ttm_pool_prealloc;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -119,13 +120,16 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 				struct xe_tile *tile, struct dma_resv *resv,
 				struct ttm_lru_bulk_move *bulk, size_t size,
 				u16 cpu_caching, enum ttm_bo_type type,
-				u32 flags, struct drm_exec *exec);
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec);
 struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
 				  struct xe_vm *vm, size_t size,
 				  enum ttm_bo_type type, u32 flags,
 				  struct drm_exec *exec);
 struct xe_bo *xe_bo_create_user(struct xe_device *xe, struct xe_vm *vm, size_t size,
-				u16 cpu_caching, u32 flags, struct drm_exec *exec);
+				u16 cpu_caching, u32 flags,
+				struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec);
 struct xe_bo *xe_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
 				   struct xe_vm *vm, size_t size,
 				   enum ttm_bo_type type, u32 flags,
drivers/gpu/drm/xe/xe_dma_buf.c +1 -1
index 8a920e58245c..ec947d86a1ce 100644
@@ -302,7 +302,7 @@ xe_dma_buf_create_obj(struct drm_device *dev, struct dma_buf *dma_buf)
 
 		bo = xe_bo_init_locked(xe, NULL, NULL, resv, NULL, dma_buf->size,
 				       0, /* Will require 1way or 2way for vm_bind */
-				       ttm_bo_type_sg, XE_BO_FLAG_SYSTEM, &exec);
+				       ttm_bo_type_sg, XE_BO_FLAG_SYSTEM, NULL, &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			ret = PTR_ERR(bo);
Signature · 1 line
2.34.1
#98 lore raw

Re: [PATCH v3 25/33] drm/xe: Preallocate system BO backing outside the dma-resv lock

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [Critical] xe_device_ccs_bytes() truncates the calculated CCS size to u32, causing massive under-allocation of the ttm_tt pages array for buffers >= 1TB. --

--- Patch [25]: [PATCH v3 25/33] drm/xe: Preallocate system BO backing outside the dma-resv lock --- commit 4ef9a2744ced48ab96c8a05eeb4fe0fa0b3bafac
Author: Matthew Brost <[email protected]>

drm/xe: Preallocate system BO backing outside the dma-resv lock

This commit uses the TTM full-preallocation mechanism to allocate the entire tt backing up front before entering the validation guard for system-only, non-deferred user BOs. It sizes the preallocation by querying the CCS-pages decision directly from the ioctl.

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
index 25e5b72f870c0..a646a72122d40 100644

[ ... ]

Quoted 22 lines
drivers/gpu/drm/xe/xe_bo.c +18 -0
@@ -4018,6 +4033,64 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			return -ENOENT;
 	}
 
+	/*
+	 * For system-only BOs, preallocate the whole backing outside the
+	 * dma-resv lock so the populate under the validation guard does not
+	 * stall in reclaim/compaction. The caching mirrors the system-BO path
+	 * in xe_ttm_tt_create(); the pool falls back to in-line allocation for
+	 * any shortfall, so a failed fill is harmless.
+	 */
+	if ((bo_flags & XE_BO_FLAG_SYSTEM) &&
+	    !(bo_flags & (XE_BO_FLAG_DEFER_BACKING | XE_BO_FLAG_VRAM_MASK |
+			  XE_BO_FLAG_STOLEN))) {
+		struct ttm_resource_manager *tt_man =
+			ttm_manager_type(&xe->ttm, XE_PL_TT);
+		enum ttm_caching caching = ttm_cached;
+		unsigned long num_pages = args->size >> PAGE_SHIFT;
+
+		if (!IS_DGFX(xe) &&
+		    args->cpu_caching == DRM_XE_GEM_CPU_CACHING_WC)
+			caching = ttm_write_combined;

drivers/gpu/drm/xe/xe_bo.c int xe_gem_create_ioctl(struct drm_device *dev, void *data, · line 4063

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+
+		/*
+		 * Cover the CCS backup pages appended to the tt (see
+		 * xe_ttm_tt_create()) so the whole tt is preallocated.
+		 */
+		if (__xe_bo_needs_ccs_pages(xe, ttm_bo_type_device, bo_flags,
+					    args->cpu_caching))
+			num_pages += DIV_ROUND_UP(xe_device_ccs_bytes(xe,
+								      args->size),
+						  PAGE_SIZE);

[Severity: Critical]
This is a pre-existing issue, but does xe_device_ccs_bytes() truncate the calculated size for very large buffers?

Looking at drivers/gpu/drm/xe/xe_device.c:

u32 xe_device_ccs_bytes(struct xe_device *xe, u64 size)

{
	return xe_device_has_flat_ccs(xe) ?
		DIV_ROUND_UP_ULL(size, NUM_BYTES_PER_CCS_BYTE(xe)) : 0;
}

Because the return type is u32, if a user requests a buffer of 1TB or larger, the calculated CCS size truncates. For a 1TB buffer with a 256:1 compression ratio, size / 256 exactly equals 0x100000000, which truncates to 0.

This means num_pages will not include the necessary CCS backup pages (and similarly extra_pages in xe_ttm_tt_create() will be 0), which can lead to a massive heap buffer overflow when the driver or GPU writes past the end of the under-sized ttm_tt pages array.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
#99 lore raw

Re: [PATCH v3 25/33] drm/xe: Preallocate system BO backing outside the dma-resv lock

In reply to Matthew Brost
Quoted 353 lines · Matthew Brost

xe_gem_create_ioctl() populates a buffer object's backing store inside xe_validation_guard(), i.e. under the dma-resv lock. For a system-memory buffer that means the whole page allocation - potentially stalling in reclaim or compaction - happens in the critical section, holding the reservation and blocking anything that contends on it.

Use the TTM full-preallocation mechanism to move that work out of the lock. For a system-only, non-deferred user BO, allocate the entire tt backing up front, before entering the validation guard, and hand the bag down to the populate so it merely installs the pages:

- Thread an optional struct ttm_pool_prealloc through xe_bo_create_user() -> __xe_bo_create_locked() -> xe_bo_init_locked(), which stashes it in ttm_operation_ctx::prealloc. All other callers pass NULL.

- In xe_gem_create_ioctl(), for XE_BO_FLAG_SYSTEM BOs that are not VRAM, stolen or deferred-backing, call ttm_pool_prealloc_fill_full() before the guard and ttm_pool_prealloc_fini() after it. The bag size covers both the data pages and the appended CCS backup pages, matching the tt layout in xe_ttm_tt_create(), and the caching mirrors the same path.

The fill is best-effort: on a short fill (or if it is skipped) the pool allocates the remainder in-line as before, so this is purely an optimisation with no behavioural change to the created BO. fini() only releases the unconsumed tail, so it is safe on every success, error and OOM-retry path (consumed pages are owned by the tt).

The fill requests reclaim backoff for higher-order chunks (@beneficial_reclaim_backoff): Xe runs a background defragmenter that upgrades suboptimal pages to beneficial order in place, so there is no need to stall this user context reclaiming/compacting for contiguity.

To size the preallocation before the xe_bo exists, factor the CCS-pages decision in xe_bo_needs_ccs_pages() into a parameterised helper, __xe_bo_needs_ccs_pages(), and query it directly from the ioctl.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Preallocate only when the backing fits the available TT space (Sashiko)
---

drivers/gpu/drm/xe/tests/xe_bo.c      |   8 +-
drivers/gpu/drm/xe/tests/xe_dma_buf.c |   2 +-
drivers/gpu/drm/xe/tests/xe_migrate.c |   6 +-
drivers/gpu/drm/xe/xe_bo.c            | 139 +++++++++++++++++++++-----
drivers/gpu/drm/xe/xe_bo.h            |   8 +-
drivers/gpu/drm/xe/xe_dma_buf.c       |   2 +-
6 files changed, 128 insertions(+), 37 deletions(-)
drivers/gpu/drm/xe/tests/xe_bo.c +4 -4
index 49c95ed67d7e..78781317b420 100644
@@ -141,7 +141,7 @@ static void ccs_test_run_tile(struct xe_device *xe, struct xe_tile *tile,
 		kunit_info(test, "Testing system memory\n");
 
 	bo = xe_bo_create_user(xe, NULL, SZ_1M, DRM_XE_GEM_CPU_CACHING_WC,
-			       bo_flags, exec);
+			       bo_flags, NULL, exec);
 	if (IS_ERR(bo)) {
 		KUNIT_FAIL(test, "Failed to create bo.\n");
 		return;
@@ -220,7 +220,7 @@ static int evict_test_run_tile(struct xe_device *xe, struct xe_tile *tile, struc
 		xe_vm_lock(vm, false);
 		bo = xe_bo_create_user(xe, vm, 0x10000,
 				       DRM_XE_GEM_CPU_CACHING_WC,
-				       bo_flags, exec);
+				       bo_flags, NULL, exec);
 		xe_vm_unlock(vm);
 		if (IS_ERR(bo)) {
 			KUNIT_FAIL(test, "bo create err=%pe\n", bo);
@@ -229,7 +229,7 @@ static int evict_test_run_tile(struct xe_device *xe, struct xe_tile *tile, struc
 
 		external = xe_bo_create_user(xe, NULL, 0x10000,
 					     DRM_XE_GEM_CPU_CACHING_WC,
-					     bo_flags, NULL);
+					     bo_flags, NULL, NULL);
 		if (IS_ERR(external)) {
 			KUNIT_FAIL(test, "external bo create err=%pe\n", external);
 			goto cleanup_bo;
@@ -494,7 +494,7 @@ static int shrink_test_run_device(struct xe_device *xe)
 		/* We can create bos using WC caching here. But it is slower. */
 		bo = xe_bo_create_user(xe, NULL, XE_BO_SHRINK_SIZE,
 				       DRM_XE_GEM_CPU_CACHING_WB,
-				       XE_BO_FLAG_SYSTEM, NULL);
+				       XE_BO_FLAG_SYSTEM, NULL, NULL);
 		if (IS_ERR(bo)) {
 			if (bo != ERR_PTR(-ENOMEM) && bo != ERR_PTR(-ENOSPC) &&
 			    bo != ERR_PTR(-EINTR) && bo != ERR_PTR(-ERESTARTSYS))
drivers/gpu/drm/xe/tests/xe_dma_buf.c +1 -1
index 0be8440b3976..e4fdc247c0c7 100644
@@ -127,7 +127,7 @@ static void xe_test_dmabuf_import_same_driver(struct xe_device *xe)
 
 	kunit_info(test, "running %s\n", __func__);
 	bo = xe_bo_create_user(xe, NULL, size, DRM_XE_GEM_CPU_CACHING_WC,
-			       params->mem_mask, NULL);
+			       params->mem_mask, NULL, NULL);
 	if (IS_ERR(bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
 			   PTR_ERR(bo));
drivers/gpu/drm/xe/tests/xe_migrate.c +3 -3
index 3c1be809be82..41de648b2c86 100644
@@ -647,7 +647,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 				   DRM_XE_GEM_CPU_CACHING_WC,
 				   XE_BO_FLAG_SYSTEM |
 				   XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				   XE_BO_FLAG_PINNED, NULL);
+				   XE_BO_FLAG_PINNED, NULL, NULL);
 
 	if (IS_ERR(sys_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
@@ -673,7 +673,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 	ccs_bo = xe_bo_create_user(xe, NULL, SZ_4M,
 				   DRM_XE_GEM_CPU_CACHING_WC,
 				   bo_flags | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				   XE_BO_FLAG_PINNED, NULL);
+				   XE_BO_FLAG_PINNED, NULL, NULL);
 
 	if (IS_ERR(ccs_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
@@ -698,7 +698,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 	vram_bo = xe_bo_create_user(xe, NULL, SZ_4M,
 				    DRM_XE_GEM_CPU_CACHING_WC,
 				    bo_flags | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				    XE_BO_FLAG_PINNED, NULL);
+				    XE_BO_FLAG_PINNED, NULL, NULL);
 	if (IS_ERR(vram_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
 			   PTR_ERR(vram_bo));
drivers/gpu/drm/xe/xe_bo.c +74 -11
index 25e5b72f870c..a646a72122d4 100644
@@ -1948,7 +1948,7 @@ int xe_bo_notifier_prepare_pinned(struct xe_bo *bo)
 		backup = xe_bo_init_locked(xe, NULL, NULL, bo->ttm.base.resv, NULL, xe_bo_size(bo),
 					   DRM_XE_GEM_CPU_CACHING_WB, ttm_bo_type_kernel,
 					   XE_BO_FLAG_SYSTEM | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-					   XE_BO_FLAG_PINNED, &exec);
+					   XE_BO_FLAG_PINNED, NULL, &exec);
 		if (IS_ERR(backup)) {
 			drm_exec_retry_on_contention(&exec);
 			ret = PTR_ERR(backup);
@@ -2089,7 +2089,7 @@ int xe_bo_evict_pinned(struct xe_bo *bo)
 						   xe_bo_size(bo),
 						   DRM_XE_GEM_CPU_CACHING_WB, ttm_bo_type_kernel,
 						   XE_BO_FLAG_SYSTEM | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-						   XE_BO_FLAG_PINNED, &exec);
+						   XE_BO_FLAG_PINNED, NULL, &exec);
 			if (IS_ERR(backup)) {
 				drm_exec_retry_on_contention(&exec);
 				ret = PTR_ERR(backup);
@@ -2884,6 +2884,8 @@ void xe_bo_free(struct xe_bo *bo)
 * @cpu_caching: The cpu caching used for system memory backing store.
 * @type: The TTM buffer object type.
 * @flags: XE_BO_FLAG_ flags.
+ * @prealloc: Optional pages preallocated outside the dma-resv lock to back the
+ * bo (see ttm_operation_ctx::prealloc), or NULL.
 * @exec: The drm_exec transaction to use for exhaustive eviction.
 *
 * Initialize or create an xe buffer object. On failure, any allocated buffer
@@ -2895,12 +2897,14 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 				struct xe_tile *tile, struct dma_resv *resv,
 				struct ttm_lru_bulk_move *bulk, size_t size,
 				u16 cpu_caching, enum ttm_bo_type type,
-				u32 flags, struct drm_exec *exec)
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec)
 {
 	struct ttm_operation_ctx ctx = {
 		.interruptible = true,
 		.no_wait_gpu = false,
 		.gfp_retry_mayfail = true,
+		.prealloc = prealloc,
 	};
 	struct ttm_placement *placement;
 	uint32_t alignment;
@@ -3077,7 +3081,8 @@ __xe_bo_create_locked(struct xe_device *xe,
 		      struct xe_tile *tile, struct xe_vm *vm,
 		      size_t size, u64 start, u64 end,
 		      u16 cpu_caching, enum ttm_bo_type type, u32 flags,
-		      u64 alignment, struct drm_exec *exec)
+		      u64 alignment, struct ttm_pool_prealloc *prealloc,
+		      struct drm_exec *exec)
 {
 	struct xe_bo *bo = NULL;
 	int err;
@@ -3102,7 +3107,7 @@ __xe_bo_create_locked(struct xe_device *xe,
 			       vm && !xe_vm_in_fault_mode(vm) &&
 			       flags & XE_BO_FLAG_USER ?
 			       &vm->lru_bulk_move : NULL, size,
-			       cpu_caching, type, flags, exec);
+			       cpu_caching, type, flags, prealloc, exec);
 	if (IS_ERR(bo))
 		return bo;
 
@@ -3177,7 +3182,7 @@ struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
 				  struct drm_exec *exec)
 {
 	return __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL, 0, type,
-				     flags, 0, exec);
+				     flags, 0, NULL, exec);
 }
 
 static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *tile,
@@ -3193,7 +3198,7 @@ static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *til
 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = intr},
 			    ret) {
 		bo = __xe_bo_create_locked(xe, tile, NULL, size, 0, ~0ULL,
-					   cpu_caching, type, flags, alignment, &exec);
+					   cpu_caching, type, flags, alignment, NULL, &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			ret = PTR_ERR(bo);
@@ -3213,6 +3218,9 @@ static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *til
 * @size: The storage size to use for the bo.
 * @cpu_caching: The caching mode to be used for system backing store.
 * @flags: XE_BO_FLAG_ flags.
+ * @prealloc: Optional pages preallocated outside the dma-resv lock to back the
+ * bo (see ttm_operation_ctx::prealloc), or NULL. Only consumed on the locked
+ * (@vm or @exec) path.
 * @exec: The drm_exec transaction to use for exhaustive eviction, or NULL
 * if such a transaction should be initiated by the call.
 *
@@ -3223,7 +3231,8 @@ static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *til
 struct xe_bo *xe_bo_create_user(struct xe_device *xe,
 				struct xe_vm *vm, size_t size,
 				u16 cpu_caching,
-				u32 flags, struct drm_exec *exec)
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec)
 {
 	struct xe_bo *bo;
 
@@ -3233,7 +3242,7 @@ struct xe_bo *xe_bo_create_user(struct xe_device *xe,
 		xe_assert(xe, exec);
 		bo = __xe_bo_create_locked(xe, NULL, vm, size, 0, ~0ULL,
 					   cpu_caching, ttm_bo_type_device,
-					   flags, 0, exec);
+					   flags, 0, prealloc, exec);
 		if (!IS_ERR(bo))
 			xe_bo_unlock_vm_held(bo);
 	} else {
@@ -3272,7 +3281,7 @@ struct xe_bo *xe_bo_create_pin_range_novm(struct xe_device *xe, struct xe_tile *
 
 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {}, err) {
 		bo = __xe_bo_create_locked(xe, tile, NULL, size, start, end,
-					   0, type, flags, 0, &exec);
+					   0, type, flags, 0, NULL, &exec);
 		if (IS_ERR(bo)) {
 			drm_exec_retry_on_contention(&exec);
 			err = PTR_ERR(bo);
@@ -3311,7 +3320,7 @@ static struct xe_bo *xe_bo_create_pin_map_at_aligned(struct xe_device *xe,
 
 	bo = __xe_bo_create_locked(xe, tile, vm, size, start, end, 0, type,
 				   flags | XE_BO_FLAG_NEEDS_CPU_ACCESS | XE_BO_FLAG_PINNED,
-				   alignment, exec);
+				   alignment, NULL, exec);
 	if (IS_ERR(bo))
 		return bo;
 
@@ -3926,6 +3935,10 @@ static int gem_create_user_extensions(struct xe_device *xe, struct xe_bo *bo,
 	return 0;
 }
 
+static bool __xe_bo_needs_ccs_pages(struct xe_device *xe,
+				    enum ttm_bo_type type, u32 flags,
+				    u16 cpu_caching);
+
 int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			struct drm_file *file)
 {
@@ -3936,6 +3949,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	struct drm_exec exec;
 	struct xe_vm *vm = NULL;
 	struct xe_bo *bo;
+	struct ttm_pool_prealloc prealloc = {};
+	bool have_prealloc = false;
 	unsigned int bo_flags;
 	u32 handle;
 	int err;
@@ -4018,6 +4033,64 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			return -ENOENT;
 	}
 
+	/*
+	 * For system-only BOs, preallocate the whole backing outside the
+	 * dma-resv lock so the populate under the validation guard does not
+	 * stall in reclaim/compaction. The caching mirrors the system-BO path
+	 * in xe_ttm_tt_create(); the pool falls back to in-line allocation for
+	 * any shortfall, so a failed fill is harmless.
+	 */
+	if ((bo_flags & XE_BO_FLAG_SYSTEM) &&
+	    !(bo_flags & (XE_BO_FLAG_DEFER_BACKING | XE_BO_FLAG_VRAM_MASK |
+			  XE_BO_FLAG_STOLEN))) {
+		struct ttm_resource_manager *tt_man =
+			ttm_manager_type(&xe->ttm, XE_PL_TT);
+		enum ttm_caching caching = ttm_cached;
+		unsigned long num_pages = args->size >> PAGE_SHIFT;
+
+		if (!IS_DGFX(xe) &&
+		    args->cpu_caching == DRM_XE_GEM_CPU_CACHING_WC)
+			caching = ttm_write_combined;
+
+		/*
+		 * Cover the CCS backup pages appended to the tt (see
+		 * xe_ttm_tt_create()) so the whole tt is preallocated.
+		 */
+		if (__xe_bo_needs_ccs_pages(xe, ttm_bo_type_device, bo_flags,
+					    args->cpu_caching))
+			num_pages += DIV_ROUND_UP(xe_device_ccs_bytes(xe,
+								      args->size),
+						  PAGE_SIZE);
+
+		/*
+		 * Only prealloc when the backing fits the currently-available
+		 * TT space (manager size minus current usage). This skips the
+		 * up-front reclaim/compaction both for over-large,
+		 * user-controlled sizes and when TT is already near full; the
+		 * populate under the validation guard handles those cases.
+		 */
+		if (tt_man) {
+			u64 used = ttm_resource_manager_usage(tt_man);
+			u64 shift_size = tt_man->size << PAGE_SHIFT;
+			u64 avail = shift_size > used ? shift_size - used : 0;
+
+			if ((u64)num_pages << PAGE_SHIFT <= avail) {
+				/*
+				 * Back off aggressive reclaim/compaction for
+				 * higher-order chunks here: Xe runs a background
+				 * defragmenter that upgrades suboptimal pages to
+				 * beneficial order in place later, so there is no
+				 * need to stall this user context reclaiming for

drivers/gpu/drm/xe/xe_bo.c int xe_gem_create_ioctl(struct drm_device *dev, void *data, · line 4093

Quoted 10 lines
drivers/gpu/drm/xe/xe_bo.c +10 -0
+				 * contiguity.
+				 */
+				ttm_pool_prealloc_fill_full(&xe->ttm.pool,
+							    caching, &prealloc,
+							    num_pages, true);
+				have_prealloc = true;
+			}
+		}
+	}
+

May be extract this new code block into a separte static function?

Niranjana

Quoted 149 lines
drivers/gpu/drm/xe/xe_bo.c +29 -15
 	err = 0;
 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = true},
 			    err) {
@@ -4028,7 +4101,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 				break;
 		}
 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
-				       bo_flags, &exec);
+				       bo_flags, have_prealloc ? &prealloc : NULL,
+				       &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			err = PTR_ERR(bo);
@@ -4036,6 +4110,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			break;
 		}
 	}
+	if (have_prealloc)
+		ttm_pool_prealloc_fini(&xe->ttm.pool, &prealloc);
 	if (err)
 		goto out_vm;
 
@@ -4331,21 +4407,19 @@ int xe_bo_evict(struct xe_bo *bo, struct drm_exec *exec)
 	return 0;
 }
 
-/**
- * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
- * placed in system memory.
- * @bo: The xe_bo
- *
- * Return: true if extra pages need to be allocated, false otherwise.
+/*
+ * Whether a bo with the given attributes needs to back up CCS pages when placed
+ * in system memory. Split out so callers can query before the xe_bo exists (see
+ * xe_gem_create_ioctl() preallocation).
 */
-bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
+static bool __xe_bo_needs_ccs_pages(struct xe_device *xe,
+				    enum ttm_bo_type type, u32 flags,
+				    u16 cpu_caching)
 {
-	struct xe_device *xe = xe_bo_device(bo);
-
 	if (GRAPHICS_VER(xe) >= 20 && IS_DGFX(xe))
 		return false;
 
-	if (!xe_device_has_flat_ccs(xe) || bo->ttm.type != ttm_bo_type_device)
+	if (!xe_device_has_flat_ccs(xe) || type != ttm_bo_type_device)
 		return false;
 
 	/* On discrete GPUs, if the GPU can access this buffer from
@@ -4353,24 +4427,37 @@ bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
 	 * can't be used since there's no CCS storage associated with
 	 * non-VRAM addresses.
 	 */
-	if (IS_DGFX(xe) && (bo->flags & XE_BO_FLAG_SYSTEM))
+	if (IS_DGFX(xe) && (flags & XE_BO_FLAG_SYSTEM))
 		return false;
 
 	/* Check if userspace explicitly requested no compression */
-	if (bo->flags & XE_BO_FLAG_NO_COMPRESSION)
+	if (flags & XE_BO_FLAG_NO_COMPRESSION)
 		return false;
 
 	/*
 	 * For WB (Write-Back) CPU caching mode, check if the device
 	 * supports WB compression with coherency.
 	 */
-	if (bo->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB &&
+	if (cpu_caching == DRM_XE_GEM_CPU_CACHING_WB &&
 	    xe->pat.idx[XE_CACHE_WB_COMPRESSION] == XE_PAT_INVALID_IDX)
 		return false;
 
 	return true;
 }
 
+/**
+ * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
+ * placed in system memory.
+ * @bo: The xe_bo
+ *
+ * Return: true if extra pages need to be allocated, false otherwise.
+ */
+bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
+{
+	return __xe_bo_needs_ccs_pages(xe_bo_device(bo), bo->ttm.type,
+				       bo->flags, bo->cpu_caching);
+}
+
 /**
 * __xe_bo_release_dummy() - Dummy kref release function
 * @kref: The embedded struct kref.
@@ -4477,7 +4564,7 @@ int xe_bo_dumb_create(struct drm_file *file_priv,
 			       DRM_XE_GEM_CPU_CACHING_WC,
 			       XE_BO_FLAG_VRAM_IF_DGFX(xe_device_get_root_tile(xe)) |
 			       XE_BO_FLAG_FORCE_WC |
-			       XE_BO_FLAG_NEEDS_CPU_ACCESS, NULL);
+			       XE_BO_FLAG_NEEDS_CPU_ACCESS, NULL, NULL);
 	if (IS_ERR(bo))
 		return PTR_ERR(bo);
 
drivers/gpu/drm/xe/xe_bo.h +6 -2
index 38d50f8122cb..18fcccd082b7 100644
@@ -111,6 +111,7 @@ enum xe_madv_purgeable_state {
 
 struct sg_table;
 struct ttm_tt;
+struct ttm_pool_prealloc;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -119,13 +120,16 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 				struct xe_tile *tile, struct dma_resv *resv,
 				struct ttm_lru_bulk_move *bulk, size_t size,
 				u16 cpu_caching, enum ttm_bo_type type,
-				u32 flags, struct drm_exec *exec);
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec);
 struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
 				  struct xe_vm *vm, size_t size,
 				  enum ttm_bo_type type, u32 flags,
 				  struct drm_exec *exec);
 struct xe_bo *xe_bo_create_user(struct xe_device *xe, struct xe_vm *vm, size_t size,
-				u16 cpu_caching, u32 flags, struct drm_exec *exec);
+				u16 cpu_caching, u32 flags,
+				struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec);
 struct xe_bo *xe_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
 				   struct xe_vm *vm, size_t size,
 				   enum ttm_bo_type type, u32 flags,
drivers/gpu/drm/xe/xe_dma_buf.c +1 -1
index 8a920e58245c..ec947d86a1ce 100644
@@ -302,7 +302,7 @@ xe_dma_buf_create_obj(struct drm_device *dev, struct dma_buf *dma_buf)
 
 		bo = xe_bo_init_locked(xe, NULL, NULL, resv, NULL, dma_buf->size,
 				       0, /* Will require 1way or 2way for vm_bind */
-				       ttm_bo_type_sg, XE_BO_FLAG_SYSTEM, &exec);
+				       ttm_bo_type_sg, XE_BO_FLAG_SYSTEM, NULL, &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			ret = PTR_ERR(bo);
Signature · 1 line
2.34.1
author maintainer
#100 lore raw

Re: [PATCH v3 25/33] drm/xe: Preallocate system BO backing outside the dma-resv lock

Quoted 358 lines · Niranjana Vishwanathapura
Quoted 357 lines · Matthew Brost

xe_gem_create_ioctl() populates a buffer object's backing store inside xe_validation_guard(), i.e. under the dma-resv lock. For a system-memory buffer that means the whole page allocation - potentially stalling in reclaim or compaction - happens in the critical section, holding the reservation and blocking anything that contends on it.

Use the TTM full-preallocation mechanism to move that work out of the lock. For a system-only, non-deferred user BO, allocate the entire tt backing up front, before entering the validation guard, and hand the bag down to the populate so it merely installs the pages:

- Thread an optional struct ttm_pool_prealloc through xe_bo_create_user() -> __xe_bo_create_locked() -> xe_bo_init_locked(), which stashes it in ttm_operation_ctx::prealloc. All other callers pass NULL.

- In xe_gem_create_ioctl(), for XE_BO_FLAG_SYSTEM BOs that are not VRAM, stolen or deferred-backing, call ttm_pool_prealloc_fill_full() before the guard and ttm_pool_prealloc_fini() after it. The bag size covers both the data pages and the appended CCS backup pages, matching the tt layout in xe_ttm_tt_create(), and the caching mirrors the same path.

The fill is best-effort: on a short fill (or if it is skipped) the pool allocates the remainder in-line as before, so this is purely an optimisation with no behavioural change to the created BO. fini() only releases the unconsumed tail, so it is safe on every success, error and OOM-retry path (consumed pages are owned by the tt).

The fill requests reclaim backoff for higher-order chunks (@beneficial_reclaim_backoff): Xe runs a background defragmenter that upgrades suboptimal pages to beneficial order in place, so there is no need to stall this user context reclaiming/compacting for contiguity.

To size the preallocation before the xe_bo exists, factor the CCS-pages decision in xe_bo_needs_ccs_pages() into a parameterised helper, __xe_bo_needs_ccs_pages(), and query it directly from the ioctl.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Preallocate only when the backing fits the available TT space (Sashiko)
---

drivers/gpu/drm/xe/tests/xe_bo.c      |   8 +-
drivers/gpu/drm/xe/tests/xe_dma_buf.c |   2 +-
drivers/gpu/drm/xe/tests/xe_migrate.c |   6 +-
drivers/gpu/drm/xe/xe_bo.c            | 139 +++++++++++++++++++++-----
drivers/gpu/drm/xe/xe_bo.h            |   8 +-
drivers/gpu/drm/xe/xe_dma_buf.c       |   2 +-
6 files changed, 128 insertions(+), 37 deletions(-)
drivers/gpu/drm/xe/tests/xe_bo.c +4 -4
index 49c95ed67d7e..78781317b420 100644
@@ -141,7 +141,7 @@ static void ccs_test_run_tile(struct xe_device *xe, struct xe_tile *tile,
 		kunit_info(test, "Testing system memory\n");
 
 	bo = xe_bo_create_user(xe, NULL, SZ_1M, DRM_XE_GEM_CPU_CACHING_WC,
-			       bo_flags, exec);
+			       bo_flags, NULL, exec);
 	if (IS_ERR(bo)) {
 		KUNIT_FAIL(test, "Failed to create bo.\n");
 		return;
@@ -220,7 +220,7 @@ static int evict_test_run_tile(struct xe_device *xe, struct xe_tile *tile, struc
 		xe_vm_lock(vm, false);
 		bo = xe_bo_create_user(xe, vm, 0x10000,
 				       DRM_XE_GEM_CPU_CACHING_WC,
-				       bo_flags, exec);
+				       bo_flags, NULL, exec);
 		xe_vm_unlock(vm);
 		if (IS_ERR(bo)) {
 			KUNIT_FAIL(test, "bo create err=%pe\n", bo);
@@ -229,7 +229,7 @@ static int evict_test_run_tile(struct xe_device *xe, struct xe_tile *tile, struc
 
 		external = xe_bo_create_user(xe, NULL, 0x10000,
 					     DRM_XE_GEM_CPU_CACHING_WC,
-					     bo_flags, NULL);
+					     bo_flags, NULL, NULL);
 		if (IS_ERR(external)) {
 			KUNIT_FAIL(test, "external bo create err=%pe\n", external);
 			goto cleanup_bo;
@@ -494,7 +494,7 @@ static int shrink_test_run_device(struct xe_device *xe)
 		/* We can create bos using WC caching here. But it is slower. */
 		bo = xe_bo_create_user(xe, NULL, XE_BO_SHRINK_SIZE,
 				       DRM_XE_GEM_CPU_CACHING_WB,
-				       XE_BO_FLAG_SYSTEM, NULL);
+				       XE_BO_FLAG_SYSTEM, NULL, NULL);
 		if (IS_ERR(bo)) {
 			if (bo != ERR_PTR(-ENOMEM) && bo != ERR_PTR(-ENOSPC) &&
 			    bo != ERR_PTR(-EINTR) && bo != ERR_PTR(-ERESTARTSYS))
drivers/gpu/drm/xe/tests/xe_dma_buf.c +1 -1
index 0be8440b3976..e4fdc247c0c7 100644
@@ -127,7 +127,7 @@ static void xe_test_dmabuf_import_same_driver(struct xe_device *xe)
 
 	kunit_info(test, "running %s\n", __func__);
 	bo = xe_bo_create_user(xe, NULL, size, DRM_XE_GEM_CPU_CACHING_WC,
-			       params->mem_mask, NULL);
+			       params->mem_mask, NULL, NULL);
 	if (IS_ERR(bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
 			   PTR_ERR(bo));
drivers/gpu/drm/xe/tests/xe_migrate.c +3 -3
index 3c1be809be82..41de648b2c86 100644
@@ -647,7 +647,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 				   DRM_XE_GEM_CPU_CACHING_WC,
 				   XE_BO_FLAG_SYSTEM |
 				   XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				   XE_BO_FLAG_PINNED, NULL);
+				   XE_BO_FLAG_PINNED, NULL, NULL);
 
 	if (IS_ERR(sys_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
@@ -673,7 +673,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 	ccs_bo = xe_bo_create_user(xe, NULL, SZ_4M,
 				   DRM_XE_GEM_CPU_CACHING_WC,
 				   bo_flags | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				   XE_BO_FLAG_PINNED, NULL);
+				   XE_BO_FLAG_PINNED, NULL, NULL);
 
 	if (IS_ERR(ccs_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
@@ -698,7 +698,7 @@ static void validate_ccs_test_run_tile(struct xe_device *xe, struct xe_tile *til
 	vram_bo = xe_bo_create_user(xe, NULL, SZ_4M,
 				    DRM_XE_GEM_CPU_CACHING_WC,
 				    bo_flags | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-				    XE_BO_FLAG_PINNED, NULL);
+				    XE_BO_FLAG_PINNED, NULL, NULL);
 	if (IS_ERR(vram_bo)) {
 		KUNIT_FAIL(test, "xe_bo_create() failed with err=%ld\n",
 			   PTR_ERR(vram_bo));
drivers/gpu/drm/xe/xe_bo.c +78 -11
index 25e5b72f870c..a646a72122d4 100644
@@ -1948,7 +1948,7 @@ int xe_bo_notifier_prepare_pinned(struct xe_bo *bo)
 		backup = xe_bo_init_locked(xe, NULL, NULL, bo->ttm.base.resv, NULL, xe_bo_size(bo),
 					   DRM_XE_GEM_CPU_CACHING_WB, ttm_bo_type_kernel,
 					   XE_BO_FLAG_SYSTEM | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-					   XE_BO_FLAG_PINNED, &exec);
+					   XE_BO_FLAG_PINNED, NULL, &exec);
 		if (IS_ERR(backup)) {
 			drm_exec_retry_on_contention(&exec);
 			ret = PTR_ERR(backup);
@@ -2089,7 +2089,7 @@ int xe_bo_evict_pinned(struct xe_bo *bo)
 						   xe_bo_size(bo),
 						   DRM_XE_GEM_CPU_CACHING_WB, ttm_bo_type_kernel,
 						   XE_BO_FLAG_SYSTEM | XE_BO_FLAG_NEEDS_CPU_ACCESS |
-						   XE_BO_FLAG_PINNED, &exec);
+						   XE_BO_FLAG_PINNED, NULL, &exec);
 			if (IS_ERR(backup)) {
 				drm_exec_retry_on_contention(&exec);
 				ret = PTR_ERR(backup);
@@ -2884,6 +2884,8 @@ void xe_bo_free(struct xe_bo *bo)
 * @cpu_caching: The cpu caching used for system memory backing store.
 * @type: The TTM buffer object type.
 * @flags: XE_BO_FLAG_ flags.
+ * @prealloc: Optional pages preallocated outside the dma-resv lock to back the
+ * bo (see ttm_operation_ctx::prealloc), or NULL.
 * @exec: The drm_exec transaction to use for exhaustive eviction.
 *
 * Initialize or create an xe buffer object. On failure, any allocated buffer
@@ -2895,12 +2897,14 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 				struct xe_tile *tile, struct dma_resv *resv,
 				struct ttm_lru_bulk_move *bulk, size_t size,
 				u16 cpu_caching, enum ttm_bo_type type,
-				u32 flags, struct drm_exec *exec)
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec)
 {
 	struct ttm_operation_ctx ctx = {
 		.interruptible = true,
 		.no_wait_gpu = false,
 		.gfp_retry_mayfail = true,
+		.prealloc = prealloc,
 	};
 	struct ttm_placement *placement;
 	uint32_t alignment;
@@ -3077,7 +3081,8 @@ __xe_bo_create_locked(struct xe_device *xe,
 		      struct xe_tile *tile, struct xe_vm *vm,
 		      size_t size, u64 start, u64 end,
 		      u16 cpu_caching, enum ttm_bo_type type, u32 flags,
-		      u64 alignment, struct drm_exec *exec)
+		      u64 alignment, struct ttm_pool_prealloc *prealloc,
+		      struct drm_exec *exec)
 {
 	struct xe_bo *bo = NULL;
 	int err;
@@ -3102,7 +3107,7 @@ __xe_bo_create_locked(struct xe_device *xe,
 			       vm && !xe_vm_in_fault_mode(vm) &&
 			       flags & XE_BO_FLAG_USER ?
 			       &vm->lru_bulk_move : NULL, size,
-			       cpu_caching, type, flags, exec);
+			       cpu_caching, type, flags, prealloc, exec);
 	if (IS_ERR(bo))
 		return bo;
 
@@ -3177,7 +3182,7 @@ struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
 				  struct drm_exec *exec)
 {
 	return __xe_bo_create_locked(xe, tile, vm, size, 0, ~0ULL, 0, type,
-				     flags, 0, exec);
+				     flags, 0, NULL, exec);
 }
 
 static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *tile,
@@ -3193,7 +3198,7 @@ static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *til
 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = intr},
 			    ret) {
 		bo = __xe_bo_create_locked(xe, tile, NULL, size, 0, ~0ULL,
-					   cpu_caching, type, flags, alignment, &exec);
+					   cpu_caching, type, flags, alignment, NULL, &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			ret = PTR_ERR(bo);
@@ -3213,6 +3218,9 @@ static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *til
 * @size: The storage size to use for the bo.
 * @cpu_caching: The caching mode to be used for system backing store.
 * @flags: XE_BO_FLAG_ flags.
+ * @prealloc: Optional pages preallocated outside the dma-resv lock to back the
+ * bo (see ttm_operation_ctx::prealloc), or NULL. Only consumed on the locked
+ * (@vm or @exec) path.
 * @exec: The drm_exec transaction to use for exhaustive eviction, or NULL
 * if such a transaction should be initiated by the call.
 *
@@ -3223,7 +3231,8 @@ static struct xe_bo *xe_bo_create_novm(struct xe_device *xe, struct xe_tile *til
 struct xe_bo *xe_bo_create_user(struct xe_device *xe,
 				struct xe_vm *vm, size_t size,
 				u16 cpu_caching,
-				u32 flags, struct drm_exec *exec)
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec)
 {
 	struct xe_bo *bo;
 
@@ -3233,7 +3242,7 @@ struct xe_bo *xe_bo_create_user(struct xe_device *xe,
 		xe_assert(xe, exec);
 		bo = __xe_bo_create_locked(xe, NULL, vm, size, 0, ~0ULL,
 					   cpu_caching, ttm_bo_type_device,
-					   flags, 0, exec);
+					   flags, 0, prealloc, exec);
 		if (!IS_ERR(bo))
 			xe_bo_unlock_vm_held(bo);
 	} else {
@@ -3272,7 +3281,7 @@ struct xe_bo *xe_bo_create_pin_range_novm(struct xe_device *xe, struct xe_tile *
 
 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {}, err) {
 		bo = __xe_bo_create_locked(xe, tile, NULL, size, start, end,
-					   0, type, flags, 0, &exec);
+					   0, type, flags, 0, NULL, &exec);
 		if (IS_ERR(bo)) {
 			drm_exec_retry_on_contention(&exec);
 			err = PTR_ERR(bo);
@@ -3311,7 +3320,7 @@ static struct xe_bo *xe_bo_create_pin_map_at_aligned(struct xe_device *xe,
 
 	bo = __xe_bo_create_locked(xe, tile, vm, size, start, end, 0, type,
 				   flags | XE_BO_FLAG_NEEDS_CPU_ACCESS | XE_BO_FLAG_PINNED,
-				   alignment, exec);
+				   alignment, NULL, exec);
 	if (IS_ERR(bo))
 		return bo;
 
@@ -3926,6 +3935,10 @@ static int gem_create_user_extensions(struct xe_device *xe, struct xe_bo *bo,
 	return 0;
 }
 
+static bool __xe_bo_needs_ccs_pages(struct xe_device *xe,
+				    enum ttm_bo_type type, u32 flags,
+				    u16 cpu_caching);
+
 int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			struct drm_file *file)
 {
@@ -3936,6 +3949,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	struct drm_exec exec;
 	struct xe_vm *vm = NULL;
 	struct xe_bo *bo;
+	struct ttm_pool_prealloc prealloc = {};
+	bool have_prealloc = false;
 	unsigned int bo_flags;
 	u32 handle;
 	int err;
@@ -4018,6 +4033,64 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			return -ENOENT;
 	}
 
+	/*
+	 * For system-only BOs, preallocate the whole backing outside the
+	 * dma-resv lock so the populate under the validation guard does not
+	 * stall in reclaim/compaction. The caching mirrors the system-BO path
+	 * in xe_ttm_tt_create(); the pool falls back to in-line allocation for
+	 * any shortfall, so a failed fill is harmless.
+	 */
+	if ((bo_flags & XE_BO_FLAG_SYSTEM) &&
+	    !(bo_flags & (XE_BO_FLAG_DEFER_BACKING | XE_BO_FLAG_VRAM_MASK |
+			  XE_BO_FLAG_STOLEN))) {
+		struct ttm_resource_manager *tt_man =
+			ttm_manager_type(&xe->ttm, XE_PL_TT);
+		enum ttm_caching caching = ttm_cached;
+		unsigned long num_pages = args->size >> PAGE_SHIFT;
+
+		if (!IS_DGFX(xe) &&
+		    args->cpu_caching == DRM_XE_GEM_CPU_CACHING_WC)
+			caching = ttm_write_combined;
+
+		/*
+		 * Cover the CCS backup pages appended to the tt (see
+		 * xe_ttm_tt_create()) so the whole tt is preallocated.
+		 */
+		if (__xe_bo_needs_ccs_pages(xe, ttm_bo_type_device, bo_flags,
+					    args->cpu_caching))
+			num_pages += DIV_ROUND_UP(xe_device_ccs_bytes(xe,
+								      args->size),
+						  PAGE_SIZE);
+
+		/*
+		 * Only prealloc when the backing fits the currently-available
+		 * TT space (manager size minus current usage). This skips the
+		 * up-front reclaim/compaction both for over-large,
+		 * user-controlled sizes and when TT is already near full; the
+		 * populate under the validation guard handles those cases.
+		 */
+		if (tt_man) {
+			u64 used = ttm_resource_manager_usage(tt_man);
+			u64 shift_size = tt_man->size << PAGE_SHIFT;
+			u64 avail = shift_size > used ? shift_size - used : 0;
+
+			if ((u64)num_pages << PAGE_SHIFT <= avail) {
+				/*
+				 * Back off aggressive reclaim/compaction for
+				 * higher-order chunks here: Xe runs a background
+				 * defragmenter that upgrades suboptimal pages to
+				 * beneficial order in place later, so there is no
+				 * need to stall this user context reclaiming for
+				 * contiguity.
+				 */
+				ttm_pool_prealloc_fill_full(&xe->ttm.pool,
+							    caching, &prealloc,
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c int xe_gem_create_ioctl(struct drm_device *dev, void *data, · line 4093

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+							    num_pages, true);
+				have_prealloc = true;
+			}
+		}
+	}
+

May be extract this new code block into a separte static function?

Let me see what that will look like.

Matt

Quoted 151 lines

Niranjana

Quoted 149 lines
drivers/gpu/drm/xe/xe_bo.c +29 -15
 	err = 0;
 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {.interruptible = true},
 			    err) {
@@ -4028,7 +4101,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 				break;
 		}
 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
-				       bo_flags, &exec);
+				       bo_flags, have_prealloc ? &prealloc : NULL,
+				       &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			err = PTR_ERR(bo);
@@ -4036,6 +4110,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			break;
 		}
 	}
+	if (have_prealloc)
+		ttm_pool_prealloc_fini(&xe->ttm.pool, &prealloc);
 	if (err)
 		goto out_vm;
 
@@ -4331,21 +4407,19 @@ int xe_bo_evict(struct xe_bo *bo, struct drm_exec *exec)
 	return 0;
 }
 
-/**
- * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
- * placed in system memory.
- * @bo: The xe_bo
- *
- * Return: true if extra pages need to be allocated, false otherwise.
+/*
+ * Whether a bo with the given attributes needs to back up CCS pages when placed
+ * in system memory. Split out so callers can query before the xe_bo exists (see
+ * xe_gem_create_ioctl() preallocation).
 */
-bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
+static bool __xe_bo_needs_ccs_pages(struct xe_device *xe,
+				    enum ttm_bo_type type, u32 flags,
+				    u16 cpu_caching)
 {
-	struct xe_device *xe = xe_bo_device(bo);
-
 	if (GRAPHICS_VER(xe) >= 20 && IS_DGFX(xe))
 		return false;
 
-	if (!xe_device_has_flat_ccs(xe) || bo->ttm.type != ttm_bo_type_device)
+	if (!xe_device_has_flat_ccs(xe) || type != ttm_bo_type_device)
 		return false;
 
 	/* On discrete GPUs, if the GPU can access this buffer from
@@ -4353,24 +4427,37 @@ bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
 	 * can't be used since there's no CCS storage associated with
 	 * non-VRAM addresses.
 	 */
-	if (IS_DGFX(xe) && (bo->flags & XE_BO_FLAG_SYSTEM))
+	if (IS_DGFX(xe) && (flags & XE_BO_FLAG_SYSTEM))
 		return false;
 
 	/* Check if userspace explicitly requested no compression */
-	if (bo->flags & XE_BO_FLAG_NO_COMPRESSION)
+	if (flags & XE_BO_FLAG_NO_COMPRESSION)
 		return false;
 
 	/*
 	 * For WB (Write-Back) CPU caching mode, check if the device
 	 * supports WB compression with coherency.
 	 */
-	if (bo->cpu_caching == DRM_XE_GEM_CPU_CACHING_WB &&
+	if (cpu_caching == DRM_XE_GEM_CPU_CACHING_WB &&
 	    xe->pat.idx[XE_CACHE_WB_COMPRESSION] == XE_PAT_INVALID_IDX)
 		return false;
 
 	return true;
 }
 
+/**
+ * xe_bo_needs_ccs_pages - Whether a bo needs to back up CCS pages when
+ * placed in system memory.
+ * @bo: The xe_bo
+ *
+ * Return: true if extra pages need to be allocated, false otherwise.
+ */
+bool xe_bo_needs_ccs_pages(struct xe_bo *bo)
+{
+	return __xe_bo_needs_ccs_pages(xe_bo_device(bo), bo->ttm.type,
+				       bo->flags, bo->cpu_caching);
+}
+
 /**
 * __xe_bo_release_dummy() - Dummy kref release function
 * @kref: The embedded struct kref.
@@ -4477,7 +4564,7 @@ int xe_bo_dumb_create(struct drm_file *file_priv,
 			       DRM_XE_GEM_CPU_CACHING_WC,
 			       XE_BO_FLAG_VRAM_IF_DGFX(xe_device_get_root_tile(xe)) |
 			       XE_BO_FLAG_FORCE_WC |
-			       XE_BO_FLAG_NEEDS_CPU_ACCESS, NULL);
+			       XE_BO_FLAG_NEEDS_CPU_ACCESS, NULL, NULL);
 	if (IS_ERR(bo))
 		return PTR_ERR(bo);
 
drivers/gpu/drm/xe/xe_bo.h +6 -2
index 38d50f8122cb..18fcccd082b7 100644
@@ -111,6 +111,7 @@ enum xe_madv_purgeable_state {
 
 struct sg_table;
 struct ttm_tt;
+struct ttm_pool_prealloc;
 
 struct xe_bo *xe_bo_alloc(void);
 void xe_bo_free(struct xe_bo *bo);
@@ -119,13 +120,16 @@ struct xe_bo *xe_bo_init_locked(struct xe_device *xe, struct xe_bo *bo,
 				struct xe_tile *tile, struct dma_resv *resv,
 				struct ttm_lru_bulk_move *bulk, size_t size,
 				u16 cpu_caching, enum ttm_bo_type type,
-				u32 flags, struct drm_exec *exec);
+				u32 flags, struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec);
 struct xe_bo *xe_bo_create_locked(struct xe_device *xe, struct xe_tile *tile,
 				  struct xe_vm *vm, size_t size,
 				  enum ttm_bo_type type, u32 flags,
 				  struct drm_exec *exec);
 struct xe_bo *xe_bo_create_user(struct xe_device *xe, struct xe_vm *vm, size_t size,
-				u16 cpu_caching, u32 flags, struct drm_exec *exec);
+				u16 cpu_caching, u32 flags,
+				struct ttm_pool_prealloc *prealloc,
+				struct drm_exec *exec);
 struct xe_bo *xe_bo_create_pin_map(struct xe_device *xe, struct xe_tile *tile,
 				   struct xe_vm *vm, size_t size,
 				   enum ttm_bo_type type, u32 flags,
drivers/gpu/drm/xe/xe_dma_buf.c +1 -1
index 8a920e58245c..ec947d86a1ce 100644
@@ -302,7 +302,7 @@ xe_dma_buf_create_obj(struct drm_device *dev, struct dma_buf *dma_buf)
 
 		bo = xe_bo_init_locked(xe, NULL, NULL, resv, NULL, dma_buf->size,
 				       0, /* Will require 1way or 2way for vm_bind */
-				       ttm_bo_type_sg, XE_BO_FLAG_SYSTEM, &exec);
+				       ttm_bo_type_sg, XE_BO_FLAG_SYSTEM, NULL, &exec);
 		drm_exec_retry_on_contention(&exec);
 		if (IS_ERR(bo)) {
 			ret = PTR_ERR(bo);
Signature · 1 line
2.34.1
author maintainer
#101 lore raw

PATCH v3 26/33 drm/xe: Add tracepoint for xe_gem_create_ioctl

In reply to Matthew Brost

Add a xe_gem_create_ioctl tracepoint to help profile GEM creation, in particular the cost of populating a BO while holding the dma-resv lock versus the total IOCTL cost. This is useful for evaluating the out-of-lock preallocation path, which aims to shrink the time spent under the lock.

The tracepoint records the BO size, the requested placement mask, the CPU caching mode, the VM asid (0 when no VM is bound), the total time spent in the IOCTL, and the time spent under the dma-resv lock (the xe_validation_guard region where the lock is held).

The asid is captured at VM lookup time rather than at trace emission, since the VM reference is dropped before the tracepoint fires.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Guard lock_ns against an unset lock_start and use div_u64() in the tracepoint (Sashiko)

---
 drivers/gpu/drm/xe/xe_bo.c       | 17 +++++++++++++++++
 drivers/gpu/drm/xe/xe_trace_bo.h | 31 +++++++++++++++++++++++++++++++
 2 files changed, 48 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +17 -0
index a646a72122d4..caf5aa0bab53 100644
@@ -3953,6 +3953,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	bool have_prealloc = false;
 	unsigned int bo_flags;
 	u32 handle;
+	ktime_t ioctl_start = ktime_get();
+	ktime_t lock_start = ktime_set(0, 0);
+	u64 lock_ns = 0;
+	u32 asid = 0;
 	int err;
 
 	if (XE_IOCTL_DBG(xe, args->pad[0] || args->pad[1] || args->pad[2]) ||
@@ -4031,6 +4035,7 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 		vm = xe_vm_lookup(xef, args->vm_id);
 		if (XE_IOCTL_DBG(xe, !vm))
 			return -ENOENT;
+		asid = vm->usm.asid;
 	}
 
 	/*
@@ -4100,6 +4105,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			if (err)
 				break;
 		}
+
+		if (lock_start == ktime_set(0, 0))
+			lock_start = ktime_get();
+
 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
 				       bo_flags, have_prealloc ? &prealloc : NULL,
 				       &exec);
@@ -4110,6 +4119,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			break;
 		}
 	}
+	if (lock_start != ktime_set(0, 0))
+		lock_ns = ktime_to_ns(ktime_sub(ktime_get(), lock_start));
 	if (have_prealloc)
 		ttm_pool_prealloc_fini(&xe->ttm.pool, &prealloc);
 	if (err)
@@ -4140,6 +4151,12 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	if (vm)
 		xe_vm_put(vm);
 
+	trace_xe_gem_create_ioctl(xe, args->size, args->placement,
+				  args->cpu_caching, asid,
+				  div_u64(ktime_to_ns(ktime_sub(ktime_get(),
+							ioctl_start)), 1000),
+				  div_u64(lock_ns, 1000));
+
 	return err;
 }
 
drivers/gpu/drm/xe/xe_trace_bo.h +31 -0
index b159d37d39a1..63db37edadc2 100644
@@ -144,6 +144,37 @@ TRACE_EVENT(xe_bo_defrag_one,
 		      __entry->ret)
 );
 
+TRACE_EVENT(xe_gem_create_ioctl,
+	    TP_PROTO(struct xe_device *xe, u64 size, u32 placement,
+		     u16 caching, u32 asid, u64 ioctl_us, u64 lock_us),
+	    TP_ARGS(xe, size, placement, caching, asid, ioctl_us, lock_us),
+
+	    TP_STRUCT__entry(
+		     __string(dev, dev_name(xe->drm.dev))
+		     __field(u64, size)
+		     __field(u32, placement)
+		     __field(u16, caching)
+		     __field(u32, asid)
+		     __field(u64, ioctl_us)
+		     __field(u64, lock_us)
+		     ),
+
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->size = size;
+		   __entry->placement = placement;
+		   __entry->caching = caching;
+		   __entry->asid = asid;
+		   __entry->ioctl_us = ioctl_us;
+		   __entry->lock_us = lock_us;
+		   ),
+
+	    TP_printk("dev=%s, size=%llu, placement=0x%x, caching=%u, asid=%u, ioctl_us=%llu, lock_us=%llu",
+		      __get_str(dev), __entry->size, __entry->placement,
+		      __entry->caching, __entry->asid, __entry->ioctl_us,
+		      __entry->lock_us)
+);
+
 DECLARE_EVENT_CLASS(xe_vma,
 		    TP_PROTO(struct xe_vma *vma),
 		    TP_ARGS(vma),
Signature · 1 line
2.34.1
#102 lore raw

Re: [PATCH v3 26/33] drm/xe: Add tracepoint for xe_gem_create_ioctl

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Tracepoint metric lock_ns incorrectly includes lock-dropped backoff sleep time due to WW mutex…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Tracepoint metric lock_ns incorrectly includes lock-dropped backoff sleep time due to WW mutex contention retries. --

--- Patch [26]: [PATCH v3 26/33] drm/xe: Add tracepoint for xe_gem_create_ioctl --- commit 08fb65ed7bb6e79b15efc1ef9667995aaebd39fe
Author: Matthew Brost <[email protected]>

drm/xe: Add tracepoint for xe_gem_create_ioctl

This commit adds a tracepoint to profile GEM creation in the xe driver. It records the BO size, placement, CPU caching, ASID, total IOCTL duration, and the time spent under the dma-resv lock to help evaluate out-of-lock preallocation performance.

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
index a646a72122d40..caf5aa0bab533 100644

[ ... ]

drivers/gpu/drm/xe/xe_bo.c int xe_gem_create_ioctl(struct drm_device *dev, void *data, · line 4111

Quoted 8 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
@@ -4100,6 +4105,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			if (err)
 				break;
 		}
+
+		if (lock_start == ktime_set(0, 0))
+			lock_start = ktime_get();
+

[Severity: Medium]
Will this lock_start timestamp incorrectly include lock-dropped backoff sleep time when a WW mutex contention retry occurs?

When contention happens, drm_exec_cleanup() drops all locks and the next iteration might sleep in dma_resv_lock_slow_interruptible() without holding any dma-resv locks. Because of the zero-check guard here, lock_start is retained from the first iteration.

Could this cause the lock_ns metric to encapsulate the unbounded lock-dropped sleep time and corrupt the intended profiling metric? If vm != NULL, removing this zero-check would exclude the sleep (which happens early in xe_vm_drm_exec_lock). However, if vm == NULL, the sleep occurs inside xe_bo_create_user(), so does this require capturing the start time inside the locking functions or accumulating the actual duration per iteration?

Quoted 3 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
 				       bo_flags, have_prealloc ? &prealloc : NULL,
 				       &exec);

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=26
#103 lore raw

Re: [PATCH v3 26/33] drm/xe: Add tracepoint for xe_gem_create_ioctl

In reply to Matthew Brost
Quoted 84 lines · Matthew Brost

Add a xe_gem_create_ioctl tracepoint to help profile GEM creation, in particular the cost of populating a BO while holding the dma-resv lock versus the total IOCTL cost. This is useful for evaluating the out-of-lock preallocation path, which aims to shrink the time spent under the lock.

The tracepoint records the BO size, the requested placement mask, the CPU caching mode, the VM asid (0 when no VM is bound), the total time spent in the IOCTL, and the time spent under the dma-resv lock (the xe_validation_guard region where the lock is held).

The asid is captured at VM lookup time rather than at trace emission, since the VM reference is dropped before the tracepoint fires.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Guard lock_ns against an unset lock_start and use div_u64() in the tracepoint (Sashiko)
---
drivers/gpu/drm/xe/xe_bo.c | 17 +++++++++++++++++
drivers/gpu/drm/xe/xe_trace_bo.h | 31 +++++++++++++++++++++++++++++++

2 files changed, 48 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +11 -0
index a646a72122d4..caf5aa0bab53 100644
@@ -3953,6 +3953,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	bool have_prealloc = false;
 	unsigned int bo_flags;
 	u32 handle;
+	ktime_t ioctl_start = ktime_get();
+	ktime_t lock_start = ktime_set(0, 0);
+	u64 lock_ns = 0;
+	u32 asid = 0;
 	int err;
 
 	if (XE_IOCTL_DBG(xe, args->pad[0] || args->pad[1] || args->pad[2]) ||
@@ -4031,6 +4035,7 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 		vm = xe_vm_lookup(xef, args->vm_id);
 		if (XE_IOCTL_DBG(xe, !vm))
 			return -ENOENT;
+		asid = vm->usm.asid;
 	}
 
 	/*
@@ -4100,6 +4105,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			if (err)
 				break;
 		}
+
+		if (lock_start == ktime_set(0, 0))
+			lock_start = ktime_get();
+
 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
 				       bo_flags, have_prealloc ? &prealloc : NULL,
 				       &exec);
@@ -4110,6 +4119,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			break;
 		}
 	}
+	if (lock_start != ktime_set(0, 0))
+		lock_ns = ktime_to_ns(ktime_sub(ktime_get(), lock_start));
 	if (have_prealloc)
 		ttm_pool_prealloc_fini(&xe->ttm.pool, &prealloc);
 	if (err)

drivers/gpu/drm/xe/xe_bo.c int xe_gem_create_ioctl(struct drm_device *dev, void *data, · line 4159

Quoted 9 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
@@ -4140,6 +4151,12 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	if (vm)
 		xe_vm_put(vm);
 
+	trace_xe_gem_create_ioctl(xe, args->size, args->placement,
+				  args->cpu_caching, asid,
+				  div_u64(ktime_to_ns(ktime_sub(ktime_get(),
+							ioctl_start)), 1000),
+				  div_u64(lock_ns, 1000));
+

Will prealloc time (prealloc_us) also useful to print in the trace message?

Niranjana

Quoted 48 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 	return err;
 }
 
drivers/gpu/drm/xe/xe_trace_bo.h +31 -0
index b159d37d39a1..63db37edadc2 100644
@@ -144,6 +144,37 @@ TRACE_EVENT(xe_bo_defrag_one,
 		      __entry->ret)
 );
 
+TRACE_EVENT(xe_gem_create_ioctl,
+	    TP_PROTO(struct xe_device *xe, u64 size, u32 placement,
+		     u16 caching, u32 asid, u64 ioctl_us, u64 lock_us),
+	    TP_ARGS(xe, size, placement, caching, asid, ioctl_us, lock_us),
+
+	    TP_STRUCT__entry(
+		     __string(dev, dev_name(xe->drm.dev))
+		     __field(u64, size)
+		     __field(u32, placement)
+		     __field(u16, caching)
+		     __field(u32, asid)
+		     __field(u64, ioctl_us)
+		     __field(u64, lock_us)
+		     ),
+
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->size = size;
+		   __entry->placement = placement;
+		   __entry->caching = caching;
+		   __entry->asid = asid;
+		   __entry->ioctl_us = ioctl_us;
+		   __entry->lock_us = lock_us;
+		   ),
+
+	    TP_printk("dev=%s, size=%llu, placement=0x%x, caching=%u, asid=%u, ioctl_us=%llu, lock_us=%llu",
+		      __get_str(dev), __entry->size, __entry->placement,
+		      __entry->caching, __entry->asid, __entry->ioctl_us,
+		      __entry->lock_us)
+);
+
 DECLARE_EVENT_CLASS(xe_vma,
 		    TP_PROTO(struct xe_vma *vma),
 		    TP_ARGS(vma),
Signature · 1 line
2.34.1
author maintainer
#104 lore raw

Re: [PATCH v3 26/33] drm/xe: Add tracepoint for xe_gem_create_ioctl

Quoted 88 lines · Niranjana Vishwanathapura
Quoted 87 lines · Matthew Brost

Add a xe_gem_create_ioctl tracepoint to help profile GEM creation, in particular the cost of populating a BO while holding the dma-resv lock versus the total IOCTL cost. This is useful for evaluating the out-of-lock preallocation path, which aims to shrink the time spent under the lock.

The tracepoint records the BO size, the requested placement mask, the CPU caching mode, the VM asid (0 when no VM is bound), the total time spent in the IOCTL, and the time spent under the dma-resv lock (the xe_validation_guard region where the lock is held).

The asid is captured at VM lookup time rather than at trace emission, since the VM reference is dropped before the tracepoint fires.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---

v3:
- Guard lock_ns against an unset lock_start and use div_u64() in the tracepoint (Sashiko)
---
drivers/gpu/drm/xe/xe_bo.c | 17 +++++++++++++++++
drivers/gpu/drm/xe/xe_trace_bo.h | 31 +++++++++++++++++++++++++++++++

2 files changed, 48 insertions(+)
drivers/gpu/drm/xe/xe_bo.c +11 -0
index a646a72122d4..caf5aa0bab53 100644
@@ -3953,6 +3953,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	bool have_prealloc = false;
 	unsigned int bo_flags;
 	u32 handle;
+	ktime_t ioctl_start = ktime_get();
+	ktime_t lock_start = ktime_set(0, 0);
+	u64 lock_ns = 0;
+	u32 asid = 0;
 	int err;
 
 	if (XE_IOCTL_DBG(xe, args->pad[0] || args->pad[1] || args->pad[2]) ||
@@ -4031,6 +4035,7 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 		vm = xe_vm_lookup(xef, args->vm_id);
 		if (XE_IOCTL_DBG(xe, !vm))
 			return -ENOENT;
+		asid = vm->usm.asid;
 	}
 
 	/*
@@ -4100,6 +4105,10 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			if (err)
 				break;
 		}
+
+		if (lock_start == ktime_set(0, 0))
+			lock_start = ktime_get();
+
 		bo = xe_bo_create_user(xe, vm, args->size, args->cpu_caching,
 				       bo_flags, have_prealloc ? &prealloc : NULL,
 				       &exec);
@@ -4110,6 +4119,8 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 			break;
 		}
 	}
+	if (lock_start != ktime_set(0, 0))
+		lock_ns = ktime_to_ns(ktime_sub(ktime_get(), lock_start));
 	if (have_prealloc)
 		ttm_pool_prealloc_fini(&xe->ttm.pool, &prealloc);
 	if (err)
@@ -4140,6 +4151,12 @@ int xe_gem_create_ioctl(struct drm_device *dev, void *data,
 	if (vm)
 		xe_vm_put(vm);
 
Quoted 9 lines

drivers/gpu/drm/xe/xe_bo.c int xe_gem_create_ioctl(struct drm_device *dev, void *data, · line 4159

Quoted 6 lines
drivers/gpu/drm/xe/xe_bo.c +6 -0
+	trace_xe_gem_create_ioctl(xe, args->size, args->placement,
+				  args->cpu_caching, asid,
+				  div_u64(ktime_to_ns(ktime_sub(ktime_get(),
+							ioctl_start)), 1000),
+				  div_u64(lock_ns, 1000));
+

Will prealloc time (prealloc_us) also useful to print in the trace message?

I think it roughly implied ioctl_us - lock_us == prealloc_us.

Matt

Quoted 49 lines

Niranjana

Quoted 48 lines
drivers/gpu/drm/xe/xe_bo.c +0 -0
 	return err;
 }
 
drivers/gpu/drm/xe/xe_trace_bo.h +31 -0
index b159d37d39a1..63db37edadc2 100644
@@ -144,6 +144,37 @@ TRACE_EVENT(xe_bo_defrag_one,
 		      __entry->ret)
 );
 
+TRACE_EVENT(xe_gem_create_ioctl,
+	    TP_PROTO(struct xe_device *xe, u64 size, u32 placement,
+		     u16 caching, u32 asid, u64 ioctl_us, u64 lock_us),
+	    TP_ARGS(xe, size, placement, caching, asid, ioctl_us, lock_us),
+
+	    TP_STRUCT__entry(
+		     __string(dev, dev_name(xe->drm.dev))
+		     __field(u64, size)
+		     __field(u32, placement)
+		     __field(u16, caching)
+		     __field(u32, asid)
+		     __field(u64, ioctl_us)
+		     __field(u64, lock_us)
+		     ),
+
+	    TP_fast_assign(
+		   __assign_str(dev);
+		   __entry->size = size;
+		   __entry->placement = placement;
+		   __entry->caching = caching;
+		   __entry->asid = asid;
+		   __entry->ioctl_us = ioctl_us;
+		   __entry->lock_us = lock_us;
+		   ),
+
+	    TP_printk("dev=%s, size=%llu, placement=0x%x, caching=%u, asid=%u, ioctl_us=%llu, lock_us=%llu",
+		      __get_str(dev), __entry->size, __entry->placement,
+		      __entry->caching, __entry->asid, __entry->ioctl_us,
+		      __entry->lock_us)
+);
+
 DECLARE_EVENT_CLASS(xe_vma,
 		    TP_PROTO(struct xe_vma *vma),
 		    TP_ARGS(vma),
Signature · 1 line
2.34.1
author maintainer
#105 lore raw

PATCH v3 27/33 drm/xe: Add IOVA-based xe_res_cursor variant

In reply to Matthew Brost

Introduce xe_res_first_iova() to walk a buffer that was DMA mapped using the IOVA-based DMA API (dma_iova_try_alloc() and friends). Such a mapping is described by a struct dma_iova_state and is a single contiguous IOVA range, so the cursor walks it as one segment.

Add an is_iova flag to struct xe_res_cursor to distinguish this case. When set, xe_res_dma() returns the IOVA backing the current position (state->addr + cursor offset), xe_res_next() advances within the single contiguous segment, and xe_res_is_vram() returns false since IOVA mappings never point to same-device VRAM.

The flag is explicitly cleared in the existing xe_res_first(), xe_res_first_sg() and xe_res_first_dma() initializers so stale stack values cannot leak into the new path.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/xe_res_cursor.h | 56 +++++++++++++++++++++++++++++-
 1 file changed, 55 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_res_cursor.h +55 -1
index 0522caafd89d..f0f1d699e16e 100644
@@ -24,6 +24,7 @@
 #ifndef _XE_RES_CURSOR_H_
 #define _XE_RES_CURSOR_H_
 
+#include <linux/dma-mapping.h>
 #include <linux/scatterlist.h>
 
 #include <drm/drm_pagemap.h>
@@ -67,6 +68,12 @@ struct xe_res_cursor {
 	u64 dma_start;
 	/** @dma_seg_size: Size of the current DMA segment. */
 	u64 dma_seg_size;
+	/**
+	 * @is_iova: Whether the cursor walks a single contiguous IOVA
+	 * mapping described by a struct dma_iova_state. When true, the
+	 * DMA address is @dma_start + @start and never points to VRAM.
+	 */
+	bool is_iova;
 };
 
 static struct gpu_buddy *xe_res_get_buddy(struct ttm_resource *res)
@@ -93,6 +100,7 @@ static inline void xe_res_first(struct ttm_resource *res,
 {
 	cur->sgl = NULL;
 	cur->dma_addr = NULL;
+	cur->is_iova = false;
 	if (!res)
 		goto fallback;
 
@@ -224,6 +232,7 @@ static inline void xe_res_first_sg(const struct sg_table *sg,
 	cur->dma_addr = NULL;
 	cur->sgl = sg->sgl;
 	cur->mem_type = XE_PL_TT;
+	cur->is_iova = false;
 	__xe_res_sg_next(cur);
 }
 
@@ -255,6 +264,41 @@ static inline void xe_res_first_dma(const struct drm_pagemap_addr *dma_addr,
 	__xe_res_dma_next(cur);
 	cur->sgl = NULL;
 	cur->mem_type = XE_PL_TT;
+	cur->is_iova = false;
+}
+
+/**
+ * xe_res_first_iova() - initialize a xe_res_cursor with a dma_iova_state
+ *
+ * @state: struct dma_iova_state describing a single contiguous IOVA mapping
+ * @start: Start of the range
+ * @size: Size of the range
+ * @cur: cursor object to initialize
+ *
+ * Start walking over the range of an allocation that was DMA mapped using the
+ * IOVA-based DMA API (see dma_iova_try_alloc()). Such a mapping is a single
+ * contiguous IOVA range, so the cursor walks it as one segment. Subsequent
+ * calls to xe_res_next() advance within that range and xe_res_dma() returns
+ * the IOVA backing the current position. xe_res_is_vram() always returns false
+ * for such a cursor.
+ */
+static inline void xe_res_first_iova(struct dma_iova_state *state,
+				     u64 start, u64 size,
+				     struct xe_res_cursor *cur)
+{
+	XE_WARN_ON(!state);
+	XE_WARN_ON(start + size > dma_iova_size(state));
+
+	cur->node = NULL;
+	cur->start = start;
+	cur->remaining = size;
+	cur->size = size;
+	cur->dma_addr = NULL;
+	cur->sgl = NULL;
+	cur->dma_start = state->addr;
+	cur->dma_seg_size = dma_iova_size(state);
+	cur->mem_type = XE_PL_TT;
+	cur->is_iova = true;
 }
 
 /**
@@ -283,6 +327,13 @@ static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
 		return;
 	}
 
+	if (cur->is_iova) {
+		/* Single contiguous IOVA segment. */
+		cur->start += size;
+		cur->size = cur->remaining;
+		return;
+	}
+
 	if (cur->dma_addr) {
 		cur->start += size;
 		__xe_res_dma_next(cur);
@@ -334,7 +385,7 @@ static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
  */
 static inline u64 xe_res_dma(const struct xe_res_cursor *cur)
 {
-	if (cur->dma_addr)
+	if (cur->is_iova || cur->dma_addr)
 		return cur->dma_start + cur->start;
 	else if (cur->sgl)
 		return sg_dma_address(cur->sgl) + cur->start;
@@ -351,6 +402,9 @@ static inline u64 xe_res_dma(const struct xe_res_cursor *cur)
  */
 static inline bool xe_res_is_vram(const struct xe_res_cursor *cur)
 {
+	if (cur->is_iova)
+		return false;
+
 	if (cur->dma_addr)
 		return cur->dma_addr->proto == XE_INTERCONNECT_VRAM;
 
Signature · 1 line
2.34.1
#106 lore raw

Re: [PATCH v3 27/33] drm/xe: Add IOVA-based xe_res_cursor variant

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The newly added `is_iova` block in `xe_res_next()` is mathematically unreachable and completely…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The newly added is_iova block in xe_res_next() is mathematically unreachable and completely redundant. --

--- Patch [27]: [PATCH v3 27/33] drm/xe: Add IOVA-based xe_res_cursor variant --- commit 41ab8ab5c8919ddc065db2f6f0c78d6b5b1b51d0
Author: Matthew Brost <[email protected]>

drm/xe: Add IOVA-based xe_res_cursor variant

This patch introduces a variant of xe_res_cursor for walking buffer objects DMA mapped using the IOVA-based DMA API. It adds an is_iova flag to distinguish single contiguous IOVA mappings and updates the cursor functions to handle this contiguous segment appropriately.

Quoted 4 lines
drivers/gpu/drm/xe/xe_res_cursor.h +0 -0
index 0522caafd89d7..f0f1d699e16e5 100644

[ ... ]

drivers/gpu/drm/xe/xe_res_cursor.h static inline void xe_res_next(struct xe_res_cursor *cur, u64 size) · line 336

Quoted 11 lines
drivers/gpu/drm/xe/xe_res_cursor.h +7 -0
@@ -283,6 +327,13 @@ static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
 		return;
 	}
 
+	if (cur->is_iova) {
+		/* Single contiguous IOVA segment. */
+		cur->start += size;
+		cur->size = cur->remaining;
+		return;
+	}
+

[Severity: Low]
Is this block reachable?

In xe_res_first_iova(), cur->size is initialized to the full size, matching cur->remaining.

When xe_res_next(cur, size) is called, it first decrements cur->remaining:

	cur->remaining -= size;
	if (!cur->remaining)
		return;

If the cursor isn't exhausted, the original cur->remaining must have been greater than size. Since cur->size equals the original cur->remaining for single contiguous IOVA mappings, cur->size will also be greater than size.

This means execution will always enter the generic segment advancement block immediately preceding this one:

	if (cur->size > size) {
		cur->size -= size;
		cur->start += size;
		return;
	}

Does this make the newly added is_iova block mathematically unreachable dead code?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=27
reviewer Reviewed-by on v3 27/33
#107 lore raw

Re: [PATCH v3 27/33] drm/xe: Add IOVA-based xe_res_cursor variant

In reply to Matthew Brost
Quoted 15 lines · Matthew Brost

Introduce xe_res_first_iova() to walk a buffer that was DMA mapped using the IOVA-based DMA API (dma_iova_try_alloc() and friends). Such a mapping is described by a struct dma_iova_state and is a single contiguous IOVA range, so the cursor walks it as one segment.

Add an is_iova flag to struct xe_res_cursor to distinguish this case. When set, xe_res_dma() returns the IOVA backing the current position (state->addr + cursor offset), xe_res_next() advances within the single contiguous segment, and xe_res_is_vram() returns false since IOVA mappings never point to same-device VRAM.

The flag is explicitly cleared in the existing xe_res_first(), xe_res_first_sg() and xe_res_first_dma() initializers so stale stack values cannot leak into the new path.

Quoted 15 lines
Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
#108 lore raw

Re: [PATCH v3 27/33] drm/xe: Add IOVA-based xe_res_cursor variant

In reply to Matthew Brost
Quoted 76 lines · Matthew Brost

Introduce xe_res_first_iova() to walk a buffer that was DMA mapped using the IOVA-based DMA API (dma_iova_try_alloc() and friends). Such a mapping is described by a struct dma_iova_state and is a single contiguous IOVA range, so the cursor walks it as one segment.

Add an is_iova flag to struct xe_res_cursor to distinguish this case. When set, xe_res_dma() returns the IOVA backing the current position (state->addr + cursor offset), xe_res_next() advances within the single contiguous segment, and xe_res_is_vram() returns false since IOVA mappings never point to same-device VRAM.

The flag is explicitly cleared in the existing xe_res_first(), xe_res_first_sg() and xe_res_first_dma() initializers so stale stack values cannot leak into the new path.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

---
drivers/gpu/drm/xe/xe_res_cursor.h | 56 +++++++++++++++++++++++++++++-

1 file changed, 55 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_res_cursor.h +9 -0
index 0522caafd89d..f0f1d699e16e 100644
@@ -24,6 +24,7 @@
 #ifndef _XE_RES_CURSOR_H_
 #define _XE_RES_CURSOR_H_
 
+#include <linux/dma-mapping.h>
 #include <linux/scatterlist.h>
 
 #include <drm/drm_pagemap.h>
@@ -67,6 +68,12 @@ struct xe_res_cursor {
 	u64 dma_start;
 	/** @dma_seg_size: Size of the current DMA segment. */
 	u64 dma_seg_size;
+	/**
+	 * @is_iova: Whether the cursor walks a single contiguous IOVA
+	 * mapping described by a struct dma_iova_state. When true, the
+	 * DMA address is @dma_start + @start and never points to VRAM.
+	 */
+	bool is_iova;
 };
 
 static struct gpu_buddy *xe_res_get_buddy(struct ttm_resource *res)
@@ -93,6 +100,7 @@ static inline void xe_res_first(struct ttm_resource *res,
 {
 	cur->sgl = NULL;
 	cur->dma_addr = NULL;
+	cur->is_iova = false;
 	if (!res)
 		goto fallback;
 
@@ -224,6 +232,7 @@ static inline void xe_res_first_sg(const struct sg_table *sg,
 	cur->dma_addr = NULL;
 	cur->sgl = sg->sgl;
 	cur->mem_type = XE_PL_TT;
+	cur->is_iova = false;
 	__xe_res_sg_next(cur);
 }
 

drivers/gpu/drm/xe/xe_res_cursor.h static inline void xe_res_first_dma(const struct drm_pagemap_addr *dma_addr, · line 268

Quoted 5 lines
drivers/gpu/drm/xe/xe_res_cursor.h +2 -0
@@ -255,6 +264,41 @@ static inline void xe_res_first_dma(const struct drm_pagemap_addr *dma_addr,
 	__xe_res_dma_next(cur);
 	cur->sgl = NULL;
 	cur->mem_type = XE_PL_TT;
+	cur->is_iova = false;
+}
Assisted-by LLM

NIT..Instead of defining and clearing is_iova flag, would it be better to define enum defitions for different cursor types?

Quoted 21 lines
drivers/gpu/drm/xe/xe_res_cursor.h +21 -0
+
+/**
+ * xe_res_first_iova() - initialize a xe_res_cursor with a dma_iova_state
+ *
+ * @state: struct dma_iova_state describing a single contiguous IOVA mapping
+ * @start: Start of the range
+ * @size: Size of the range
+ * @cur: cursor object to initialize
+ *
+ * Start walking over the range of an allocation that was DMA mapped using the
+ * IOVA-based DMA API (see dma_iova_try_alloc()). Such a mapping is a single
+ * contiguous IOVA range, so the cursor walks it as one segment. Subsequent
+ * calls to xe_res_next() advance within that range and xe_res_dma() returns
+ * the IOVA backing the current position. xe_res_is_vram() always returns false
+ * for such a cursor.
+ */
+static inline void xe_res_first_iova(struct dma_iova_state *state,
+				     u64 start, u64 size,
+				     struct xe_res_cursor *cur)
+{
+	XE_WARN_ON(!state);

drivers/gpu/drm/xe/xe_res_cursor.h static inline void xe_res_first_dma(const struct drm_pagemap_addr *dma_addr, · line 299

Quoted 10 lines
drivers/gpu/drm/xe/xe_res_cursor.h +10 -0
+	XE_WARN_ON(start + size > dma_iova_size(state));
+
+	cur->node = NULL;
+	cur->start = start;
+	cur->remaining = size;
+	cur->size = size;
+	cur->dma_addr = NULL;
+	cur->sgl = NULL;
+	cur->dma_start = state->addr;
+	cur->dma_seg_size = dma_iova_size(state);

NIT...looks like cur->dma_seg_size is never used, but should be fine.

Quoted 6 lines
drivers/gpu/drm/xe/xe_res_cursor.h +2 -0
+	cur->mem_type = XE_PL_TT;
+	cur->is_iova = true;
 }
 
 /**

drivers/gpu/drm/xe/xe_res_cursor.h static inline void xe_res_next(struct xe_res_cursor *cur, u64 size) · line 335

Quoted 9 lines
drivers/gpu/drm/xe/xe_res_cursor.h +6 -0
@@ -283,6 +327,13 @@ static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
 		return;
 	}
 
+	if (cur->is_iova) {
+		/* Single contiguous IOVA segment. */
+		cur->start += size;
+		cur->size = cur->remaining;
+		return;
+	}

This code never gets executed. Probably remove it and add an assert if we reach here with cur->is_iova set (or add a comment)?

Niranjana

Quoted 26 lines
drivers/gpu/drm/xe/xe_res_cursor.h +5 -1
+
 	if (cur->dma_addr) {
 		cur->start += size;
 		__xe_res_dma_next(cur);
@@ -334,7 +385,7 @@ static inline void xe_res_next(struct xe_res_cursor *cur, u64 size)
 */
 static inline u64 xe_res_dma(const struct xe_res_cursor *cur)
 {
-	if (cur->dma_addr)
+	if (cur->is_iova || cur->dma_addr)
 		return cur->dma_start + cur->start;
 	else if (cur->sgl)
 		return sg_dma_address(cur->sgl) + cur->start;
@@ -351,6 +402,9 @@ static inline u64 xe_res_dma(const struct xe_res_cursor *cur)
 */
 static inline bool xe_res_is_vram(const struct xe_res_cursor *cur)
 {
+	if (cur->is_iova)
+		return false;
+
 	if (cur->dma_addr)
 		return cur->dma_addr->proto == XE_INTERCONNECT_VRAM;
 
Signature · 1 line
2.34.1
author maintainer
#109 lore raw

PATCH v3 28/33 drm/xe: Use IOVA-based DMA mapping for eligible tt BOs

In reply to Matthew Brost

Add support for mapping a ttm_tt's pages using the IOVA-based DMA API (dma_iova_try_alloc()/link()/sync()/unlink()/free()) as an alternative to the scatter-gather list. An IOVA mapping is a single contiguous DMA range, which is cheaper to walk and program than an sg list.

Whether the IOVA API can be used depends on the IOMMU mode, so the decision is made once per tt at xe_ttm_tt_create() time and recorded in struct xe_ttm_tt::use_iova. To keep the scope limited, only device BOs that are not GGTT-mapped are eligible: dma-buf imports manage their own mapping and GGTT bindings are programmed directly from the sg list. dma_iova_try_alloc() may still fail, in which case the tt transparently falls back to the sg list, which remains the default.

The IOVA reservation is allocated at tt creation and freed at tt destroy. xe_tt_map_iova() links the tt pages (coalescing physically contiguous runs) and syncs the IOTLB; xe_tt_unmap_iova() unlinks them but keeps the reservation so the tt can be remapped without re-allocating IOVA space. xe_tt_map()/xe_tt_unmap() dispatch between the IOVA and sg backends, and xe_bo_dma_unmap_pinned() learns about the IOVA case.

Consumers that walked the sg list via xe_res_first_sg(xe_bo_sg()) now go through the new xe_res_first_tt() helper, which initializes either an IOVA cursor (xe_res_first_iova()) or an sg cursor depending on the tt's mapping mode.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/xe/tests/xe_migrate.c |   6 +-
 drivers/gpu/drm/xe/xe_bo.c            | 239 ++++++++++++++++++++++++--
 drivers/gpu/drm/xe/xe_bo.h            |   5 +-
 drivers/gpu/drm/xe/xe_ggtt.c          |   2 +-
 drivers/gpu/drm/xe/xe_migrate.c       |  14 +-
 drivers/gpu/drm/xe/xe_pt.c            |   2 +-
 6 files changed, 237 insertions(+), 31 deletions(-)
drivers/gpu/drm/xe/tests/xe_migrate.c +3 -3
index 41de648b2c86..119134e67c89 100644
@@ -253,7 +253,7 @@ static void xe_migrate_sanity_test(struct xe_migrate *m, struct kunit *test,
 	if (xe_bo_is_vram(pt))
 		xe_res_first(pt->ttm.resource, 0, xe_bo_size(pt), &src_it);
 	else
-		xe_res_first_sg(xe_bo_sg(pt), 0, xe_bo_size(pt), &src_it);
+		xe_res_first_tt(pt->ttm.ttm, 0, xe_bo_size(pt), &src_it);
 
 	emit_pte(m, bb, NUM_KERNEL_PDE - 1, xe_bo_is_vram(pt), false,
 		 &src_it, XE_PAGE_SIZE, pt->ttm.resource);
@@ -385,12 +385,12 @@ static struct dma_fence *blt_copy(struct xe_tile *tile,
 	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
 
 	if (!src_is_vram)
-		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_tt(src_bo->ttm.ttm, 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 
 	if (!dst_is_vram)
-		xe_res_first_sg(xe_bo_sg(dst_bo), 0, size, &dst_it);
+		xe_res_first_tt(dst_bo->ttm.ttm, 0, size, &dst_it);
 	else
 		xe_res_first(dst, 0, size, &dst_it);
 
drivers/gpu/drm/xe/xe_bo.c +222 -17

334 lines not on this page · raw message

drivers/gpu/drm/xe/xe_bo.h +3 -2
index 18fcccd082b7..3e2eaefecb8f 100644
@@ -552,8 +552,9 @@ void xe_bo_dev_init(struct xe_bo_dev *bo_device);
 
 void xe_bo_dev_fini(struct xe_bo_dev *bo_device);
 
-struct sg_table *xe_bo_sg(struct xe_bo *bo);
-struct sg_table *xe_tt_sg(struct ttm_tt *tt);
+struct xe_res_cursor;
+void xe_res_first_tt(struct ttm_tt *tt, u64 start, u64 size,
+		     struct xe_res_cursor *cur);
 
 /*
  * xe_sg_segment_size() - Provides upper limit for sg segment size.
drivers/gpu/drm/xe/xe_ggtt.c +1 -1
index 8ec23862477f..4084bc183e06 100644
@@ -699,7 +699,7 @@ static void xe_ggtt_map_bo(struct xe_ggtt *ggtt, struct xe_ggtt_node *node,
 	if (!xe_bo_is_vram(bo) && !xe_bo_is_stolen(bo)) {
 		xe_assert(xe_bo_device(bo), bo->ttm.ttm);
 
-		for (xe_res_first_sg(xe_bo_sg(bo), 0, xe_bo_size(bo), &cur);
+		for (xe_res_first_tt(bo->ttm.ttm, 0, xe_bo_size(bo), &cur);
 		     cur.remaining; xe_res_next(&cur, XE_PAGE_SIZE))
 			ggtt->pt_ops->ggtt_set_pte(ggtt, end - cur.remaining,
 						   pte | xe_res_dma(&cur));
drivers/gpu/drm/xe/xe_migrate.c +7 -7
index 9990a7144a9f..666c715a9067 100644
@@ -1005,16 +1005,16 @@ static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
 		return ERR_PTR(-EINVAL);
 
 	if (!src_is_vram)
-		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo), 0, size, &src_it);
+		xe_res_first_tt(src_tt ? src_tt : src_bo->ttm.ttm, 0, size, &src_it);
 	else
 		xe_res_first(src, 0, size, &src_it);
 	if (!dst_is_vram)
-		xe_res_first_sg(xe_bo_sg(dst_bo), 0, size, &dst_it);
+		xe_res_first_tt(dst_bo->ttm.ttm, 0, size, &dst_it);
 	else
 		xe_res_first(dst, 0, size, &dst_it);
 
 	if (copy_system_ccs)
-		xe_res_first_sg(src_tt ? xe_tt_sg(src_tt) : xe_bo_sg(src_bo),
+		xe_res_first_tt(src_tt ? src_tt : src_bo->ttm.ttm,
 				xe_bo_ccs_pages_start(src_bo),
 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 				&ccs_it);
@@ -1383,9 +1383,9 @@ int xe_migrate_ccs_rw_copy(struct xe_tile *tile, struct xe_exec_queue *q,
 
 	ctx = &xe->sriov.vf.ccs.contexts[read_write];
 
-	xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
+	xe_res_first_tt(src_bo->ttm.ttm, 0, size, &src_it);
 
-	xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
+	xe_res_first_tt(src_bo->ttm.ttm, xe_bo_ccs_pages_start(src_bo),
 			PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
 			&ccs_it);
 
@@ -1588,7 +1588,7 @@ struct dma_fence *xe_migrate_vram_copy_chunk(struct xe_bo *vram_bo, u64 vram_off
 	xe_assert(xe, !range_overflows(sysmem_offset, size, (u64)sysmem_bo->ttm.base.size));
 
 	xe_res_first(vram, vram_offset, size, &vram_it);
-	xe_res_first_sg(xe_bo_sg(sysmem_bo), sysmem_offset, size, &sysmem_it);
+	xe_res_first_tt(sysmem_bo->ttm.ttm, sysmem_offset, size, &sysmem_it);
 
 	while (size) {
 		u32 pte_flags = PTE_UPDATE_FLAG_IS_VRAM;
@@ -1800,7 +1800,7 @@ struct dma_fence *xe_migrate_clear(struct xe_migrate *m,
 		clear_only_system_ccs = true;
 
 	if (!clear_vram)
-		xe_res_first_sg(xe_bo_sg(bo), 0, xe_bo_size(bo), &src_it);
+		xe_res_first_tt(bo->ttm.ttm, 0, xe_bo_size(bo), &src_it);
 	else
 		xe_res_first(src, 0, xe_bo_size(bo), &src_it);
 
drivers/gpu/drm/xe/xe_pt.c +1 -1
index 7111b5d0f6aa..185d15fb0a97 100644
@@ -797,7 +797,7 @@ xe_pt_stage_bind(struct xe_tile *tile, struct xe_vma *vma,
 			xe_res_first(bo->ttm.resource, xe_vma_bo_offset(vma),
 				     xe_vma_size(vma), &curs);
 		else
-			xe_res_first_sg(xe_bo_sg(bo), xe_vma_bo_offset(vma),
+			xe_res_first_tt(bo->ttm.ttm, xe_vma_bo_offset(vma),
 					xe_vma_size(vma), &curs);
 	} else if (!range) {
 		curs.size = xe_vma_size(vma);
Signature · 1 line
2.34.1
reviewer
#110 lore raw

Re: [PATCH v3 28/33] drm/xe: Use IOVA-based DMA mapping for eligible tt BOs

Quoted 41 lines · Matthew Brost

Add support for mapping a ttm_tt's pages using the IOVA-based DMA API (dma_iova_try_alloc()/link()/sync()/unlink()/free()) as an alternative to the scatter-gather list. An IOVA mapping is a single contiguous DMA range, which is cheaper to walk and program than an sg list.

Whether the IOVA API can be used depends on the IOMMU mode, so the decision is made once per tt at xe_ttm_tt_create() time and recorded in struct xe_ttm_tt::use_iova. To keep the scope limited, only device BOs that are not GGTT-mapped are eligible: dma-buf imports manage their own mapping and GGTT bindings are programmed directly from the sg list. dma_iova_try_alloc() may still fail, in which case the tt transparently falls back to the sg list, which remains the default.

The IOVA reservation is allocated at tt creation and freed at tt destroy. xe_tt_map_iova() links the tt pages (coalescing physically contiguous runs) and syncs the IOTLB; xe_tt_unmap_iova() unlinks them but keeps the reservation so the tt can be remapped without re-allocating IOVA space. xe_tt_map()/xe_tt_unmap() dispatch between the IOVA and sg backends, and xe_bo_dma_unmap_pinned() learns about the IOVA case.

Consumers that walked the sg list via xe_res_first_sg(xe_bo_sg()) now go through the new xe_res_first_tt() helper, which initializes either an IOVA cursor (xe_res_first_iova()) or an sg cursor depending on the tt's mapping mode.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

<snip>

drivers/gpu/drm/xe/xe_bo.c static void xe_ttm_tt_unpopulate(struct ttm_device *ttm_dev, struct ttm_tt *tt) · line 912

Quoted 13 lines
  static void xe_ttm_tt_destroy(struct ttm_device *ttm_dev, struct ttm_tt *tt)
  {
drivers/gpu/drm/xe/xe_bo.c +11 -0
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	/*
+	 * Release the IOVA reservation made in xe_ttm_tt_create(). The pages
+	 * must already have been unlinked by xe_tt_unmap().
+	 */
+	if (xe_tt->use_iova) {
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		xe_assert(xe, !xe_tt->iova_linked);
+		dma_iova_free(xe->drm.dev, &xe_tt->iova);

Do we know if this is allowed? I think there is xe_bo_pci_dev_remove_all() which requires that evict_all will correctly tear down iommu mappings on stuff like pci unplug and I don't think tt_destroy is called in that flow? Does having the iova here cause issues? Also, for VRAM flow I think there is a tt_create() via pipeline gutting which will now create a new iova?

Aside from that, maybe we can land 27/28 as standalone?

author maintainer
#111 lore raw

Re: [PATCH v3 28/33] drm/xe: Use IOVA-based DMA mapping for eligible tt BOs

Quoted 55 lines · Matthew Auld
Quoted 41 lines · Matthew Brost

Add support for mapping a ttm_tt's pages using the IOVA-based DMA API (dma_iova_try_alloc()/link()/sync()/unlink()/free()) as an alternative to the scatter-gather list. An IOVA mapping is a single contiguous DMA range, which is cheaper to walk and program than an sg list.

Whether the IOVA API can be used depends on the IOMMU mode, so the decision is made once per tt at xe_ttm_tt_create() time and recorded in struct xe_ttm_tt::use_iova. To keep the scope limited, only device BOs that are not GGTT-mapped are eligible: dma-buf imports manage their own mapping and GGTT bindings are programmed directly from the sg list. dma_iova_try_alloc() may still fail, in which case the tt transparently falls back to the sg list, which remains the default.

The IOVA reservation is allocated at tt creation and freed at tt destroy. xe_tt_map_iova() links the tt pages (coalescing physically contiguous runs) and syncs the IOTLB; xe_tt_unmap_iova() unlinks them but keeps the reservation so the tt can be remapped without re-allocating IOVA space. xe_tt_map()/xe_tt_unmap() dispatch between the IOVA and sg backends, and xe_bo_dma_unmap_pinned() learns about the IOVA case.

Consumers that walked the sg list via xe_res_first_sg(xe_bo_sg()) now go through the new xe_res_first_tt() helper, which initializes either an IOVA cursor (xe_res_first_iova()) or an sg cursor depending on the tt's mapping mode.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

<snip>

Quoted 9 lines
  static void xe_ttm_tt_destroy(struct ttm_device *ttm_dev, struct ttm_tt *tt)
  {
drivers/gpu/drm/xe/xe_bo.c +7 -0
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	/*
+	 * Release the IOVA reservation made in xe_ttm_tt_create(). The pages
+	 * must already have been unlinked by xe_tt_unmap().
+	 */
+	if (xe_tt->use_iova) {
Quoted 8 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_ttm_tt_unpopulate(struct ttm_device *ttm_dev, struct ttm_tt *tt) · line 912

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		xe_assert(xe, !xe_tt->iova_linked);
+		dma_iova_free(xe->drm.dev, &xe_tt->iova);

Do we know if this is allowed? I think there is xe_bo_pci_dev_remove_all() which requires that evict_all will correctly tear down iommu mappings on stuff like pci unplug and I don't think tt_destroy is called in that flow?

But unpopulate is called which unlinks / syncs (TLB flush for the IOVA).

Quoted 3 lines

Does having the iova here cause issues? Also, for VRAM flow I think there is a tt_create() via pipeline gutting which will now create a new iova?

Maybe we shuffle this around a bit so the iova alloc is tied to populate/unpopulate. It was been a while I forget exactly why I did this way.

Quoted 1 line

Aside from that, maybe we can land 27/28 as standalone?

Yes, let me extract these two into standalone patches today and reworking if needed.

Matt

reviewer
#112 lore raw

Re: [PATCH v3 28/33] drm/xe: Use IOVA-based DMA mapping for eligible tt BOs

Quoted 71 lines · Matthew Brost
Quoted 55 lines · Matthew Auld
Quoted 41 lines · Matthew Brost

Add support for mapping a ttm_tt's pages using the IOVA-based DMA API (dma_iova_try_alloc()/link()/sync()/unlink()/free()) as an alternative to the scatter-gather list. An IOVA mapping is a single contiguous DMA range, which is cheaper to walk and program than an sg list.

Whether the IOVA API can be used depends on the IOMMU mode, so the decision is made once per tt at xe_ttm_tt_create() time and recorded in struct xe_ttm_tt::use_iova. To keep the scope limited, only device BOs that are not GGTT-mapped are eligible: dma-buf imports manage their own mapping and GGTT bindings are programmed directly from the sg list. dma_iova_try_alloc() may still fail, in which case the tt transparently falls back to the sg list, which remains the default.

The IOVA reservation is allocated at tt creation and freed at tt destroy. xe_tt_map_iova() links the tt pages (coalescing physically contiguous runs) and syncs the IOTLB; xe_tt_unmap_iova() unlinks them but keeps the reservation so the tt can be remapped without re-allocating IOVA space. xe_tt_map()/xe_tt_unmap() dispatch between the IOVA and sg backends, and xe_bo_dma_unmap_pinned() learns about the IOVA case.

Consumers that walked the sg list via xe_res_first_sg(xe_bo_sg()) now go through the new xe_res_first_tt() helper, which initializes either an IOVA cursor (xe_res_first_iova()) or an sg cursor depending on the tt's mapping mode.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

<snip>

Quoted 9 lines
   static void xe_ttm_tt_destroy(struct ttm_device *ttm_dev, struct ttm_tt *tt)
   {
drivers/gpu/drm/xe/xe_bo.c +7 -0
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	/*
+	 * Release the IOVA reservation made in xe_ttm_tt_create(). The pages
+	 * must already have been unlinked by xe_tt_unmap().
+	 */
+	if (xe_tt->use_iova) {
Quoted 8 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_ttm_tt_unpopulate(struct ttm_device *ttm_dev, struct ttm_tt *tt) · line 912

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		xe_assert(xe, !xe_tt->iova_linked);
+		dma_iova_free(xe->drm.dev, &xe_tt->iova);

Do we know if this is allowed? I think there is xe_bo_pci_dev_remove_all() which requires that evict_all will correctly tear down iommu mappings on stuff like pci unplug and I don't think tt_destroy is called in that flow?

But unpopulate is called which unlinks / syncs (TLB flush for the IOVA).

Quoted 3 lines

Does having the iova here cause issues? Also, for VRAM flow I think there is a tt_create() via pipeline gutting which will now create a new iova?

Quoted 8 lines

Maybe we shuffle this around a bit so the iova alloc is tied to populate/unpopulate. It was been a while I forget exactly why I did this way.

Quoted 1 line

Aside from that, maybe we can land 27/28 as standalone?

Yes, let me extract these two into standalone patches today and reworking if needed.

Quickly double checked this, indeed looks to be needed:

[  808.058892] [IGT] core_hotunplug: finished subtest hotreplug-lateclose-with-load, SUCCESS
[  808.058928] [IGT] core_hotunplug: exiting, ret=0
[  808.059673] BUG: kernel NULL pointer dereference, address:
[  808.061068] RIP: 0010:iommu_get_dma_domain+0x10/0x20
[  808.061141] PKRU: 55555554
[  808.061144] Call Trace:
[  808.061146]  <TASK>
[  808.061149]  dma_iova_free+0x18/0xf0
[  808.061153]  xe_ttm_tt_destroy+0x23/0x40 [xe]
[  808.061231]  ttm_bo_put+0x242/0x3d0 [ttm]
[  808.061412]  ? drm_gpuvm_bo_put+0x199/0x200 [drm_gpuvm]
[  808.061418]  xe_vma_destroy_late+0x89/0x90 [xe]
[  808.061476]  xe_vm_close_and_put+0x5de/0x920 [xe]
[  808.061534]  xe_file_close+0x105/0x190 [xe]
[  808.061712]  drm_file_free+0x218/0x260
[  808.061717]  drm_release_noglobal+0x6d/0xd0
[  808.061721]  __fput+0xf9/0x270
[  808.061725]  task_work_run+0x8b/0xb0
[  808.061730]  do_exit+0x229/0x8b0
[  808.061735]  do_group_exit+0x8b/0x90
[  808.061739]  __x64_sys_exit_group+0x17/0x20
[  808.061744]  x64_sys_call+0x18c6/0x18d0
[  808.061749]  do_syscall_64+0xee/0x350
[  808.061753]  ? __pte_offset_map+0x1d/0xd0
[  808.061757]  ? next_uptodate_folio+0xbb/0x3a0
[  808.061762]  ? set_pte_range+0x20d/0x290
[  808.061766]  ? filemap_map_pages+0x8e1/0x9c0
[  808.061772]  ? count_memcg_events+0x7c/0x1b0
[  808.061776]  ? handle_mm_fault+0xbde/0x14f0
[  808.061781]  ? __se_sys_close+0x7a/0xe0
[  808.061785]  ? __se_sys_close+0x7a/0xe0
[  808.061790]  ? do_user_addr_fault+0x272/0x6c0
[  808.061794]  ? irqentry_exit+0x3f/0x640
[  808.061799]  ? do_syscall_64+0x42/0x350
[  808.061803]  entry_SYSCALL_64_after_hwframe+0x76/0x7e
[  808.061808] RIP: 0033:0x7f95428c71b8

I assume this is dev->iommu_group = NULL post unplug.

Quoted 2 lines

Matt

author maintainer
#113 lore raw

Re: [PATCH v3 28/33] drm/xe: Use IOVA-based DMA mapping for eligible tt BOs

Quoted 76 lines · Matthew Auld
Quoted 75 lines · Matthew Brost
Quoted 55 lines · Matthew Auld
Quoted 41 lines · Matthew Brost

Add support for mapping a ttm_tt's pages using the IOVA-based DMA API (dma_iova_try_alloc()/link()/sync()/unlink()/free()) as an alternative to the scatter-gather list. An IOVA mapping is a single contiguous DMA range, which is cheaper to walk and program than an sg list.

Whether the IOVA API can be used depends on the IOMMU mode, so the decision is made once per tt at xe_ttm_tt_create() time and recorded in struct xe_ttm_tt::use_iova. To keep the scope limited, only device BOs that are not GGTT-mapped are eligible: dma-buf imports manage their own mapping and GGTT bindings are programmed directly from the sg list. dma_iova_try_alloc() may still fail, in which case the tt transparently falls back to the sg list, which remains the default.

The IOVA reservation is allocated at tt creation and freed at tt destroy. xe_tt_map_iova() links the tt pages (coalescing physically contiguous runs) and syncs the IOTLB; xe_tt_unmap_iova() unlinks them but keeps the reservation so the tt can be remapped without re-allocating IOVA space. xe_tt_map()/xe_tt_unmap() dispatch between the IOVA and sg backends, and xe_bo_dma_unmap_pinned() learns about the IOVA case.

Consumers that walked the sg list via xe_res_first_sg(xe_bo_sg()) now go through the new xe_res_first_tt() helper, which initializes either an IOVA cursor (xe_res_first_iova()) or an sg cursor depending on the tt's mapping mode.

Cc Carlos Santa <[email protected]>
Cc Ryan Neph <[email protected]>
Cc Christian Koenig <[email protected]>
Cc Huang Rui <[email protected]>
Cc Matthew Auld <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc David Airlie <[email protected]>
Cc Simona Vetter <[email protected]>
Cc Thomas Hellström <[email protected]>
Assisted-by GitHub_Copilot:claude-opus-4.8

<snip>

Quoted 9 lines
   static void xe_ttm_tt_destroy(struct ttm_device *ttm_dev, struct ttm_tt *tt)
   {
drivers/gpu/drm/xe/xe_bo.c +7 -0
+	struct xe_ttm_tt *xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
+
+	/*
+	 * Release the IOVA reservation made in xe_ttm_tt_create(). The pages
+	 * must already have been unlinked by xe_tt_unmap().
+	 */
+	if (xe_tt->use_iova) {
Quoted 8 lines

drivers/gpu/drm/xe/xe_bo.c static void xe_ttm_tt_unpopulate(struct ttm_device *ttm_dev, struct ttm_tt *tt) · line 912

Quoted 4 lines
drivers/gpu/drm/xe/xe_bo.c +4 -0
+		struct xe_device *xe = ttm_to_xe_device(ttm_dev);
+
+		xe_assert(xe, !xe_tt->iova_linked);
+		dma_iova_free(xe->drm.dev, &xe_tt->iova);

Do we know if this is allowed? I think there is xe_bo_pci_dev_remove_all() which requires that evict_all will correctly tear down iommu mappings on stuff like pci unplug and I don't think tt_destroy is called in that flow?

But unpopulate is called which unlinks / syncs (TLB flush for the IOVA).

Quoted 3 lines

Does having the iova here cause issues? Also, for VRAM flow I think there is a tt_create() via pipeline gutting which will now create a new iova?

Maybe we shuffle this around a bit so the iova alloc is tied to populate/unpopulate. It was been a while I forget exactly why I did this way.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

Aside from that, maybe we can land 27/28 as standalone?

Yes, let me extract these two into standalone patches today and reworking if needed.

Quickly double checked this, indeed looks to be needed:

Thanks was able recreate this + verify a local fix.

27/28 has one TTM dependency [1] and also is staged behind dma mapping accounting [2]. So maybe once [2] lands an updated 27/28 can get posted as standalone.

Matt

[1] https://patchwork.freedesktop.org/patch/739339/?series=170216&rev=2
[2] https://patchwork.freedesktop.org/series/177790/

Quoted 43 lines
[  808.058892] [IGT] core_hotunplug: finished subtest
hotreplug-lateclose-with-load, SUCCESS
[  808.058928] [IGT] core_hotunplug: exiting, ret=0
[  808.059673] BUG: kernel NULL pointer dereference, address:
[  808.061068] RIP: 0010:iommu_get_dma_domain+0x10/0x20
[  808.061141] PKRU: 55555554
[  808.061144] Call Trace:
[  808.061146]  <TASK>
[  808.061149]  dma_iova_free+0x18/0xf0
[  808.061153]  xe_ttm_tt_destroy+0x23/0x40 [xe]
[  808.061231]  ttm_bo_put+0x242/0x3d0 [ttm]
[  808.061412]  ? drm_gpuvm_bo_put+0x199/0x200 [drm_gpuvm]
[  808.061418]  xe_vma_destroy_late+0x89/0x90 [xe]
[  808.061476]  xe_vm_close_and_put+0x5de/0x920 [xe]
[  808.061534]  xe_file_close+0x105/0x190 [xe]
[  808.061712]  drm_file_free+0x218/0x260
[  808.061717]  drm_release_noglobal+0x6d/0xd0
[  808.061721]  __fput+0xf9/0x270
[  808.061725]  task_work_run+0x8b/0xb0
[  808.061730]  do_exit+0x229/0x8b0
[  808.061735]  do_group_exit+0x8b/0x90
[  808.061739]  __x64_sys_exit_group+0x17/0x20
[  808.061744]  x64_sys_call+0x18c6/0x18d0
[  808.061749]  do_syscall_64+0xee/0x350
[  808.061753]  ? __pte_offset_map+0x1d/0xd0
[  808.061757]  ? next_uptodate_folio+0xbb/0x3a0
[  808.061762]  ? set_pte_range+0x20d/0x290
[  808.061766]  ? filemap_map_pages+0x8e1/0x9c0
[  808.061772]  ? count_memcg_events+0x7c/0x1b0
[  808.061776]  ? handle_mm_fault+0xbde/0x14f0
[  808.061781]  ? __se_sys_close+0x7a/0xe0
[  808.061785]  ? __se_sys_close+0x7a/0xe0
[  808.061790]  ? do_user_addr_fault+0x272/0x6c0
[  808.061794]  ? irqentry_exit+0x3f/0x640
[  808.061799]  ? do_syscall_64+0x42/0x350
[  808.061803]  entry_SYSCALL_64_after_hwframe+0x76/0x7e
[  808.061808] RIP: 0033:0x7f95428c71b8

I assume this is dev->iommu_group = NULL post unplug.

Quoted 2 lines

Matt