Skip to contentSkip to conversation

Using drm_exec in TTM

PATCH In review Christian König 6 participants 53 messages Jul 10, 2024 – Oct 11, 2024

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

Hi guys,

while this works in an initial test I just realized that we need to merge the GEM and TTM reference count first for it to be 100% reliable.

Otherwise it can be that we try to evict BOs which are in the process of being torn down. And this in turn will result in a whole bunch of problems.

So going to work on that first, just sending out the patch set once more so that it won't get lost.

Regards,
Christian.

#1 lore raw

PATCH 1/7 dma-buf/dma-resv: Introduce dma_resv_trylock_ctx()

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

For the drm_exec_trylock() functionality, there is a need to be able to trylock a dma-resv object as part of a drm_exec transaction. Therefore expose a variant of dma_resv_trylock that also takes a struct ww_acquire_ctx parameter.

Cc Christian König <[email protected]>
Cc Somalapuram Amaranath <[email protected]>
Cc Matthew Brost <[email protected]>
---
 include/linux/dma-resv.h | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)
include/linux/dma-resv.h +22 -1
index 8d0e34dad446..68dae8f2a22c 100644
@@ -405,6 +405,27 @@ static inline int dma_resv_lock_slow_interruptible(struct dma_resv *obj,
 	return ww_mutex_lock_slow_interruptible(&obj->lock, ctx);
 }
 
+/**
+ * dma_resv_trylock_ctx - trylock the reservation object
+ * @obj: the reservation object
+ * @ctx: The ww acquire context or NULL.
+ *
+ * Tries to lock the reservation object for exclusive access and modification.
+ * Note, that the lock is only against other writers, readers will run
+ * concurrently with a writer under RCU. The seqlock is used to notify readers
+ * if they overlap with a writer. The context parameter ensures that other
+ * ww transactions can perform deadlock backoff if necessary, and that
+ * subsequent attempts to dma_resv_lock() @obj for @ctx will return
+ * -EALREADY.
+ *
+ * Return: true if the lock was acquired, false otherwise.
+ */
+static inline bool __must_check
+dma_resv_trylock_ctx(struct dma_resv *obj, struct ww_acquire_ctx *ctx)
+{
+	return ww_mutex_trylock(&obj->lock, ctx);
+}
+
 /**
  * dma_resv_trylock - trylock the reservation object
  * @obj: the reservation object
@@ -421,7 +442,7 @@ static inline int dma_resv_lock_slow_interruptible(struct dma_resv *obj,
  */
 static inline bool __must_check dma_resv_trylock(struct dma_resv *obj)
 {
-	return ww_mutex_trylock(&obj->lock, NULL);
+	return dma_resv_trylock_ctx(obj, NULL);
 }
 
 /**
Signature · 1 line
2.34.1
#2 lore raw

PATCH 2/7 drm/exec: don't immediately add the prelocked obj

In reply to Christian König

Some contended objects might never be locked again in the case of eviction handling for example.

Make sure that those doesn't show up in the list of locked objects until they are explicitely mentioned.

---
 drivers/gpu/drm/drm_exec.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/gpu/drm/drm_exec.c +9 -9
index 2da094bdf8a4..220df336fbd9 100644
@@ -61,8 +61,11 @@ static void drm_exec_unlock_all(struct drm_exec *exec)
 		drm_gem_object_put(obj);
 	}
 
-	drm_gem_object_put(exec->prelocked);
-	exec->prelocked = NULL;
+	if (exec->prelocked) {
+		dma_resv_unlock(exec->prelocked->resv);
+		drm_gem_object_put(exec->prelocked);
+		exec->prelocked = NULL;
+	}
 }
 
 /**
@@ -179,16 +182,9 @@ static int drm_exec_lock_contended(struct drm_exec *exec)
 		dma_resv_lock_slow(obj->resv, &exec->ticket);
 	}
 
-	ret = drm_exec_obj_locked(exec, obj);
-	if (unlikely(ret))
-		goto error_unlock;
-
 	exec->prelocked = obj;
 	return 0;
 
-error_unlock:
-	dma_resv_unlock(obj->resv);
-
 error_dropref:
 	drm_gem_object_put(obj);
 	return ret;
@@ -214,6 +210,10 @@ int drm_exec_lock_obj(struct drm_exec *exec, struct drm_gem_object *obj)
 		return ret;
 
 	if (exec->prelocked == obj) {
+		ret = drm_exec_obj_locked(exec, obj);
+		if (unlikely(ret))
+			return ret;
+
 		drm_gem_object_put(exec->prelocked);
 		exec->prelocked = NULL;
 		return 0;
Signature · 1 line
2.34.1
#3 lore raw

PATCH 3/7 drm/exec: provide trylock interface for eviction

In reply to Christian König

The TTM eviction path has some additional requirements which make it necessary to trylock an object and then eventually keep or drop the lock again.

---
 drivers/gpu/drm/drm_exec.c | 77 ++++++++++++++++++++++++++++++++++++++
 include/drm/drm_exec.h     |  5 +++
 2 files changed, 82 insertions(+)
drivers/gpu/drm/drm_exec.c +77 -0
index 220df336fbd9..b81bf5a92d97 100644
@@ -336,5 +336,82 @@ int drm_exec_prepare_array(struct drm_exec *exec,
 }
 EXPORT_SYMBOL(drm_exec_prepare_array);
 
+/**
+ * drm_exec_trylock_obj - try to lock a GEM object
+ * @exec: the drm_exec object with the state
+ * @obj: the GEM object to trylock
+ *
+ * Try to lock a GEM object but don't grab a reference yet.
+ *
+ * Since we can't handle contention here it's illegal to trylock the first
+ * object.
+ *
+ * This function is suposed to be used from atomic context and we don't
+ * know if the GEM object will actually be used or not. So we don't grab a
+ * reference yet.
+ *
+ * Returns: True if the object could be locked, false otherwise.
+ */
+bool drm_exec_trylock_obj(struct drm_exec *exec, struct drm_gem_object *obj)
+{
+	if (WARN_ON(!exec->num_objects))
+		return false;
+
+	if (exec->prelocked == obj)
+		return true;
+
+	return dma_resv_trylock_ctx(obj->resv, &exec->ticket);
+}
+EXPORT_SYMBOL(drm_exec_trylock_obj);
+
+/**
+ * drm_exec_keep_trylocked_obj - keep the trylocked obj
+ * @exec: the drm_exec object with the state
+ * @obj: the GEM object to trylock
+ *
+ * Keep a trylocked object in the drm_exec state object. Grabs a reference to
+ * the object and adds it to the container of locked objects.
+ */
+int drm_exec_keep_trylocked_obj(struct drm_exec *exec,
+				struct drm_gem_object *obj)
+{
+	int ret;
+
+	ret = drm_exec_obj_locked(exec, obj);
+	if (ret) {
+		dma_resv_unlock(obj->resv);
+		return ret;
+	}
+
+	if (exec->prelocked == obj) {
+		drm_gem_object_put(exec->prelocked);
+		exec->prelocked = NULL;
+	}
+
+	return ret;
+}
+EXPORT_SYMBOL(drm_exec_keep_trylocked_obj);
+
+/**
+ * drm_exec_drop_trylocked_obj - drop the trylocked obj
+ * @exec: the drm_exec object with the state
+ * @obj: the GEM object to trylock
+ *
+ * Used to drop a trylocked object in the drm_exec state object, drop the
+ * reservation lock again and cleanup all references.
+ */
+void drm_exec_drop_trylocked_obj(struct drm_exec *exec,
+				 struct drm_gem_object *obj)
+{
+	/*
+	 * We can't drop the reference of prelocked objects since we might still
+	 * be in atomic context. Additionally it makes sense to keep the
+	 * prelocked object around since we might need it again later on.
+	 */
+	if (exec->prelocked != obj)
+		dma_resv_unlock(obj->resv);
+}
+EXPORT_SYMBOL(drm_exec_drop_trylocked_obj);
+
 MODULE_DESCRIPTION("DRM execution context");
 MODULE_LICENSE("Dual MIT/GPL");
include/drm/drm_exec.h +5 -0
index aa786b828a0a..a3943057a3e8 100644
@@ -146,5 +146,10 @@ int drm_exec_prepare_array(struct drm_exec *exec,
 			   struct drm_gem_object **objects,
 			   unsigned int num_objects,
 			   unsigned int num_fences);
+bool drm_exec_trylock_obj(struct drm_exec *exec, struct drm_gem_object *obj);
+int drm_exec_keep_trylocked_obj(struct drm_exec *exec,
+				struct drm_gem_object *obj);
+void drm_exec_drop_trylocked_obj(struct drm_exec *exec,
+				struct drm_gem_object *obj);
 
 #endif
Signature · 1 line
2.34.1
#4 lore raw

PATCH 4/7 drm/ttm: move LRU walk defines into new internal header

In reply to Christian König

That is something drivers really shouldn't mess with.

---
 drivers/gpu/drm/ttm/ttm_bo.c      |  1 +
 drivers/gpu/drm/ttm/ttm_bo_util.c |  2 +
 drivers/gpu/drm/ttm/ttm_bo_util.h | 67 +++++++++++++++++++++++++++++++
 include/drm/ttm/ttm_bo.h          | 35 ----------------
 4 files changed, 70 insertions(+), 35 deletions(-)
 create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h
drivers/gpu/drm/ttm/ttm_bo.c +1 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
 #include <linux/dma-resv.h>
 
 #include "ttm_module.h"
+#include "ttm_bo_util.h"
 
 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
 					struct ttm_placement *placement)
drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@
 
 #include <drm/drm_cache.h>
 
+#include "ttm_bo_util.h"
+
 struct ttm_transfer_obj {
 	struct ttm_buffer_object base;
 	struct ttm_buffer_object *bo;
drivers/gpu/drm/ttm/ttm_bo_util.h new file +67 -0

67 lines not on this page · raw message

include/drm/ttm/ttm_bo.h +0 -35
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
 	uint64_t bytes_moved;
 };
 
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-defined positive value
-	 * (typically, but not always, size of the processed bo) on success.
-	 * On success, the returned values are summed by the walk and the
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo was skipped.
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo);
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx. */
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
-			   struct ttm_resource_manager *man, s64 target);
-
 /**
  * ttm_bo_get - reference a struct ttm_buffer_object
  *
Signature · 1 line
2.34.1
reviewer
#5 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 2 lines · Christian König

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need to remain available for drivers.

Matt

[1] https://patchwork.freedesktop.org/patch/602165/?series=131815&rev=6

Quoted 156 lines
---
 drivers/gpu/drm/ttm/ttm_bo.c      |  1 +
 drivers/gpu/drm/ttm/ttm_bo_util.c |  2 +
 drivers/gpu/drm/ttm/ttm_bo_util.h | 67 +++++++++++++++++++++++++++++++
 include/drm/ttm/ttm_bo.h          | 35 ----------------
 4 files changed, 70 insertions(+), 35 deletions(-)
 create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h
drivers/gpu/drm/ttm/ttm_bo.c +1 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
 #include <linux/dma-resv.h>
 
 #include "ttm_module.h"
+#include "ttm_bo_util.h"
 
 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
 					struct ttm_placement *placement)
drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@
 
 #include <drm/drm_cache.h>
 
+#include "ttm_bo_util.h"
+
 struct ttm_transfer_obj {
 	struct ttm_buffer_object base;
 	struct ttm_buffer_object *bo;
drivers/gpu/drm/ttm/ttm_bo_util.h new file +67 -0
new file mode 100644
index 000000000000..c19b50809208
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/**************************************************************************
+ * Copyright 2024 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ **************************************************************************/
+#ifndef _TTM_BO_UTIL_H_
+#define _TTM_BO_UTIL_H_
+
+struct ww_acquire_ctx;
+
+struct ttm_buffer_object;
+struct ttm_operation_ctx;
+struct ttm_lru_walk;
+
+/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
+struct ttm_lru_walk_ops {
+	/**
+	 * process_bo - Process this bo.
+	 * @walk: struct ttm_lru_walk describing the walk.
+	 * @bo: A locked and referenced buffer object.
+	 *
+	 * Return: Negative error code on error, User-defined positive value
+	 * (typically, but not always, size of the processed bo) on success.
+	 * On success, the returned values are summed by the walk and the
+	 * walk exits when its target is met.
+	 * 0 also indicates success, -EBUSY means this bo was skipped.
+	 */
+	s64 (*process_bo)(struct ttm_lru_walk *walk,
+			  struct ttm_buffer_object *bo);
+};
+
+/**
+ * struct ttm_lru_walk - Structure describing a LRU walk.
+ */
+struct ttm_lru_walk {
+	/** @ops: Pointer to the ops structure. */
+	const struct ttm_lru_walk_ops *ops;
+	/** @ctx: Pointer to the struct ttm_operation_ctx. */
+	struct ttm_operation_ctx *ctx;
+	/** @ticket: The struct ww_acquire_ctx if any. */
+	struct ww_acquire_ctx *ticket;
+	/** @tryock_only: Only use trylock for locking. */
+	bool trylock_only;
+};
+
+s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
+			   struct ttm_resource_manager *man, s64 target);
+
+#endif
include/drm/ttm/ttm_bo.h +0 -35
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
 	uint64_t bytes_moved;
 };
 
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-defined positive value
-	 * (typically, but not always, size of the processed bo) on success.
-	 * On success, the returned values are summed by the walk and the
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo was skipped.
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo);
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx. */
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
-			   struct ttm_resource_manager *man, s64 target);
-
 /**
  * ttm_bo_get - reference a struct ttm_buffer_object
  *
Signature · 1 line
2.34.1
#6 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 5 lines · Christian König
Quoted 2 lines

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need to remain available for drivers.

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never use it directly.

Regards,
Christian.

Quoted 161 lines

Matt

[1] https://patchwork.freedesktop.org/patch/602165/?series=131815&rev=6

Quoted 156 lines
---
  drivers/gpu/drm/ttm/ttm_bo.c      |  1 +
  drivers/gpu/drm/ttm/ttm_bo_util.c |  2 +
  drivers/gpu/drm/ttm/ttm_bo_util.h | 67 +++++++++++++++++++++++++++++++
  include/drm/ttm/ttm_bo.h          | 35 ----------------
  4 files changed, 70 insertions(+), 35 deletions(-)

create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h

drivers/gpu/drm/ttm/ttm_bo.c +1 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
  #include <linux/dma-resv.h>
 
  #include "ttm_module.h"
+#include "ttm_bo_util.h"
 
  static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
  					struct ttm_placement *placement)
drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@
 
  #include <drm/drm_cache.h>
 
+#include "ttm_bo_util.h"
+
  struct ttm_transfer_obj {
  	struct ttm_buffer_object base;
  	struct ttm_buffer_object *bo;
drivers/gpu/drm/ttm/ttm_bo_util.h new file +67 -0
new file mode 100644
index 000000000000..c19b50809208
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/**************************************************************************
+ * Copyright 2024 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ **************************************************************************/
+#ifndef _TTM_BO_UTIL_H_
+#define _TTM_BO_UTIL_H_
+
+struct ww_acquire_ctx;
+
+struct ttm_buffer_object;
+struct ttm_operation_ctx;
+struct ttm_lru_walk;
+
+/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
+struct ttm_lru_walk_ops {
+	/**
+	 * process_bo - Process this bo.
+	 * @walk: struct ttm_lru_walk describing the walk.
+	 * @bo: A locked and referenced buffer object.
+	 *
+	 * Return: Negative error code on error, User-defined positive value
+	 * (typically, but not always, size of the processed bo) on success.
+	 * On success, the returned values are summed by the walk and the
+	 * walk exits when its target is met.
+	 * 0 also indicates success, -EBUSY means this bo was skipped.
+	 */
+	s64 (*process_bo)(struct ttm_lru_walk *walk,
+			  struct ttm_buffer_object *bo);
+};
+
+/**
+ * struct ttm_lru_walk - Structure describing a LRU walk.
+ */
+struct ttm_lru_walk {
+	/** @ops: Pointer to the ops structure. */
+	const struct ttm_lru_walk_ops *ops;
+	/** @ctx: Pointer to the struct ttm_operation_ctx. */
+	struct ttm_operation_ctx *ctx;
+	/** @ticket: The struct ww_acquire_ctx if any. */
+	struct ww_acquire_ctx *ticket;
+	/** @tryock_only: Only use trylock for locking. */
+	bool trylock_only;
+};
+
+s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
+			   struct ttm_resource_manager *man, s64 target);
+
+#endif
include/drm/ttm/ttm_bo.h +0 -35
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
  	uint64_t bytes_moved;
  };
 
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-defined positive value
-	 * (typically, but not always, size of the processed bo) on success.
-	 * On success, the returned values are summed by the walk and the
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo was skipped.
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo);
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx. */
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
-			   struct ttm_resource_manager *man, s64 target);
-
  /**
   * ttm_bo_get - reference a struct ttm_buffer_object
   *
Signature · 1 line
2.34.1
reviewer
#7 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 11 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 5 lines · Christian König
Quoted 2 lines

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need to remain available for drivers.

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never use it directly.

Admittedly having fully gotten through Thomas's shrinker patches so I can't reasonably defend how Thomas is using the LRU walker in the Xe driver but I will say Thomas is generally correct wrt layering code.

I'd say since he for the next month, table this patch until he returns and we can all discuss options.

Matt

Quoted 160 lines

Regards,
Christian.

Quoted 156 lines

Matt

[1] https://patchwork.freedesktop.org/patch/602165/?series=131815&rev=6

Quoted 151 lines
---
  drivers/gpu/drm/ttm/ttm_bo.c      |  1 +
  drivers/gpu/drm/ttm/ttm_bo_util.c |  2 +
  drivers/gpu/drm/ttm/ttm_bo_util.h | 67 +++++++++++++++++++++++++++++++
  include/drm/ttm/ttm_bo.h          | 35 ----------------
  4 files changed, 70 insertions(+), 35 deletions(-)

create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h

drivers/gpu/drm/ttm/ttm_bo.c +1 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
  #include <linux/dma-resv.h>
  #include "ttm_module.h"
+#include "ttm_bo_util.h"
  static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
  					struct ttm_placement *placement)
drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@
  #include <drm/drm_cache.h>
+#include "ttm_bo_util.h"
+
  struct ttm_transfer_obj {
  	struct ttm_buffer_object base;
  	struct ttm_buffer_object *bo;
drivers/gpu/drm/ttm/ttm_bo_util.h new file +67 -0
new file mode 100644
index 000000000000..c19b50809208
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/**************************************************************************
+ * Copyright 2024 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ **************************************************************************/
+#ifndef _TTM_BO_UTIL_H_
+#define _TTM_BO_UTIL_H_
+
+struct ww_acquire_ctx;
+
+struct ttm_buffer_object;
+struct ttm_operation_ctx;
+struct ttm_lru_walk;
+
+/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
+struct ttm_lru_walk_ops {
+	/**
+	 * process_bo - Process this bo.
+	 * @walk: struct ttm_lru_walk describing the walk.
+	 * @bo: A locked and referenced buffer object.
+	 *
+	 * Return: Negative error code on error, User-defined positive value
+	 * (typically, but not always, size of the processed bo) on success.
+	 * On success, the returned values are summed by the walk and the
+	 * walk exits when its target is met.
+	 * 0 also indicates success, -EBUSY means this bo was skipped.
+	 */
+	s64 (*process_bo)(struct ttm_lru_walk *walk,
+			  struct ttm_buffer_object *bo);
+};
+
+/**
+ * struct ttm_lru_walk - Structure describing a LRU walk.
+ */
+struct ttm_lru_walk {
+	/** @ops: Pointer to the ops structure. */
+	const struct ttm_lru_walk_ops *ops;
+	/** @ctx: Pointer to the struct ttm_operation_ctx. */
+	struct ttm_operation_ctx *ctx;
+	/** @ticket: The struct ww_acquire_ctx if any. */
+	struct ww_acquire_ctx *ticket;
+	/** @tryock_only: Only use trylock for locking. */
+	bool trylock_only;
+};
+
+s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
+			   struct ttm_resource_manager *man, s64 target);
+
+#endif
include/drm/ttm/ttm_bo.h +0 -35
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
  	uint64_t bytes_moved;
  };
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-defined positive value
-	 * (typically, but not always, size of the processed bo) on success.
-	 * On success, the returned values are summed by the walk and the
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo was skipped.
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo);
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx. */
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
-			   struct ttm_resource_manager *man, s64 target);
-
  /**
   * ttm_bo_get - reference a struct ttm_buffer_object
   *
Signature · 1 line
2.34.1
#8 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Christian König

Hi, Christian.

Quoted 4 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 3 lines · Christian König
Quoted 2 lines

That is something drivers really shouldn't mess with.

Quoted 8 lines
Quoted 3 lines

Thomas uses this in Xe to implement a shrinker [1]. Seems to need to
remain available for drivers.

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never use it directly.

That driver-facing LRU walker is a direct response/solution to this comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

That is also mentioned in the cover letter of the recent shrinker series, and this walker has been around in that shrinker series for more than half a year now so if you think it's not the correct driver facing API IMHO that should be addressed by a review comment in that series rather than in posting a conflicting patch?

So assuming that we still want the driver to register the shrinker, IMO that helper abstracts away all the nasty locking and pitfalls for a driver-registered shrinker, and is similar in structure to for example the pagewalk helper in mm/pagewalk.c.

An alternative that could be tried as a driver-facing API is to provide a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it quite fragile since the driver might exit the loop without performing the necessary cleanup.

However with using scoped_guard() in linux/cleanup.h that could probably be mitigated to some exent, but I still think that a walker helper like this is the safer choice and given the complexity of a for_ macro involving scoped_guard(), I think the walker helper is the easiest-to-maintain solution moving forward.

But open to suggestions.

Thanks
Thomas

Quoted 202 lines

Regards,
Christian.

Quoted 197 lines

Matt

[1]
https://patchwork.freedesktop.org/patch/602165/?series=131815&rev=6

Quoted 191 lines

---
  drivers/gpu/drm/ttm/ttm_bo.c      |  1 + drivers/gpu/drm/ttm/ttm_bo_util.c |  2 + drivers/gpu/drm/ttm/ttm_bo_util.h | 67
+++++++++++++++++++++++++++++++
  include/drm/ttm/ttm_bo.h          | 35 ----------------

  4 files changed, 70 insertions(+), 35 deletions(-)

  create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h

drivers/gpu/drm/ttm/ttm_bo.c +0 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
   #include <linux/dma-resv.h>


  #include "ttm_module.h"
+#include "ttm_bo_util.h"

  static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
   struct ttm_placement *placement)

drivers/gpu/drm/ttm/ttm_bo_util.c +0 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@


  #include <drm/drm_cache.h>

drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
+#include "ttm_bo_util.h"
+

  struct ttm_transfer_obj {
   struct ttm_buffer_object base;
   struct ttm_buffer_object *bo;

drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
new file mode 100644
index 000000000000..c19b50809208
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/***************************************************************

***********
+ * Copyright 2024 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+
*****************************************************************
*********/

drivers/gpu/drm/ttm/ttm_bo_util.h new file +17 -0
+#ifndef _TTM_BO_UTIL_H_
+#define _TTM_BO_UTIL_H_
+
+struct ww_acquire_ctx;
+
+struct ttm_buffer_object;
+struct ttm_operation_ctx;
+struct ttm_lru_walk;
+
+/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
+struct ttm_lru_walk_ops {
+	/**
+	 * process_bo - Process this bo.
+	 * @walk: struct ttm_lru_walk describing the walk.
+	 * @bo: A locked and referenced buffer object.
+	 *
+	 * Return: Negative error code on error, User-defined

positive value

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+	 * (typically, but not always, size of the processed bo)

on success.

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+	 * On success, the returned values are summed by the

walk and the

drivers/gpu/drm/ttm/ttm_bo_util.h new file +22 -0
+	 * walk exits when its target is met.
+	 * 0 also indicates success, -EBUSY means this bo was
skipped.
+	 */
+	s64 (*process_bo)(struct ttm_lru_walk *walk,
+			  struct ttm_buffer_object *bo);
+};
+
+/**
+ * struct ttm_lru_walk - Structure describing a LRU walk.
+ */
+struct ttm_lru_walk {
+	/** @ops: Pointer to the ops structure. */
+	const struct ttm_lru_walk_ops *ops;
+	/** @ctx: Pointer to the struct ttm_operation_ctx. */
+	struct ttm_operation_ctx *ctx;
+	/** @ticket: The struct ww_acquire_ctx if any. */
+	struct ww_acquire_ctx *ticket;
+	/** @tryock_only: Only use trylock for locking. */
+	bool trylock_only;
+};
+
+s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct

ttm_device *bdev,

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+			   struct ttm_resource_manager *man, s64

target);

drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
+
+#endif
include/drm/ttm/ttm_bo.h +0 -0
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
   	uint64_t bytes_moved;
   };

include/drm/ttm/ttm_bo.h +0 -10
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-defined

positive value

include/drm/ttm/ttm_bo.h +0 -1
-	 * (typically, but not always, size of the processed bo)

on success.

include/drm/ttm/ttm_bo.h +0 -1
-	 * On success, the returned values are summed by the

walk and the

include/drm/ttm/ttm_bo.h +0 -4
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo was
skipped.
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct

ttm_buffer_object *bo);

include/drm/ttm/ttm_bo.h +0 -17
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx. */
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct

ttm_device *bdev,

include/drm/ttm/ttm_bo.h +0 -1
-			   struct ttm_resource_manager *man, s64

