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 164 messages Jul 11 – Dec 1 Page 2 of 4

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

Re: [PATCH v3 10/33] drm/ttm: Add full out-of-lock preallocation for ttm_pool_alloc()

In reply to Niranjana Vishwanathapura
Quoted 235 lines · Niranjana Vishwanathapura
Quoted 187 lines · Matthew Brost
Quoted 168 lines · Niranjana Vishwanathapura
Quoted 167 lines · Matthew Brost

ttm_pool_prealloc_fill() lets a driver preallocate beneficial-order pages outside the dma-resv lock for a defragmentation move, so the high-order allocations that may stall in reclaim/compaction happen off the critical section. That bag is deliberately partial: it holds only interchangeable beneficial-order chunks and the allocator consumes it opportunistically, falling back to in-line allocation for everything else.

An ordinary populate of a system-memory buffer object has the same problem - the whole backing is allocated under the dma-resv lock - but no way to move it out of the critical section, because the existing bag does not cover sub-beneficial orders and does not describe a full tt.

Add a "full" flavour of the same preallocation mechanism:

- struct ttm_pool_prealloc gains a @full flag. In full mode the bag is an ordered tiling of an entire tt at mixed orders (pool pages included), rather than a set of interchangeable beneficial-order chunks. The per-chunk order is recorded on the page itself and read back at consume time, so no parallel order array is needed.

- ttm_pool_prealloc_fill_full() allocates the whole backing for a tt of @num_pages pages up front, mirroring the in-line allocator's order walk (highest order first, capped by the remaining page count). It reuses the existing unlocked helpers (ttm_pool_prealloc_gfp(), ttm_pool_set_caching()) via a new ttm_pool_take_page() helper that tries a same-order pool page before a fresh system allocation.

- ttm_pool_prealloc_fini() frees any unconsumed tail at each chunk's own order when @full.

- ttm_pool_prealloc_fill_full() takes a @beneficial_reclaim_backoff argument, plumbed to ttm_pool_alloc_page(), that lets the caller allocate higher-order chunks without aggressive reclaim/compaction. This suits a driver that upgrades suboptimal pages to beneficial order in place later (e.g. via a background defragmenter) and so has no need to stall the user context reclaiming for contiguity up front.

- __ttm_pool_alloc() consumes a full bag with a single early branch in ttm_pool_iter_acquire_page(): install the next chunk as-is (order taken from the page) and return; once the best-effort bag is drained the loop falls through to normal in-line allocation. The defrag harvest and reuse-old phases are inert here as there is no defrag_old_tt.

Like the defrag bag, this is best-effort: a short fill is fine (the pool allocates the shortfall in-line) and DMA-alloc pools are unsupported (caching is applied on the kernel mapping). No functional change for existing users; the new fill routine has no in-tree caller yet.

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/ttm/ttm_pool.c | 232 ++++++++++++++++++++++++++++++++-
include/drm/ttm/ttm_bo.h       |  19 +--
include/drm/ttm/ttm_pool.h     |  27 +++-
3 files changed, 258 insertions(+), 20 deletions(-)
drivers/gpu/drm/ttm/ttm_pool.c +82 -0
index da7d132c8297..4746f5d8cd7e 100644
@@ -1046,6 +1046,7 @@ int ttm_pool_prealloc_fill(struct ttm_pool *pool, enum ttm_caching tt_caching,
 	pp->caching = tt_caching;
 	pp->count = 0;
 	pp->used = 0;
+	pp->full = false;
 
 	/* Nothing to gain without a beneficial order or for DMA-alloc pools. */
 	if (!order || !count || ttm_pool_uses_dma_alloc(pool))
@@ -1102,6 +1103,187 @@ int ttm_pool_prealloc_fill(struct ttm_pool *pool, enum ttm_caching tt_caching,
 }
 EXPORT_SYMBOL(ttm_pool_prealloc_fill);
 
+/*
+ * Acquire a single *@order chunk, trying a same-order pool page first (already
+ * carries @caching) then a fresh system allocation (write-back). Runs unlocked.
+ * When @beneficial_reclaim_backoff is set, higher-order system allocations skip
+ * aggressive reclaim/compaction (see ttm_pool_alloc_page()).
+ *
+ * A fresh system page is write-back and needs the tt's caching applied later in
+ * bulk; *@need_caching is set true for it and false for a (pre-cached) pool
+ * page.
+ *
+ * On a genuine failure *@order is left untouched (the caller lowers it by one
+ * and retries). Fault injection instead pretends allocation at (or above) the
+ * beneficial order failed and lowers *@order to the beneficial order, so the
+ * caller's next attempt lands below it - mirroring the in-line acquire path's
+ * fail_beneficial jump and exercising the beneficial_order_failed tracking
+ * without driving the system into real fragmentation.
+ *
+ * Returns NULL if no page of *@order could be obtained.
+ */
+static struct page *ttm_pool_take_page(struct ttm_pool *pool,
+				       enum ttm_caching caching,
+				       unsigned int *order, gfp_t gfp,
+				       bool *need_caching,
+				       bool beneficial_reclaim_backoff)
+{
+	unsigned int beneficial = ttm_pool_beneficial_order(pool);
+	struct ttm_pool_type *pt;
+	struct page *p;
+
+	*need_caching = false;
+
+	if (IS_ENABLED(CONFIG_FAULT_INJECTION) && beneficial &&
+	    *order >= beneficial &&
+	    should_fail(&beneficial_order_fault_inject, 1)) {
+		*order = beneficial;
+		return NULL;
+	}
+
+	pt = ttm_pool_select_type(pool, caching, *order);
+	if (pt) {
+		p = ttm_pool_type_take(pt, ttm_pool_nid(pool));
+		if (p)
+			return p;	/* pool page already carries @caching */
+	}
+
+	p = ttm_pool_alloc_page(pool, gfp, *order, beneficial_reclaim_backoff);
+	if (!p)
+		return NULL;
+
+	/* Fresh system page is write-back; caller applies @caching in bulk. */
+	*need_caching = true;
+	return p;
+}
+
+/**
+ * ttm_pool_prealloc_fill_full() - Preallocate a whole tt's backing outside any
+ * lock
+ * @pool: The pool to allocate from.
+ * @tt_caching: The requested cpu-caching for the pages allocated.
+ * @pp: Prealloc bag to fill; marked @full and tiled with mixed-order chunks.
+ * @num_pages: Number of 4K pages the tt needs backed.
+ *
+ * Unlike ttm_pool_prealloc_fill() (which parks a bag of interchangeable
+ * beneficial-order defrag chunks), this allocates the ENTIRE backing for a tt
+ * of @num_pages pages up front, at whatever mix of orders is available (pool
+ * pages included), so that the subsequent __ttm_pool_alloc() under the dma-resv
+ * lock merely installs the pages without stalling in reclaim/compaction. The
+ * chunk orders mirror the in-line allocator's order walk; each chunk's order is
+ * recorded on the page itself and read back at consume time.
+ *
+ * May sleep/reclaim freely as it runs unlocked. When
+ * @beneficial_reclaim_backoff is set, higher-order chunks are taken without
+ * aggressive reclaim/compaction: the caller relies on a background
+ * defragmenter to upgrade to beneficial-order pages in place later, so there
+ * is no need to stall the user context reclaiming for contiguity here. A short
+ * fill is fine: the pool falls back to in-line allocation for the shortfall.
+ * DMA-alloc pools are not supported (the bag stays empty). Returns 0 (release
+ * with ttm_pool_prealloc_fini()).
+ */
+int ttm_pool_prealloc_fill_full(struct ttm_pool *pool,
+				enum ttm_caching tt_caching,
Quoted 9 lines

drivers/gpu/drm/ttm/ttm_pool.c int ttm_pool_prealloc_fill(struct ttm_pool *pool, enum ttm_caching tt_caching, · line 1192

Quoted 6 lines
drivers/gpu/drm/ttm/ttm_pool.c +6 -0
+				struct ttm_pool_prealloc *pp,
+				unsigned int num_pages,
+				bool beneficial_reclaim_backoff)
+{
+	gfp_t gfp = ttm_pool_prealloc_gfp(pool) | __GFP_ZERO |
+		__GFP_RETRY_MAYFAIL | __GFP_NOWARN;
Assisted-by LLM

Yes.

Quoted 5 lines

__GFP_RETRY_MAYFAIL is bit confusing here as as ttm_pool_alloc_page() is expected to suppy it (patch 1). I see that only applies to beneficial order, but here we have mixed-order and hence it is set here. May be add some documentation to clarify it?

Quoted 9 lines

Ye, this is a bit confusing. ttm_pool_alloc_page will change these flags based beneficial_reclaim_backoff / beneficial_order. In general I chose to set __GFP_RETRY_MAYFAIL here as a default to avoid the prealloc to avoid any chance of triggering OOM - i.e., if prealloc fails for whatever reason we fall back the traditional TTM alloc path which I think is correct.

So maybe '__GFP_RETRY_MAYFAIL is set to never trigger OOM on prealloc'.

Sounds good.

Quoted 35 lines
Quoted 34 lines
Quoted 21 lines
drivers/gpu/drm/ttm/ttm_pool.c +21 -0
+	unsigned int highest = MAX_PAGE_ORDER;
+	unsigned int remaining = num_pages;
+	struct page **cpages = NULL;
+	unsigned int ncpages = 0;
+	int r;
+
+	pp->pages = NULL;
+	pp->order = 0;
+	pp->caching = tt_caching;
+	pp->count = 0;
+	pp->used = 0;
+	pp->full = true;
+
+	/* Caching is applied on the kernel mapping, so DMA-alloc is unsupported. */
+	if (!num_pages || ttm_pool_uses_dma_alloc(pool))
+		return 0;
+
+	/* Worst case is one order-0 chunk per page. */
+	pp->pages = kvzalloc_objs(*pp->pages, num_pages);
+	if (!pp->pages)
+		return 0;

drivers/gpu/drm/ttm/ttm_pool.c int ttm_pool_prealloc_fill(struct ttm_pool *pool, enum ttm_caching tt_caching, · line 1223

Quoted 10 lines
drivers/gpu/drm/ttm/ttm_pool.c +10 -0
+
+	/*
+	 * Fresh write-back chunks get their caching changed in a single
+	 * set_pages_array_*() after the fill; collect their constituent pages
+	 * into an unpacked scratch array (one entry per 4K page) since the
+	 * packed bag holds mixed-order chunks. Cached tts and pool pages need
+	 * no change (and non-x86 handles caching at map time).
+	 */
+	if (IS_ENABLED(CONFIG_X86) && tt_caching != ttm_cached) {
+		cpages = kvzalloc_objs(*cpages, num_pages);

Same comment as in patch 9.
cpages is tansient memory and unlike patch 9, it is not bounded by 'budget' here.

Quoted 8 lines
Quoted 3 lines

It is not bounded by any budget rather by the number pages in the BO size.

I mean in defragment case, it is bounded by XE_BO_DEFRAG_SIZE_LIMIT, but in gem_create ioctl, it is not. So, for a 1GB BO, the required memory for this array is 2MB.

This is true, but again the right trade is memory + one expensive call vs code complexity + many expensive calls.

Quoted 157 lines
Quoted 9 lines
Quoted 3 lines

may be it can be avoided altogether by using a one static 4k page in the pool and flush it with set_pages_array*() as and when it fills up?

I think that is the wrong trade. set_pages_array on x86 does some hardware interaction which is rather expensive, thus the entire reason TTM pool exist to avoid calling set_pages_array on every alloc / free. i.e., more tansient memory vs 1 hardware interaction is the right trade.

I meant batched set_pages_array*() call with fixed batch size (not for every page). But I agree, we shouldn't complicate it unless it is really required. So, code is fine as is.

Quoted 66 lines
Quoted 57 lines
Quoted 57 lines
drivers/gpu/drm/ttm/ttm_pool.c +57 -0
+		if (!cpages) {
+			kvfree(pp->pages);
+			pp->pages = NULL;
+			return 0;
+		}
+	}
+
+	while (remaining) {
+		unsigned int order = min_t(unsigned int, highest,
+					   __fls(remaining));
+		bool need_caching;
+		struct page *p;
+
+		for (;;) {
+			p = ttm_pool_take_page(pool, tt_caching, &order, gfp,
+					       &need_caching,
+					       beneficial_reclaim_backoff);
+			if (p)
+				break;
+			if (!order)
+				goto apply_caching;	/* short fill */
+			/*
+			 * Genuine failure: retry one order down. A fault
+			 * injection lowered @order to the beneficial order
+			 * above, so this drops it below - landing on a
+			 * sub-optimal (defrag-worthy) chunk.
+			 */
+			order--;
+		}
+
+		pp->pages[pp->count++] = p;
+		if (cpages && need_caching)
+			ttm_pool_prealloc_stage_caching(cpages, &ncpages, p,
+							order);
+		remaining -= 1u << order;
+		highest = order;
+	}
+
+apply_caching:
+	/*
+	 * Apply the requested caching to every collected page in one shot. On
+	 * failure the pages' caching is indeterminate, so drop the whole bag
+	 * (freeing restores write-back) and let the consumer allocate in-line.
+	 */
+	r = ttm_pool_prealloc_apply_caching(tt_caching, cpages, ncpages);
+	kvfree(cpages);
+	if (r) {
+		unsigned int i;
+
+		for (i = 0; i < pp->count; i++) {
+			struct page *p = pp->pages[i];
+
+			ttm_pool_free_page(pool, tt_caching,
+					   ttm_pool_page_order_nodma(p), p,
+					   false);
+		}
+		pp->count = 0;
Quoted 8 lines

drivers/gpu/drm/ttm/ttm_pool.c int ttm_pool_prealloc_fill(struct ttm_pool *pool, enum ttm_caching tt_caching, · line 1285

Quoted 5 lines
drivers/gpu/drm/ttm/ttm_pool.c +5 -0
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL(ttm_pool_prealloc_fill_full);

It has lot of code common with ttm_pool_prealloc_fill(). May be extract common code to separate function/s?

Quoted 8 lines

I see what you mean, but the algorithms are different. One tries to obtain N beneficially ordered pages, while the other fills an array with any set of pages regardless of order.

I'm hesitant to force the code into helpers or create a single unified function with conditionals just to save 70 lines of code. In my opinion, the abstraction is already at the right level.

Ok

Quoted 66 lines
Quoted 50 lines
Quoted 50 lines
drivers/gpu/drm/ttm/ttm_pool.c +22 -6
+
 /**
 * ttm_pool_prealloc_fini() - Release unconsumed preallocated pages
 * @pool: The pool the pages came from.
@@ -1111,9 +1293,13 @@ void ttm_pool_prealloc_fini(struct ttm_pool *pool, struct ttm_pool_prealloc *pp)
 {
 	unsigned int i;
 
-	for (i = pp->used; i < pp->count; ++i)
-		ttm_pool_free_page(pool, pp->caching, pp->order, pp->pages[i],
-				   false);
+	for (i = pp->used; i < pp->count; ++i) {
+		struct page *p = pp->pages[i];
+		unsigned int order = pp->full ?
+			ttm_pool_page_order_nodma(p) : pp->order;
+
+		ttm_pool_free_page(pool, pp->caching, order, p, false);
+	}
 	kvfree(pp->pages);
 	pp->pages = NULL;
 	pp->count = 0;
@@ -1251,9 +1437,10 @@ static int ttm_pool_iter_reuse_old(struct ttm_pool_alloc_iter *it)
 
 /*
 * Acquire a single page for the current order, leaving it in @it->p (NULL on
- * failure). Tries, in order: a beneficial-order page preallocated outside the
- * dma-resv lock (defrag), a same-order pool page, then a fresh system
- * allocation. Fault injection can force the beneficial-order paths to "fail".
+ * failure). Tries, in order: a chunk from a full out-of-lock prealloc (populate
+ * of the whole tt), a beneficial-order page preallocated outside the dma-resv
+ * lock (defrag), a same-order pool page, then a fresh system allocation. Fault
+ * injection can force the beneficial-order paths to "fail".
 */
 static void ttm_pool_iter_acquire_page(struct ttm_pool_alloc_iter *it)
 {
@@ -1262,6 +1449,39 @@ static void ttm_pool_iter_acquire_page(struct ttm_pool_alloc_iter *it)
 
 	it->p = NULL;
 
+	/*
+	 * Full prealloc: the entire backing was allocated (pool + system, at
+	 * mixed orders) outside the dma-resv lock. Install the next chunk as-is,
+	 * taking its order from the page. Falls through to in-line allocation
+	 * once the best-effort bag is drained.
+	 */
+	if (pp && pp->full && pp->used < pp->count) {
+		it->fail_beneficial = false;
+		it->p = pp->pages[pp->used++];
+		it->order = ttm_pool_page_order_nodma(it->p);
Quoted 9 lines

drivers/gpu/drm/ttm/ttm_pool.c static void ttm_pool_iter_acquire_page(struct ttm_pool_alloc_iter *it) · line 1462

Quoted 1 line
drivers/gpu/drm/ttm/ttm_pool.c +1 -0
+		it->page_caching = it->tt->caching;

Same comment as in 23.
We should ensure caching has not changed here after prefill (ie., pp->caching == it->tt->caching). Though it is not expected to change in gem_create_ioctl call (unlike defragmentation case of patch 23), probably it is still better to check to ensure TTM prealloc() and pool_alloc_page() interfaces work correctly together?

We don't have formalized assert framework in TTM like we do in Xe but perhaps we should - I'd like add one in a follow up as there as so many undocumented invarients in TTM...

So...

Quoted 7 lines
Quoted 3 lines

/* TODO: formalize invarients in a common TTM assert framework */ WARN_ON(it->tt->caching != pp->pp->caching)?

In gem_create ioctl case (which is the case here), the tt->caching is not expected to change between prefill and allocation (whereas in defragmentation case of patch 23, it can). So, yes a WARN_ON should be good here.

The caching should never change, so will add a warn_on.

Quoted 4 lines

But given it is ttm code, may be in both cases (gem_create ioctl and defragmentation), we should probably fall back to regular allocation and free the preallocated pages?

For gem_create:

If the prealloc fails mid allocation (non-fatal), we consume the prealloc and fall back to TTM alloc page flow - if the 2nd step falls this is fatal -ENOMEM. Or at least this was my intent.

For defrag:

We just prune in whatever amount of pages available in the pre-alloc.

Matt

Quoted 117 lines

Niranjana

Quoted 115 lines

Matt

Quoted 113 lines
Quoted 113 lines
drivers/gpu/drm/ttm/ttm_pool.c +22 -0
+
+		/*
+		 * The full prealloc tiles at whatever orders were available
+		 * without stalling in reclaim. A sub-beneficial chunk only
+		 * means a sub-optimal backing (defrag-worthy) when it sits in a
+		 * beneficial-order aligned region that fully fits in the tt -
+		 * that region could have been a beneficial-order page. A low
+		 * order in the unaligned trailing tail is expected and must not
+		 * flag the tt (mirrors ttm_pool_harvest_remaining()).
+		 */
+		if (it->beneficial_order && it->order < it->beneficial_order) {
+			pgoff_t bnr = 1UL << it->beneficial_order;
+			pgoff_t off = it->tt->num_pages -
+				      it->alloc->remaining_pages;
+
+			if (round_down(off, bnr) + bnr <= it->tt->num_pages)
+				it->tt->page_flags |=
+					TTM_TT_FLAG_BENEFICIAL_ORDER_FAILED;
+		}
+		return;
+	}
+
 	/*
 	 * Fault injection: pretend allocation at (or above) the device's
 	 * beneficial order failed, forcing a sub-optimal backing. Exercises the
include/drm/ttm/ttm_bo.h +11 -8
index a80304f179ba..52ec7e5c0d2d 100644
@@ -238,14 +238,17 @@ struct ttm_operation_ctx {
 	 */
 	s64 defrag_bytes_remaining;
 	/**
-	 * @prealloc: Pages preallocated outside the dma-resv lock for a defrag
-	 * move. The pool allocator consumes these instead of allocating fresh
-	 * beneficial-order pages under the lock, moving the (potentially
-	 * reclaim/compaction stalling) high-order allocations out of the
-	 * critical section. NULL means allocate in-line as usual. The pool
-	 * silently falls back to in-line allocation for any shortfall. The
-	 * allocator consumes it for beneficial-order chunks of any populate;
-	 * drivers only set it for a defrag move.
+	 * @prealloc: Pages preallocated outside the dma-resv lock. The pool
+	 * allocator consumes these instead of allocating under the lock, moving
+	 * the (potentially reclaim/compaction stalling) allocations out of the
+	 * critical section. NULL means allocate in-line as usual. Two flavours,
+	 * distinguished by ttm_pool_prealloc::full:
+	 *   - defrag bag (full=false): a bag of interchangeable beneficial-order
+	 *     chunks consumed only for beneficial-order chunks of a defrag move.
+	 *   - full tiling (full=true): the entire backing of the tt, at mixed
+	 *     orders, consumed for every chunk of an ordinary populate.
+	 * The allocator silently falls back to in-line allocation for any
+	 * shortfall.
 	 */
 	struct ttm_pool_prealloc *prealloc;
 	/**
include/drm/ttm/ttm_pool.h +21 -7
index 71670350eb15..777d5aa08f6a 100644
@@ -83,18 +83,27 @@ void ttm_pool_free(struct ttm_pool *pool, struct ttm_tt *tt);
 
 /**
 * struct ttm_pool_prealloc - Pages preallocated outside the dma-resv lock
- * @pages: Array of @count beneficial-order pages (or fewer if a fill fell
- *         short); each entry is the head page of a 1 << @order chunk.
- * @order: Page order of every preallocated chunk.
+ * @pages: Array of @count preallocated chunks; each entry is the head page of a
+ *         chunk. In defrag mode every chunk is @order pages; in @full mode the
+ *         chunks tile a whole tt at mixed orders and the per-chunk order is read
+ *         back from the page itself.
+ * @order: Page order of every preallocated chunk (defrag mode only; 0 in @full
+ *         mode where each chunk carries its own order).
 * @caching: CPU caching applied to the pages, so leftovers can be restored
 *           to write-back before being freed.
 * @count: Number of valid entries in @pages.
 * @used: Number of entries already consumed by the pool allocator.
+ * @full: When set the bag holds a full, mixed-order tiling of an entire tt
+ *        (produced by ttm_pool_prealloc_fill_full()) rather than a bag of
+ *        interchangeable beneficial-order defrag chunks. The pool allocator
+ *        then drains the bag in order for every populate, taking each chunk's
+ *        order from the page, and falls back to in-line allocation only for any
+ *        shortfall.
 *
 * Defrag pages are interchangeable, so only a count of beneficial-order chunks
- * is needed. ttm_pool_prealloc_fill() populates this outside the lock and
- * __ttm_pool_alloc() drains it; any unused tail is released by
- * ttm_pool_prealloc_fini().
+ * is needed. ttm_pool_prealloc_fill() / ttm_pool_prealloc_fill_full() populate
+ * this outside the lock and __ttm_pool_alloc() drains it; any unused tail is
+ * released by ttm_pool_prealloc_fini().
 */
 struct ttm_pool_prealloc {
 	struct page **pages;
@@ -102,10 +111,16 @@ struct ttm_pool_prealloc {
 	enum ttm_caching caching;
 	unsigned int count;
 	unsigned int used;
+	bool full;
 };
 
 int ttm_pool_prealloc_fill(struct ttm_pool *pool, enum ttm_caching tt_caching,
 			   struct ttm_pool_prealloc *pp, unsigned int count);
+int ttm_pool_prealloc_fill_full(struct ttm_pool *pool,
+				enum ttm_caching tt_caching,
+				struct ttm_pool_prealloc *pp,
+				unsigned int num_pages,
+				bool beneficial_reclaim_backoff);
 void ttm_pool_prealloc_fini(struct ttm_pool *pool,
 			    struct ttm_pool_prealloc *pp);
 unsigned int ttm_pool_prealloc_order(struct ttm_pool *pool);
--

2.34.1

author maintainer
#46 lore raw

PATCH v3 11/33 drm/gpusvm: Add a DMA-mapping accounting callback

In reply to Matthew Brost

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

Drivers that use the GPU SVM core to DMA-map system memory for GPU access may want to keep track of how many pages they have mapped, for example to expose statistics or to detect leaks. Doing this accounting in the driver around drm_gpusvm_get_pages() / drm_gpusvm_unmap_pages() is error prone: the number, order and kind of the dma_addr[] entries can change between map and unmap (migration, partial unmaps, the iova vs non-iova paths), which makes symmetric accounting hard to get right.

Add an optional @dma_map_account callback to struct drm_gpusvm_ops and invoke it once per &drm_pagemap_addr entry at the exact points where the entry is DMA-mapped (sign == +1) in drm_gpusvm_get_pages() and unmapped (sign == -1) in __drm_gpusvm_unmap_pages(). Since the map error path and every unmap/free path funnel through __drm_gpusvm_unmap_pages() for the entries that were actually mapped, the accounting is symmetric by construction. The callback receives the full &drm_pagemap_addr so the driver can use the order and the proto field to distinguish system memory mappings from device interconnect mappings.

The callback must also be usable by the core drm_gpusvm_pages-only API (mm == NULL), as used e.g. for userptr-style mappings. Relax drm_gpusvm_init() to allow such users to pass a restricted @ops that only implements the page-level hooks; the full-SVM hooks (@invalidate) and the chunk configuration must still be unset in that mode.

Assisted-by GitHub_Copilot:claude-opus-4.8
---
 drivers/gpu/drm/drm_gpusvm.c | 17 +++++++++++++++--
 include/drm/drm_gpusvm.h     | 19 +++++++++++++++++++
 2 files changed, 34 insertions(+), 2 deletions(-)
drivers/gpu/drm/drm_gpusvm.c +15 -2
index fcfe635bc195..512f52471419 100644
@@ -474,8 +474,15 @@ int drm_gpusvm_init(struct drm_gpusvm *gpusvm,
 			return -EINVAL;
 		mmgrab(mm);
 	} else {
-		/* No full SVM mode, only core drm_gpusvm_pages API. */
-		if (ops || num_chunks || mm_range || notifier_size)
+		/*
+		 * No full SVM mode, only core drm_gpusvm_pages API. A
+		 * restricted @ops that only implements the page-level hooks
+		 * (e.g. @dma_map_account) is allowed; the full-SVM hooks must
+		 * not be set.
+		 */
+		if (num_chunks || mm_range || notifier_size)
+			return -EINVAL;
+		if (ops && ops->invalidate)
 			return -EINVAL;
 	}
 
@@ -1246,6 +1253,8 @@ static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm,
 			else if (dpagemap && dpagemap->ops->device_unmap)
 				dpagemap->ops->device_unmap(dpagemap,
 							    dev, addr);
+			if (gpusvm->ops && gpusvm->ops->dma_map_account)
+				gpusvm->ops->dma_map_account(gpusvm, addr, -1);
 			i += 1 << addr->order;
 		}
 
@@ -1654,6 +1663,10 @@ int drm_gpusvm_get_pages(struct drm_gpusvm *gpusvm,
 				(addr, DRM_INTERCONNECT_SYSTEM, order,
 				 dma_dir);
 		}
+		if (gpusvm->ops && gpusvm->ops->dma_map_account)
+			gpusvm->ops->dma_map_account(gpusvm,
+						     &svm_pages->dma_addr[j],
+						     1);
 		i += 1 << order;
 		num_dma_mapped = i;
 		flags.has_dma_mapping = true;
include/drm/drm_gpusvm.h +19 -0
index b7d987bf76aa..36f35816a569 100644
@@ -75,6 +75,25 @@ struct drm_gpusvm_ops {
 	void (*invalidate)(struct drm_gpusvm *gpusvm,
 			   struct drm_gpusvm_notifier *notifier,
 			   const struct mmu_notifier_range *mmu_range);
+
+	/**
+	 * @dma_map_account: Account a DMA-mapping change (optional)
+	 * @gpusvm: Pointer to the GPU SVM
+	 * @addr: The address descriptor of the chunk being (un)mapped
+	 * @sign: +1 when @addr has just been DMA-mapped, -1 when it is being
+	 *        unmapped
+	 *
+	 * Called once per &drm_pagemap_addr entry, when the entry is
+	 * DMA-mapped by drm_gpusvm_get_pages() (@sign == +1) and when it is
+	 * unmapped (@sign == -1), so the driver can keep symmetric accounting
+	 * of the pages it has mapped for GPU access. The @addr->proto field
+	 * can be used to distinguish system-memory mappings from device
+	 * interconnect mappings. May be provided in both full SVM mode and the
+	 * core drm_gpusvm_pages-only mode.
+	 */
+	void (*dma_map_account)(struct drm_gpusvm *gpusvm,
+				const struct drm_pagemap_addr *addr,
+				int sign);
 };
 
 /**
Signature · 1 line
2.34.1
#47 lore raw

Re: [PATCH v3 11/33] drm/gpusvm: Add a DMA-mapping accounting callback

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:

Pre-existing issues:
- [High] Uninitialized memory read of svm_pages->dma_addr[0].dir passed to dma_iova_destroy() on the error path.
- [High] System memory pages are erroneously unmapped using the device-specific unmap callback in mixed SVM ranges.
- [High] Device memory DMA mappings are leaked on the error path because svm_pages->dpagemap is assigned too late. --

--- Patch [11]: [PATCH v3 11/33] drm/gpusvm: Add a DMA-mapping accounting callback --- commit c12d7531ab5aab8f1172b95a5e7473303dec85e1
Author: Thomas Hellström <[email protected]>

drm/gpusvm: Add a DMA-mapping accounting callback

The patch adds a dma_map_account callback to drm_gpusvm_ops to allow drivers to symmetrically account for DMA-mapped pages during map and unmap operations.

Quoted 4 lines
drivers/gpu/drm/drm_gpusvm.c +0 -0
index fcfe635bc1956..512f52471419e 100644

[ ... ]

drivers/gpu/drm/drm_gpusvm.c static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm, · line 1255

Quoted 4 lines
drivers/gpu/drm/drm_gpusvm.c +0 -0
@@ -1246,6 +1253,8 @@ static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm,
 			else if (dpagemap && dpagemap->ops->device_unmap)
 				dpagemap->ops->device_unmap(dpagemap,
 							    dev, addr);

[Severity: High]
This isn't a bug introduced by this patch, but does the error path in drm_gpusvm_get_pages() trigger an uninitialized memory read here?

If the first page's mapping fails (e.g., dma_iova_link() fails), the code jumps to the err_unmap label with num_dma_mapped = 0. Because dma_iova_try_alloc() succeeded, use_iova evaluates to true in __drm_gpusvm_unmap_pages(). This unconditionally executes dma_iova_destroy() just before this loop, reading svm_pages->dma_addr[0].dir by value:

    if (use_iova)
        dma_iova_destroy(dev, &svm_pages->state, svm_pages->state_offset,
                         svm_pages->dma_addr[0].dir, 0);

Since svm_pages->dma_addr was allocated using kvmalloc_objs without zero-initialization, this passes an uninitialized enum dma_data_direction into a kernel DMA API, which can trigger KMSAN panics or BUG_ON checks in DMA debugging routines.

[Severity: High]
This is a pre-existing issue, but does this logic misroute system memory pages to the device unmap callback?

When ctx->allow_mixed is true, an SVM range can contain both system and device pages. In this scenario, use_iova evaluates to true, and svm_pages->dpagemap is initialized to the device's pagemap. During __drm_gpusvm_unmap_pages(), the loop iterates over all pages. For a system page, addr->proto == DRM_INTERCONNECT_SYSTEM is true, but !use_iova evaluates to false.

This causes the execution to fall through to the else if condition without validating the page type:

    else if (dpagemap && dpagemap->ops->device_unmap)
        dpagemap->ops->device_unmap(dpagemap, dev, addr);

This incorrectly executes the device's unmap callback on a system memory page (containing an IOVA address), which seems likely to cause memory corruption or a crash.

[Severity: High]
This is also a pre-existing issue, but are device memory DMA mappings leaked on the error path because svm_pages->dpagemap is assigned too late?

If an error occurs during drm_gpusvm_get_pages() after successfully mapping one or more device private pages, the code jumps to the err_unmap cleanup path. However, svm_pages->dpagemap is only updated at the very end of the success path:

    if (pagemap) {
        flags.has_devmem_pages = true;
        drm_pagemap_get(dpagemap);
        drm_pagemap_put(svm_pages->dpagemap);
        svm_pages->dpagemap = dpagemap;
    }

Consequently, inside __drm_gpusvm_unmap_pages(), the local dpagemap variable is NULL, causing the condition dpagemap && dpagemap->ops->device_unmap to evaluate to false. The device unmap callback is skipped, leaking the device memory mappings. The newly added dma_map_account callback will un-account these leaked pages, causing internal accounting to irreversibly drift from the hardware state.

Quoted 4 lines
drivers/gpu/drm/drm_gpusvm.c +2 -0
+			if (gpusvm->ops && gpusvm->ops->dma_map_account)
+				gpusvm->ops->dma_map_account(gpusvm, addr, -1);
 			i += 1 << addr->order;
 		}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Reviewed-by on v3 11/33
#48 lore raw

Re: [PATCH v3 11/33] drm/gpusvm: Add a DMA-mapping accounting callback

In reply to Matthew Brost
Quoted 20 lines · Matthew Brost

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

Drivers that use the GPU SVM core to DMA-map system memory for GPU access may want to keep track of how many pages they have mapped, for example to expose statistics or to detect leaks. Doing this accounting in the driver around drm_gpusvm_get_pages() / drm_gpusvm_unmap_pages() is error prone: the number, order and kind of the dma_addr[] entries can change between map and unmap (migration, partial unmaps, the iova vs non-iova paths), which makes symmetric accounting hard to get right.

Add an optional @dma_map_account callback to struct drm_gpusvm_ops and invoke it once per &drm_pagemap_addr entry at the exact points where the entry is DMA-mapped (sign == +1) in drm_gpusvm_get_pages() and unmapped (sign == -1) in __drm_gpusvm_unmap_pages(). Since the map error path and every unmap/free path funnel through __drm_gpusvm_unmap_pages() for the entries that were actually mapped, the accounting is symmetric by construction. The callback receives the full &drm_pagemap_addr so the driver can use the order and the proto field to distinguish system memory mappings from device interconnect mappings.

Quoted 8 lines

The callback must also be usable by the core drm_gpusvm_pages-only API (mm == NULL), as used e.g. for userptr-style mappings. Relax drm_gpusvm_init() to allow such users to pass a restricted @ops that only implements the page-level hooks; the full-SVM hooks (@invalidate) and the chunk configuration must still be unset in that mode.

Assisted-by GitHub_Copilot:claude-opus-4.8

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

LGTM.

Quoted 80 lines

---
drivers/gpu/drm/drm_gpusvm.c | 17 +++++++++++++++--
include/drm/drm_gpusvm.h | 19 +++++++++++++++++++

2 files changed, 34 insertions(+), 2 deletions(-)
drivers/gpu/drm/drm_gpusvm.c +15 -2
index fcfe635bc195..512f52471419 100644
@@ -474,8 +474,15 @@ int drm_gpusvm_init(struct drm_gpusvm *gpusvm,
 			return -EINVAL;
 		mmgrab(mm);
 	} else {
-		/* No full SVM mode, only core drm_gpusvm_pages API. */
-		if (ops || num_chunks || mm_range || notifier_size)
+		/*
+		 * No full SVM mode, only core drm_gpusvm_pages API. A
+		 * restricted @ops that only implements the page-level hooks
+		 * (e.g. @dma_map_account) is allowed; the full-SVM hooks must
+		 * not be set.
+		 */
+		if (num_chunks || mm_range || notifier_size)
+			return -EINVAL;
+		if (ops && ops->invalidate)
 			return -EINVAL;
 	}
 
@@ -1246,6 +1253,8 @@ static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm,
 			else if (dpagemap && dpagemap->ops->device_unmap)
 				dpagemap->ops->device_unmap(dpagemap,
 							    dev, addr);
+			if (gpusvm->ops && gpusvm->ops->dma_map_account)
+				gpusvm->ops->dma_map_account(gpusvm, addr, -1);
 			i += 1 << addr->order;
 		}
 
@@ -1654,6 +1663,10 @@ int drm_gpusvm_get_pages(struct drm_gpusvm *gpusvm,
 				(addr, DRM_INTERCONNECT_SYSTEM, order,
 				 dma_dir);
 		}
+		if (gpusvm->ops && gpusvm->ops->dma_map_account)
+			gpusvm->ops->dma_map_account(gpusvm,
+						     &svm_pages->dma_addr[j],
+						     1);
 		i += 1 << order;
 		num_dma_mapped = i;
 		flags.has_dma_mapping = true;
include/drm/drm_gpusvm.h +19 -0
index b7d987bf76aa..36f35816a569 100644
@@ -75,6 +75,25 @@ struct drm_gpusvm_ops {
 	void (*invalidate)(struct drm_gpusvm *gpusvm,
 			   struct drm_gpusvm_notifier *notifier,
 			   const struct mmu_notifier_range *mmu_range);
+
+	/**
+	 * @dma_map_account: Account a DMA-mapping change (optional)
+	 * @gpusvm: Pointer to the GPU SVM
+	 * @addr: The address descriptor of the chunk being (un)mapped
+	 * @sign: +1 when @addr has just been DMA-mapped, -1 when it is being
+	 *        unmapped
+	 *
+	 * Called once per &drm_pagemap_addr entry, when the entry is
+	 * DMA-mapped by drm_gpusvm_get_pages() (@sign == +1) and when it is
+	 * unmapped (@sign == -1), so the driver can keep symmetric accounting
+	 * of the pages it has mapped for GPU access. The @addr->proto field
+	 * can be used to distinguish system-memory mappings from device
+	 * interconnect mappings. May be provided in both full SVM mode and the
+	 * core drm_gpusvm_pages-only mode.
+	 */
+	void (*dma_map_account)(struct drm_gpusvm *gpusvm,
+				const struct drm_pagemap_addr *addr,
+				int sign);
 };
 
 /**
Signature · 1 line
2.34.1
#49 lore raw

Re: [PATCH v3 11/33] drm/gpusvm: Add a DMA-mapping accounting callback

Quoted 27 lines · Niranjana Vishwanathapura
Quoted 26 lines · Matthew Brost

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

Drivers that use the GPU SVM core to DMA-map system memory for GPU access may want to keep track of how many pages they have mapped, for example to expose statistics or to detect leaks. Doing this accounting in the driver around drm_gpusvm_get_pages() / drm_gpusvm_unmap_pages() is error prone: the number, order and kind of the dma_addr[] entries can change between map and unmap (migration, partial unmaps, the iova vs non-iova paths), which makes symmetric accounting hard to get right.

Add an optional @dma_map_account callback to struct drm_gpusvm_ops and invoke it once per &drm_pagemap_addr entry at the exact points where the entry is DMA-mapped (sign == +1) in drm_gpusvm_get_pages() and unmapped (sign == -1) in __drm_gpusvm_unmap_pages(). Since the map error path and every unmap/free path funnel through __drm_gpusvm_unmap_pages() for the entries that were actually mapped, the accounting is symmetric by construction. The callback receives the full &drm_pagemap_addr so the driver can use the order and the proto field to distinguish system memory mappings from device interconnect mappings.

The callback must also be usable by the core drm_gpusvm_pages-only API (mm == NULL), as used e.g. for userptr-style mappings. Relax drm_gpusvm_init() to allow such users to pass a restricted @ops that only implements the page-level hooks; the full-SVM hooks (@invalidate) and the chunk configuration must still be unset in that mode.

Quoted 8 lines
Quoted 2 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).

LGTM.

One other point below...

Quoted 28 lines
Quoted 28 lines

---
drivers/gpu/drm/drm_gpusvm.c | 17 +++++++++++++++--
include/drm/drm_gpusvm.h | 19 +++++++++++++++++++

2 files changed, 34 insertions(+), 2 deletions(-)
drivers/gpu/drm/drm_gpusvm.c +9 -2
index fcfe635bc195..512f52471419 100644
@@ -474,8 +474,15 @@ int drm_gpusvm_init(struct drm_gpusvm *gpusvm,
 			return -EINVAL;
 		mmgrab(mm);
 	} else {
-		/* No full SVM mode, only core drm_gpusvm_pages API. */
-		if (ops || num_chunks || mm_range || notifier_size)
+		/*
+		 * No full SVM mode, only core drm_gpusvm_pages API. A
+		 * restricted @ops that only implements the page-level hooks
+		 * (e.g. @dma_map_account) is allowed; the full-SVM hooks must
+		 * not be set.
+		 */
+		if (num_chunks || mm_range || notifier_size)
+			return -EINVAL;
+		if (ops && ops->invalidate)
 			return -EINVAL;
 	}
 
Quoted 6 lines

drivers/gpu/drm/drm_gpusvm.c static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm, · line 1257

Quoted 6 lines
drivers/gpu/drm/drm_gpusvm.c +2 -0
@@ -1246,6 +1253,8 @@ static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm,
 			else if (dpagemap && dpagemap->ops->device_unmap)
 				dpagemap->ops->device_unmap(dpagemap,
 							    dev, addr);
+			if (gpusvm->ops && gpusvm->ops->dma_map_account)
+				gpusvm->ops->dma_map_account(gpusvm, addr, -1);

In the latest code, there is use_iova path and unamp there doesn't seem to come here for that case. Something to take care of during rebase.

Niranjana

Quoted 47 lines
Quoted 47 lines
drivers/gpu/drm/drm_gpusvm.c +4 -0
 			i += 1 << addr->order;
 		}
 
@@ -1654,6 +1663,10 @@ int drm_gpusvm_get_pages(struct drm_gpusvm *gpusvm,
 				(addr, DRM_INTERCONNECT_SYSTEM, order,
 				 dma_dir);
 		}
+		if (gpusvm->ops && gpusvm->ops->dma_map_account)
+			gpusvm->ops->dma_map_account(gpusvm,
+						     &svm_pages->dma_addr[j],
+						     1);
 		i += 1 << order;
 		num_dma_mapped = i;
 		flags.has_dma_mapping = true;
include/drm/drm_gpusvm.h +19 -0
index b7d987bf76aa..36f35816a569 100644
@@ -75,6 +75,25 @@ struct drm_gpusvm_ops {
 	void (*invalidate)(struct drm_gpusvm *gpusvm,
 			   struct drm_gpusvm_notifier *notifier,
 			   const struct mmu_notifier_range *mmu_range);
+
+	/**
+	 * @dma_map_account: Account a DMA-mapping change (optional)
+	 * @gpusvm: Pointer to the GPU SVM
+	 * @addr: The address descriptor of the chunk being (un)mapped
+	 * @sign: +1 when @addr has just been DMA-mapped, -1 when it is being
+	 *        unmapped
+	 *
+	 * Called once per &drm_pagemap_addr entry, when the entry is
+	 * DMA-mapped by drm_gpusvm_get_pages() (@sign == +1) and when it is
+	 * unmapped (@sign == -1), so the driver can keep symmetric accounting
+	 * of the pages it has mapped for GPU access. The @addr->proto field
+	 * can be used to distinguish system-memory mappings from device
+	 * interconnect mappings. May be provided in both full SVM mode and the
+	 * core drm_gpusvm_pages-only mode.
+	 */
+	void (*dma_map_account)(struct drm_gpusvm *gpusvm,
+				const struct drm_pagemap_addr *addr,
+				int sign);
 };
 
 /**
Signature · 1 line
2.34.1
author maintainer
#50 lore raw

Re: [PATCH v3 11/33] drm/gpusvm: Add a DMA-mapping accounting callback

Quoted 67 lines · Niranjana Vishwanathapura
Quoted 27 lines · Niranjana Vishwanathapura
Quoted 26 lines · Matthew Brost

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

Drivers that use the GPU SVM core to DMA-map system memory for GPU access may want to keep track of how many pages they have mapped, for example to expose statistics or to detect leaks. Doing this accounting in the driver around drm_gpusvm_get_pages() / drm_gpusvm_unmap_pages() is error prone: the number, order and kind of the dma_addr[] entries can change between map and unmap (migration, partial unmaps, the iova vs non-iova paths), which makes symmetric accounting hard to get right.

Add an optional @dma_map_account callback to struct drm_gpusvm_ops and invoke it once per &drm_pagemap_addr entry at the exact points where the entry is DMA-mapped (sign == +1) in drm_gpusvm_get_pages() and unmapped (sign == -1) in __drm_gpusvm_unmap_pages(). Since the map error path and every unmap/free path funnel through __drm_gpusvm_unmap_pages() for the entries that were actually mapped, the accounting is symmetric by construction. The callback receives the full &drm_pagemap_addr so the driver can use the order and the proto field to distinguish system memory mappings from device interconnect mappings.

The callback must also be usable by the core drm_gpusvm_pages-only API (mm == NULL), as used e.g. for userptr-style mappings. Relax drm_gpusvm_init() to allow such users to pass a restricted @ops that only implements the page-level hooks; the full-SVM hooks (@invalidate) and the chunk configuration must still be unset in that mode.

Quoted 8 lines
Quoted 2 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).

LGTM.

One other point below...

Quoted 28 lines
Quoted 28 lines

---
drivers/gpu/drm/drm_gpusvm.c | 17 +++++++++++++++--
include/drm/drm_gpusvm.h | 19 +++++++++++++++++++

2 files changed, 34 insertions(+), 2 deletions(-)
drivers/gpu/drm/drm_gpusvm.c +9 -2
index fcfe635bc195..512f52471419 100644
@@ -474,8 +474,15 @@ int drm_gpusvm_init(struct drm_gpusvm *gpusvm,
 			return -EINVAL;
 		mmgrab(mm);
 	} else {
-		/* No full SVM mode, only core drm_gpusvm_pages API. */
-		if (ops || num_chunks || mm_range || notifier_size)
+		/*
+		 * No full SVM mode, only core drm_gpusvm_pages API. A
+		 * restricted @ops that only implements the page-level hooks
+		 * (e.g. @dma_map_account) is allowed; the full-SVM hooks must
+		 * not be set.
+		 */
+		if (num_chunks || mm_range || notifier_size)
+			return -EINVAL;
+		if (ops && ops->invalidate)
 			return -EINVAL;
 	}
 
Quoted 10 lines
Quoted 6 lines

drivers/gpu/drm/drm_gpusvm.c static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm, · line 1257

Quoted 6 lines
drivers/gpu/drm/drm_gpusvm.c +2 -0
@@ -1246,6 +1253,8 @@ static void __drm_gpusvm_unmap_pages(struct drm_gpusvm *gpusvm,
 			else if (dpagemap && dpagemap->ops->device_unmap)
 				dpagemap->ops->device_unmap(dpagemap,
 							    dev, addr);
+			if (gpusvm->ops && gpusvm->ops->dma_map_account)
+				gpusvm->ops->dma_map_account(gpusvm, addr, -1);

In the latest code, there is use_iova path and unamp there doesn't seem to come here for that case. Something to take care of during rebase.

Yep. I have this fixed also because of inline mappings some further adjustments are needed.

Posting now with this fixed.

Matt

Quoted 49 lines

Niranjana

Quoted 47 lines
Quoted 47 lines
drivers/gpu/drm/drm_gpusvm.c +4 -0
 			i += 1 << addr->order;
 		}
 
@@ -1654,6 +1663,10 @@ int drm_gpusvm_get_pages(struct drm_gpusvm *gpusvm,
 				(addr, DRM_INTERCONNECT_SYSTEM, order,
 				 dma_dir);
 		}
+		if (gpusvm->ops && gpusvm->ops->dma_map_account)
+			gpusvm->ops->dma_map_account(gpusvm,
+						     &svm_pages->dma_addr[j],
+						     1);
 		i += 1 << order;
 		num_dma_mapped = i;
 		flags.has_dma_mapping = true;
include/drm/drm_gpusvm.h +19 -0
index b7d987bf76aa..36f35816a569 100644
@@ -75,6 +75,25 @@ struct drm_gpusvm_ops {
 	void (*invalidate)(struct drm_gpusvm *gpusvm,
 			   struct drm_gpusvm_notifier *notifier,
 			   const struct mmu_notifier_range *mmu_range);
+
+	/**
+	 * @dma_map_account: Account a DMA-mapping change (optional)
+	 * @gpusvm: Pointer to the GPU SVM
+	 * @addr: The address descriptor of the chunk being (un)mapped
+	 * @sign: +1 when @addr has just been DMA-mapped, -1 when it is being
+	 *        unmapped
+	 *
+	 * Called once per &drm_pagemap_addr entry, when the entry is
+	 * DMA-mapped by drm_gpusvm_get_pages() (@sign == +1) and when it is
+	 * unmapped (@sign == -1), so the driver can keep symmetric accounting
+	 * of the pages it has mapped for GPU access. The @addr->proto field
+	 * can be used to distinguish system-memory mappings from device
+	 * interconnect mappings. May be provided in both full SVM mode and the
+	 * core drm_gpusvm_pages-only mode.
+	 */
+	void (*dma_map_account)(struct drm_gpusvm *gpusvm,
+				const struct drm_pagemap_addr *addr,
+				int sign);
 };
 
 /**
Signature · 1 line
2.34.1
author maintainer
#51 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
#52 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
#53 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
#54 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
#55 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
#56 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
#57 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
#58 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
#59 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
#60 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
#61 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
#62 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
#63 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
#64 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
#65 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
#66 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
#67 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
#68 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
#69 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
#70 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
#71 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
#72 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);
#73 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
#74 lore raw

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

Quoted 88 lines · Niranjana Vishwanathapura
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?

Quoted 8 lines

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 */
};

Yes, this is better. Will change.

Matt

Quoted 227 lines

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
#75 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
#76 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
#77 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
#78 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
#79 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
#80 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
#81 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
#82 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
#83 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
#84 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
#85 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
#86 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
#87 lore raw

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

Quoted 253 lines · Matthew Brost
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?

Quoted 7 lines

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.

Ok, yah, pre-alloc of pages later in the series is a strong reason not to use try_lock here.

Quoted 162 lines
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?

Quoted 7 lines

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.

For the needs_more case I agree — it comes down to list ordering policy (FIFO vs. size-aware), and since the aggregate work to drain the list is the same either way, that's fine to leave as-is and tune later if needed. For the ret-failure case though, I think it's a bit different: today a single BO's failure backs off the whole worker for up to 15s, stalling every other listed BO regardless of whether they'd have hit the same failure. Was that intentional, or worth reconsidering — e.g. only backing off further attempts on that specific BO rather than the whole run?"

Niranjana

Quoted 115 lines
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 -1
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;
 
--

2.34.1

author maintainer
#88 lore raw

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

Quoted 435 lines · Niranjana Vishwanathapura
Quoted 253 lines · Matthew Brost
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?

Quoted 7 lines

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.

Ok, yah, pre-alloc of pages later in the series is a strong reason not to use try_lock here.

Quoted 162 lines
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?

Quoted 7 lines

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 9 lines

For the needs_more case I agree — it comes down to list ordering policy (FIFO vs. size-aware), and since the aggregate work to drain the list is the same either way, that's fine to leave as-is and tune later if needed. For the ret-failure case though, I think it's a bit different: today a single BO's failure backs off the whole worker for up to 15s, stalling every other listed BO regardless of whether they'd have hit the same failure. Was that intentional, or worth reconsidering — e.g. only backing off further attempts on that specific BO rather than the whole run?"

All BOs resolve to an order-9 page allocation from core MM (alloc_pages_node is a core MM call), so the specific BO being allocated is immaterial. The process is also iterative: it continues calling alloc_pages_node as long as budget remains, then prunes whatever it has gathered into a BO. If additional budget remains, it moves on to the next BO.

So yes, this is an intentional iterative design where core MM, rather than any specific BO, acts as the gate. Consequently, processing BOs in FIFO order is the correct algorithm.

Matt

Quoted 117 lines

Niranjana

Quoted 115 lines
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 -1
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;
 
--

2.34.1

author maintainer
#89 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
#90 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
#91 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
#92 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
#93 lore raw

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

Quoted 102 lines · Matthew Brost
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.

Quoted 7 lines

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.

The concern is that we do the MB truncation (>> 20) per-call, before adding to the running counter, rather than accumulating raw bytes and truncating once at report time. Each successful call can lose up to just under 1MB to truncation (e.g. consumed=2.4M becomes 2, not 2.4), and since xe_gt_stats_incr() only stores the already-truncated int, that lost remainder is gone for good. Over many defrag calls these per-call losses add up, so the counter can drift further from the real total the longer the system runs - not a one-time rounding fuzz.

Would tracking the running total in bytes (u64) internally, and only right-shifting to MB at the point of the stats increment (or report time), avoid this?

Niranjana

Quoted 92 lines
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 -1
 	/* must be the last entry */
 	__XE_GT_STATS_NUM_IDS,
 };