target);
-
  /**
   * ttm_bo_get - reference a struct ttm_buffer_object *

Signature · 1 line
2.34.1
maintainer
#9 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 10 lines

Hi, Christian.

Quoted 7 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 6 lines · Christian König
Quoted 2 lines

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need to
remain available for drivers.

Quoted 8 lines
Quoted 4 lines

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never use it directly.

That driver-facing LRU walker is a direct response/solution to this comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle layer design.

But a function which returns the next candidate for eviction and a function which calls a callback for eviction is exactly the opposite.

Quoted 5 lines

That is also mentioned in the cover letter of the recent shrinker series, and this walker has been around in that shrinker series for more than half a year now so if you think it's not the correct driver facing API IMHO that should be addressed by a review comment in that series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch series. E.g. a walker function with a callback is basically a middle layer.

What outlined in the link above is that a function which returns the next eviction candidate is a better approach than a callback.

Quoted 10 lines

So assuming that we still want the driver to register the shrinker, IMO that helper abstracts away all the nasty locking and pitfalls for a driver-registered shrinker, and is similar in structure to for example the pagewalk helper in mm/pagewalk.c.

An alternative that could be tried as a driver-facing API is to provide a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it quite fragile since the driver might exit the loop without performing the necessary cleanup.

The point is that the shrinker should *never* need to have context. E.g. a walker which allows going over multiple BOs for eviction is exactly the wrong approach for that.

The shrinker should evict always only exactly one BO and the next invocation of a shrinker should not depend on the result of the previous one.

Or am I missing something vital here?

Regards,
Christian.

Quoted 212 lines

However with using scoped_guard() in linux/cleanup.h that could probably be mitigated to some exent, but I still think that a walker helper like this is the safer choice and given the complexity of a for_ macro involving scoped_guard(), I think the walker helper is the easiest-to-maintain solution moving forward.

But open to suggestions.

Thanks
Thomas

Quoted 199 lines

Regards,
Christian.

Quoted 196 lines

Matt

[1]
https://patchwork.freedesktop.org/patch/602165/?series=131815&rev=6

Quoted 191 lines
---
   drivers/gpu/drm/ttm/ttm_bo.c      |  1 +
   drivers/gpu/drm/ttm/ttm_bo_util.c |  2 +
   drivers/gpu/drm/ttm/ttm_bo_util.h | 67
+++++++++++++++++++++++++++++++
   include/drm/ttm/ttm_bo.h          | 35 ----------------
   4 files changed, 70 insertions(+), 35 deletions(-)

  create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h

drivers/gpu/drm/ttm/ttm_bo.c +1 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
   #include <linux/dma-resv.h>
 
   #include "ttm_module.h"
+#include "ttm_bo_util.h"
 
   static void ttm_bo_mem_space_debug(struct ttm_buffer_object
 *bo,

   struct ttm_placement
*placement)

drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@
 
   #include <drm/drm_cache.h>
 
+#include "ttm_bo_util.h"
+
   struct ttm_transfer_obj {
   	struct ttm_buffer_object base;
   	struct ttm_buffer_object *bo;
drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
new file mode 100644
index 000000000000..c19b50809208
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/***************************************************************

***********
+ * Copyright 2024 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+
*****************************************************************
*********/

drivers/gpu/drm/ttm/ttm_bo_util.h new file +17 -0
+#ifndef _TTM_BO_UTIL_H_
+#define _TTM_BO_UTIL_H_
+
+struct ww_acquire_ctx;
+
+struct ttm_buffer_object;
+struct ttm_operation_ctx;
+struct ttm_lru_walk;
+
+/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
+struct ttm_lru_walk_ops {
+	/**
+	 * process_bo - Process this bo.
+	 * @walk: struct ttm_lru_walk describing the walk.
+	 * @bo: A locked and referenced buffer object.
+	 *
+	 * Return: Negative error code on error, User-defined

positive value

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+	 * (typically, but not always, size of the processed bo)

on success.

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+	 * On success, the returned values are summed by the

walk and the

drivers/gpu/drm/ttm/ttm_bo_util.h new file +22 -0
+	 * walk exits when its target is met.
+	 * 0 also indicates success, -EBUSY means this bo was
skipped.
+	 */
+	s64 (*process_bo)(struct ttm_lru_walk *walk,
+			  struct ttm_buffer_object *bo);
+};
+
+/**
+ * struct ttm_lru_walk - Structure describing a LRU walk.
+ */
+struct ttm_lru_walk {
+	/** @ops: Pointer to the ops structure. */
+	const struct ttm_lru_walk_ops *ops;
+	/** @ctx: Pointer to the struct ttm_operation_ctx. */
+	struct ttm_operation_ctx *ctx;
+	/** @ticket: The struct ww_acquire_ctx if any. */
+	struct ww_acquire_ctx *ticket;
+	/** @tryock_only: Only use trylock for locking. */
+	bool trylock_only;
+};
+
+s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct

ttm_device *bdev,

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+			   struct ttm_resource_manager *man, s64

target);

drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
+
+#endif
include/drm/ttm/ttm_bo.h +0 -10
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
   	uint64_t bytes_moved;
   };
 
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-defined

positive value

include/drm/ttm/ttm_bo.h +0 -1
-	 * (typically, but not always, size of the processed bo)

on success.

include/drm/ttm/ttm_bo.h +0 -1
-	 * On success, the returned values are summed by the

walk and the

include/drm/ttm/ttm_bo.h +0 -4
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo was
skipped.
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct

ttm_buffer_object *bo);

include/drm/ttm/ttm_bo.h +0 -17
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx. */
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct

ttm_device *bdev,

include/drm/ttm/ttm_bo.h +0 -1
-			   struct ttm_resource_manager *man, s64

target);
-
  /**
   * ttm_bo_get - reference a struct ttm_buffer_object *

Signature · 1 line
2.34.1
#10 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Hi, Christian,

Quoted 63 lines · Christian König

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 14 lines

Hi, Christian.

Quoted 11 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 8 lines
Quoted 2 lines · Christian König

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need
to
remain available for drivers.

No, that is exactly what I try to prevent with that.

Quoted 7 lines
Quoted 3 lines

This is an internally thing of TTM and drivers should never use it
directly.

That driver-facing LRU walker is a direct response/solution to this comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle layer design.

But a function which returns the next candidate for eviction and a function which calls a callback for eviction is exactly the opposite.

Quoted 7 lines

That is also mentioned in the cover letter of the recent shrinker series, and this walker has been around in that shrinker series for more than half a year now so if you think it's not the correct driver
facing API IMHO that should be addressed by a review comment in that
series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch series. E.g. a walker function with a callback is basically a middle layer.

What outlined in the link above is that a function which returns the next eviction candidate is a better approach than a callback.

Quoted 7 lines

So assuming that we still want the driver to register the shrinker, IMO that helper abstracts away all the nasty locking and pitfalls for a
driver-registered shrinker, and is similar in structure to for example
the pagewalk helper in mm/pagewalk.c.

Quoted 7 lines

An alternative that could be tried as a driver-facing API is to provide
a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it quite
fragile since the driver might exit the loop without performing the necessary cleanup.

The point is that the shrinker should *never* need to have context. E.g.
a walker which allows going over multiple BOs for eviction is exactly the wrong approach for that.

Quoted 6 lines

The shrinker should evict always only exactly one BO and the next invocation of a shrinker should not depend on the result of the previous
one.

Or am I missing something vital here?

A couple of things,

1) I'd like to think of the middle-layer vs helper like the helper has its own ops, and can be used optionally from the driver. IIRC, the atomic modesetting / pageflip ops are implemented in exactly this way.

Sometimes a certain loop operation can't be easily or at least robustly implemented using a for_each_.. approach. Like for example mm/pagewalk.c. In this shrinking case I think it's probably possible using the scoped_guard() in cleanup.h. This way we could get rid of this middle layer discussion by turning the interface inside-out:

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

But I do think the currently suggested approach is less fragile and prone to driver error.

FWIW in addition to the above examples, also drm_gem_lru_scan works like this.

2) The shrinkers suggest to shrink a number of pages, not a single bo, again drm_gem_lru_scan works like this. i915 works like this. I think we should align with those.

3) Even if we had a function to obtain the driver to shrink, the driver needs to have its say about the suitability for shrinking, so a callback is needed anyway (eviction_valuable).
In addition, if shrinking fails for some reason, what would stop that function to return the same bo, again and again just like the problem we previously had in TTM?

So basically all the restartable LRU work was motivated by this use- case in mind, so making that private I must say comes as a pretty major surprise.

I could have a look at the

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

approach, but having TTM just blindly return a single bo without context will not work IMO.

Thanks,
/Thomas

Quoted 242 lines

Regards,
Christian.

Quoted 237 lines

However with using scoped_guard() in linux/cleanup.h that could probably be mitigated to some exent, but I still think that a walker
helper like this is the safer choice and given the complexity of a for_
macro involving scoped_guard(), I think the walker helper is the easiest-to-maintain solution moving forward.

But open to suggestions.

Thanks
Thomas

Quoted 222 lines

Regards,
Christian.

Quoted 219 lines

Matt

[1]
https://patchwork.freedesktop.org/patch/602165/?series=131815&rev=6

Quoted 214 lines

---
   drivers/gpu/drm/ttm/ttm_bo.c      |  1 + drivers/gpu/drm/ttm/ttm_bo_util.c |  2 + drivers/gpu/drm/ttm/ttm_bo_util.h | 67
+++++++++++++++++++++++++++++++
   include/drm/ttm/ttm_bo.h          | 35 ----------------

   4 files changed, 70 insertions(+), 35 deletions(-)

   create mode 100644 drivers/gpu/drm/ttm/ttm_bo_util.h

drivers/gpu/drm/ttm/ttm_bo.c +0 -0
index 0131ec802066..41bee8696e69 100644
@@ -45,6 +45,7 @@
    #include <linux/dma-resv.h>


   #include "ttm_module.h"
+#include "ttm_bo_util.h"

   static void ttm_bo_mem_space_debug(struct ttm_buffer_object
*bo,
    struct ttm_placement *placement)

drivers/gpu/drm/ttm/ttm_bo_util.c +0 -0
index 3c07f4712d5c..03e28e3d0d03 100644
@@ -37,6 +37,8 @@


   #include <drm/drm_cache.h>

drivers/gpu/drm/ttm/ttm_bo_util.c +2 -0
+#include "ttm_bo_util.h"
+

   struct ttm_transfer_obj {
    struct ttm_buffer_object base;
    struct ttm_buffer_object *bo;

drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
new file mode 100644
index 000000000000..c19b50809208
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/***********************************************************

****
***********
+ * Copyright 2024 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person
obtaining a
+ * copy of this software and associated documentation files (the
"Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute,
sublicense,
+ * and/or sell copies of the Software, and to permit persons to
whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall
be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO
EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM,
DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+
*************************************************************
****
*********/

drivers/gpu/drm/ttm/ttm_bo_util.h new file +17 -0
+#ifndef _TTM_BO_UTIL_H_
+#define _TTM_BO_UTIL_H_
+
+struct ww_acquire_ctx;
+
+struct ttm_buffer_object;
+struct ttm_operation_ctx;
+struct ttm_lru_walk;
+
+/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
+struct ttm_lru_walk_ops {
+	/**
+	 * process_bo - Process this bo.
+	 * @walk: struct ttm_lru_walk describing the walk.
+	 * @bo: A locked and referenced buffer object.
+	 *
+	 * Return: Negative error code on error, User-

defined
positive value

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+	 * (typically, but not always, size of the processed

bo)
on success.

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+	 * On success, the returned values are summed by the

walk and the

drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
+	 * walk exits when its target is met.
+	 * 0 also indicates success, -EBUSY means this bo

was
skipped.

drivers/gpu/drm/ttm/ttm_bo_util.h new file +12 -0
+	 */
+	s64 (*process_bo)(struct ttm_lru_walk *walk,
+			  struct ttm_buffer_object *bo);
+};
+
+/**
+ * struct ttm_lru_walk - Structure describing a LRU walk.
+ */
+struct ttm_lru_walk {
+	/** @ops: Pointer to the ops structure. */
+	const struct ttm_lru_walk_ops *ops;
+	/** @ctx: Pointer to the struct ttm_operation_ctx.

*/

drivers/gpu/drm/ttm/ttm_bo_util.h new file +8 -0
+	struct ttm_operation_ctx *ctx;
+	/** @ticket: The struct ww_acquire_ctx if any. */
+	struct ww_acquire_ctx *ticket;
+	/** @tryock_only: Only use trylock for locking. */
+	bool trylock_only;
+};
+
+s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct

ttm_device *bdev,

drivers/gpu/drm/ttm/ttm_bo_util.h new file +1 -0
+			   struct ttm_resource_manager *man,

s64
target);

drivers/gpu/drm/ttm/ttm_bo_util.h new file +2 -0
+
+#endif
include/drm/ttm/ttm_bo.h +0 -0
index d1a732d56259..5f7c967222a2 100644
@@ -194,41 +194,6 @@ struct ttm_operation_ctx {
    	uint64_t bytes_moved;
    };

include/drm/ttm/ttm_bo.h +0 -10
-struct ttm_lru_walk;
-
-/** struct ttm_lru_walk_ops - Operations for a LRU walk. */
-struct ttm_lru_walk_ops {
-	/**
-	 * process_bo - Process this bo.
-	 * @walk: struct ttm_lru_walk describing the walk.
-	 * @bo: A locked and referenced buffer object.
-	 *
-	 * Return: Negative error code on error, User-

defined
positive value

include/drm/ttm/ttm_bo.h +0 -1
-	 * (typically, but not always, size of the processed

bo)
on success.

include/drm/ttm/ttm_bo.h +0 -1
-	 * On success, the returned values are summed by the

walk and the

include/drm/ttm/ttm_bo.h +0 -2
-	 * walk exits when its target is met.
-	 * 0 also indicates success, -EBUSY means this bo

was
skipped.

include/drm/ttm/ttm_bo.h +0 -2
-	 */
-	s64 (*process_bo)(struct ttm_lru_walk *walk, struct

ttm_buffer_object *bo);

include/drm/ttm/ttm_bo.h +0 -9
-};
-
-/**
- * struct ttm_lru_walk - Structure describing a LRU walk.
- */
-struct ttm_lru_walk {
-	/** @ops: Pointer to the ops structure. */
-	const struct ttm_lru_walk_ops *ops;
-	/** @ctx: Pointer to the struct ttm_operation_ctx.

*/

include/drm/ttm/ttm_bo.h +0 -8
-	struct ttm_operation_ctx *ctx;
-	/** @ticket: The struct ww_acquire_ctx if any. */
-	struct ww_acquire_ctx *ticket;
-	/** @tryock_only: Only use trylock for locking. */
-	bool trylock_only;
-};
-
-s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct

ttm_device *bdev,

include/drm/ttm/ttm_bo.h +0 -1
-			   struct ttm_resource_manager *man,