--

2.34.1

author maintainer
#94 lore raw

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

Quoted 108 lines · Niranjana Vishwanathapura
Quoted 107 lines · Matthew Brost
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.

Quoted 4 lines
Quoted 2 lines

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

The concern is that we do the MB truncation (>> 20) per-call, before

consumed is also 2M aligned.

Matt

Quoted 106 lines

adding to the running counter, rather than accumulating raw bytes and truncating once at report time. Each successful call can lose up to just under 1MB to truncation (e.g. consumed=2.4M becomes 2, not 2.4), and since xe_gt_stats_incr() only stores the already-truncated int, that lost remainder is gone for good. Over many defrag calls these per-call losses add up, so the counter can drift further from the real total the longer the system runs - not a one-time rounding fuzz.

Would tracking the running total in bytes (u64) internally, and only right-shifting to MB at the point of the stats increment (or report time), avoid this?

Niranjana

Quoted 92 lines
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 -1
 	/* must be the last entry */
 	__XE_GT_STATS_NUM_IDS,
 };
--

2.34.1

author maintainer
#95 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
#96 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
#97 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
#98 lore raw

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

Quoted 119 lines · Matthew Brost
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.

Quoted 3 lines

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.

Side effect this is, given in patch 20, interval_ms is calculated as, interval_ms = min(INTERVAL_MS * 2, INTERVAL_MAX_MS), the wrong config (INTERVAL_MS > INTERVAL_MAX_MS) ends up scheduling the worker sooner in the first time instead of intended backoff.

May be we can assert for such wrong configs in defrag_init_early function as below?
xe_assert(xe, XE_BO_DEFRAG_INTERVAL_MS <= XE_BO_DEFRAG_INTERVAL_MAX_MS)

Niranjana

Quoted 113 lines
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 -1
 	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
--

2.34.1

author maintainer
#99 lore raw

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

Quoted 124 lines · Niranjana Vishwanathapura
Quoted 119 lines · Matthew Brost
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.

Quoted 3 lines

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 9 lines

Side effect this is, given in patch 20, interval_ms is calculated as, interval_ms = min(INTERVAL_MS * 2, INTERVAL_MAX_MS), the wrong config (INTERVAL_MS > INTERVAL_MAX_MS) ends up scheduling the worker sooner in the first time instead of intended backoff.

May be we can assert for such wrong configs in defrag_init_early function as below?
xe_assert(xe, XE_BO_DEFRAG_INTERVAL_MS <= XE_BO_DEFRAG_INTERVAL_MAX_MS)

Actually I think a BUILD_BUG_ON will work - the kernel just won't compile if someone tries a bogus Kconfig.

Matt

Quoted 115 lines

Niranjana

Quoted 113 lines
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 -1
 	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
--

2.34.1

author maintainer
#100 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
#101 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
#102 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
#103 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