s64
target);
-
   /**
    * ttm_bo_get - reference a struct ttm_buffer_object *

Signature · 1 line
2.34.1
#11 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 85 lines · Thomas Hellström

Hi, Christian,

Quoted 63 lines · Christian König

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 14 lines

Hi, Christian.

Quoted 11 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 8 lines
Quoted 2 lines · Christian König

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need
to
remain available for drivers.

No, that is exactly what I try to prevent with that.

Quoted 7 lines
Quoted 3 lines

This is an internally thing of TTM and drivers should never use it
directly.

That driver-facing LRU walker is a direct response/solution to this comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle layer design.

But a function which returns the next candidate for eviction and a function which calls a callback for eviction is exactly the opposite.

Quoted 7 lines

That is also mentioned in the cover letter of the recent shrinker series, and this walker has been around in that shrinker series for more than half a year now so if you think it's not the correct driver
facing API IMHO that should be addressed by a review comment in that
series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch series. E.g. a walker function with a callback is basically a middle layer.

What outlined in the link above is that a function which returns the next eviction candidate is a better approach than a callback.

Quoted 7 lines

So assuming that we still want the driver to register the shrinker, IMO that helper abstracts away all the nasty locking and pitfalls for a
driver-registered shrinker, and is similar in structure to for example
the pagewalk helper in mm/pagewalk.c.

Quoted 7 lines

An alternative that could be tried as a driver-facing API is to provide
a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it quite
fragile since the driver might exit the loop without performing the necessary cleanup.

The point is that the shrinker should *never* need to have context. E.g.
a walker which allows going over multiple BOs for eviction is exactly the wrong approach for that.

Quoted 6 lines

The shrinker should evict always only exactly one BO and the next invocation of a shrinker should not depend on the result of the previous
one.

Or am I missing something vital here?

A couple of things,

1) I'd like to think of the middle-layer vs helper like the helper has its own ops, and can be used optionally from the driver. IIRC, the atomic modesetting / pageflip ops are implemented in exactly this way.

Sometimes a certain loop operation can't be easily or at least robustly implemented using a for_each_.. approach. Like for example mm/pagewalk.c. In this shrinking case I think it's probably possible using the scoped_guard() in cleanup.h. This way we could get rid of this middle layer discussion by turning the interface inside-out:

Quoted 8 lines

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

But I do think the currently suggested approach is less fragile and prone to driver error.

FWIW in addition to the above examples, also drm_gem_lru_scan works like this.

a iteration state structure (like drm_connector_iter) plus then a macro for the common case that uses cleanup.h should get the job done.

Quoted 3 lines

2) The shrinkers suggest to shrink a number of pages, not a single bo, again drm_gem_lru_scan works like this. i915 works like this. I think we should align with those.

Yeah that's how shrinkers work, so if we demidlayer then it realls needs to be a loop in the driver, not a "here's the next bo to nuke" I think.

Quoted 6 lines

3) Even if we had a function to obtain the driver to shrink, the driver needs to have its say about the suitability for shrinking, so a callback is needed anyway (eviction_valuable).
In addition, if shrinking fails for some reason, what would stop that function to return the same bo, again and again just like the problem we previously had in TTM?

Yeah I think if consensus moves back to drivers not looking at ttm lru directly, then that entire shrinker looping needs to be as some kind of midlayer in ttm itself. Otherwise I don't think it works, so agreeing with Thomas here.

Quoted 11 lines

So basically all the restartable LRU work was motivated by this use- case in mind, so making that private I must say comes as a pretty major surprise.

I could have a look at the

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

approach, but having TTM just blindly return a single bo without context will not work IMO.

Another thing to keep in mind is that at least experience from really resource-starved igpu platforms says that cpu consumption for shrinking matters. So really need to not toss list walk state, and also at least from I think msm experience and maybe also i915 (i915-gem's a bit ... too complex to really understand it anymore) is that parallelism matters too. Eventually under memory pressures multiple cpu cores just aboslutely hammer the shrinkers, so being stuck on locks is no good.

But maybe let's get this off the ground first.
-Sima

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
maintainer
#12 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 19.08.24 um 16:14 schrieb Daniel Vetter:

Quoted 85 lines · Thomas Hellström
Quoted 84 lines

Hi, Christian,

Quoted 60 lines · Christian König

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 14 lines

Hi, Christian.

Quoted 11 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 8 lines
Quoted 2 lines · Christian König

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to need
to
remain available for drivers.

No, that is exactly what I try to prevent with that.

Quoted 7 lines
Quoted 3 lines

This is an internally thing of TTM and drivers should never use it
directly.

That driver-facing LRU walker is a direct response/solution to this comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle layer design.

But a function which returns the next candidate for eviction and a function which calls a callback for eviction is exactly the opposite.

Quoted 7 lines

That is also mentioned in the cover letter of the recent shrinker series, and this walker has been around in that shrinker series for more than half a year now so if you think it's not the correct driver
facing API IMHO that should be addressed by a review comment in that
series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch series. E.g. a walker function with a callback is basically a middle layer.

What outlined in the link above is that a function which returns the next eviction candidate is a better approach than a callback.

Quoted 7 lines

So assuming that we still want the driver to register the shrinker, IMO that helper abstracts away all the nasty locking and pitfalls for a
driver-registered shrinker, and is similar in structure to for example
the pagewalk helper in mm/pagewalk.c.

Quoted 7 lines

An alternative that could be tried as a driver-facing API is to provide
a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it quite
fragile since the driver might exit the loop without performing the necessary cleanup.

The point is that the shrinker should *never* need to have context. E.g.
a walker which allows going over multiple BOs for eviction is exactly the wrong approach for that.

Quoted 6 lines

The shrinker should evict always only exactly one BO and the next invocation of a shrinker should not depend on the result of the previous
one.

Or am I missing something vital here?

A couple of things,

1) I'd like to think of the middle-layer vs helper like the helper has its own ops, and can be used optionally from the driver. IIRC, the atomic modesetting / pageflip ops are implemented in exactly this way.

Sometimes a certain loop operation can't be easily or at least robustly implemented using a for_each_.. approach. Like for example mm/pagewalk.c. In this shrinking case I think it's probably possible using the scoped_guard() in cleanup.h. This way we could get rid of this middle layer discussion by turning the interface inside-out:

for_each_bo_on_lru_locked(xxx)

	driver_shrink();
Quoted 7 lines
Quoted 5 lines

But I do think the currently suggested approach is less fragile and prone to driver error.

FWIW in addition to the above examples, also drm_gem_lru_scan works like this.

a iteration state structure (like drm_connector_iter) plus then a macro for the common case that uses cleanup.h should get the job done.

Yeah, completely agree. It basically boils down to which one needs to pack a state bag.

In a mid-layer design it's the driver or the caller of functions, e.g. the much hated init callback in the DRM layer was a perfect example of that.

In a non mid-layer approach it's the framework or the called function, examples are how the fence iterators in the dma_resv or the drm_connector, plane etc.. work.

One big difference between the two approach is who and where things like preparation and cleanup are done, e.g. who takes locks for example.

Quoted 5 lines
Quoted 3 lines

2) The shrinkers suggest to shrink a number of pages, not a single bo, again drm_gem_lru_scan works like this. i915 works like this. I think we should align with those.

Yeah that's how shrinkers work, so if we demidlayer then it realls needs to be a loop in the driver, not a "here's the next bo to nuke" I think.

Hui? Well that's not how I understand shrinkers.

The shrinker gives you the maximum number of objects to scan and not how many pages to free. In return you give the actual number of objects to scanned and pages freed.

As far as I know the number of objects are in the sense of SLUBs or rather different LRU lists.

So for BO shrinking we should probably only free or rather unpin a single BO per callback otherwise we mess up the fairness between shrinkers in the MM layer.

Quoted 10 lines
Quoted 6 lines

3) Even if we had a function to obtain the driver to shrink, the driver needs to have its say about the suitability for shrinking, so a callback is needed anyway (eviction_valuable).
In addition, if shrinking fails for some reason, what would stop that function to return the same bo, again and again just like the problem we previously had in TTM?

Yeah I think if consensus moves back to drivers not looking at ttm lru directly, then that entire shrinker looping needs to be as some kind of midlayer in ttm itself. Otherwise I don't think it works, so agreeing with Thomas here.

Well, the idea was to get rid of callbacks like eviction_valuable.

So instead of TTM calling the driver asking if a BO is valuable to evict TTM provides the functionality to iterate over the possible candidates and the driver then says "oh yeah evict that one".

We probably can't do that fully, e.g. in case of contention on a resource we still need a callback to inform the driver and we also need a copy callback. But that's basically it.

Quoted 11 lines
Quoted 11 lines

So basically all the restartable LRU work was motivated by this use- case in mind, so making that private I must say comes as a pretty major surprise.

I could have a look at the

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

approach, but having TTM just blindly return a single bo without context will not work IMO.

Quoted 7 lines

Another thing to keep in mind is that at least experience from really resource-starved igpu platforms says that cpu consumption for shrinking matters. So really need to not toss list walk state, and also at least from I think msm experience and maybe also i915 (i915-gem's a bit ... too complex to really understand it anymore) is that parallelism matters too. Eventually under memory pressures multiple cpu cores just aboslutely hammer the shrinkers, so being stuck on locks is no good.

Yeah that's basically the reason why I looked into this before as well.

Thomas implementation is actually pretty good at that because it only has the LRU spinlock as contented object and multiple CPUs can walk the LRU at the same time otherwise.

Regards,
Christian.

Quoted 3 lines

But maybe let's get this off the ground first.
-Sima

#13 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Hi,

Quoted 133 lines · Christian König

Am 19.08.24 um 16:14 schrieb Daniel Vetter:

Quoted 117 lines · Thomas Hellström
Quoted 116 lines

Hi, Christian,

Quoted 81 lines · Christian König

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 19 lines

Hi, Christian.

Quoted 10 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 9 lines
Quoted 2 lines · Christian König

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to
need
to
remain available for drivers.

Quoted 6 lines

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never use
it
directly.

Quoted 5 lines

That driver-facing LRU walker is a direct response/solution to this
comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle layer
design.

But a function which returns the next candidate for eviction and a
function which calls a callback for eviction is exactly the opposite.

Quoted 11 lines

That is also mentioned in the cover letter of the recent shrinker
series, and this walker has been around in that shrinker series for
more than half a year now so if you think it's not the correct
driver
facing API IMHO that should be addressed by a review comment in
that
series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch series.
E.g. a walker function with a callback is basically a middle layer.

What outlined in the link above is that a function which returns the
next eviction candidate is a better approach than a callback.

Quoted 10 lines

So assuming that we still want the driver to register the shrinker,
IMO that helper abstracts away all the nasty locking and pitfalls
for a
driver-registered shrinker, and is similar in structure to for
example
the pagewalk helper in mm/pagewalk.c.

Quoted 10 lines

An alternative that could be tried as a driver-facing API is to
provide
a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it
quite
fragile since the driver might exit the loop without performing the
necessary cleanup.

The point is that the shrinker should *never* need to have context.
E.g.
a walker which allows going over multiple BOs for eviction is exactly
the wrong approach for that.

Quoted 7 lines

The shrinker should evict always only exactly one BO and the next
invocation of a shrinker should not depend on the result of the previous
one.

Or am I missing something vital here?

A couple of things,

1) I'd like to think of the middle-layer vs helper like the helper has
its own ops, and can be used optionally from the driver. IIRC, the
atomic modesetting / pageflip ops are implemented in exactly this way.

Sometimes a certain loop operation can't be easily or at least robustly
implemented using a for_each_.. approach. Like for example mm/pagewalk.c. In this shrinking case I think it's probably possible
using the scoped_guard() in cleanup.h. This way we could get rid of
this middle layer discussion by turning the interface inside-out:

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

But I do think the currently suggested approach is less fragile and
prone to driver error.

Quoted 6 lines
Quoted 3 lines

FWIW in addition to the above examples, also drm_gem_lru_scan works
like this.

a iteration state structure (like drm_connector_iter) plus then a macro
for the common case that uses cleanup.h should get the job done.

Yeah, completely agree. It basically boils down to which one needs to pack a state bag.

In a mid-layer design it's the driver or the caller of functions, e.g.
the much hated init callback in the DRM layer was a perfect example of that.

Quoted 8 lines

In a non mid-layer approach it's the framework or the called function,
examples are how the fence iterators in the dma_resv or the drm_connector, plane etc.. work.

One big difference between the two approach is who and where things like
preparation and cleanup are done, e.g. who takes locks for example.

So what in your opinion is an acceptable solution here?
The "get next object to shrink" approach won't work, since it's subject to the old TTM swap problem now removed:
If shrinking fails we will get the same object upon subsequent calls. If we bump LRU we could end up with infinite loops.
So IMO we need to be able to loop. I don't really care wether we do this as an explicit loop or whether we use the LRU walker, but I think from a maintainability point-of-view it is better to keep LRU walking in a single place.

If we return an unlocked object, we'd need to refcount and drop the lru lock, but maybe that's not a bad thing.

But what's the main drawback of exporting the existing helper.

Quoted 19 lines
Quoted 10 lines
Quoted 6 lines

2) The shrinkers suggest to shrink a number of pages, not a single bo,
again drm_gem_lru_scan works like this. i915 works like this. I think
we should align with those.

Yeah that's how shrinkers work, so if we demidlayer then it realls needs
to be a loop in the driver, not a "here's the next bo to nuke" I think.

Hui? Well that's not how I understand shrinkers.

The shrinker gives you the maximum number of objects to scan and not how
many pages to free. In return you give the actual number of objects to
scanned and pages freed.

Quoted 6 lines

As far as I know the number of objects are in the sense of SLUBs or rather different LRU lists.

So for BO shrinking we should probably only free or rather unpin a single BO per callback otherwise we mess up the fairness between shrinkers in the MM layer.

Hm. AFAICT all drm shrinkers use pages as objects, and the docs of nr_to_scan says it's the number of objects to scan and try to reclaim. I think this strategy has had a fair amount of testing with the i915 driver.
In any case, I don't think TTM should enforce a different way of shrinking by the means of a severely restricted helper?

/Thomas

maintainer
#14 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 20.08.24 um 12:37 schrieb Thomas Hellström:

Quoted 140 lines

Hi,

Quoted 137 lines · Christian König

Am 19.08.24 um 16:14 schrieb Daniel Vetter:

Quoted 117 lines · Thomas Hellström
Quoted 116 lines

Hi, Christian,

Quoted 81 lines · Christian König

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 19 lines

Hi, Christian.

Quoted 10 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 9 lines
Quoted 2 lines · Christian König

That is something drivers really shouldn't mess with.

Thomas uses this in Xe to implement a shrinker [1]. Seems to
need
to
remain available for drivers.

Quoted 6 lines

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never use
it
directly.

Quoted 5 lines

That driver-facing LRU walker is a direct response/solution to this
comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle layer
design.

But a function which returns the next candidate for eviction and a
function which calls a callback for eviction is exactly the opposite.

Quoted 11 lines

That is also mentioned in the cover letter of the recent shrinker
series, and this walker has been around in that shrinker series for
more than half a year now so if you think it's not the correct
driver
facing API IMHO that should be addressed by a review comment in
that
series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch series.
E.g. a walker function with a callback is basically a middle layer.

What outlined in the link above is that a function which returns the
next eviction candidate is a better approach than a callback.

Quoted 10 lines

So assuming that we still want the driver to register the shrinker,
IMO that helper abstracts away all the nasty locking and pitfalls
for a
driver-registered shrinker, and is similar in structure to for
example
the pagewalk helper in mm/pagewalk.c.

Quoted 10 lines

An alternative that could be tried as a driver-facing API is to
provide
a for_each_bo_in_lru_lock() macro where the driver open-codes "process_bo()" inside the for loop but I tried this and found it
quite
fragile since the driver might exit the loop without performing the
necessary cleanup.

The point is that the shrinker should *never* need to have context.
E.g.
a walker which allows going over multiple BOs for eviction is exactly
the wrong approach for that.

Quoted 7 lines

The shrinker should evict always only exactly one BO and the next
invocation of a shrinker should not depend on the result of the previous
one.

Or am I missing something vital here?

A couple of things,

1) I'd like to think of the middle-layer vs helper like the helper has
its own ops, and can be used optionally from the driver. IIRC, the
atomic modesetting / pageflip ops are implemented in exactly this way.

Sometimes a certain loop operation can't be easily or at least robustly
implemented using a for_each_.. approach. Like for example mm/pagewalk.c. In this shrinking case I think it's probably possible
using the scoped_guard() in cleanup.h. This way we could get rid of
this middle layer discussion by turning the interface inside-out:

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

But I do think the currently suggested approach is less fragile and
prone to driver error.

Quoted 6 lines
Quoted 3 lines

FWIW in addition to the above examples, also drm_gem_lru_scan works
like this.

a iteration state structure (like drm_connector_iter) plus then a macro
for the common case that uses cleanup.h should get the job done.

Yeah, completely agree. It basically boils down to which one needs to pack a state bag.

In a mid-layer design it's the driver or the caller of functions, e.g.
the much hated init callback in the DRM layer was a perfect example of that.

In a non mid-layer approach it's the framework or the called function,
examples are how the fence iterators in the dma_resv or the drm_connector, plane etc.. work.

Quoted 7 lines
Quoted 3 lines

One big difference between the two approach is who and where things like
preparation and cleanup are done, e.g. who takes locks for example.

So what in your opinion is an acceptable solution here?
The "get next object to shrink" approach won't work, since it's subject to the old TTM swap problem now removed:
If shrinking fails we will get the same object upon subsequent calls.

But and that is expected behavior. If shrinking fails just going to the next object is invalid as far as I can see.

That's why I was so puzzled why you tried to apply the walker to the TTM shrinker.

Or why exactly should shrinking fail?

Quoted 10 lines

If we bump LRU we could end up with infinite loops.
So IMO we need to be able to loop. I don't really care wether we do this as an explicit loop or whether we use the LRU walker, but I think from a maintainability point-of-view it is better to keep LRU walking in a single place.

If we return an unlocked object, we'd need to refcount and drop the lru lock, but maybe that's not a bad thing.

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard to remove from TTM.

Quoted 23 lines
Quoted 17 lines
Quoted 9 lines
Quoted 5 lines

2) The shrinkers suggest to shrink a number of pages, not a single bo,
again drm_gem_lru_scan works like this. i915 works like this. I think
we should align with those.

Yeah that's how shrinkers work, so if we demidlayer then it realls needs
to be a loop in the driver, not a "here's the next bo to nuke" I think.

Hui? Well that's not how I understand shrinkers.

The shrinker gives you the maximum number of objects to scan and not how
many pages to free. In return you give the actual number of objects to
scanned and pages freed.

Quoted 6 lines

As far as I know the number of objects are in the sense of SLUBs or rather different LRU lists.

So for BO shrinking we should probably only free or rather unpin a single BO per callback otherwise we mess up the fairness between shrinkers in the MM layer.

Quoted 6 lines

Hm. AFAICT all drm shrinkers use pages as objects, and the docs of nr_to_scan says it's the number of objects to scan and try to reclaim. I think this strategy has had a fair amount of testing with the i915 driver.
In any case, I don't think TTM should enforce a different way of shrinking by the means of a severely restricted helper?

Well, as far as I can see that is exactly what TTM should do.

I mean the main advantage to make a common component is to enforce correct behavior.

Regards,
Christian.

Quoted 3 lines

/Thomas

#15 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 186 lines · Christian König

Am 20.08.24 um 12:37 schrieb Thomas Hellström:

Quoted 174 lines

Hi,

Quoted 166 lines · Christian König

Am 19.08.24 um 16:14 schrieb Daniel Vetter:

Quoted 142 lines
Quoted 140 lines · Thomas Hellström

Hi, Christian,

Quoted 105 lines · Christian König

Am 06.08.24 um 10:29 schrieb Thomas Hellström:

Quoted 23 lines

Hi, Christian.

Quoted 13 lines · Christian König

Am 10.07.24 um 20:19 schrieb Matthew Brost:

Quoted 6 lines
Quoted 3 lines · Christian König

That is something drivers really shouldn't mess
with.

Quoted 6 lines

Thomas uses this in Xe to implement a shrinker [1]. Seems
to
need
to
remain available for drivers.

Quoted 7 lines

No, that is exactly what I try to prevent with that.

This is an internally thing of TTM and drivers should never
use
it
directly.

Quoted 6 lines

That driver-facing LRU walker is a direct response/solution
to this
comment that you made in the first shrinker series:

https://lore.kernel.org/linux-mm/[email protected]/T/#ma918844aa8a6efe8768fdcda0c6590d5c93850c9

Ah, yeah that was about how we are should be avoiding middle
layer
design.

But a function which returns the next candidate for eviction
and a
function which calls a callback for eviction is exactly the opposite.

Quoted 4 lines

That is also mentioned in the cover letter of the recent shrinker
series, and this walker has been around in that shrinker series for

Quoted 8 lines

more than half a year now so if you think it's not the correct
driver
facing API IMHO that should be addressed by a review comment
in
that
series rather than in posting a conflicting patch?

I actually outlined that in the review comments for the patch
series.
E.g. a walker function with a callback is basically a middle
layer.

What outlined in the link above is that a function which returns the
next eviction candidate is a better approach than a callback.

Quoted 11 lines

So assuming that we still want the driver to register the shrinker,
IMO that helper abstracts away all the nasty locking and pitfalls
for a
driver-registered shrinker, and is similar in structure to
for
example
the pagewalk helper in mm/pagewalk.c.

Quoted 13 lines

An alternative that could be tried as a driver-facing API is
to
provide
a for_each_bo_in_lru_lock() macro where the driver open- codes
"process_bo()" inside the for loop but I tried this and found
it
quite
fragile since the driver might exit the loop without performing the
necessary cleanup.

The point is that the shrinker should *never* need to have context.
E.g.
a walker which allows going over multiple BOs for eviction is
exactly
the wrong approach for that.

The shrinker should evict always only exactly one BO and the
next
invocation of a shrinker should not depend on the result of the
previous
one.

Quoted 1 line

Or am I missing something vital here?

A couple of things,

1) I'd like to think of the middle-layer vs helper like the helper has
its own ops, and can be used optionally from the driver. IIRC,
the
atomic modesetting / pageflip ops are implemented in exactly this
way.

Sometimes a certain loop operation can't be easily or at least
robustly
implemented using a for_each_.. approach. Like for example mm/pagewalk.c. In this shrinking case I think it's probably possible
using the scoped_guard() in cleanup.h. This way we could get rid
of
this middle layer discussion by turning the interface inside- out:

for_each_bo_on_lru_locked(xxx)

	driver_shrink();

But I do think the currently suggested approach is less fragile
and
prone to driver error.

Quoted 8 lines
Quoted 3 lines

FWIW in addition to the above examples, also drm_gem_lru_scan works
like this.

a iteration state structure (like drm_connector_iter) plus then a
macro
for the common case that uses cleanup.h should get the job done.

Yeah, completely agree. It basically boils down to which one needs to
pack a state bag.

In a mid-layer design it's the driver or the caller of functions, e.g.
the much hated init callback in the DRM layer was a perfect example
of that.

In a non mid-layer approach it's the framework or the called function,
examples are how the fence iterators in the dma_resv or the drm_connector, plane etc.. work.

Quoted 5 lines

One big difference between the two approach is who and where things
like
preparation and cleanup are done, e.g. who takes locks for example.

Quoted 6 lines

So what in your opinion is an acceptable solution here? The "get next object to shrink" approach won't work, since it's subject
to the old TTM swap problem now removed:
If shrinking fails we will get the same object upon subsequent calls.

But and that is expected behavior. If shrinking fails just going to the
next object is invalid as far as I can see.

Quoted 5 lines

That's why I was so puzzled why you tried to apply the walker to the TTM
shrinker.

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

And again, all other drm bo shrinkers do this. We just want to do the same.

Quoted 13 lines
Quoted 13 lines

If we bump LRU we could end up with infinite loops.
So IMO we need to be able to loop. I don't really care wether we do this as an explicit loop or whether we use the LRU walker, but I think
from a maintainability point-of-view it is better to keep LRU walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop the lru
lock, but maybe that's not a bad thing.

Quoted 5 lines
Quoted 1 line

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard to
remove from TTM.

It doesn't IMO. I agree the first attempt did. This affects only the LRU iteration itself and I'm even fine to get rid of the callback using a for_ macro.

Quoted 40 lines
Quoted 31 lines
Quoted 23 lines
Quoted 7 lines
Quoted 7 lines

2) The shrinkers suggest to shrink a number of pages, not a single bo,
again drm_gem_lru_scan works like this. i915 works like this. I
think
we should align with those.

Quoted 6 lines

Yeah that's how shrinkers work, so if we demidlayer then it realls
needs
to be a loop in the driver, not a "here's the next bo to nuke" I
think.

Hui? Well that's not how I understand shrinkers.

The shrinker gives you the maximum number of objects to scan and not
how
many pages to free. In return you give the actual number of objects
to
scanned and pages freed.

Quoted 8 lines

As far as I know the number of objects are in the sense of SLUBs or
rather different LRU lists.

So for BO shrinking we should probably only free or rather unpin a
single BO per callback otherwise we mess up the fairness between shrinkers in the MM layer.

Quoted 8 lines

Hm. AFAICT all drm shrinkers use pages as objects, and the docs of nr_to_scan says it's the number of objects to scan and try to reclaim.
I think this strategy has had a fair amount of testing with the i915
driver.
In any case, I don't think TTM should enforce a different way of shrinking by the means of a severely restricted helper?

Quoted 4 lines

Well, as far as I can see that is exactly what TTM should do.

I mean the main advantage to make a common component is to enforce correct behavior.

But if all other drivers don't agree this as correct behavior and instead want to keep behavior that is proven to work, that's a dead end.

/Thomas

Quoted 7 lines

Regards,
Christian.

Quoted 3 lines

/Thomas

maintainer
#16 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 4 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them because the device is powered down?

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of time.

In other words an application can allocate memory, map it into GGTT and then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

That really sounds like a bug in the driver design to me.

Quoted 2 lines

And again, all other drm bo shrinkers do this. We just want to do the same.

Do you have pointers?

Quoted 12 lines
Quoted 12 lines
Quoted 12 lines

If we bump LRU we could end up with infinite loops.
So IMO we need to be able to loop. I don't really care wether we do this as an explicit loop or whether we use the LRU walker, but I think
from a maintainability point-of-view it is better to keep LRU walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop the lru
lock, but maybe that's not a bad thing.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard to
remove from TTM.

It doesn't IMO. I agree the first attempt did. This affects only the LRU iteration itself and I'm even fine to get rid of the callback using a for_ macro.

Well, I mean using a for_each approach is objectively better than having a callback and a state bag.

But the fundamental question is if drivers are allowed to reject shrinking. And I think the answer is no, they need to be designed in a way where shrinking is always possible.

What can be that we can't get the necessary locks to evict and object (because it's about to be used etc...), but that are the per-requisites TTM should be checking.

Quoted 9 lines
Quoted 6 lines
Quoted 2 lines

In any case, I don't think TTM should enforce a different way of shrinking by the means of a severely restricted helper?

Well, as far as I can see that is exactly what TTM should do.

I mean the main advantage to make a common component is to enforce correct behavior.

But if all other drivers don't agree this as correct behavior and instead want to keep behavior that is proven to work, that's a dead end.

Well no, even if all drivers agree to (for example) drop security precautions it's still not something acceptable.

And same thing here, if we block shrinking because drivers think they want their runtime PM implemented in a certain way then upstream needs to block this and push back.

As far as I can see it's mandatory to have shrinkers not depend on runtime PM, cause otherwise you run into resources handling which depends on the well behavior of userspace and that in turn in something we can't allow.

Regards,
Christian.

Quoted 9 lines

/Thomas

Quoted 5 lines

Regards,
Christian.

Quoted 2 lines

/Thomas

#17 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 16 lines · Christian König

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 5 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo
needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them
because the device is powered down?

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of
time.

Quoted 6 lines

In other words an application can allocate memory, map it into GGTT and
then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

That really sounds like a bug in the driver design to me.

It's bad but it's not as bad as it sounds.

Problem is we can't wake up during direct reclaim IIRC due to runtime pm lockdep violations, but we can and do fire up a thread to wake the device and after the wakeup delay have subsequent shrink calls succeed, or punt to kswapd or the oom handler.
I think that's an orthogonal discussion, though. There are other reasons shrinking might fail, like the bo being busy in direct reclaim (shouldn't wait for idle there but ok in kswapd), Other points of failure is ofc shmem radix tree allocations (not seen one yet, though) which might succeed with a smaller bo.
(Not saying, though, that there isn't more to be done with the xe runtime pm implementation).

Quoted 6 lines
Quoted 4 lines

And again, all other drm bo shrinkers do this. We just want to do the
same.

Do you have pointers?

As Sima said, this is complicated but not beyond comprehension: i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

msm:
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317
which uses
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426
that is very similar in structure to what I implemented for TTM.

Panfrost: (although only purgeable objects AFAICT).
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426

Quoted 27 lines
Quoted 21 lines
Quoted 16 lines
Quoted 16 lines

If we bump LRU we could end up with infinite loops. So IMO we need to be able to loop. I don't really care wether we do
this as an explicit loop or whether we use the LRU walker, but I
think
from a maintainability point-of-view it is better to keep LRU walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop the
lru
lock, but maybe that's not a bad thing.

Quoted 5 lines
Quoted 1 line

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard
to
remove from TTM.

Quoted 5 lines

It doesn't IMO. I agree the first attempt did. This affects only the
LRU iteration itself and I'm even fine to get rid of the callback using
a for_ macro.

Quoted 8 lines

Well, I mean using a for_each approach is objectively better than having
a callback and a state bag.

But the fundamental question is if drivers are allowed to reject shrinking. And I think the answer is no, they need to be designed in a
way where shrinking is always possible.

Rejects can be out of our control, due to anticipated deadlocks, oom and deferring to kswapd.

Quoted 26 lines

What can be that we can't get the necessary locks to evict and object (because it's about to be used etc...), but that are the per- requisites
TTM should be checking.

Quoted 11 lines
Quoted 8 lines
Quoted 3 lines

In any case, I don't think TTM should enforce a different way of
shrinking by the means of a severely restricted helper?

Well, as far as I can see that is exactly what TTM should do.

I mean the main advantage to make a common component is to enforce
correct behavior.

But if all other drivers don't agree this as correct behavior and instead want to keep behavior that is proven to work, that's a dead end.

Well no, even if all drivers agree to (for example) drop security precautions it's still not something acceptable.

And same thing here, if we block shrinking because drivers think they want their runtime PM implemented in a certain way then upstream needs
to block this and push back.

Quoted 5 lines

As far as I can see it's mandatory to have shrinkers not depend on runtime PM, cause otherwise you run into resources handling which depends on the well behavior of userspace and that in turn in something
we can't allow.

Please see the above explanation for runtime pm, and for the record I agree that enforcing disallowed or security violations is a completely valid thing.

/Thomas

Quoted 13 lines

Regards,
Christian.

Quoted 9 lines

/Thomas

Quoted 5 lines

Regards,
Christian.

Quoted 2 lines

/Thomas

#18 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 142 lines · Thomas Hellström
Quoted 19 lines · Christian König

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 7 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular
bo
needs it to unbind, we want to try the next bo. Example: i915 GGTT
bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them
because the device is powered down?

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount
of
time.

Quoted 6 lines

In other words an application can allocate memory, map it into GGTT and
then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

That really sounds like a bug in the driver design to me.

It's bad but it's not as bad as it sounds.

Problem is we can't wake up during direct reclaim IIRC due to runtime pm lockdep violations, but we can and do fire up a thread to wake the device and after the wakeup delay have subsequent shrink calls succeed,
or punt to kswapd or the oom handler.
I think that's an orthogonal discussion, though. There are other reasons shrinking might fail, like the bo being busy in direct reclaim
(shouldn't wait for idle there but ok in kswapd), Other points of failure is ofc shmem radix tree allocations (not seen one yet, though)
which might succeed with a smaller bo.
(Not saying, though, that there isn't more to be done with the xe runtime pm implementation).

Quoted 6 lines
Quoted 4 lines

And again, all other drm bo shrinkers do this. We just want to do the
same.

Do you have pointers?

As Sima said, this is complicated but not beyond comprehension: i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

msm:
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317
which uses
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426
that is very similar in structure to what I implemented for TTM.

Panfrost: (although only purgeable objects AFAICT).
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426

Quoted 34 lines
Quoted 24 lines
Quoted 18 lines
Quoted 18 lines

If we bump LRU we could end up with infinite loops. So IMO we need to be able to loop. I don't really care wether we do
this as an explicit loop or whether we use the LRU walker, but
I
think
from a maintainability point-of-view it is better to keep LRU walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop
the
lru
lock, but maybe that's not a bad thing.

Quoted 6 lines
Quoted 2 lines

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard
to
remove from TTM.

Quoted 5 lines

It doesn't IMO. I agree the first attempt did. This affects only the
LRU iteration itself and I'm even fine to get rid of the callback using
a for_ macro.

Well, I mean using a for_each approach is objectively better than having
a callback and a state bag.

Quoted 5 lines

But the fundamental question is if drivers are allowed to reject shrinking. And I think the answer is no, they need to be designed in
a
way where shrinking is always possible.

Rejects can be out of our control, due to anticipated deadlocks, oom and deferring to kswapd.

Quoted 29 lines

What can be that we can't get the necessary locks to evict and object
(because it's about to be used etc...), but that are the per- requisites
TTM should be checking.

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines

In any case, I don't think TTM should enforce a different way of
shrinking by the means of a severely restricted helper?

Well, as far as I can see that is exactly what TTM should do.

Quoted 7 lines
Quoted 3 lines

I mean the main advantage to make a common component is to enforce
correct behavior.

But if all other drivers don't agree this as correct behavior and instead want to keep behavior that is proven to work, that's a dead
end.

Well no, even if all drivers agree to (for example) drop security precautions it's still not something acceptable.

And same thing here, if we block shrinking because drivers think they
want their runtime PM implemented in a certain way then upstream needs
to block this and push back.

Quoted 5 lines

As far as I can see it's mandatory to have shrinkers not depend on runtime PM, cause otherwise you run into resources handling which depends on the well behavior of userspace and that in turn in something
we can't allow.

Quoted 4 lines

Please see the above explanation for runtime pm, and for the record I agree that enforcing disallowed or security violations is a completely
valid thing.

Meant to say enforcing disallowing security violations..

Another thing that came to my mind is ofc swap_space. Depending on how backup is done if we're out of swap space we can only shrink purgeable WONTNEED objects (user-space pools typically), and TTM has no knowledge of those (currently at least).

/Thomas

Quoted 17 lines

/Thomas

Quoted 13 lines

Regards,
Christian.

Quoted 9 lines

/Thomas

Quoted 5 lines

Regards,
Christian.

Quoted 2 lines

/Thomas

maintainer
#19 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Thomas Hellström

Am 21.08.24 um 10:57 schrieb Thomas Hellström:

Quoted 21 lines · Christian König
Quoted 20 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 5 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo
needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them
because the device is powered down?

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of
time.

In other words an application can allocate memory, map it into GGTT and
then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

Quoted 7 lines
Quoted 1 line

That really sounds like a bug in the driver design to me.

It's bad but it's not as bad as it sounds.

Problem is we can't wake up during direct reclaim IIRC due to runtime pm lockdep violations, but we can and do fire up a thread to wake the device and after the wakeup delay have subsequent shrink calls succeed, or punt to kswapd or the oom handler.

Yeah that is obvious. The runtime PM is an interface designed to be used from a very high level IOCTL/system call.

And delegating that from a shrinker to a worker is not valid as far as I can see, instead of reducing the memory pressure the shrinker would then increase it.

Quoted 7 lines

I think that's an orthogonal discussion, though. There are other reasons shrinking might fail, like the bo being busy in direct reclaim (shouldn't wait for idle there but ok in kswapd), Other points of failure is ofc shmem radix tree allocations (not seen one yet, though) which might succeed with a smaller bo.
(Not saying, though, that there isn't more to be done with the xe runtime pm implementation).

I don't think that argumentation is valid.

When a BO is locked then that it is ok to not shrink it, but TTM should be able to determine all those prerequisites.

In other words the idea of a function returning a BO to the driver is that the driver is obligated to shrink that one.

That other necessary allocation can fail like shmen for example is obvious as well, but that's why we discussed to allow shrinking BOs partially as well.

And I really don't think this discussion is orthogonal. We are basically discussing what drivers should do and not should do. And as far as I can see the requirement to expose the LRUs to drivers comes up only because the driver wants to do something it shouldn't.

Quoted 6 lines
Quoted 4 lines
Quoted 3 lines

And again, all other drm bo shrinkers do this. We just want to do the
same.

Do you have pointers?

As Sima said, this is complicated but not beyond comprehension: i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

    if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
        with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd() that it can synchronously wait for runtime PM to power up the device again.

As far as I can tell that means that a device driver makes strong and completely undocumented assumptions how kswapd works internally.

Quoted 8 lines

msm:
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317
which uses
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426
that is very similar in structure to what I implemented for TTM.

Panfrost: (although only purgeable objects AFAICT).
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426

From skimming over the source only MSM actually seems to use this and the criteria for rejecting shrinking is everything TTM should know, e.g. if a BO is pinned, idle etc...

Quoted 60 lines
Quoted 25 lines
Quoted 20 lines
Quoted 15 lines
Quoted 15 lines

If we bump LRU we could end up with infinite loops. So IMO we need to be able to loop. I don't really care wether we do
this as an explicit loop or whether we use the LRU walker, but I
think
from a maintainability point-of-view it is better to keep LRU walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop the
lru
lock, but maybe that's not a bad thing.

Quoted 5 lines
Quoted 1 line

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard
to
remove from TTM.

Quoted 5 lines

It doesn't IMO. I agree the first attempt did. This affects only the
LRU iteration itself and I'm even fine to get rid of the callback using
a for_ macro.

Quoted 8 lines

Well, I mean using a for_each approach is objectively better than having
a callback and a state bag.

But the fundamental question is if drivers are allowed to reject shrinking. And I think the answer is no, they need to be designed in a
way where shrinking is always possible.

Rejects can be out of our control, due to anticipated deadlocks, oom and deferring to kswapd.

Quoted 24 lines

What can be that we can't get the necessary locks to evict and object (because it's about to be used etc...), but that are the per- requisites
TTM should be checking.

Quoted 11 lines
Quoted 8 lines
Quoted 3 lines

In any case, I don't think TTM should enforce a different way of
shrinking by the means of a severely restricted helper?

Well, as far as I can see that is exactly what TTM should do.

I mean the main advantage to make a common component is to enforce
correct behavior.

But if all other drivers don't agree this as correct behavior and instead want to keep behavior that is proven to work, that's a dead end.

Well no, even if all drivers agree to (for example) drop security precautions it's still not something acceptable.

And same thing here, if we block shrinking because drivers think they want their runtime PM implemented in a certain way then upstream needs
to block this and push back.

Quoted 8 lines
Quoted 5 lines

As far as I can see it's mandatory to have shrinkers not depend on runtime PM, cause otherwise you run into resources handling which depends on the well behavior of userspace and that in turn in something
we can't allow.

Please see the above explanation for runtime pm, and for the record I agree that enforcing disallowed or security violations is a completely valid thing.

Putting the TTM issue aside as far as I can tell what i915 is extremely questionable and doing the same thing in XE is most likely not something we should allow.

Regards,
Christian.

Quoted 14 lines

/Thomas

Quoted 11 lines

Regards,
Christian.

Quoted 8 lines

/Thomas

Quoted 5 lines

Regards,
Christian.

Quoted 2 lines

/Thomas

#20 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Hi,

Quoted 43 lines · Christian König

Am 21.08.24 um 10:57 schrieb Thomas Hellström:

Quoted 30 lines · Christian König
Quoted 19 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 7 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular
bo
needs it to unbind, we want to try the next bo. Example: i915 GGTT
bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind
them
because the device is powered down?

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount
of
time.

Quoted 8 lines

In other words an application can allocate memory, map it into GGTT
and
then suspend or even get killed and we are not able to recover the
memory because there is no activity on the GPU any more?

That really sounds like a bug in the driver design to me.

It's bad but it's not as bad as it sounds.

Quoted 7 lines

Problem is we can't wake up during direct reclaim IIRC due to runtime
pm lockdep violations, but we can and do fire up a thread to wake the
device and after the wakeup delay have subsequent shrink calls succeed,
or punt to kswapd or the oom handler.

Yeah that is obvious. The runtime PM is an interface designed to be used
from a very high level IOCTL/system call.

Quoted 5 lines

And delegating that from a shrinker to a worker is not valid as far as I
can see, instead of reducing the memory pressure the shrinker would then
increase it.

Perhaps an ignorant question, but aren't IO devices potentially woken up for swapout at memory pressure time using runtime PM, thereby increasing memory pressure in a similar way?

Quoted 11 lines
Quoted 10 lines

I think that's an orthogonal discussion, though. There are other reasons shrinking might fail, like the bo being busy in direct reclaim
(shouldn't wait for idle there but ok in kswapd), Other points of failure is ofc shmem radix tree allocations (not seen one yet, though)
which might succeed with a smaller bo.
(Not saying, though, that there isn't more to be done with the xe runtime pm implementation).

Quoted 8 lines

I don't think that argumentation is valid.

When a BO is locked then that it is ok to not shrink it, but TTM should
be able to determine all those prerequisites.

In other words the idea of a function returning a BO to the driver is that the driver is obligated to shrink that one.

But that doesn't take potential driver deadlock avoidance into account, so it would restrict the driver shrinkers by assuming that all deadlock avoidance needed is known by TTM.

And since small memory allocations are allowed even at reclaim time to be able so reclaim or shrink even more memory, IMO the pm resume problem reduces into a deadlock avoidance problem where we use pm_tryget similar to bo_trylock. Important thing, though, in both cases, that the device is woken or similarly the lock is released in reasonable time for the reclaim to retry and succeed.

Quoted 4 lines

That other necessary allocation can fail like shmen for example is obvious as well, but that's why we discussed to allow shrinking BOs partially as well.

Good point, that eliminates that problem.

Quoted 8 lines

And I really don't think this discussion is orthogonal. We are basically
discussing what drivers should do and not should do. And as far as I can
see the requirement to expose the LRUs to drivers comes up only because
the driver wants to do something it shouldn't.

Currently we have the purgeable vs non-purgeable and driver-level trylock-type deadlock avoidance not falling into those categories. And I'd like to categorize runtime pm as a trylock-type deadlock avoidance.

bo trylock and idle could, as you say, be handled in the TTM helper, so can purgeable and non-purgeable at lack of swap-space, provided that we provide such a flag in the ttm_bo ofc?

Quoted 16 lines
Quoted 9 lines
Quoted 6 lines
Quoted 5 lines

And again, all other drm bo shrinkers do this. We just want to do
the
same.

Do you have pointers?

As Sima said, this is complicated but not beyond comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

     if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
         with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

Quoted 8 lines

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd() that it can synchronously wait for runtime PM to power up the device again.

As far as I can tell that means that a device driver makes strong and completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

But I'd really expect a reclaim lockdep splat to happen there if the i915 pm did something not-allowed. IIRC, the design direction the i915 people got from mm people regarding the shrinkers was to avoid any sleeps in direct reclaim and punt it to kswapd. Need to ask i915 people how they can get away with that.

Quoted 103 lines
Quoted 9 lines

msm:
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317
which uses
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426
that is very similar in structure to what I implemented for TTM.

Panfrost: (although only purgeable objects AFAICT).
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/drm_gem.c#L1426

 From skimming over the source only MSM actually seems to use this and
the criteria for rejecting shrinking is everything TTM should know, e.g.
if a BO is pinned, idle etc...

Quoted 81 lines
Quoted 37 lines
Quoted 26 lines
Quoted 19 lines
Quoted 19 lines

If we bump LRU we could end up with infinite loops. So IMO we need to be able to loop. I don't really care wether
we do
this as an explicit loop or whether we use the LRU walker, but
I
think
from a maintainability point-of-view it is better to keep LRU
walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop
the
lru
lock, but maybe that's not a bad thing.

Quoted 7 lines
Quoted 2 lines

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so
hard
to
remove from TTM.

Quoted 7 lines

It doesn't IMO. I agree the first attempt did. This affects only
the
LRU iteration itself and I'm even fine to get rid of the callback
using
a for_ macro.

Well, I mean using a for_each approach is objectively better than having
a callback and a state bag.

Quoted 5 lines

But the fundamental question is if drivers are allowed to reject shrinking. And I think the answer is no, they need to be designed in
a
way where shrinking is always possible.

Rejects can be out of our control, due to anticipated deadlocks, oom
and deferring to kswapd.

Quoted 29 lines

What can be that we can't get the necessary locks to evict and object
(because it's about to be used etc...), but that are the per- requisites
TTM should be checking.

Quoted 6 lines
Quoted 6 lines
Quoted 4 lines

In any case, I don't think TTM should enforce a different way
of
shrinking by the means of a severely restricted helper?

Well, as far as I can see that is exactly what TTM should do.

Quoted 8 lines
Quoted 3 lines

I mean the main advantage to make a common component is to enforce
correct behavior.

But if all other drivers don't agree this as correct behavior and
instead want to keep behavior that is proven to work, that's a dead
end.

Well no, even if all drivers agree to (for example) drop security precautions it's still not something acceptable.

And same thing here, if we block shrinking because drivers think they
want their runtime PM implemented in a certain way then upstream needs
to block this and push back.

Quoted 6 lines

As far as I can see it's mandatory to have shrinkers not depend on
runtime PM, cause otherwise you run into resources handling which depends on the well behavior of userspace and that in turn in something
we can't allow.

Quoted 5 lines

Please see the above explanation for runtime pm, and for the record I
agree that enforcing disallowed or security violations is a completely
valid thing.

Quoted 5 lines

Putting the TTM issue aside as far as I can tell what i915 is extremely
questionable and doing the same thing in XE is most likely not something
we should allow.

Xe is currently not doing the same but relying on a separate thread rather than kswapd to wake the device.

Thanks,
Thomas

Quoted 18 lines

Regards,
Christian.

Quoted 14 lines

/Thomas

Quoted 11 lines

Regards,
Christian.

Quoted 8 lines

/Thomas

Quoted 5 lines

Regards,
Christian.

Quoted 2 lines

/Thomas

#21 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 152 lines · Thomas Hellström

Hi,

Quoted 44 lines · Christian König

Am 21.08.24 um 10:57 schrieb Thomas Hellström:

Quoted 31 lines · Christian König
Quoted 20 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 7 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular
bo
needs it to unbind, we want to try the next bo. Example: i915 GGTT
bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind
them
because the device is powered down?

I would say that this is a serious NO-GO. It basically means that
powered down devices can lock down system memory for undefined amount
of
time.

Quoted 8 lines

In other words an application can allocate memory, map it into GGTT
and
then suspend or even get killed and we are not able to recover the
memory because there is no activity on the GPU any more?

That really sounds like a bug in the driver design to me.

It's bad but it's not as bad as it sounds.

Quoted 7 lines

Problem is we can't wake up during direct reclaim IIRC due to runtime
pm lockdep violations, but we can and do fire up a thread to wake the
device and after the wakeup delay have subsequent shrink calls succeed,
or punt to kswapd or the oom handler.

Yeah that is obvious. The runtime PM is an interface designed to be used
from a very high level IOCTL/system call.

Quoted 5 lines

And delegating that from a shrinker to a worker is not valid as far as I
can see, instead of reducing the memory pressure the shrinker would then
increase it.

Perhaps an ignorant question, but aren't IO devices potentially woken up for swapout at memory pressure time using runtime PM, thereby increasing memory pressure in a similar way?

Quoted 13 lines
Quoted 10 lines

I think that's an orthogonal discussion, though. There are other reasons shrinking might fail, like the bo being busy in direct reclaim
(shouldn't wait for idle there but ok in kswapd), Other points of failure is ofc shmem radix tree allocations (not seen one yet, though)
which might succeed with a smaller bo.
(Not saying, though, that there isn't more to be done with the xe runtime pm implementation).

I don't think that argumentation is valid.

Quoted 7 lines

When a BO is locked then that it is ok to not shrink it, but TTM should
be able to determine all those prerequisites.

In other words the idea of a function returning a BO to the driver is
that the driver is obligated to shrink that one.

But that doesn't take potential driver deadlock avoidance into account,
so it would restrict the driver shrinkers by assuming that all deadlock
avoidance needed is known by TTM.

And since small memory allocations are allowed even at reclaim time to
be able so reclaim or shrink even more memory, IMO the pm resume problem reduces into a deadlock avoidance problem where we use pm_tryget similar to bo_trylock. Important thing, though, in both cases, that the device is woken or similarly the lock is released in reasonable time for the reclaim to retry and succeed.

Quoted 4 lines

That other necessary allocation can fail like shmen for example is obvious as well, but that's why we discussed to allow shrinking BOs partially as well.

Good point, that eliminates that problem.

Quoted 9 lines

And I really don't think this discussion is orthogonal. We are basically
discussing what drivers should do and not should do. And as far as I
can
see the requirement to expose the LRUs to drivers comes up only because
the driver wants to do something it shouldn't.

Currently we have the purgeable vs non-purgeable and driver-level trylock-type deadlock avoidance not falling into those categories. And
I'd like to categorize runtime pm as a trylock-type deadlock avoidance.

bo trylock and idle could, as you say, be handled in the TTM helper, so
can purgeable and non-purgeable at lack of swap-space, provided that we
provide such a flag in the ttm_bo ofc?

Quoted 25 lines
Quoted 10 lines
Quoted 7 lines
Quoted 6 lines

And again, all other drm bo shrinkers do this. We just want to
do
the
same.

Do you have pointers?

As Sima said, this is complicated but not beyond comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

     if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
         with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd()
that it can synchronously wait for runtime PM to power up the device
again.

Quoted 3 lines

As far as I can tell that means that a device driver makes strong and
completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

Quoted 9 lines

But I'd really expect a reclaim lockdep splat to happen there if the i915 pm did something not-allowed. IIRC, the design direction the i915
people got from mm people regarding the shrinkers was to avoid any sleeps in direct reclaim and punt it to kswapd. Need to ask i915 people
how they can get away with that.

So it turns out that Xe integrated pm resume is reclaim-safe, and I'd expect i915's to be as well. Xe discrete pm resume isn't.

So that means that, at least for integrated, the i915 shrinker should be ok from that POW, and punting certain bos to kswapd is not AFAICT abusing any undocumented features of kswapd but rather a way to avoid resuming the device during direct reclaim, like documented.

/Thomas

maintainer
#22 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 22.08.24 um 08:47 schrieb Thomas Hellström:

Quoted 31 lines
Quoted 22 lines
Quoted 17 lines
Quoted 3 lines

As Sima said, this is complicated but not beyond comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

     if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
         with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd()
that it can synchronously wait for runtime PM to power up the device
again.

Quoted 3 lines

As far as I can tell that means that a device driver makes strong and
completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

Quoted 9 lines

But I'd really expect a reclaim lockdep splat to happen there if the i915 pm did something not-allowed. IIRC, the design direction the i915
people got from mm people regarding the shrinkers was to avoid any sleeps in direct reclaim and punt it to kswapd. Need to ask i915 people
how they can get away with that.

Quoted 7 lines

So it turns out that Xe integrated pm resume is reclaim-safe, and I'd expect i915's to be as well. Xe discrete pm resume isn't.

So that means that, at least for integrated, the i915 shrinker should be ok from that POW, and punting certain bos to kswapd is not AFAICT abusing any undocumented features of kswapd but rather a way to avoid resuming the device during direct reclaim, like documented.

The more I think about this the more I disagree to this driver design. In my opinion device drivers should *never* resume runtime PM in a shrinker callback in the first place.

When the device is turned off it means that all of it's operations are stopped and eventually power to caches etc turned off as well. So I don't see any ongoing writeback operations or similar either.

So the question is why do we need to power on the device in a shrinker in the first place?

What could be is that the device needs to flush GART TLBs or similar when it is turned on, e.g. that you grab a PM reference to make sure that during your HW operation the device doesn't suspend.

But that doesn't mean that you should resume the device. In other words when the device is powered down you shouldn't power it up again.

And for GART we already have the necessary move callback implemented in TTM. This is done by radeon, amdgpu and nouveu in a common way as far as I can see.

So why should Xe be special and follow the very questionable approach of i915 here?

Regards,
Christian.

Quoted 5 lines

/Thomas

#23 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 51 lines · Christian König

Am 22.08.24 um 08:47 schrieb Thomas Hellström:

Quoted 42 lines
Quoted 27 lines
Quoted 20 lines
Quoted 4 lines

As Sima said, this is complicated but not beyond
comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

      if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
          with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd()
that it can synchronously wait for runtime PM to power up the device
again.

Quoted 5 lines

As far as I can tell that means that a device driver makes strong
and
completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

Quoted 11 lines

But I'd really expect a reclaim lockdep splat to happen there if the
i915 pm did something not-allowed. IIRC, the design direction the i915
people got from mm people regarding the shrinkers was to avoid any
sleeps in direct reclaim and punt it to kswapd. Need to ask i915 people
how they can get away with that.

So it turns out that Xe integrated pm resume is reclaim-safe, and I'd
expect i915's to be as well. Xe discrete pm resume isn't.

Quoted 7 lines

So that means that, at least for integrated, the i915 shrinker should
be ok from that POW, and punting certain bos to kswapd is not AFAICT
abusing any undocumented features of kswapd but rather a way to avoid
resuming the device during direct reclaim, like documented.

Quoted 4 lines

The more I think about this the more I disagree to this driver design.
In my opinion device drivers should *never* resume runtime PM in a shrinker callback in the first place.

Runtime PM resume is allowed even from irq context if carefully implemented by the driver and flagged as such to the core.

https://docs.kernel.org/power/runtime_pm.html

Resuming runtime PM from reclaim therefore shouldn't be an issue IMO, and really up to the driver.

Quoted 6 lines

When the device is turned off it means that all of it's operations are
stopped and eventually power to caches etc turned off as well. So I don't see any ongoing writeback operations or similar either.

Quoted 7 lines

So the question is why do we need to power on the device in a shrinker
in the first place?

What could be is that the device needs to flush GART TLBs or similar when it is turned on, e.g. that you grab a PM reference to make sure that during your HW operation the device doesn't suspend.

Exactly why the i915 needs to flush the GART I'm not sure of but I suspect the gart TLB might be forgotten while suspended.

Quoted 11 lines

But that doesn't mean that you should resume the device. In other words
when the device is powered down you shouldn't power it up again.

And for GART we already have the necessary move callback implemented in
TTM. This is done by radeon, amdgpu and nouveu in a common way as far as
I can see.

Quoted 3 lines

So why should Xe be special and follow the very questionable approach of
i915 here?

For Xe, Lunar Lake (integrated) has the interesting design that each bo carries compression metadata that needs to be blitted to system pages during shrinking. The alternative is to resolve all buffer objects at device runtime suspend...

But runtime PM aside, with a one-bo only approach we still have the drawbacks that it

* eliminates possibility for driver deadlock avoidance
* Requires TTM knowledge of "purgeable" bos
* Requires an additional LRU to avoid O(n2) traversal of already shrunken objects
* Drivers with legitimate shrinker designs that don't fit in the TTM- enforced model will have frustrated maintainers.

Thanks,
Thomas

Quoted 10 lines

Regards,
Christian.

Quoted 5 lines

/Thomas

maintainer
#24 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 22.08.24 um 10:21 schrieb Thomas Hellström:

Quoted 55 lines · Christian König
Quoted 50 lines

Am 22.08.24 um 08:47 schrieb Thomas Hellström:

Quoted 42 lines
Quoted 27 lines
Quoted 20 lines
Quoted 4 lines

As Sima said, this is complicated but not beyond
comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

      if (sc->nr_scanned < sc->nr_to_scan &&
current_is_kswapd()) {
....
          with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd()
that it can synchronously wait for runtime PM to power up the device
again.

Quoted 5 lines

As far as I can tell that means that a device driver makes strong
and
completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

Quoted 11 lines

But I'd really expect a reclaim lockdep splat to happen there if the
i915 pm did something not-allowed. IIRC, the design direction the i915
people got from mm people regarding the shrinkers was to avoid any
sleeps in direct reclaim and punt it to kswapd. Need to ask i915 people
how they can get away with that.

So it turns out that Xe integrated pm resume is reclaim-safe, and I'd
expect i915's to be as well. Xe discrete pm resume isn't.

Quoted 7 lines

So that means that, at least for integrated, the i915 shrinker should
be ok from that POW, and punting certain bos to kswapd is not AFAICT
abusing any undocumented features of kswapd but rather a way to avoid
resuming the device during direct reclaim, like documented.

Quoted 4 lines

The more I think about this the more I disagree to this driver design.
In my opinion device drivers should *never* resume runtime PM in a shrinker callback in the first place.

Quoted 7 lines

Runtime PM resume is allowed even from irq context if carefully implemented by the driver and flagged as such to the core.

https://docs.kernel.org/power/runtime_pm.html

Resuming runtime PM from reclaim therefore shouldn't be an issue IMO, and really up to the driver.

Mhm when it's up to the driver on which level to use runtime PM then that at least explains why the framework doesn't have lockdep annotations.

Ok, that is at least convincing the what i915 does here should work somehow.

Quoted 9 lines
Quoted 9 lines

When the device is turned off it means that all of it's operations are
stopped and eventually power to caches etc turned off as well. So I don't see any ongoing writeback operations or similar either.

So the question is why do we need to power on the device in a shrinker
in the first place?

Quoted 5 lines
Quoted 3 lines

What could be is that the device needs to flush GART TLBs or similar when it is turned on, e.g. that you grab a PM reference to make sure that during your HW operation the device doesn't suspend.

Exactly why the i915 needs to flush the GART I'm not sure of but I suspect the gart TLB might be forgotten while suspended.

Well that is unproblematic. Amdgpu and I think nouveau does something similar.

But you don't need to resume the hardware for this, just grabbing the reference to make sure that it doesn't suspend is sufficient.

The assumption I make here is that you don't need to do anything when the hardware is power down anyway. That seems to be true for at least the hardware designs I'm aware of.

Quoted 10 lines
Quoted 10 lines

But that doesn't mean that you should resume the device. In other words
when the device is powered down you shouldn't power it up again.

And for GART we already have the necessary move callback implemented in
TTM. This is done by radeon, amdgpu and nouveu in a common way as far as
I can see.

Quoted 7 lines
Quoted 3 lines

So why should Xe be special and follow the very questionable approach of
i915 here?

For Xe, Lunar Lake (integrated) has the interesting design that each bo carries compression metadata that needs to be blitted to system pages during shrinking. The alternative is to resolve all buffer objects at device runtime suspend...

That's the same for amdgpu as well, but when the device is powered down those compression data needs to be evacuated anyway.

Quoted 9 lines

But runtime PM aside, with a one-bo only approach we still have the drawbacks that it

* eliminates possibility for driver deadlock avoidance
* Requires TTM knowledge of "purgeable" bos
* Requires an additional LRU to avoid O(n2) traversal of already shrunken objects
* Drivers with legitimate shrinker designs that don't fit in the TTM- enforced model will have frustrated maintainers.

I still find that only halve-convincing. The real question is if it's a good idea to give drivers the power to decide what to shrink and what not to shrink.

And at least with the arguments and experience at hand I would vote for not doing that. We have added the eviction_valuable callback for amdgpu and ended up in quite a mess with that.

Background is that some eviction decision done by the driver where not as optimal as we hoped it to be.

On the other hand keeping track of all the swapped out objects should be TTMs job anyway, e.g. having a TTM_PL_SWAPPED domain.

So in my mind the ideal solution still looks like this:

driver_specific_shrinker_scan(...)
{
    driver_specific_preparations(...);
    bo = ttm_reserve_next_bo_to_shrink(...);
    ttm_bo_validate(bo, TTM_PL_SWAPPED);
    ttm_bo_unreserver(bo);
    driver_specific_cleanups(...);
}

When there is a potential deadlock because the shrinker might be called from driver code which holds locks the driver needs to it's specific preparation or cleanup then those would apply to all BOs and not just the one returned from TTM.

The only use case I can see were the driver would need to filter out the BOs to shrink would be if TTM doesn't know about all the information to make a decision what to shrink and exactly that is what I try to avoid.

Regards,
Christian.

Quoted 13 lines

Thanks,
Thomas

Quoted 8 lines

Regards,
Christian.

Quoted 4 lines

/Thomas

#25 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 103 lines · Christian König

Am 22.08.24 um 10:21 schrieb Thomas Hellström:

Quoted 64 lines · Christian König
Quoted 58 lines

Am 22.08.24 um 08:47 schrieb Thomas Hellström:

Quoted 50 lines
Quoted 30 lines
Quoted 23 lines
Quoted 4 lines

As Sima said, this is complicated but not beyond
comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

       if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
           with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from
kswapd()
that it can synchronously wait for runtime PM to power up the
device
again.

Quoted 5 lines

As far as I can tell that means that a device driver makes strong
and
completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

Quoted 15 lines

But I'd really expect a reclaim lockdep splat to happen there if
the
i915 pm did something not-allowed. IIRC, the design direction the
i915
people got from mm people regarding the shrinkers was to avoid
any
sleeps in direct reclaim and punt it to kswapd. Need to ask i915
people
how they can get away with that.

So it turns out that Xe integrated pm resume is reclaim-safe, and
I'd
expect i915's to be as well. Xe discrete pm resume isn't.

Quoted 7 lines

So that means that, at least for integrated, the i915 shrinker should
be ok from that POW, and punting certain bos to kswapd is not AFAICT
abusing any undocumented features of kswapd but rather a way to avoid
resuming the device during direct reclaim, like documented.

Quoted 5 lines

The more I think about this the more I disagree to this driver design.
In my opinion device drivers should *never* resume runtime PM in a
shrinker callback in the first place.

Quoted 8 lines

Runtime PM resume is allowed even from irq context if carefully implemented by the driver and flagged as such to the core.

https://docs.kernel.org/power/runtime_pm.html

Resuming runtime PM from reclaim therefore shouldn't be an issue IMO,
and really up to the driver.

Mhm when it's up to the driver on which level to use runtime PM then that at least explains why the framework doesn't have lockdep annotations.

Ok, that is at least convincing the what i915 does here should work somehow.

Quoted 11 lines
Quoted 11 lines

When the device is turned off it means that all of it's operations
are
stopped and eventually power to caches etc turned off as well. So I
don't see any ongoing writeback operations or similar either.

So the question is why do we need to power on the device in a shrinker
in the first place?

Quoted 7 lines
Quoted 5 lines

What could be is that the device needs to flush GART TLBs or similar
when it is turned on, e.g. that you grab a PM reference to make sure
that during your HW operation the device doesn't suspend.

Exactly why the i915 needs to flush the GART I'm not sure of but I suspect the gart TLB might be forgotten while suspended.

Well that is unproblematic. Amdgpu and I think nouveau does something similar.

Quoted 6 lines

But you don't need to resume the hardware for this, just grabbing the reference to make sure that it doesn't suspend is sufficient.

The assumption I make here is that you don't need to do anything when the hardware is power down anyway. That seems to be true for at least the hardware designs I'm aware of.

I'm not sure I understand you correctly but do you suggest that each bo with a GGTT mapping should hold a pm reference and we refuse to suspend while there are GGTT mappings?

Quoted 25 lines
Quoted 17 lines
Quoted 13 lines

But that doesn't mean that you should resume the device. In other words
when the device is powered down you shouldn't power it up again.

And for GART we already have the necessary move callback implemented
in
TTM. This is done by radeon, amdgpu and nouveu in a common way as far
as
I can see.

Quoted 4 lines

So why should Xe be special and follow the very questionable approach
of
i915 here?

Quoted 7 lines

For Xe, Lunar Lake (integrated) has the interesting design that each bo
carries compression metadata that needs to be blitted to system pages
during shrinking. The alternative is to resolve all buffer objects at
device runtime suspend...

Quoted 3 lines

That's the same for amdgpu as well, but when the device is powered down
those compression data needs to be evacuated anyway.

That's true for Intel discrete when entering D3Cold, which is typically not done if that means a huge amount of data to evict.

Integrated doesn't suspend to D3Cold but using D3Hot and the compression metadata is persistent, but is only accessible when the device is woken.

Quoted 50 lines
Quoted 6 lines

But runtime PM aside, with a one-bo only approach we still have the drawbacks that it

Quoted 7 lines

* eliminates possibility for driver deadlock avoidance
* Requires TTM knowledge of "purgeable" bos
* Requires an additional LRU to avoid O(n2) traversal of already shrunken objects
* Drivers with legitimate shrinker designs that don't fit in the TTM-
enforced model will have frustrated maintainers.

I still find that only halve-convincing. The real question is if it's a
good idea to give drivers the power to decide what to shrink and what not to shrink.

And at least with the arguments and experience at hand I would vote for
not doing that. We have added the eviction_valuable callback for amdgpu
and ended up in quite a mess with that.

Background is that some eviction decision done by the driver where not
as optimal as we hoped it to be.

On the other hand keeping track of all the swapped out objects should be
TTMs job anyway, e.g. having a TTM_PL_SWAPPED domain.

So in my mind the ideal solution still looks like this:

driver_specific_shrinker_scan(...)
{
     driver_specific_preparations(...);
     bo = ttm_reserve_next_bo_to_shrink(...);
     ttm_bo_validate(bo, TTM_PL_SWAPPED);
     ttm_bo_unreserver(bo);
     driver_specific_cleanups(...);
}

When there is a potential deadlock because the shrinker might be called
from driver code which holds locks the driver needs to it's specific preparation or cleanup then those would apply to all BOs and not just the one returned from TTM.

Quoted 6 lines

The only use case I can see were the driver would need to filter out the
BOs to shrink would be if TTM doesn't know about all the information to
make a decision what to shrink and exactly that is what I try to avoid.

Yeah, but unfortunately the use cases we have require per-bo decisions, so suggested strucure becomes:

driver_specific_shrinker_scan(...)

{
     ttm_for_each_suggested_bo_to_shrink(&bo) {
	if (driver_preparations_and_ok_to_shrink(bo)) {
		ttm_shrink_this(&bo);
		driver_cleanups();
		if (vmscan_thinks_weve_done_enough())
			break;
     }
}

Thanks,
Thomas

Quoted 17 lines

Regards,
Christian.

Quoted 13 lines

Thanks,
Thomas

Quoted 8 lines

Regards,
Christian.

Quoted 4 lines

/Thomas

#26 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Christian König
Quoted 7 lines · Christian König

Am 22.08.24 um 10:21 schrieb Thomas Hellström:

Quoted 6 lines · Christian König
Quoted 2 lines

In my opinion device drivers should *never* resume runtime PM in a shrinker callback in the first place.

Runtime PM resume is allowed even from irq context if carefully implemented by the driver and flagged as such to the core.

Quoted 7 lines
Quoted 4 lines

https://docs.kernel.org/power/runtime_pm.html

Resuming runtime PM from reclaim therefore shouldn't be an issue IMO, and really up to the driver.

Mhm when it's up to the driver on which level to use runtime PM then that at least explains why the framework doesn't have lockdep annotations.

Aside on the lockdep question:

Per-device lockdep annotations would be doable I think (since the rules really are per-device). But lockdep really doesn't cope too well with too many dynamic lockdep classes, so that's maybe the reason this was never done?

It's the same with module reload, eventually you run out of lockdep class keys :-/

What we perhaps could do is register a driver lockdep key (which is static), that runtime pm core code could optionally use when set?

Hm, thinking about this some more, if we embed this in struct device_driver when it's statically created, this could work perhaps automatically?
-Sima

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
#27 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Thomas Hellström
Quoted 78 lines · Thomas Hellström
Quoted 54 lines · Christian König

Am 22.08.24 um 08:47 schrieb Thomas Hellström:

Quoted 45 lines
Quoted 27 lines
Quoted 20 lines
Quoted 4 lines

As Sima said, this is complicated but not beyond
comprehension:
i915
https://elixir.bootlin.com/linux/v6.11-rc4/source/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c#L317

As far as I can tell what i915 does here is extremely questionable.

      if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
....
          with_intel_runtime_pm(&i915->runtime_pm, wakeref) {

with_intel_runtime_pm() then calls pm_runtime_get_sync().

So basically the i915 shrinker assumes that when called from kswapd()
that it can synchronously wait for runtime PM to power up the device
again.

Quoted 5 lines

As far as I can tell that means that a device driver makes strong
and
completely undocumented assumptions how kswapd works internally.

Admittedly that looks weird

Quoted 14 lines

But I'd really expect a reclaim lockdep splat to happen there if
the
i915 pm did something not-allowed. IIRC, the design direction the
i915
people got from mm people regarding the shrinkers was to avoid any
sleeps in direct reclaim and punt it to kswapd. Need to ask i915
people
how they can get away with that.

So it turns out that Xe integrated pm resume is reclaim-safe, and I'd
expect i915's to be as well. Xe discrete pm resume isn't.

Quoted 7 lines

So that means that, at least for integrated, the i915 shrinker should
be ok from that POW, and punting certain bos to kswapd is not AFAICT
abusing any undocumented features of kswapd but rather a way to avoid
resuming the device during direct reclaim, like documented.

Quoted 4 lines

The more I think about this the more I disagree to this driver design.
In my opinion device drivers should *never* resume runtime PM in a shrinker callback in the first place.

Runtime PM resume is allowed even from irq context if carefully implemented by the driver and flagged as such to the core.

https://docs.kernel.org/power/runtime_pm.html

Resuming runtime PM from reclaim therefore shouldn't be an issue IMO, and really up to the driver.

Quoted 10 lines

When the device is turned off it means that all of it's operations are
stopped and eventually power to caches etc turned off as well. So I don't see any ongoing writeback operations or similar either.

So the question is why do we need to power on the device in a shrinker
in the first place?

Quoted 8 lines
Quoted 5 lines

What could be is that the device needs to flush GART TLBs or similar
when it is turned on, e.g. that you grab a PM reference to make sure
that during your HW operation the device doesn't suspend.

Exactly why the i915 needs to flush the GART I'm not sure of but I suspect the gart TLB might be forgotten while suspended.

To be clear, the intel GGTTs are programmed using device mmio. And while i915 is a data point, there's no immediate plans to convert it to using the TTM page pool AFAIK, so for the sake of discussion let's focus on the Xe usage.

/Thomas

#28 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Christian König
Quoted 8 lines · Christian König

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 4 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them because the device is powered down?

Yes. amdgpu does the same btw :-)

It's a fairly fundamental issue of rpm on discrete gpus, or anything that looks a lot like a discrete gpu. The deadlock scenario is roughly:

- In runtime suspend you need to copy any bo out of vram into system ram before you power the gpu. This requires bo and ttm locks.

- You can't just avoid this by holding an rpm reference as long as any bo is still in vram, because that defacto means you'll never autosuspend at runtime. Plus most real hw is complex enough that you have some driver objects that you need to throw out or recreate, so in practice no way to avoid all this.

- runtime resume tends to be easier and mostly doable without taking bo and ttm locks, because by design you know no one else can possibly have any need to get at the gpu hw - it was all powered off after all. It's still messy, but doable.

- Unfortunately this doesn't help, because your runtime resume might need to wait for a in-progress suspend operation to complete. Which means you still deadlock even if your resume path has entirely reasonable locking.

On integrated you can mostly avoid this all because there's no need to swap out bo to system memory, they're there already. Exceptions like the busted coherency stuff on LNL aside.

But on discrete it's just suck.

TTM discrete gpu drivers avoided all that by simply not having a shrinker where you need to runtime pm get, instead all runtime pm gets are outmost, without holding any ttm or bo locks.

Quoted 8 lines

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of time.

In other words an application can allocate memory, map it into GGTT and then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

That really sounds like a bug in the driver design to me.

It's a bug in the runtime pm core imo. I think interim what Thomas laid out is the best solution, since in practice when the gpu is off you really shouldn't need to wake it up. Except when you're unlucky and racing a runtime suspend against a shrinker activity (like runtime suspend throws a bo into system memory, and the shrinker then immediately wants to swap it out).

I've been pondering this mess for a few months, and I think I have a solution. But it's a lot of work in core pm code unfortunately:

I think we need to split the runtime_suspend callback into two halfes:

->runtime_suspend_prepare

This would be run by the rpm core code from a worker without holding any locks at all. Also, any runtime_pm_get call will not wait on this prepare callback to finish, so it's up to the driver to make sure all the locking is there. Synchronous suspend calls obviously have to wait for this to finish, but that should only happen during system suspend or driver unload, where we don't have these deadlock issues.

Drivers can use this callback for any non-destructive prep work (non-destructive aside from the copy engine time wasted if it fails) like swapping bo from vram to system memory. Drivers must not actually shut down the hardware because a runtime_pm_get call must succeed without waiting for this callback to finish.

If any runtime_pm_get call happens while the suspend attempt will be aborted without further action.

->runtime_suspend

This does the actual hw power-off. The power core must guarantee that the ->runtime_suspend_prepare has successfully completed at least once without the rpm refcount being elevated from 0 to 1 again.

This way drivers can assume that all bo have been swapped out from vram already, and there's no need to acquire bo or ttm locks in the suspend path that could block the resume path.

Which would then allow unconditional runtime_pm_get in the shrinker paths.

Unfortunately this will be all really tricky to implement and I think needs to be done in the rumtime pm core.

Cheers, Sima

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
maintainer
#29 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 22.08.24 um 11:23 schrieb Daniel Vetter:

Quoted 9 lines · Christian König
Quoted 7 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 4 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them because the device is powered down?

Yes. amdgpu does the same btw :-)

Well, amdgpu wouldn't block shrinking as far as I know.

When the GPU is powered down all fences are signaled and things like GART unbinding is just postponed until the GPU wakes up again.

Quoted 12 lines

It's a fairly fundamental issue of rpm on discrete gpus, or anything that looks a lot like a discrete gpu. The deadlock scenario is roughly:

- In runtime suspend you need to copy any bo out of vram into system ram before you power the gpu. This requires bo and ttm locks.

- You can't just avoid this by holding an rpm reference as long as any bo is still in vram, because that defacto means you'll never autosuspend at runtime. Plus most real hw is complex enough that you have some driver objects that you need to throw out or recreate, so in practice no way to avoid all this.

Quoted 8 lines

- runtime resume tends to be easier and mostly doable without taking bo and ttm locks, because by design you know no one else can possibly have any need to get at the gpu hw - it was all powered off after all. It's still messy, but doable.

- Unfortunately this doesn't help, because your runtime resume might need to wait for a in-progress suspend operation to complete. Which means you still deadlock even if your resume path has entirely reasonable locking.

Uff, yeah that totally confirms my gut feeling that this looked really questionable.

Quoted 5 lines

On integrated you can mostly avoid this all because there's no need to swap out bo to system memory, they're there already. Exceptions like the busted coherency stuff on LNL aside.

But on discrete it's just suck.

Mhm, I never worked with pure integrated devices but at least radeon, amdgpu and nouveau seems to have a solution which would work as far as I can tell.

Basically on suspend you make sure that everything necessary for shrinking is done, e.g. waiting for fences, evacuating VRAM etc...

Hardware specific updates like GART while the device is suspended are postponed until resume.

Quoted 3 lines

TTM discrete gpu drivers avoided all that by simply not having a shrinker where you need to runtime pm get, instead all runtime pm gets are outmost, without holding any ttm or bo locks.

Yes, exactly that.

Quoted 7 lines
Quoted 7 lines

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of time.

In other words an application can allocate memory, map it into GGTT and then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

Quoted 7 lines
Quoted 1 line

That really sounds like a bug in the driver design to me.

It's a bug in the runtime pm core imo. I think interim what Thomas laid out is the best solution, since in practice when the gpu is off you really shouldn't need to wake it up. Except when you're unlucky and racing a runtime suspend against a shrinker activity (like runtime suspend throws a bo into system memory, and the shrinker then immediately wants to swap it out).

Mhm, why exactly is that problematic?

Wouldn't pm_runtime_get_if_in_use() just return 0 in this situation and we postpone any hw activity?

Quoted 29 lines

I've been pondering this mess for a few months, and I think I have a solution. But it's a lot of work in core pm code unfortunately:

I think we need to split the runtime_suspend callback into two halfes:

->runtime_suspend_prepare

This would be run by the rpm core code from a worker without holding any locks at all. Also, any runtime_pm_get call will not wait on this prepare callback to finish, so it's up to the driver to make sure all the locking is there. Synchronous suspend calls obviously have to wait for this to finish, but that should only happen during system suspend or driver unload, where we don't have these deadlock issues.

Drivers can use this callback for any non-destructive prep work (non-destructive aside from the copy engine time wasted if it fails) like swapping bo from vram to system memory. Drivers must not actually shut down the hardware because a runtime_pm_get call must succeed without waiting for this callback to finish.

If any runtime_pm_get call happens while the suspend attempt will be aborted without further action.

->runtime_suspend

This does the actual hw power-off. The power core must guarantee that the ->runtime_suspend_prepare has successfully completed at least once without the rpm refcount being elevated from 0 to 1 again.

Quoted 8 lines

This way drivers can assume that all bo have been swapped out from vram already, and there's no need to acquire bo or ttm locks in the suspend path that could block the resume path.

Which would then allow unconditional runtime_pm_get in the shrinker paths.

Unfortunately this will be all really tricky to implement and I think needs to be done in the rumtime pm core.

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

At least for amdgpu that shouldn't be a problem at all.

Regards,
Christian.

Quoted 2 lines

Cheers, Sima

#30 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

[machine died, new one working now, I can read complicated mails again an answer.]

Quoted 40 lines · Christian König

Am 22.08.24 um 11:23 schrieb Daniel Vetter:

Quoted 9 lines · Christian König
Quoted 7 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 4 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them because the device is powered down?

Yes. amdgpu does the same btw :-)

Well, amdgpu wouldn't block shrinking as far as I know.

When the GPU is powered down all fences are signaled and things like GART unbinding is just postponed until the GPU wakes up again.

Quoted 12 lines

It's a fairly fundamental issue of rpm on discrete gpus, or anything that looks a lot like a discrete gpu. The deadlock scenario is roughly:

- In runtime suspend you need to copy any bo out of vram into system ram before you power the gpu. This requires bo and ttm locks.

- You can't just avoid this by holding an rpm reference as long as any bo is still in vram, because that defacto means you'll never autosuspend at runtime. Plus most real hw is complex enough that you have some driver objects that you need to throw out or recreate, so in practice no way to avoid all this.

Quoted 8 lines

- runtime resume tends to be easier and mostly doable without taking bo and ttm locks, because by design you know no one else can possibly have any need to get at the gpu hw - it was all powered off after all. It's still messy, but doable.

- Unfortunately this doesn't help, because your runtime resume might need to wait for a in-progress suspend operation to complete. Which means you still deadlock even if your resume path has entirely reasonable locking.

Uff, yeah that totally confirms my gut feeling that this looked really questionable.

Quoted 8 lines
Quoted 5 lines

On integrated you can mostly avoid this all because there's no need to swap out bo to system memory, they're there already. Exceptions like the busted coherency stuff on LNL aside.

But on discrete it's just suck.

Mhm, I never worked with pure integrated devices but at least radeon, amdgpu and nouveau seems to have a solution which would work as far as I can tell.

Yeah integrated is easy (if you don't do silly stuff like intel on their latest).

Quoted 2 lines

Basically on suspend you make sure that everything necessary for shrinking is done, e.g. waiting for fences, evacuating VRAM etc...

This is the hard part, or the "evacuating VRAM" part at least. My proposal is that essentially the runtime_suspend_prepare hook does that. Imo the clean design is that we wait for rpm autosuspend, and only then start to evacuate VRAM. Otherwise you need to hold a rpm reference if there's anything in VRAM, which kinda defeats the point of runtime pm ...

Or you have your own runtime pm refcount that tracks whether anyone uses the gpu, and if that drops to 0 for long enough you evacuate VRAM, and then drop the rpm reference. Which is just implementing the idea I've typed up, except hand-rolled in driver code and with a rpm refcount that's entirely driver internal.

And at least last time I checked, amdgpu does the VRAM evacuation in the runtime pm suspend callback, which is why all your runtime_pm_get calls are outside of the big bo/ttm locks.

Quoted 2 lines

Hardware specific updates like GART while the device is suspended are postponed until resume.

Yeah GART shouldn't be the issue, except when you're racing.

Quoted 21 lines
Quoted 3 lines

TTM discrete gpu drivers avoided all that by simply not having a shrinker where you need to runtime pm get, instead all runtime pm gets are outmost, without holding any ttm or bo locks.

Yes, exactly that.

Quoted 7 lines
Quoted 7 lines

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of time.

In other words an application can allocate memory, map it into GGTT and then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

Quoted 7 lines
Quoted 1 line

That really sounds like a bug in the driver design to me.

It's a bug in the runtime pm core imo. I think interim what Thomas laid out is the best solution, since in practice when the gpu is off you really shouldn't need to wake it up. Except when you're unlucky and racing a runtime suspend against a shrinker activity (like runtime suspend throws a bo into system memory, and the shrinker then immediately wants to swap it out).

Quoted 4 lines

Mhm, why exactly is that problematic?

Wouldn't pm_runtime_get_if_in_use() just return 0 in this situation and we postpone any hw activity?

So when you're runtime suspend, you need to evacuate VRAM. Which means potentially a lot needs to be moved into system memory. Which means it's likely the shrinker gets active. Also, it's the point where pm_runtime_get_if_in_use() will consistently fail, so right when you need the shrinker to be reliable it will fail the most.

Quoted 35 lines
Quoted 35 lines

I've been pondering this mess for a few months, and I think I have a solution. But it's a lot of work in core pm code unfortunately:

I think we need to split the runtime_suspend callback into two halfes:

->runtime_suspend_prepare

This would be run by the rpm core code from a worker without holding any locks at all. Also, any runtime_pm_get call will not wait on this prepare callback to finish, so it's up to the driver to make sure all the locking is there. Synchronous suspend calls obviously have to wait for this to finish, but that should only happen during system suspend or driver unload, where we don't have these deadlock issues.

Drivers can use this callback for any non-destructive prep work (non-destructive aside from the copy engine time wasted if it fails) like swapping bo from vram to system memory. Drivers must not actually shut down the hardware because a runtime_pm_get call must succeed without waiting for this callback to finish.

If any runtime_pm_get call happens while the suspend attempt will be aborted without further action.

->runtime_suspend

This does the actual hw power-off. The power core must guarantee that the ->runtime_suspend_prepare has successfully completed at least once without the rpm refcount being elevated from 0 to 1 again.

This way drivers can assume that all bo have been swapped out from vram already, and there's no need to acquire bo or ttm locks in the suspend path that could block the resume path.

Which would then allow unconditional runtime_pm_get in the shrinker paths.

Quoted 8 lines
Quoted 2 lines

Unfortunately this will be all really tricky to implement and I think needs to be done in the rumtime pm core.

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity to resume doesn't solve the deadlock issue, if you still need to grab ttm locks on resume.

Quoted 1 line

At least for amdgpu that shouldn't be a problem at all.

Yeah, because atm amdgpu has the rpm_get calls outside of ttm locks, which is exactly the inversion you've complained about as being broken driver design.
-Sima

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
#31 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 10 lines · Daniel Vetter
Quoted 5 lines · Christian König

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity to resume doesn't solve the deadlock issue, if you still need to grab ttm locks on resume.

Pondered this specific aspect some more, and I think you still have a race here (even if you avoid the deadlock): If the condiditional rpm_get call fails there's no guarantee that the device will suspend/resume and clean up the GART mapping. The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when resume almost finished.

That means we'll have ttm bo hanging around with GART allocations/mappings which aren't actually valid anymore (since they might escape the cleanup upon resume due to the race). That doesn't feel like a solid design either.
-Sima

Signature · 3 lines
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
maintainer
#32 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 7 lines · Daniel Vetter
Quoted 6 lines · Christian König
Quoted 5 lines

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

Quoted 7 lines
Quoted 3 lines

Not good enough, at least long term I think. Also postponing hw activity to resume doesn't solve the deadlock issue, if you still need to grab ttm locks on resume.

Pondered this specific aspect some more, and I think you still have a race here (even if you avoid the deadlock): If the condiditional rpm_get call fails there's no guarantee that the device will suspend/resume and clean up the GART mapping.

Well I think we have a major disconnect here. When the device is powered down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is powered down this table is completely destroyed. Any BO which was mapped inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped to GART and the device is powered down we just skip the GART unmapping part because that has already implicitly happened during power down.

Before mapping any BO into the GART again we power the GPU up through the runtime PM calls. And while powering it up again the GART is restored.

Quoted 3 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when resume almost finished.

What race are you talking about?

The worst thing which could happen is that we restore a GART entry which isn't needed any more, but that is pretty much irrelevant since we only clear them to avoid some hw bugs.

Quoted 4 lines

That means we'll have ttm bo hanging around with GART allocations/mappings which aren't actually valid anymore (since they might escape the cleanup upon resume due to the race). That doesn't feel like a solid design either.

I'm most likely missing something, but I'm really scratching my head where you see a problem here.

Regards,
Christian.

Quoted 1 line

-Sima

#33 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 33 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 14 lines · Daniel Vetter
Quoted 5 lines · Christian König
Quoted 4 lines

Completely agree that this is complicated, but I still don't see the need
for it.

Quoted 8 lines
Quoted 3 lines

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

Quoted 8 lines

So when the shrinker wants to evict a BO which is marked as mapped to GART and the device is powered down we just skip the GART unmapping part
because that has already implicitly happened during power down.

Before mapping any BO into the GART again we power the GPU up through the runtime PM calls. And while powering it up again the GART is restored.

I think you're forgetting the main Xe use-case of Lunar-lake compression metadata. I'ts retained by the device during D3hot, but cannot, at that time, be accessed for shrinking.

And copying it all out "Just in case" when transitioning to D3hot just isn't a viable solution.

/Thomas

maintainer
#34 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 28.08.24 um 16:05 schrieb Thomas Hellström:

Quoted 38 lines · Christian König
Quoted 37 lines

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 14 lines · Daniel Vetter
Quoted 5 lines · Christian König
Quoted 4 lines

Completely agree that this is complicated, but I still don't see the need
for it.

Quoted 8 lines
Quoted 3 lines

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped to GART and the device is powered down we just skip the GART unmapping part
because that has already implicitly happened during power down.

Quoted 6 lines
Quoted 3 lines

Before mapping any BO into the GART again we power the GPU up through the runtime PM calls. And while powering it up again the GART is restored.

I think you're forgetting the main Xe use-case of Lunar-lake compression metadata. I'ts retained by the device during D3hot, but cannot, at that time, be accessed for shrinking.

Yeah, that is really something we don't have an equivalent for on AMD GPUs.

When the ASIC is powered down VRAM is basically dead as well because it won't get refreshed any more.

Quoted 2 lines

And copying it all out "Just in case" when transitioning to D3hot just isn't a viable solution.

I would say that this is solvable with a hierarchy of power management functionality.

E.g. the runtime PM interface works the same for you as it does for amdgpu with evicting TTM BOs etc....

Then separate from runtime PM you have a reference count for the accessibility of compressed metadata. And while shrinking you only resume this specific part.

Christian.

Quoted 3 lines

/Thomas

#35 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 43 lines · Christian König

Am 28.08.24 um 16:05 schrieb Thomas Hellström:

Quoted 41 lines · Christian König
Quoted 40 lines

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 14 lines · Daniel Vetter
Quoted 5 lines · Christian König
Quoted 4 lines

Completely agree that this is complicated, but I still don't see the need
for it.

Quoted 8 lines
Quoted 3 lines

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped to GART and the device is powered down we just skip the GART unmapping part
because that has already implicitly happened during power down.

Before mapping any BO into the GART again we power the GPU up through the runtime PM calls. And while powering it up again the GART is restored.

Quoted 8 lines
Quoted 3 lines

I think you're forgetting the main Xe use-case of Lunar-lake compression metadata. I'ts retained by the device during D3hot, but cannot, at that time, be accessed for shrinking.

Yeah, that is really something we don't have an equivalent for on AMD GPUs.

When the ASIC is powered down VRAM is basically dead as well because it won't get refreshed any more.

We actually support memory self refresh for VRAM on some platforms, but the rest of the GPU is powered down, so only the VRAM contents is retained.

Alex

Quoted 20 lines
Quoted 3 lines

And copying it all out "Just in case" when transitioning to D3hot just isn't a viable solution.

I would say that this is solvable with a hierarchy of power management functionality.

E.g. the runtime PM interface works the same for you as it does for amdgpu with evicting TTM BOs etc....

Then separate from runtime PM you have a reference count for the accessibility of compressed metadata. And while shrinking you only resume this specific part.

Christian.

Quoted 3 lines

/Thomas

#36 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Christian König
Quoted 73 lines · Christian König

Am 28.08.24 um 16:05 schrieb Thomas Hellström:

Quoted 49 lines · Christian König
Quoted 48 lines

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 19 lines · Daniel Vetter
Quoted 11 lines
Quoted 9 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the
shrinker and
postpone all hw activity until resume.

Quoted 7 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still need to
grab ttm
locks on resume.

Quoted 10 lines

Pondered this specific aspect some more, and I think you still have
a race
here (even if you avoid the deadlock): If the condiditional rpm_get
call
fails there's no guarantee that the device will suspend/resume and
clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device
is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped to
GART and the device is powered down we just skip the GART unmapping
part
because that has already implicitly happened during power down.

Quoted 7 lines
Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through
the runtime PM calls. And while powering it up again the GART is restored.

I think you're forgetting the main Xe use-case of Lunar-lake compression metadata. I'ts retained by the device during D3hot, but cannot, at that time, be accessed for shrinking.

Yeah, that is really something we don't have an equivalent for on AMD GPUs.

When the ASIC is powered down VRAM is basically dead as well because it
won't get refreshed any more.

Quoted 3 lines

And copying it all out "Just in case" when transitioning to D3hot just
isn't a viable solution.

I would say that this is solvable with a hierarchy of power management
functionality.

Quoted 6 lines

E.g. the runtime PM interface works the same for you as it does for amdgpu with evicting TTM BOs etc....

Then separate from runtime PM you have a reference count for the accessibility of compressed metadata. And while shrinking you only resume this specific part.

Well this looks like exactly what have with current hardware, or rather *current* hardware that needs to take the bo lock during runtime pm doesn't need this type of metadata access, which is currently Lunar- lake only.

So from a runtime pm deadlock point-of-view we're safe. But then we need to blit out the metadata and we get a fence to wait for, which we've been told to avoid in direct reclaim but rather is preferred from kswapd.

And I must admit I still don't get what the problem is with allowing a driver LRU loop? The fact that some AMD eviction_valuable() implementations made bad decisions by far doesn't weigh up for the loss of flexibility IMO.

/Thomas

Quoted 7 lines

Christian.

Quoted 3 lines

/Thomas

#37 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Christian König
Quoted 23 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 7 lines · Daniel Vetter
Quoted 6 lines · Christian König
Quoted 5 lines

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

Quoted 7 lines
Quoted 3 lines

Not good enough, at least long term I think. Also postponing hw activity to resume doesn't solve the deadlock issue, if you still need to grab ttm locks on resume.

Pondered this specific aspect some more, and I think you still have a race here (even if you avoid the deadlock): If the condiditional rpm_get call fails there's no guarantee that the device will suspend/resume and clean up the GART mapping.

Well I think we have a major disconnect here. When the device is powered down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is powered down this table is completely destroyed. Any BO which was mapped inside this table is now not mapped any more.

Quoted 6 lines

So when the shrinker wants to evict a BO which is marked as mapped to GART and the device is powered down we just skip the GART unmapping part because that has already implicitly happened during power down.

Before mapping any BO into the GART again we power the GPU up through the runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or not, you can only tell whether there's a chance it might be powering down and so you can't get at the rpm reference without deadlock issues.

Quoted 9 lines
Quoted 3 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when resume almost finished.

What race are you talking about?

The worst thing which could happen is that we restore a GART entry which isn't needed any more, but that is pretty much irrelevant since we only clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue, tossed an object, but the device didn't suspend, so might still use it.

I guess if we're clearly separating the sw allocation of the TTM_TT with the physical entries in the GART that should all work, but feels a bit tricky. The race I've seen is essentially these two getting out of sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore side you need to get some locks to figure out which gart mappings exist and need restoring. And that's the same locks as the shrinker needs to figure out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly as-is, so that there's no shared locks?

Quoted 7 lines
Quoted 4 lines

That means we'll have ttm bo hanging around with GART allocations/mappings which aren't actually valid anymore (since they might escape the cleanup upon resume due to the race). That doesn't feel like a solid design either.

I'm most likely missing something, but I'm really scratching my head where you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have nested runtime pm within dma_resv lock. And dgpu drivers the other way round. Which is a bit awkward if you're trying for common code.

Cheers, Sima

Signature · 3 lines
Simona Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
#38 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

(Note I forgot to remove the export of the previous LRU walker).

so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting the LRU loop early.

So remaining is the question whether the driver is allowed to discard a suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.
2) Devices who need the blitter during shrinking would want to punt runtime_pm_get() to kswapd to avoid sleeping direct reclaim.
3) If those devices end up blitting (LNL) to be able to shrink, they would want to punt waiting for the fence to signal to kswapd to avoid waiting in direct reclaim.
4) It looks like we need to resort to folio_trylock in the shmem backup backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Arguments against:
None really. I thought the idea of demidlayering would be to allow the driver more freedom.

So any feedback appreciated. If that is found acceptable we can proceed with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 109 lines · Daniel Vetter
Quoted 40 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 15 lines · Daniel Vetter
Quoted 6 lines
Quoted 4 lines · Christian König

Completely agree that this is complicated, but I still don't see the need
for it.

Quoted 8 lines
Quoted 3 lines

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped to GART
and the device is powered down we just skip the GART unmapping part because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or not,
you can only tell whether there's a chance it might be powering down and
so you can't get at the rpm reference without deadlock issues.

Quoted 5 lines
Quoted 4 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when
resume almost finished.

Quoted 7 lines

What race are you talking about?

The worst thing which could happen is that we restore a GART entry which
isn't needed any more, but that is pretty much irrelevant since we only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue, tossed an object, but the device didn't suspend, so might still use it.

I guess if we're clearly separating the sw allocation of the TTM_TT with
the physical entries in the GART that should all work, but feels a bit
tricky. The race I've seen is essentially these two getting out of sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore side
you need to get some locks to figure out which gart mappings exist and
need restoring. And that's the same locks as the shrinker needs to figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly as-is,
so that there's no shared locks?

Quoted 11 lines
Quoted 7 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape the cleanup
upon resume due to the race). That doesn't feel like a solid design
either.

I'm most likely missing something, but I'm really scratching my head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

#39 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Hi, Christian,

Ping? Can i get an ack to proceed with this?

Thanks,
Thomas

Quoted 165 lines · Thomas Hellström

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

(Note I forgot to remove the export of the previous LRU walker).

 so the midlayer argument is now not an issue anymore. The cleanup.h guard provides some additional protection against drivers exiting the LRU loop early.

So remaining is the question whether the driver is allowed to discard a
suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.
2) Devices who need the blitter during shrinking would want to punt runtime_pm_get() to kswapd to avoid sleeping direct reclaim.
3) If those devices end up blitting (LNL) to be able to shrink, they would want to punt waiting for the fence to signal to kswapd to avoid waiting in direct reclaim.
4) It looks like we need to resort to folio_trylock in the shmem backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Arguments against:
None really. I thought the idea of demidlayering would be to allow the
driver more freedom.

So any feedback appreciated. If that is found acceptable we can proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 119 lines · Daniel Vetter
Quoted 44 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 17 lines · Daniel Vetter
Quoted 10 lines
Quoted 8 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Quoted 6 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped
to GART
and the device is powered down we just skip the GART unmapping part
because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or
not,
you can only tell whether there's a chance it might be powering down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 7 lines
Quoted 4 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when
resume almost finished.

What race are you talking about?

Quoted 7 lines

The worst thing which could happen is that we restore a GART entry
which
isn't needed any more, but that is pretty much irrelevant since we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue,
tossed an object, but the device didn't suspend, so might still use it.

I guess if we're clearly separating the sw allocation of the TTM_TT with
the physical entries in the GART that should all work, but feels a bit
tricky. The race I've seen is essentially these two getting out of sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore side
you need to get some locks to figure out which gart mappings exist and
need restoring. And that's the same locks as the shrinker needs to figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly as-is,
so that there's no shared locks?

Quoted 9 lines
Quoted 8 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape the
cleanup
upon resume due to the race). That doesn't feel like a solid design
either.

Quoted 3 lines

I'm most likely missing something, but I'm really scratching my head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

maintainer
#40 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Ah, yes sorry totally forgotten about that.

Give me till Friday to swap everything back into my head again.

Christian.

Am 02.10.24 um 13:30 schrieb Thomas Hellström:

Quoted 168 lines

Hi, Christian,

Ping? Can i get an ack to proceed with this?

Thanks,
Thomas

Quoted 158 lines · Thomas Hellström

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

(Note I forgot to remove the export of the previous LRU walker).

 so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting the LRU loop early.

So remaining is the question whether the driver is allowed to discard a
suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.
2) Devices who need the blitter during shrinking would want to punt runtime_pm_get() to kswapd to avoid sleeping direct reclaim.
3) If those devices end up blitting (LNL) to be able to shrink, they would want to punt waiting for the fence to signal to kswapd to avoid waiting in direct reclaim.
4) It looks like we need to resort to folio_trylock in the shmem backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Arguments against:
None really. I thought the idea of demidlayering would be to allow the
driver more freedom.

So any feedback appreciated. If that is found acceptable we can proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 113 lines · Daniel Vetter
Quoted 43 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 17 lines · Daniel Vetter
Quoted 10 lines
Quoted 8 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Quoted 6 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped
to GART
and the device is powered down we just skip the GART unmapping part
because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or
not,
you can only tell whether there's a chance it might be powering down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 6 lines
Quoted 4 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when
resume almost finished.

What race are you talking about?

Quoted 7 lines

The worst thing which could happen is that we restore a GART entry
which
isn't needed any more, but that is pretty much irrelevant since we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue,
tossed an object, but the device didn't suspend, so might still use it.

I guess if we're clearly separating the sw allocation of the TTM_TT with
the physical entries in the GART that should all work, but feels a bit
tricky. The race I've seen is essentially these two getting out of sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore side
you need to get some locks to figure out which gart mappings exist and
need restoring. And that's the same locks as the shrinker needs to figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly as-is,
so that there's no shared locks?

Quoted 11 lines
Quoted 8 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape the
cleanup
upon resume due to the race). That doesn't feel like a solid design
either.

I'm most likely missing something, but I'm really scratching my head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

#41 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Hi

Quoted 5 lines · Christian König

Ah, yes sorry totally forgotten about that.

Give me till Friday to swap everything back into my head again.

Christian.

Thanks!

Once we agree on a direction MBrost is ready to do an in-depth review.

/Thomas

Quoted 205 lines

Am 02.10.24 um 13:30 schrieb Thomas Hellström:

Quoted 202 lines

Hi, Christian,

Ping? Can i get an ack to proceed with this?

Thanks,
Thomas

Quoted 192 lines · Thomas Hellström

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro
instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

(Note I forgot to remove the export of the previous LRU walker).

  so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting the
LRU loop early.

So remaining is the question whether the driver is allowed to discard
a
suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.
2) Devices who need the blitter during shrinking would want to punt
runtime_pm_get() to kswapd to avoid sleeping direct reclaim.
3) If those devices end up blitting (LNL) to be able to shrink, they
would want to punt waiting for the fence to signal to kswapd to avoid
waiting in direct reclaim.
4) It looks like we need to resort to folio_trylock in the shmem backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Arguments against:
None really. I thought the idea of demidlayering would be to allow
the
driver more freedom.

So any feedback appreciated. If that is found acceptable we can proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 139 lines · Daniel Vetter
Quoted 53 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 21 lines
Quoted 11 lines · Daniel Vetter
Quoted 9 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside
the shrinker and
postpone all hw activity until resume.

Quoted 8 lines

Not good enough, at least long term I think. Also postponing
hw
activity
to resume doesn't solve the deadlock issue, if you still need
to grab ttm
locks on resume.

Quoted 9 lines

Pondered this specific aspect some more, and I think you still
have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume
and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is
powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the
device is
powered down this table is completely destroyed. Any BO which was
mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped
to GART
and the device is powered down we just skip the GART unmapping
part
because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down
or
not,
you can only tell whether there's a chance it might be powering down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 7 lines
Quoted 5 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it
right when
resume almost finished.

What race are you talking about?

Quoted 8 lines

The worst thing which could happen is that we restore a GART entry
which
isn't needed any more, but that is pretty much irrelevant since
we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue,
tossed an object, but the device didn't suspend, so might still use
it.

I guess if we're clearly separating the sw allocation of the TTM_TT
with
the physical entries in the GART that should all work, but feels a
bit
tricky. The race I've seen is essentially these two getting out of
sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore
side
you need to get some locks to figure out which gart mappings exist
and
need restoring. And that's the same locks as the shrinker needs to
figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly
as-is,
so that there's no shared locks?

Quoted 10 lines
Quoted 10 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape
the
cleanup
upon resume due to the race). That doesn't feel like a solid
design
either.

Quoted 4 lines

I'm most likely missing something, but I'm really scratching my
head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have
nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

maintainer
#42 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Thomas Hellström

Hi Thomas,

I'm on sick leave, but I will try to answer questions and share some thoughts on this to unblock you.

Am 18.09.24 um 14:57 schrieb Thomas Hellström:

Quoted 6 lines

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

Yeah that looks like a big step in the right direction.

Quoted 6 lines

(Note I forgot to remove the export of the previous LRU walker).

so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting the LRU loop early.

Quoted 7 lines

So remaining is the question whether the driver is allowed to discard a suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.

I think that is actually not correct. TTM already knows about purgeable objects.

E.g. when TTM asks the driver what to do with evicted objects it is perfectly valid to return an empty placement list indicating that the backing store can just be thrown away.

We use this for things like temporary buffers for example.

That this doesn't apply to swapping looks like a design bug in the driver/TTM interface to me.

Quoted 2 lines

2) Devices who need the blitter during shrinking would want to punt runtime_pm_get() to kswapd to avoid sleeping direct reclaim.

I think the outcome of the discussion is that runtime PM should never be mixed into TTM swapping.

You can power up blocks to enable a HW blitter for swapping, but this then can't be driven by the runtime PM framework.

Quoted 3 lines

3) If those devices end up blitting (LNL) to be able to shrink, they would want to punt waiting for the fence to signal to kswapd to avoid waiting in direct reclaim.

Mhm, what do you mean with that?

Quoted 3 lines

4) It looks like we need to resort to folio_trylock in the shmem backup backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Why would a folio trylock succeed with one BO and not another?

And why would that trylock something the device specific driver should handle?

Quoted 3 lines

Arguments against:
None really. I thought the idea of demidlayering would be to allow the driver more freedom.

Well that is a huge argument against it. Giving drivers more freedom is absolutely not something which turned out to be valuable in the past.

Instead we should put device drivers in a very strict corset of validated approaches to do things.

Background is that in my experience driver developers are perfectly willing to do unclean approaches which only work in like 99% of all cases just to get a bit more performance or simpler driver implementation.

Those approaches are not legal and in my opinion as subsystem maintainer I think we need to be more strict and push back much harder on stuff like that.

Regards,
Christian.

Quoted 112 lines

So any feedback appreciated. If that is found acceptable we can proceed with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 103 lines · Daniel Vetter
Quoted 39 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 15 lines · Daniel Vetter
Quoted 6 lines
Quoted 4 lines · Christian König

Completely agree that this is complicated, but I still don't see the need
for it.

Quoted 8 lines
Quoted 3 lines

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and
postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity
to resume doesn't solve the deadlock issue, if you still need to grab ttm
locks on resume.

Quoted 7 lines

Pondered this specific aspect some more, and I think you still have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped to GART
and the device is powered down we just skip the GART unmapping part because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or not,
you can only tell whether there's a chance it might be powering down and
so you can't get at the rpm reference without deadlock issues.

Quoted 11 lines
Quoted 4 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when
resume almost finished.

What race are you talking about?

The worst thing which could happen is that we restore a GART entry which
isn't needed any more, but that is pretty much irrelevant since we only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue, tossed an object, but the device didn't suspend, so might still use it.

I guess if we're clearly separating the sw allocation of the TTM_TT with
the physical entries in the GART that should all work, but feels a bit
tricky. The race I've seen is essentially these two getting out of sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore side
you need to get some locks to figure out which gart mappings exist and
need restoring. And that's the same locks as the shrinker needs to figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly as-is,
so that there's no shared locks?

Quoted 10 lines
Quoted 7 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape the cleanup
upon resume due to the race). That doesn't feel like a solid design
either.

I'm most likely missing something, but I'm really scratching my head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

#43 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 36 lines · Christian König

Hi Thomas,

I'm on sick leave, but I will try to answer questions and share some thoughts on this to unblock you.

Am 18.09.24 um 14:57 schrieb Thomas Hellström:

Quoted 6 lines

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

Yeah that looks like a big step in the right direction.

Quoted 8 lines

(Note I forgot to remove the export of the previous LRU walker).

  so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting the
LRU loop early.

Quoted 8 lines

So remaining is the question whether the driver is allowed to discard a
suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.

I think that is actually not correct. TTM already knows about purgeable
objects.

Quoted 8 lines

E.g. when TTM asks the driver what to do with evicted objects it is perfectly valid to return an empty placement list indicating that the backing store can just be thrown away.

We use this for things like temporary buffers for example.

That this doesn't apply to swapping looks like a design bug in the driver/TTM interface to me.

Yes we can do that with TTM, but for shrinking there's no point in trying to shrink when there is no swap-space left, other than purgeable object. The number of shrinkable objects returned in shrinker::count needs to reflect that, and *then* only those objects should be selected for shrinking. If we were to announce that to TTM using a callback, we're actually back to version 1 of this series which was rejected by you exactly since it was using callbacks a year or so ago????

Quoted 10 lines
Quoted 3 lines

2) Devices who need the blitter during shrinking would want to punt runtime_pm_get() to kswapd to avoid sleeping direct reclaim.

I think the outcome of the discussion is that runtime PM should never be
mixed into TTM swapping.

You can power up blocks to enable a HW blitter for swapping, but this then can't be driven by the runtime PM framework.

Still that power-on might be sleeping, so what's the difference using runtime-pm or not? Why should the driver implement yet another power interface, just because TTM refuses to publish a sane LRU walk interface?

Quoted 8 lines
Quoted 6 lines

3) If those devices end up blitting (LNL) to be able to shrink, they
would want to punt waiting for the fence to signal to kswapd to avoid
waiting in direct reclaim.

Mhm, what do you mean with that?

When we fired the blitter from direct reclaim, we get a fence. If we wait for it in direct reclaim we will be sleeping waiting for gpu, which is bad form. We'd like return a failure so the object is retried when idle, or from kswapd.

Quoted 8 lines
Quoted 6 lines

4) It looks like we need to resort to folio_trylock in the shmem backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Why would a folio trylock succeed with one BO and not another?

Good point. We'd fail anyway but would perhaps need to call SHRINK_STOP..

Quoted 4 lines

And why would that trylock something the device specific driver should
handle?

It happens in the TTM shrinker helper called from the driver in the spirit of demidlayering.

Quoted 9 lines
Quoted 5 lines

Arguments against:
None really. I thought the idea of demidlayering would be to allow the
driver more freedom.

Well that is a huge argument against it. Giving drivers more freedom is
absolutely not something which turned out to be valuable in the past.

So then what's the point of demidlayering?

Quoted 9 lines

Instead we should put device drivers in a very strict corset of validated approaches to do things.

Background is that in my experience driver developers are perfectly willing to do unclean approaches which only work in like 99% of all cases just to get a bit more performance or simpler driver implementation.

Quoted 4 lines

Those approaches are not legal and in my opinion as subsystem maintainer
I think we need to be more strict and push back much harder on stuff like that.

Still, historically that has made developers abandon common components for driver-specific solutions.

And the question is still not answered.

Exactly *why* can't the driver fail and continue traversing the LRU, because all our argumentation revolves around this and you have yet to provide an objective reason why.

/Thomas

Quoted 144 lines

Regards,
Christian.

Quoted 139 lines

So any feedback appreciated. If that is found acceptable we can proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 129 lines · Daniel Vetter
Quoted 50 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 20 lines
Quoted 11 lines · Daniel Vetter
Quoted 9 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside
the shrinker and
postpone all hw activity until resume.

Quoted 7 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still need
to grab ttm
locks on resume.

Quoted 9 lines

Pondered this specific aspect some more, and I think you still
have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume
and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is
powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the device is
powered down this table is completely destroyed. Any BO which was
mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped
to GART
and the device is powered down we just skip the GART unmapping part
because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or
not,
you can only tell whether there's a chance it might be powering down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 6 lines
Quoted 4 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it right when
resume almost finished.

What race are you talking about?

Quoted 7 lines

The worst thing which could happen is that we restore a GART entry
which
isn't needed any more, but that is pretty much irrelevant since we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue,
tossed an object, but the device didn't suspend, so might still use
it.

I guess if we're clearly separating the sw allocation of the TTM_TT
with
the physical entries in the GART that should all work, but feels a
bit
tricky. The race I've seen is essentially these two getting out of
sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore
side
you need to get some locks to figure out which gart mappings exist
and
need restoring. And that's the same locks as the shrinker needs to
figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly
as-is,
so that there's no shared locks?

Quoted 11 lines
Quoted 8 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape the
cleanup
upon resume due to the race). That doesn't feel like a solid design
either.

I'm most likely missing something, but I'm really scratching my head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have
nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

#44 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 147 lines · Thomas Hellström
Quoted 43 lines · Christian König

Hi Thomas,

I'm on sick leave, but I will try to answer questions and share some
thoughts on this to unblock you.

Am 18.09.24 um 14:57 schrieb Thomas Hellström:

Quoted 7 lines

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro
instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

Yeah that looks like a big step in the right direction.

Quoted 8 lines

(Note I forgot to remove the export of the previous LRU walker).

  so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting the
LRU loop early.

Quoted 8 lines

So remaining is the question whether the driver is allowed to discard a
suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.

I think that is actually not correct. TTM already knows about purgeable
objects.

E.g. when TTM asks the driver what to do with evicted objects it is perfectly valid to return an empty placement list indicating that the
backing store can just be thrown away.

Quoted 4 lines

We use this for things like temporary buffers for example.

That this doesn't apply to swapping looks like a design bug in the driver/TTM interface to me.

Yes we can do that with TTM, but for shrinking there's no point in trying to shrink when there is no swap-space left, other than purgeable
object. The number of shrinkable objects returned in shrinker::count needs to reflect that, and *then* only those objects should be selected
for shrinking. If we were to announce that to TTM using a callback, we're actually back to version 1 of this series which was rejected by you exactly since it was using callbacks a year or so ago????

Quoted 5 lines
Quoted 4 lines

2) Devices who need the blitter during shrinking would want to punt
runtime_pm_get() to kswapd to avoid sleeping direct reclaim.

Quoted 8 lines

I think the outcome of the discussion is that runtime PM should never
be
mixed into TTM swapping.

You can power up blocks to enable a HW blitter for swapping, but this
then can't be driven by the runtime PM framework.

Still that power-on might be sleeping, so what's the difference using runtime-pm or not? Why should the driver implement yet another power interface, just because TTM refuses to publish a sane LRU walk interface?

Quoted 8 lines
Quoted 6 lines

3) If those devices end up blitting (LNL) to be able to shrink, they
would want to punt waiting for the fence to signal to kswapd to avoid
waiting in direct reclaim.

Mhm, what do you mean with that?

When we fired the blitter from direct reclaim, we get a fence. If we wait for it in direct reclaim we will be sleeping waiting for gpu, which is bad form. We'd like return a failure so the object is retried
when idle, or from kswapd.

Quoted 8 lines
Quoted 6 lines

4) It looks like we need to resort to folio_trylock in the shmem backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Why would a folio trylock succeed with one BO and not another?

Good point. We'd fail anyway but would perhaps need to call SHRINK_STOP..

Quoted 4 lines

And why would that trylock something the device specific driver should
handle?

It happens in the TTM shrinker helper called from the driver in the spirit of demidlayering.

Quoted 7 lines
Quoted 6 lines

Arguments against:
None really. I thought the idea of demidlayering would be to allow
the
driver more freedom.

Quoted 5 lines

Well that is a huge argument against it. Giving drivers more freedom
is
absolutely not something which turned out to be valuable in the past.

So then what's the point of demidlayering?

Quoted 9 lines

Instead we should put device drivers in a very strict corset of validated approaches to do things.

Background is that in my experience driver developers are perfectly willing to do unclean approaches which only work in like 99% of all cases just to get a bit more performance or simpler driver implementation.

Quoted 5 lines

Those approaches are not legal and in my opinion as subsystem maintainer
I think we need to be more strict and push back much harder on stuff
like that.

Still, historically that has made developers abandon common components
for driver-specific solutions.

Quoted 6 lines

And the question is still not answered.

Exactly *why* can't the driver fail and continue traversing the LRU, because all our argumentation revolves around this and you have yet to
provide an objective reason why.

And in the end, while I think there definitely things worthy of discussion in this series,

I don't think there is a point in trying to land a LNL shrinker operating against a crippled TTM LRU walk interface, nor do I think anyone would want to attempt to port i915 over, and reworking it three times I'm now pretty familiar with what works and what doesn't.

So question becomes, with proper reviews can I merge the series here as is, *with* the de-midlayered LRU walk and noting your advise against it, or not?

Thanks,
Thomas

Quoted 160 lines

/Thomas

Quoted 153 lines

Regards,
Christian.

Quoted 148 lines

So any feedback appreciated. If that is found acceptable we can proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 138 lines · Daniel Vetter
Quoted 52 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 20 lines
Quoted 11 lines · Daniel Vetter
Quoted 9 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside
the shrinker and
postpone all hw activity until resume.

Quoted 7 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still need
to grab ttm
locks on resume.

Quoted 9 lines

Pondered this specific aspect some more, and I think you still
have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume
and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is
powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the
device is
powered down this table is completely destroyed. Any BO which was
mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped
to GART
and the device is powered down we just skip the GART unmapping
part
because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or
not,
you can only tell whether there's a chance it might be powering down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 7 lines
Quoted 5 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it
right when
resume almost finished.

What race are you talking about?

Quoted 8 lines

The worst thing which could happen is that we restore a GART entry
which
isn't needed any more, but that is pretty much irrelevant since
we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue,
tossed an object, but the device didn't suspend, so might still use
it.

I guess if we're clearly separating the sw allocation of the TTM_TT
with
the physical entries in the GART that should all work, but feels
a
bit
tricky. The race I've seen is essentially these two getting out of
sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore
side
you need to get some locks to figure out which gart mappings exist
and
need restoring. And that's the same locks as the shrinker needs to
figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly
as-is,
so that there's no shared locks?

Quoted 10 lines
Quoted 10 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape
the
cleanup
upon resume due to the race). That doesn't feel like a solid
design
either.

Quoted 4 lines

I'm most likely missing something, but I'm really scratching my
head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have
nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

maintainer
#45 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Am 09.10.24 um 16:17 schrieb Thomas Hellström:

Quoted 47 lines · Thomas Hellström
Quoted 46 lines · Christian König
Quoted 45 lines

Hi Thomas,

I'm on sick leave, but I will try to answer questions and share some
thoughts on this to unblock you.

Am 18.09.24 um 14:57 schrieb Thomas Hellström:

Quoted 7 lines

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro
instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

Yeah that looks like a big step in the right direction.

Quoted 8 lines

(Note I forgot to remove the export of the previous LRU walker).

  so the midlayer argument is now not an issue anymore. The
cleanup.h
guard provides some additional protection against drivers exiting the
LRU loop early.

Quoted 8 lines

So remaining is the question whether the driver is allowed to discard a
suggested bo to shrink from TTM.

Arguments for:

1) Not allowing that would require teaching TTM about purgeable objects.

I think that is actually not correct. TTM already knows about purgeable
objects.

E.g. when TTM asks the driver what to do with evicted objects it is perfectly valid to return an empty placement list indicating that the
backing store can just be thrown away.

We use this for things like temporary buffers for example.

That this doesn't apply to swapping looks like a design bug in the driver/TTM interface to me.

Quoted 9 lines
Quoted 9 lines

Yes we can do that with TTM, but for shrinking there's no point in trying to shrink when there is no swap-space left, other than purgeable
object. The number of shrinkable objects returned in shrinker::count needs to reflect that, and *then* only those objects should be selected
for shrinking. If we were to announce that to TTM using a callback, we're actually back to version 1 of this series which was rejected by you exactly since it was using callbacks a year or so ago????

Yeah that indeed doesn't sound like a good idea.

On the other hand the decision that only purgeable objects should be selected when there is no swap space left sounds like something TTM should do and not the driver.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

2) Devices who need the blitter during shrinking would want to punt
runtime_pm_get() to kswapd to avoid sleeping direct reclaim.

I think the outcome of the discussion is that runtime PM should never
be
mixed into TTM swapping.

Quoted 7 lines
Quoted 7 lines
Quoted 3 lines

You can power up blocks to enable a HW blitter for swapping, but this
then can't be driven by the runtime PM framework.

Still that power-on might be sleeping, so what's the difference using runtime-pm or not? Why should the driver implement yet another power interface, just because TTM refuses to publish a sane LRU walk interface?

See the discussion with Sima around the PM functions.

My understanding might be wrong, but I now think that with local memory you can't do the i915 approach where the PM functions are so low level that they can also be called inside the shrinker.

So you basically have PM functions for your whole device and PM functions for only the HW blocks necessary for the shrinker.

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

3) If those devices end up blitting (LNL) to be able to shrink, they
would want to punt waiting for the fence to signal to kswapd to avoid
waiting in direct reclaim.

Quoted 6 lines
Quoted 6 lines
Quoted 1 line

Mhm, what do you mean with that?

When we fired the blitter from direct reclaim, we get a fence. If we wait for it in direct reclaim we will be sleeping waiting for gpu, which is bad form. We'd like return a failure so the object is retried
when idle, or from kswapd.

Oh, that is a really good point. So basically you want to avoid dependencies on the dma_fence.

Quoted 19 lines
Quoted 19 lines
Quoted 5 lines
Quoted 4 lines

4) It looks like we need to resort to folio_trylock in the shmem backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing trylock will require a new bo.

Why would a folio trylock succeed with one BO and not another?

Good point. We'd fail anyway but would perhaps need to call SHRINK_STOP..

Quoted 3 lines

And why would that trylock something the device specific driver should
handle?

It happens in the TTM shrinker helper called from the driver in the spirit of demidlayering.

Quoted 5 lines
Quoted 5 lines

Arguments against:
None really. I thought the idea of demidlayering would be to allow
the
driver more freedom.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

Well that is a huge argument against it. Giving drivers more freedom
is
absolutely not something which turned out to be valuable in the past.

So then what's the point of demidlayering?

So that drivers can prepare the environment for TTM to work with instead of TTM asking for it.

In your case for example that means powering up HW blocks so that BOs could be moved.

Quoted 26 lines
Quoted 17 lines
Quoted 8 lines

Instead we should put device drivers in a very strict corset of validated approaches to do things.

Background is that in my experience driver developers are perfectly willing to do unclean approaches which only work in like 99% of all cases just to get a bit more performance or simpler driver implementation.

Quoted 5 lines

Those approaches are not legal and in my opinion as subsystem maintainer
I think we need to be more strict and push back much harder on stuff
like that.

Still, historically that has made developers abandon common components
for driver-specific solutions.

Quoted 6 lines

And the question is still not answered.

Exactly *why* can't the driver fail and continue traversing the LRU, because all our argumentation revolves around this and you have yet to
provide an objective reason why.

And in the end, while I think there definitely things worthy of discussion in this series,

Quoted 8 lines

I don't think there is a point in trying to land a LNL shrinker operating against a crippled TTM LRU walk interface, nor do I think anyone would want to attempt to port i915 over, and reworking it three times I'm now pretty familiar with what works and what doesn't.

So question becomes, with proper reviews can I merge the series here as is, *with* the de-midlayered LRU walk and noting your advise against it, or not?

More or less yes, I still have a bad feeling about it but we probably need to see the whole thing getting used to judge if it really works or not.

I mean it's not UAPI we are talking about, so even if we find in 5years from now that it was a bad idea we can still roll it back and try something else.

So yeah, feel free to go ahead.

Regards,
Christian.

Quoted 163 lines

Thanks,
Thomas

Quoted 155 lines

/Thomas

Quoted 150 lines

Regards,
Christian.

Quoted 147 lines

So any feedback appreciated. If that is found acceptable we can proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 138 lines · Daniel Vetter
Quoted 52 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 20 lines
Quoted 11 lines · Daniel Vetter
Quoted 9 lines · Christian König

Completely agree that this is complicated, but I still don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside
the shrinker and
postpone all hw activity until resume.

Quoted 7 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still need
to grab ttm
locks on resume.

Quoted 9 lines

Pondered this specific aspect some more, and I think you still
have a race
here (even if you avoid the deadlock): If the condiditional rpm_get call
fails there's no guarantee that the device will suspend/resume
and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device is
powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when the
device is
powered down this table is completely destroyed. Any BO which was
mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as mapped
to GART
and the device is powered down we just skip the GART unmapping
part
because
that has already implicitly happened during power down.

Quoted 4 lines

Before mapping any BO into the GART again we power the GPU up through the
runtime PM calls. And while powering it up again the GART is restored.

My point is that you can't tell whether the device will power down or
not,
you can only tell whether there's a chance it might be powering down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 7 lines
Quoted 5 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch it
right when
resume almost finished.

What race are you talking about?

Quoted 8 lines

The worst thing which could happen is that we restore a GART entry
which
isn't needed any more, but that is pretty much irrelevant since
we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not issue,
tossed an object, but the device didn't suspend, so might still use
it.

I guess if we're clearly separating the sw allocation of the TTM_TT
with
the physical entries in the GART that should all work, but feels
a
bit
tricky. The race I've seen is essentially these two getting out of
sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore
side
you need to get some locks to figure out which gart mappings exist
and
need restoring. And that's the same locks as the shrinker needs to
figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly
as-is,
so that there's no shared locks?

Quoted 10 lines
Quoted 10 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape
the
cleanup
upon resume due to the race). That doesn't feel like a solid
design
either.

Quoted 4 lines

I'm most likely missing something, but I'm really scratching my
head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers have
nested
runtime pm within dma_resv lock. And dgpu drivers the other way round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

#46 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 207 lines · Christian König

Am 09.10.24 um 16:17 schrieb Thomas Hellström:

Quoted 53 lines · Thomas Hellström
Quoted 52 lines · Christian König
Quoted 51 lines

Hi Thomas,

I'm on sick leave, but I will try to answer questions and share some
thoughts on this to unblock you.

Am 18.09.24 um 14:57 schrieb Thomas Hellström:

Quoted 7 lines

Sima, Christian

I've updated the shrinker series now with a guarded for_each macro
instead:

https://patchwork.freedesktop.org/patch/614514/?series=131815&rev=9

Yeah that looks like a big step in the right direction.

Quoted 14 lines

(Note I forgot to remove the export of the previous LRU walker).

   so the midlayer argument is now not an issue anymore. The cleanup.h
guard provides some additional protection against drivers exiting
the
LRU loop early.

So remaining is the question whether the driver is allowed to discard a
suggested bo to shrink from TTM.

Quoted 5 lines

Arguments for:

1) Not allowing that would require teaching TTM about purgeable
objects.

I think that is actually not correct. TTM already knows about purgeable
objects.

E.g. when TTM asks the driver what to do with evicted objects it is
perfectly valid to return an empty placement list indicating that
the
backing store can just be thrown away.

We use this for things like temporary buffers for example.

That this doesn't apply to swapping looks like a design bug in the
driver/TTM interface to me.

Quoted 13 lines
Quoted 5 lines

Yes we can do that with TTM, but for shrinking there's no point in
trying to shrink when there is no swap-space left, other than purgeable
object. The number of shrinkable objects returned in

Quoted 8 lines

shrinker::count
needs to reflect that, and *then* only those objects should be selected
for shrinking. If we were to announce that to TTM using a callback,
we're actually back to version 1 of this series which was rejected by
you exactly since it was using callbacks a year or so ago????

Yeah that indeed doesn't sound like a good idea.

On the other hand the decision that only purgeable objects should be selected when there is no swap space left sounds like something TTM should do and not the driver.

Quoted 13 lines
Quoted 13 lines
Quoted 13 lines
Quoted 4 lines

2) Devices who need the blitter during shrinking would want to
punt
runtime_pm_get() to kswapd to avoid sleeping direct reclaim.

I think the outcome of the discussion is that runtime PM should never
be
mixed into TTM swapping.

You can power up blocks to enable a HW blitter for swapping, but
this
then can't be driven by the runtime PM framework.

Quoted 6 lines
Quoted 6 lines

Still that power-on might be sleeping, so what's the difference using
runtime-pm or not? Why should the driver implement yet another power
interface, just because TTM refuses to publish a sane LRU walk interface?

See the discussion with Sima around the PM functions.

My understanding might be wrong, but I now think that with local memory
you can't do the i915 approach where the PM functions are so low level
that they can also be called inside the shrinker.

So you basically have PM functions for your whole device and PM functions for only the HW blocks necessary for the shrinker.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

3) If those devices end up blitting (LNL) to be able to shrink,
they
would want to punt waiting for the fence to signal to kswapd to
avoid
waiting in direct reclaim.

Quoted 8 lines
Quoted 8 lines
Quoted 1 line

Mhm, what do you mean with that?

When we fired the blitter from direct reclaim, we get a fence. If we
wait for it in direct reclaim we will be sleeping waiting for gpu,
which is bad form. We'd like return a failure so the object is retried
when idle, or from kswapd.

Oh, that is a really good point. So basically you want to avoid dependencies on the dma_fence.

Quoted 22 lines
Quoted 22 lines
Quoted 7 lines
Quoted 6 lines

4) It looks like we need to resort to folio_trylock in the shmem
backup
backend when shrinking is called for gfp_t = GFP_NOFS. A failing
trylock will require a new bo.

Why would a folio trylock succeed with one BO and not another?

Good point. We'd fail anyway but would perhaps need to call SHRINK_STOP..

Quoted 3 lines

And why would that trylock something the device specific driver should
handle?

It happens in the TTM shrinker helper called from the driver in the
spirit of demidlayering.

Quoted 5 lines
Quoted 5 lines

Arguments against:
None really. I thought the idea of demidlayering would be to allow
the
driver more freedom.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

Well that is a huge argument against it. Giving drivers more freedom
is
absolutely not something which turned out to be valuable in the past.

So then what's the point of demidlayering?

So that drivers can prepare the environment for TTM to work with instead
of TTM asking for it.

In your case for example that means powering up HW blocks so that BOs could be moved.

Quoted 36 lines
Quoted 19 lines
Quoted 10 lines

Instead we should put device drivers in a very strict corset of validated approaches to do things.

Background is that in my experience driver developers are perfectly
willing to do unclean approaches which only work in like 99% of all
cases just to get a bit more performance or simpler driver implementation.

Quoted 5 lines

Those approaches are not legal and in my opinion as subsystem maintainer
I think we need to be more strict and push back much harder on stuff
like that.

Still, historically that has made developers abandon common components
for driver-specific solutions.

Quoted 8 lines

And the question is still not answered.

Exactly *why* can't the driver fail and continue traversing the LRU,
because all our argumentation revolves around this and you have yet
to
provide an objective reason why.

And in the end, while I think there definitely things worthy of discussion in this series,

I don't think there is a point in trying to land a LNL shrinker operating against a crippled TTM LRU walk interface, nor do I think anyone would want to attempt to port i915 over, and reworking it three
times I'm now pretty familiar with what works and what doesn't.

Quoted 5 lines

So question becomes, with proper reviews can I merge the series here as
is, *with* the de-midlayered LRU walk and noting your advise against
it, or not?

More or less yes, I still have a bad feeling about it but we probably need to see the whole thing getting used to judge if it really works or not.

Quoted 6 lines

I mean it's not UAPI we are talking about, so even if we find in 5years
from now that it was a bad idea we can still roll it back and try something else.

So yeah, feel free to go ahead.

Thanks, I'll respin a version moving the checks you pointed out, (get_nr_swap_pages() + all other checks TTM can really do) etc, into TTM helpers to simplify such a change in the future if it becomes needed.

/Thomas

Quoted 194 lines

Regards,
Christian.

Quoted 189 lines

Thanks,
Thomas

Quoted 181 lines

/Thomas

Quoted 176 lines

Regards,
Christian.

Quoted 173 lines

So any feedback appreciated. If that is found acceptable we can
proceed
with reviewing this patch and also with the shrinker series.

Thanks,
Thomas

Quoted 163 lines · Daniel Vetter
Quoted 61 lines · Christian König

Am 27.08.24 um 19:53 schrieb Daniel Vetter:

Quoted 23 lines
Quoted 13 lines · Daniel Vetter
Quoted 10 lines · Christian König

Completely agree that this is complicated, but I
still
don't
see the need
for it.

Drivers just need to use pm_runtime_get_if_in_use() inside
the shrinker and
postpone all hw activity until resume.

Quoted 8 lines

Not good enough, at least long term I think. Also postponing hw
activity
to resume doesn't solve the deadlock issue, if you still
need
to grab ttm
locks on resume.

Quoted 11 lines

Pondered this specific aspect some more, and I think you
still
have a race
here (even if you avoid the deadlock): If the condiditional
rpm_get call
fails there's no guarantee that the device will suspend/resume
and clean
up the GART mapping.

Well I think we have a major disconnect here. When the device
is
powered
down there is no GART mapping to clean up any more.

In other words GART is a table in local memory (VRAM) when
the
device is
powered down this table is completely destroyed. Any BO which
was
mapped
inside this table is now not mapped any more.

So when the shrinker wants to evict a BO which is marked as
mapped
to GART
and the device is powered down we just skip the GART unmapping
part
because
that has already implicitly happened during power down.

Quoted 6 lines

Before mapping any BO into the GART again we power the GPU up
through the
runtime PM calls. And while powering it up again the GART is
restored.

My point is that you can't tell whether the device will power
down or
not,
you can only tell whether there's a chance it might be powering
down
and
so you can't get at the rpm reference without deadlock issues.

Quoted 8 lines
Quoted 6 lines

The race gets a bit smaller if you use pm_runtime_get_if_active(), but even then you might catch
it
right when
resume almost finished.

What race are you talking about?

Quoted 9 lines

The worst thing which could happen is that we restore a GART
entry
which
isn't needed any more, but that is pretty much irrelevant since
we
only
clear them to avoid some hw bugs.

The race I'm seeing is where you thought the GART entry is not
issue,
tossed an object, but the device didn't suspend, so might still
use
it.

I guess if we're clearly separating the sw allocation of the
TTM_TT
with
the physical entries in the GART that should all work, but feels
a
bit
tricky. The race I've seen is essentially these two getting out
of
sync.

So maybe it was me who's stuck.

What I wonder is whether it works in practice, since on the restore
side
you need to get some locks to figure out which gart mappings
exist
and
need restoring. And that's the same locks as the shrinker needs
to
figure
out whether it might need to reap a gart mapping.

Or do you just copy the gart entries over and restore them exactly
as-is,
so that there's no shared locks?

Quoted 10 lines
Quoted 10 lines

That means we'll have ttm bo hanging around with GART allocations/mappings
which aren't actually valid anymore (since they might escape
the
cleanup
upon resume due to the race). That doesn't feel like a solid
design
either.

Quoted 5 lines

I'm most likely missing something, but I'm really
scratching
my
head where
you see a problem here.

I guess one issue is that at least traditionally, igfx drivers
have
nested
runtime pm within dma_resv lock. And dgpu drivers the other way
round.
Which is a bit awkward if you're trying for common code.

Cheers, Sima

#47 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Daniel Vetter
Quoted 72 lines · Daniel Vetter

[machine died, new one working now, I can read complicated mails again an answer.]

Quoted 40 lines · Christian König

Am 22.08.24 um 11:23 schrieb Daniel Vetter:

Quoted 9 lines · Christian König
Quoted 7 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 4 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them because the device is powered down?

Yes. amdgpu does the same btw :-)

Well, amdgpu wouldn't block shrinking as far as I know.

When the GPU is powered down all fences are signaled and things like GART unbinding is just postponed until the GPU wakes up again.

Quoted 12 lines

It's a fairly fundamental issue of rpm on discrete gpus, or anything that looks a lot like a discrete gpu. The deadlock scenario is roughly:

- In runtime suspend you need to copy any bo out of vram into system ram before you power the gpu. This requires bo and ttm locks.

- You can't just avoid this by holding an rpm reference as long as any bo is still in vram, because that defacto means you'll never autosuspend at runtime. Plus most real hw is complex enough that you have some driver objects that you need to throw out or recreate, so in practice no way to avoid all this.

Quoted 8 lines

- runtime resume tends to be easier and mostly doable without taking bo and ttm locks, because by design you know no one else can possibly have any need to get at the gpu hw - it was all powered off after all. It's still messy, but doable.

- Unfortunately this doesn't help, because your runtime resume might need to wait for a in-progress suspend operation to complete. Which means you still deadlock even if your resume path has entirely reasonable locking.

Uff, yeah that totally confirms my gut feeling that this looked really questionable.

Quoted 8 lines
Quoted 5 lines

On integrated you can mostly avoid this all because there's no need to swap out bo to system memory, they're there already. Exceptions like the busted coherency stuff on LNL aside.

But on discrete it's just suck.

Mhm, I never worked with pure integrated devices but at least radeon, amdgpu and nouveau seems to have a solution which would work as far as I can tell.

Yeah integrated is easy (if you don't do silly stuff like intel on their latest).

Quoted 2 lines

Basically on suspend you make sure that everything necessary for shrinking is done, e.g. waiting for fences, evacuating VRAM etc...

This is the hard part, or the "evacuating VRAM" part at least. My proposal is that essentially the runtime_suspend_prepare hook does that. Imo the clean design is that we wait for rpm autosuspend, and only then start to evacuate VRAM. Otherwise you need to hold a rpm reference if there's anything in VRAM, which kinda defeats the point of runtime pm ...

Or you have your own runtime pm refcount that tracks whether anyone uses the gpu, and if that drops to 0 for long enough you evacuate VRAM, and then drop the rpm reference. Which is just implementing the idea I've typed up, except hand-rolled in driver code and with a rpm refcount that's entirely driver internal.

Quoted 3 lines

And at least last time I checked, amdgpu does the VRAM evacuation in the runtime pm suspend callback, which is why all your runtime_pm_get calls are outside of the big bo/ttm locks.

It used to do the eviction in the runtime_suspend callback, but we ran into problems where eviction would sometimes fail if there was too much memory pressure during suspend. Moving it to prepare made things fail earlier. Ultimately, I think the problem is that runtime pm disables swap during runtime pm. See:
https://gitlab.freedesktop.org/drm/amd/-/issues/2362#note_2111666

Alex

Quoted 96 lines
Quoted 3 lines

Hardware specific updates like GART while the device is suspended are postponed until resume.

Yeah GART shouldn't be the issue, except when you're racing.

Quoted 21 lines
Quoted 3 lines

TTM discrete gpu drivers avoided all that by simply not having a shrinker where you need to runtime pm get, instead all runtime pm gets are outmost, without holding any ttm or bo locks.

Yes, exactly that.

Quoted 7 lines
Quoted 7 lines

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of time.

In other words an application can allocate memory, map it into GGTT and then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

Quoted 7 lines
Quoted 1 line

That really sounds like a bug in the driver design to me.

It's a bug in the runtime pm core imo. I think interim what Thomas laid out is the best solution, since in practice when the gpu is off you really shouldn't need to wake it up. Except when you're unlucky and racing a runtime suspend against a shrinker activity (like runtime suspend throws a bo into system memory, and the shrinker then immediately wants to swap it out).

Quoted 4 lines

Mhm, why exactly is that problematic?

Wouldn't pm_runtime_get_if_in_use() just return 0 in this situation and we postpone any hw activity?

So when you're runtime suspend, you need to evacuate VRAM. Which means potentially a lot needs to be moved into system memory. Which means it's likely the shrinker gets active. Also, it's the point where pm_runtime_get_if_in_use() will consistently fail, so right when you need the shrinker to be reliable it will fail the most.

Quoted 35 lines
Quoted 35 lines

I've been pondering this mess for a few months, and I think I have a solution. But it's a lot of work in core pm code unfortunately:

I think we need to split the runtime_suspend callback into two halfes:

->runtime_suspend_prepare

This would be run by the rpm core code from a worker without holding any locks at all. Also, any runtime_pm_get call will not wait on this prepare callback to finish, so it's up to the driver to make sure all the locking is there. Synchronous suspend calls obviously have to wait for this to finish, but that should only happen during system suspend or driver unload, where we don't have these deadlock issues.

Drivers can use this callback for any non-destructive prep work (non-destructive aside from the copy engine time wasted if it fails) like swapping bo from vram to system memory. Drivers must not actually shut down the hardware because a runtime_pm_get call must succeed without waiting for this callback to finish.

If any runtime_pm_get call happens while the suspend attempt will be aborted without further action.

->runtime_suspend

This does the actual hw power-off. The power core must guarantee that the ->runtime_suspend_prepare has successfully completed at least once without the rpm refcount being elevated from 0 to 1 again.

This way drivers can assume that all bo have been swapped out from vram already, and there's no need to acquire bo or ttm locks in the suspend path that could block the resume path.

Which would then allow unconditional runtime_pm_get in the shrinker paths.

Quoted 8 lines
Quoted 2 lines

Unfortunately this will be all really tricky to implement and I think needs to be done in the rumtime pm core.

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity to resume doesn't solve the deadlock issue, if you still need to grab ttm locks on resume.

Quoted 1 line

At least for amdgpu that shouldn't be a problem at all.

Yeah, because atm amdgpu has the rpm_get calls outside of ttm locks, which is exactly the inversion you've complained about as being broken driver design.
-Sima
--
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch

#48 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

Quoted 77 lines · Alex Deucher
Quoted 72 lines · Daniel Vetter

[machine died, new one working now, I can read complicated mails again an answer.]

Quoted 40 lines · Christian König

Am 22.08.24 um 11:23 schrieb Daniel Vetter:

Quoted 9 lines · Christian König
Quoted 7 lines

Am 20.08.24 um 18:00 schrieb Thomas Hellström:

Quoted 4 lines
Quoted 1 line

Or why exactly should shrinking fail?

A common example would be not having runtime pm and the particular bo needs it to unbind, we want to try the next bo. Example: i915 GGTT bound bos and Lunar Lake PL_TT bos.

WHAT? So you basically block shrinking BOs because you can't unbind them because the device is powered down?

Yes. amdgpu does the same btw :-)

Well, amdgpu wouldn't block shrinking as far as I know.

When the GPU is powered down all fences are signaled and things like GART unbinding is just postponed until the GPU wakes up again.

Quoted 12 lines

It's a fairly fundamental issue of rpm on discrete gpus, or anything that looks a lot like a discrete gpu. The deadlock scenario is roughly:

- In runtime suspend you need to copy any bo out of vram into system ram before you power the gpu. This requires bo and ttm locks.

- You can't just avoid this by holding an rpm reference as long as any bo is still in vram, because that defacto means you'll never autosuspend at runtime. Plus most real hw is complex enough that you have some driver objects that you need to throw out or recreate, so in practice no way to avoid all this.

Quoted 8 lines

- runtime resume tends to be easier and mostly doable without taking bo and ttm locks, because by design you know no one else can possibly have any need to get at the gpu hw - it was all powered off after all. It's still messy, but doable.

- Unfortunately this doesn't help, because your runtime resume might need to wait for a in-progress suspend operation to complete. Which means you still deadlock even if your resume path has entirely reasonable locking.

Uff, yeah that totally confirms my gut feeling that this looked really questionable.

Quoted 8 lines
Quoted 5 lines

On integrated you can mostly avoid this all because there's no need to swap out bo to system memory, they're there already. Exceptions like the busted coherency stuff on LNL aside.

But on discrete it's just suck.

Mhm, I never worked with pure integrated devices but at least radeon, amdgpu and nouveau seems to have a solution which would work as far as I can tell.

Yeah integrated is easy (if you don't do silly stuff like intel on their latest).

Quoted 2 lines

Basically on suspend you make sure that everything necessary for shrinking is done, e.g. waiting for fences, evacuating VRAM etc...

This is the hard part, or the "evacuating VRAM" part at least. My proposal is that essentially the runtime_suspend_prepare hook does that. Imo the clean design is that we wait for rpm autosuspend, and only then start to evacuate VRAM. Otherwise you need to hold a rpm reference if there's anything in VRAM, which kinda defeats the point of runtime pm ...

Or you have your own runtime pm refcount that tracks whether anyone uses the gpu, and if that drops to 0 for long enough you evacuate VRAM, and then drop the rpm reference. Which is just implementing the idea I've typed up, except hand-rolled in driver code and with a rpm refcount that's entirely driver internal.

Quoted 3 lines

And at least last time I checked, amdgpu does the VRAM evacuation in the runtime pm suspend callback, which is why all your runtime_pm_get calls are outside of the big bo/ttm locks.

Quoted 6 lines

It used to do the eviction in the runtime_suspend callback, but we ran into problems where eviction would sometimes fail if there was too much memory pressure during suspend. Moving it to prepare made things fail earlier. Ultimately, I think the problem is that runtime pm disables swap during runtime pm. See:
https://gitlab.freedesktop.org/drm/amd/-/issues/2362#note_2111666

That's system suspend/resume, where you have a prepare callback. At least as far as I know, for runtime pm this doesn't exist.
-Sima

Quoted 99 lines

Alex

Quoted 96 lines
Quoted 3 lines

Hardware specific updates like GART while the device is suspended are postponed until resume.

Yeah GART shouldn't be the issue, except when you're racing.

Quoted 21 lines
Quoted 3 lines

TTM discrete gpu drivers avoided all that by simply not having a shrinker where you need to runtime pm get, instead all runtime pm gets are outmost, without holding any ttm or bo locks.

Yes, exactly that.

Quoted 7 lines
Quoted 7 lines

I would say that this is a serious NO-GO. It basically means that powered down devices can lock down system memory for undefined amount of time.

In other words an application can allocate memory, map it into GGTT and then suspend or even get killed and we are not able to recover the memory because there is no activity on the GPU any more?

Quoted 7 lines
Quoted 1 line

That really sounds like a bug in the driver design to me.

It's a bug in the runtime pm core imo. I think interim what Thomas laid out is the best solution, since in practice when the gpu is off you really shouldn't need to wake it up. Except when you're unlucky and racing a runtime suspend against a shrinker activity (like runtime suspend throws a bo into system memory, and the shrinker then immediately wants to swap it out).

Quoted 4 lines

Mhm, why exactly is that problematic?

Wouldn't pm_runtime_get_if_in_use() just return 0 in this situation and we postpone any hw activity?

So when you're runtime suspend, you need to evacuate VRAM. Which means potentially a lot needs to be moved into system memory. Which means it's likely the shrinker gets active. Also, it's the point where pm_runtime_get_if_in_use() will consistently fail, so right when you need the shrinker to be reliable it will fail the most.

Quoted 35 lines
Quoted 35 lines

I've been pondering this mess for a few months, and I think I have a solution. But it's a lot of work in core pm code unfortunately:

I think we need to split the runtime_suspend callback into two halfes:

->runtime_suspend_prepare

This would be run by the rpm core code from a worker without holding any locks at all. Also, any runtime_pm_get call will not wait on this prepare callback to finish, so it's up to the driver to make sure all the locking is there. Synchronous suspend calls obviously have to wait for this to finish, but that should only happen during system suspend or driver unload, where we don't have these deadlock issues.

Drivers can use this callback for any non-destructive prep work (non-destructive aside from the copy engine time wasted if it fails) like swapping bo from vram to system memory. Drivers must not actually shut down the hardware because a runtime_pm_get call must succeed without waiting for this callback to finish.

If any runtime_pm_get call happens while the suspend attempt will be aborted without further action.

->runtime_suspend

This does the actual hw power-off. The power core must guarantee that the ->runtime_suspend_prepare has successfully completed at least once without the rpm refcount being elevated from 0 to 1 again.

This way drivers can assume that all bo have been swapped out from vram already, and there's no need to acquire bo or ttm locks in the suspend path that could block the resume path.

Which would then allow unconditional runtime_pm_get in the shrinker paths.

Quoted 8 lines
Quoted 2 lines

Unfortunately this will be all really tricky to implement and I think needs to be done in the rumtime pm core.

Completely agree that this is complicated, but I still don't see the need for it.

Drivers just need to use pm_runtime_get_if_in_use() inside the shrinker and postpone all hw activity until resume.

Not good enough, at least long term I think. Also postponing hw activity to resume doesn't solve the deadlock issue, if you still need to grab ttm locks on resume.

Quoted 1 line

At least for amdgpu that shouldn't be a problem at all.

Yeah, because atm amdgpu has the rpm_get calls outside of ttm locks, which is exactly the inversion you've complained about as being broken driver design.
-Sima
--
Daniel Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch

Signature · 3 lines
Simona Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
#49 lore raw

Re: [PATCH 4/7] drm/ttm: move LRU walk defines into new internal header

In reply to Christian König

Hi, Christian,

Quoted 1 line · Christian König

Am 20.08.24 um 12:37 schrieb Thomas Hellström:

...

Quoted 12 lines
Quoted 12 lines

I don't really care wether we do
this as an explicit loop or whether we use the LRU walker, but I think
from a maintainability point-of-view it is better to keep LRU walking
in a single place.

If we return an unlocked object, we'd need to refcount and drop the lru
lock, but maybe that's not a bad thing.

Quoted 7 lines
Quoted 1 line

But what's the main drawback of exporting the existing helper.

Well that we re-creates exactly the mid-layer mess I worked so hard to
remove from TTM.

Quoted 1 line
Quoted 1 line
Quoted 1 line

So could you please answer whether a solution with an iterator and a loop macro to de-midlayer is an OK solution form your POW, or suggest an alternative solution that you find acceptable that also allows bo shrinking with LRU traversal similar to how it's done elsewhere in DRM?

Thanks,
Thomas

#50 lore raw

PATCH 5/7 drm/ttm: move needs_unlock into the walk

In reply to Christian König

Not a walk parameter but important to have that status around.

---
 drivers/gpu/drm/ttm/ttm_bo_util.c | 26 ++++++++++++--------------
 drivers/gpu/drm/ttm/ttm_bo_util.h |  2 ++
 2 files changed, 14 insertions(+), 14 deletions(-)
drivers/gpu/drm/ttm/ttm_bo_util.c +12 -14
index 03e28e3d0d03..7a4bc7e9950b 100644
@@ -772,15 +772,14 @@ int ttm_bo_pipeline_gutting(struct ttm_buffer_object *bo)
 }
 
 static bool ttm_lru_walk_trylock(struct ttm_lru_walk *walk,
-				 struct ttm_buffer_object *bo,
-				 bool *needs_unlock)
+				 struct ttm_buffer_object *bo)
 {
 	struct ttm_operation_ctx *ctx = walk->ctx;
 
-	*needs_unlock = false;
+	walk->needs_unlock = false;
 
 	if (dma_resv_trylock(bo->base.resv)) {
-		*needs_unlock = true;
+		walk->needs_unlock = true;
 		return true;
 	}
 
@@ -793,8 +792,7 @@ static bool ttm_lru_walk_trylock(struct ttm_lru_walk *walk,
 }
 
 static int ttm_lru_walk_ticketlock(struct ttm_lru_walk *walk,
-				   struct ttm_buffer_object *bo,
-				   bool *needs_unlock)
+				   struct ttm_buffer_object *bo)
 {
 	struct dma_resv *resv = bo->base.resv;
 	int ret;
@@ -805,7 +803,7 @@ static int ttm_lru_walk_ticketlock(struct ttm_lru_walk *walk,
 		ret = dma_resv_lock(resv, walk->ticket);
 
 	if (!ret) {
-		*needs_unlock = true;
+		walk->needs_unlock = true;
 		/*
 		 * Only a single ticketlock per loop. Ticketlocks are prone
 		 * to return -EDEADLK causing the eviction to fail, so
@@ -821,9 +819,10 @@ static int ttm_lru_walk_ticketlock(struct ttm_lru_walk *walk,
 	return ret;
 }
 
-static void ttm_lru_walk_unlock(struct ttm_buffer_object *bo, bool locked)
+static void ttm_lru_walk_unlock(struct ttm_lru_walk *walk,
+				struct ttm_buffer_object *bo)
 {
-	if (locked)
+	if (walk->needs_unlock)
 		dma_resv_unlock(bo->base.resv);
 }
 
@@ -869,7 +868,6 @@ s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
 	spin_lock(&bdev->lru_lock);
 	ttm_resource_manager_for_each_res(man, &cursor, res) {
 		struct ttm_buffer_object *bo = res->bo;
-		bool bo_needs_unlock = false;
 		bool bo_locked = false;
 		int mem_type;
 
@@ -878,14 +876,14 @@ s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
 		 * since if we do it the other way around, and the trylock fails,
 		 * we need to drop the lru lock to put the bo.
 		 */
-		if (ttm_lru_walk_trylock(walk, bo, &bo_needs_unlock))
+		if (ttm_lru_walk_trylock(walk, bo))
 			bo_locked = true;
 		else if (!walk->ticket || walk->ctx->no_wait_gpu ||
 			 walk->trylock_only)
 			continue;
 
 		if (!ttm_bo_get_unless_zero(bo)) {
-			ttm_lru_walk_unlock(bo, bo_needs_unlock);
+			ttm_lru_walk_unlock(walk, bo);
 			continue;
 		}
 
@@ -894,7 +892,7 @@ s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
 
 		lret = 0;
 		if (!bo_locked)
-			lret = ttm_lru_walk_ticketlock(walk, bo, &bo_needs_unlock);
+			lret = ttm_lru_walk_ticketlock(walk, bo);
 
 		/*
 		 * Note that in between the release of the lru lock and the
@@ -906,7 +904,7 @@ s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
 		if (!lret && bo->resource && bo->resource->mem_type == mem_type)
 			lret = walk->ops->process_bo(walk, bo);
 
-		ttm_lru_walk_unlock(bo, bo_needs_unlock);
+		ttm_lru_walk_unlock(walk, bo);
 		ttm_bo_put(bo);
 		if (lret == -EBUSY || lret == -EALREADY)
 			lret = 0;
drivers/gpu/drm/ttm/ttm_bo_util.h +2 -0
index c19b50809208..c653e16ccb76 100644
@@ -59,6 +59,8 @@ struct ttm_lru_walk {
 	struct ww_acquire_ctx *ticket;
 	/** @tryock_only: Only use trylock for locking. */
 	bool trylock_only;
+	/** @needs_unlock: If the current BO needs unlocking */
+	bool needs_unlock;
 };
 
 s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
Signature · 1 line
2.34.1
#51 lore raw

PATCH 6/7 drm/ttm: support using drm_exec during eviction v2

In reply to Christian König

Allow specifying a drm_exec object in TTMs operation context which is used to lock objects during eviction.

This allows to handle deadlocks much more gracefully and with that avoid returning -ENOMEM on heavily contended domains.

v2: rebased on top of Thomas work

TODO: This still doesn't handle BOs which are about to be torn down correctly.

---
 drivers/gpu/drm/ttm/ttm_bo_util.c | 45 +++++++++++++++++++++++++------
 drivers/gpu/drm/ttm/ttm_bo_util.h |  2 ++
 include/drm/ttm/ttm_bo.h          |  3 +++
 3 files changed, 42 insertions(+), 8 deletions(-)
drivers/gpu/drm/ttm/ttm_bo_util.c +37 -8
index 7a4bc7e9950b..850e329ab5a5 100644
@@ -36,6 +36,7 @@
 #include <drm/ttm/ttm_tt.h>
 
 #include <drm/drm_cache.h>
+#include <drm/drm_exec.h>
 
 #include "ttm_bo_util.h"
 
@@ -776,15 +777,22 @@ static bool ttm_lru_walk_trylock(struct ttm_lru_walk *walk,
 {
 	struct ttm_operation_ctx *ctx = walk->ctx;
 
+	walk->needs_drop = false;
 	walk->needs_unlock = false;
 
-	if (dma_resv_trylock(bo->base.resv)) {
-		walk->needs_unlock = true;
+	if (bo->base.resv == ctx->resv && ctx->allow_res_evict) {
+		dma_resv_assert_held(bo->base.resv);
 		return true;
 	}
 
-	if (bo->base.resv == ctx->resv && ctx->allow_res_evict) {
-		dma_resv_assert_held(bo->base.resv);
+	if (walk->ctx->exec) {
+		if (drm_exec_trylock_obj(walk->ctx->exec, &bo->base)) {
+			walk->needs_drop = true;
+			return true;
+		}
+
+	} else if (dma_resv_trylock(bo->base.resv)) {
+		walk->needs_unlock = true;
 		return true;
 	}
 
@@ -797,7 +805,9 @@ static int ttm_lru_walk_ticketlock(struct ttm_lru_walk *walk,
 	struct dma_resv *resv = bo->base.resv;
 	int ret;
 
-	if (walk->ctx->interruptible)
+	if (walk->ctx->exec)
+		ret = drm_exec_lock_obj(walk->ctx->exec, &bo->base);
+	else if (walk->ctx->interruptible)
 		ret = dma_resv_lock_interruptible(resv, walk->ticket);
 	else
 		ret = dma_resv_lock(resv, walk->ticket);
@@ -811,7 +821,8 @@ static int ttm_lru_walk_ticketlock(struct ttm_lru_walk *walk,
 		 * trylocking for this walk.
 		 */
 		walk->ticket = NULL;
-	} else if (ret == -EDEADLK) {
+
+	} else if (!walk->ctx->exec && ret == -EDEADLK) {
 		/* Caller needs to exit the ww transaction. */
 		ret = -ENOSPC;
 	}
@@ -822,7 +833,15 @@ static int ttm_lru_walk_ticketlock(struct ttm_lru_walk *walk,
 static void ttm_lru_walk_unlock(struct ttm_lru_walk *walk,
 				struct ttm_buffer_object *bo)
 {
-	if (walk->needs_unlock)
+	if (walk->needs_drop)
+		drm_exec_drop_trylocked_obj(walk->ctx->exec, &bo->base);
+
+	if (!walk->needs_unlock)
+		return;
+
+	if (walk->ctx->exec)
+		drm_exec_unlock_obj(walk->ctx->exec, &bo->base);
+	else
 		dma_resv_unlock(bo->base.resv);
 }
 
@@ -891,8 +910,18 @@ s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
 		spin_unlock(&bdev->lru_lock);
 
 		lret = 0;
-		if (!bo_locked)
+		if (!bo_locked) {
 			lret = ttm_lru_walk_ticketlock(walk, bo);
+		} else if (walk->ctx->exec && !bo->deleted) {
+			lret = drm_exec_keep_trylocked_obj(walk->ctx->exec,
+							   &bo->base);
+			if (!lret) {
+				walk->needs_drop = false;
+				walk->needs_unlock = true;
+			}
+		} else {
+			lret = 0;
+		}
 
 		/*
 		 * Note that in between the release of the lru lock and the
drivers/gpu/drm/ttm/ttm_bo_util.h +2 -0
index c653e16ccb76..5e1bb156837f 100644
@@ -59,6 +59,8 @@ struct ttm_lru_walk {
 	struct ww_acquire_ctx *ticket;
 	/** @tryock_only: Only use trylock for locking. */
 	bool trylock_only;
+	/** @needs_drop: If the current BO needs a drm_exec trylock drop */
+	bool needs_drop;
 	/** @needs_unlock: If the current BO needs unlocking */
 	bool needs_unlock;
 };
include/drm/ttm/ttm_bo.h +3 -0
index 5f7c967222a2..5bee917e01e2 100644
@@ -180,6 +180,8 @@ struct ttm_bo_kmap_obj {
  * faults. Should only be used by TTM internally.
  * @resv: Reservation object to allow reserved evictions with.
  * @bytes_moved: Statistics on how many bytes have been moved.
+ * @exec: optional drm_exec object to use for locking BOs and tracking which are
+ * locked.
  *
  * Context for TTM operations like changing buffer placement or general memory
  * allocation.
@@ -192,6 +194,7 @@ struct ttm_operation_ctx {
 	bool force_alloc;
 	struct dma_resv *resv;
 	uint64_t bytes_moved;
+	struct drm_exec *exec;
 };
 
 /**
Signature · 1 line
2.34.1
#52 lore raw

PATCH 7/7 drm/amdgpu: use drm_exec during BO validation

In reply to Christian König

This allows to detect deadlocks happening because of resource constraints.

Especially submissions which want to use all of GDS doesn't result in sporadic -ENOMEM any more.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c | 86 ++++++++++++++------------
 1 file changed, 46 insertions(+), 40 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c +46 -40
index ec888fc6ead8..ff532c8b7a62 100644
@@ -782,7 +782,7 @@ static int amdgpu_cs_bo_validate(void *param, struct amdgpu_bo *bo)
 	struct ttm_operation_ctx ctx = {
 		.interruptible = true,
 		.no_wait_gpu = false,
-		.resv = bo->tbo.base.resv
+		.exec = &p->exec,
 	};
 	uint32_t domain;
 	int r;
@@ -834,7 +834,10 @@ static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p,
 				union drm_amdgpu_cs *cs)
 {
 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
-	struct ttm_operation_ctx ctx = { true, false };
+	struct ttm_operation_ctx ctx = {
+		.interruptible =true,
+		.exec = &p->exec
+	};
 	struct amdgpu_vm *vm = &fpriv->vm;
 	struct amdgpu_bo_list_entry *e;
 	struct drm_gem_object *obj;
@@ -919,50 +922,56 @@ static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p,
 			if (unlikely(r))
 				goto out_free_user_pages;
 		}
-	}
-
-	amdgpu_bo_list_for_each_userptr_entry(e, p->bo_list) {
-		struct mm_struct *usermm;
 
-		usermm = amdgpu_ttm_tt_get_usermm(e->bo->tbo.ttm);
-		if (usermm && usermm != current->mm) {
-			r = -EPERM;
-			goto out_free_user_pages;
-		}
+		amdgpu_bo_list_for_each_userptr_entry(e, p->bo_list) {
+			struct mm_struct *usermm;
 
-		if (amdgpu_ttm_tt_is_userptr(e->bo->tbo.ttm) &&
-		    e->user_invalidated && e->user_pages) {
-			amdgpu_bo_placement_from_domain(e->bo,
-							AMDGPU_GEM_DOMAIN_CPU);
-			r = ttm_bo_validate(&e->bo->tbo, &e->bo->placement,
-					    &ctx);
-			if (r)
+			usermm = amdgpu_ttm_tt_get_usermm(e->bo->tbo.ttm);
+			if (usermm && usermm != current->mm) {
+				r = -EPERM;
 				goto out_free_user_pages;
+			}
+
+			if (amdgpu_ttm_tt_is_userptr(e->bo->tbo.ttm) &&
+			    e->user_invalidated && e->user_pages) {
+				amdgpu_bo_placement_from_domain(e->bo,
+								AMDGPU_GEM_DOMAIN_CPU);
+				r = ttm_bo_validate(&e->bo->tbo, &e->bo->placement,
+						    &ctx);
+				drm_exec_retry_on_contention(&p->exec);
+				if (r)
+					goto out_free_user_pages;
+
+				amdgpu_ttm_tt_set_user_pages(e->bo->tbo.ttm,
+							     e->user_pages);
+			}
 
-			amdgpu_ttm_tt_set_user_pages(e->bo->tbo.ttm,
-						     e->user_pages);
+			kvfree(e->user_pages);
+			e->user_pages = NULL;
 		}
 
-		kvfree(e->user_pages);
-		e->user_pages = NULL;
-	}
+		amdgpu_cs_get_threshold_for_moves(p->adev, &p->bytes_moved_threshold,
+						  &p->bytes_moved_vis_threshold);
+		p->bytes_moved = 0;
+		p->bytes_moved_vis = 0;
 
-	amdgpu_cs_get_threshold_for_moves(p->adev, &p->bytes_moved_threshold,
-					  &p->bytes_moved_vis_threshold);
-	p->bytes_moved = 0;
-	p->bytes_moved_vis = 0;
+		r = amdgpu_vm_validate(p->adev, &fpriv->vm, NULL,
+				       amdgpu_cs_bo_validate, p);
+		drm_exec_retry_on_contention(&p->exec);
+		if (r) {
+			DRM_ERROR("amdgpu_vm_validate() failed.\n");
+			goto out_free_user_pages;
+		}
 
-	r = amdgpu_vm_validate(p->adev, &fpriv->vm, NULL,
-			       amdgpu_cs_bo_validate, p);
-	if (r) {
-		DRM_ERROR("amdgpu_vm_validate() failed.\n");
-		goto out_free_user_pages;
-	}
+		drm_exec_for_each_locked_object(&p->exec, index, obj) {
+			r = amdgpu_cs_bo_validate(p, gem_to_amdgpu_bo(obj));
+			drm_exec_retry_on_contention(&p->exec);
+			if (unlikely(r))
+				goto out_free_user_pages;
+		}
 
-	drm_exec_for_each_locked_object(&p->exec, index, obj) {
-		r = amdgpu_cs_bo_validate(p, gem_to_amdgpu_bo(obj));
-		if (unlikely(r))
-			goto out_free_user_pages;
+		amdgpu_cs_report_moved_bytes(p->adev, p->bytes_moved,
+					     p->bytes_moved_vis);
 	}
 
 	if (p->uf_bo) {
@@ -973,9 +982,6 @@ static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p,
 		p->gang_leader->uf_addr += amdgpu_bo_gpu_offset(p->uf_bo);
 	}
 
-	amdgpu_cs_report_moved_bytes(p->adev, p->bytes_moved,
-				     p->bytes_moved_vis);
-
 	for (i = 0; i < p->gang_size; ++i)
 		amdgpu_job_set_resources(p->jobs[i], p->bo_list->gds_obj,
 					 p->bo_list->gws_obj,
Signature · 1 line
2.34.1