Skip to contentSkip to conversation

dma-fence: Remove TIMESTAMP bit

RFC PATCH New Philipp Stanner 3 participants 15 messages Nov 27

Subsystems (9)
lore
Share & tools
lore

Philipp Stanner

author maintainer
#0 lore raw

cover dma-fence: Remove TIMESTAMP bit

The timestamp bit is annoying and dangerous because it makes memory ordering difficult. It's only accessor function, dma_fence_timestamp(), is unnecessarily complicated.

The current state is largely UB. Most notably, since there is no memory ordering, people might accidentally read a list head for a timestamp, generating total bogus output.

I have previously proposed backporting a hot fix for the ordering [1]. Tvrtko recently dived into fixing drm_sched [2].

My hope would be that the full drm_sched fix could be set on top of this series.

The first two patches could be backported into misc-fixes, and the rest enter into misc-next? I'm not entirely sure what the best strategy is.

Pls review,
P.

[1] https://lore.kernel.org/dri-devel/[email protected]/
[2] https://lore.kernel.org/dri-devel/[email protected]/

Philipp Stanner (8):
dma-buf: dma-fence: Hot-fix timestamp misordering drm/sched: Hot-fix timestamp misordering
dma-buf: dma-fence: Ensure ordering with locks for timestamps
dma-buf: dma-fence: Improve dma_fence_timestamp() drm/amdgpu: Stop using dma_fence internals
dma-buf: sync_debug: don't use TIMESTAMP bit drm/i915: Remove TIMESTAMP bit
dma-buf: dma-fence: Remove TIMESTAMP bit

 drivers/dma-buf/dma-fence-unwrap.c          | 20 ++++++++++-----
 drivers/dma-buf/dma-fence.c                 |  2 --
 drivers/dma-buf/sync_debug.c                |  8 +++---
 drivers/dma-buf/sync_file.c                 |  8 +++---
 drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c     | 11 ++++----
 drivers/gpu/drm/i915/gt/intel_breadcrumbs.c |  1 -
 drivers/gpu/drm/scheduler/sched_entity.c    |  4 +--
 drivers/gpu/drm/scheduler/sched_main.c      | 26 +++++++++++++++----
 include/linux/dma-fence.h                   | 28 +++++++++++++--------
 9 files changed, 68 insertions(+), 40 deletions(-)
Signature · 1 line
2.56.0
author maintainer
#1 lore raw

RFC PATCH 1/8 dma-buf: dma-fence: Hot-fix timestamp misordering

fence timestamps can be written and read without any memory ordering since, presumably, forever. This can cause real bugs, other than false accounting, for parties whose algorithms depend on the timestamp.

Hot-fix the problem for now so that it can be backported until we found a suitable way forward for mainline.

Fixes 76250f2b743b ("dma-buf/fence: Avoid use of uninitialised timestamp")
---
 drivers/dma-buf/dma-fence.c | 9 +++++++++
 include/linux/dma-fence.h   | 8 ++++++--
 2 files changed, 15 insertions(+), 2 deletions(-)
drivers/dma-buf/dma-fence.c +9 -0
index ab02afdb0f18..c947aec1bf91 100644
@@ -378,6 +378,15 @@ void dma_fence_signal_timestamp_locked(struct dma_fence *fence,
 	list_replace(&fence->cb_list, &cb_list);
 
 	fence->timestamp = timestamp;
+	/*
+	 * TODO:
+	 * This is a temporary hotfix to prevent misordering until we
+	 * can completely remove the TIMESTAMP bit.
+	 *
+	 * The counterpart of this barrier are the test_bit_acquire()s in
+	 * dma_fence_timestamp().
+	 */
+	smp_mb__before_atomic();
 	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
 
 	list_for_each_entry_safe(cur, tmp, &cb_list, node) {
include/linux/dma-fence.h +6 -2
index 513d9dbbff47..29c4332c8662 100644
@@ -686,10 +686,14 @@ static inline void dma_fence_set_error(struct dma_fence *fence,
  */
 static inline ktime_t dma_fence_timestamp(struct dma_fence *fence)
 {
-	if (WARN_ON(!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)))
+	/*
+	 * The test_bit_acquire() calls order against the
+	 * smp_mb__before_atomic() in dma_fence_signal_timestamp_locked().
+	 */
+	if (WARN_ON(!test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)))
 		return ktime_get();
 
-	while (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags))
+	while (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags))
 		cpu_relax();
 
 	return fence->timestamp;
Signature · 1 line
2.56.0
author maintainer
#2 lore raw

RFC PATCH 2/8 drm/sched: Hot-fix timestamp misordering

In reply to Philipp Stanner

dma_fence timestamps could so far be written and read without any memory ordering, a bug that presumably got overlooked because x86 is strongly ordered.

Hot-fix the scheduler's manual timestamp evaluation until we found a more suitable solution for mainline linux.

Fixes f7fe64ad0f22 ("drm/sched: Split free_job into own work item")
---
 drivers/gpu/drm/scheduler/sched_main.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/gpu/drm/scheduler/sched_main.c +10 -2
index 85a49e219837..44553db9b04c 100644
@@ -928,8 +928,16 @@ drm_sched_get_finished_job(struct drm_gpu_scheduler *sched)
 		next = list_first_entry_or_null(&sched->pending_list,
 						typeof(*next), list);
 		if (next) {
-			/* make the scheduled timestamp more accurate */
-			if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT,
+			/* Make the scheduled timestamp more accurate.
+			 *
+			 * TODO
+			 * The test_bit_acquire() is a hotfix against timestamp
+			 * misordering. Replace it with something better.
+			 *
+			 * The counter-part of the barrier is located in
+			 * dma_fence_signal_timestamp_locked().
+			 */
+			if (test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT,
 				     &next->s_fence->scheduled.flags))
 				next->s_fence->scheduled.timestamp =
 					dma_fence_timestamp(&job->s_fence->finished);
Signature · 1 line
2.56.0
author maintainer
#3 lore raw

RFC PATCH 3/8 dma-buf: dma-fence: Ensure ordering with locks for timestamps

In reply to Philipp Stanner

The memory ordering in dma_fence_timestamp() is currently being done manually with acquire functions. It can be done more elegantly with the fence's spinlock. This also allows for removing the TIMESTAMP bit in the long run.

Use locking in dma_fence_timestamp().

---
 drivers/dma-buf/dma-fence.c |  9 ---------
 include/linux/dma-fence.h   | 24 ++++++++++++------------
 2 files changed, 12 insertions(+), 21 deletions(-)
drivers/dma-buf/dma-fence.c +0 -9
index c947aec1bf91..ab02afdb0f18 100644
@@ -378,15 +378,6 @@ void dma_fence_signal_timestamp_locked(struct dma_fence *fence,
 	list_replace(&fence->cb_list, &cb_list);
 
 	fence->timestamp = timestamp;
-	/*
-	 * TODO:
-	 * This is a temporary hotfix to prevent misordering until we
-	 * can completely remove the TIMESTAMP bit.
-	 *
-	 * The counterpart of this barrier are the test_bit_acquire()s in
-	 * dma_fence_timestamp().
-	 */
-	smp_mb__before_atomic();
 	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
 
 	list_for_each_entry_safe(cur, tmp, &cb_list, node) {
include/linux/dma-fence.h +12 -12
index 29c4332c8662..1c1aa4c7635a 100644
@@ -680,23 +680,23 @@ static inline void dma_fence_set_error(struct dma_fence *fence,
  * dma_fence_timestamp - helper to get the completion timestamp of a fence
  * @fence: fence to get the timestamp from.
  *
- * After a fence is signaled the timestamp is updated with the signaling time,
- * but setting the timestamp can race with tasks waiting for the signaling. This
- * helper busy waits for the correct timestamp to appear.
+ * Return:
+ * The fence's timestamp if the fence is already signaled, the current time
+ * otherwise.
  */
 static inline ktime_t dma_fence_timestamp(struct dma_fence *fence)
 {
-	/*
-	 * The test_bit_acquire() calls order against the
-	 * smp_mb__before_atomic() in dma_fence_signal_timestamp_locked().
-	 */
+	unsigned long flags;
+	ktime_t ret;
+
+	dma_fence_lock_irqsave(fence, flags);
 	if (WARN_ON(!test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)))
-		return ktime_get();
+		ret = ktime_get();
+	else
+		ret = fence->timestamp;
+	dma_fence_unlock_irqrestore(fence, flags);
 
-	while (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags))
-		cpu_relax();
-
-	return fence->timestamp;
+	return ret;
 }
 
 signed long dma_fence_wait_timeout(struct dma_fence *,
Signature · 1 line
2.56.0
#4 lore raw

Re: [RFC PATCH 3/8] dma-buf: dma-fence: Ensure ordering with locks for timestamps

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] dma-buf: dma-fence: union cb_list pointer read in dma_fence_timestamp() - [High] dma-buf: dma-fence…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] dma-buf: dma-fence: union cb_list pointer read in dma_fence_timestamp()
- [High] dma-buf: dma-fence: dma_fence_timestamp() locks fence after signaling
- [Medium] dma-buf: dma-fence: unconditional spin_lock_irqsave in dma_fence_timestamp()
- [Medium] dma-buf: dma-fence: undocumented lock and no locked dma_fence_timestamp()
--

commit 2dafcb9d7a9ed94c64a7c7994912a38c5f4e4ac5
Author: Philipp Stanner <[email protected]>

dma-buf: dma-fence: Ensure ordering with locks for timestamps

This commit replaces the spin-wait on DMA_FENCE_FLAG_TIMESTAMP_BIT in dma_fence_timestamp() with acquiring the fence's spinlock and drops the corresponding smp_mb__before_atomic() barrier from dma_fence_signal_timestamp_locked().

Quoted 30 lines
include/linux/dma-fence.h +7 -11
index 9743d217264de..3a05fe9f64e8f 100644
@@ -706,23 +706,23 @@ static inline void dma_fence_set_error(struct dma_fence *fence,
  * dma_fence_timestamp - helper to get the completion timestamp of a fence
  * @fence: fence to get the timestamp from.
  *
- * After a fence is signaled the timestamp is updated with the signaling time,
- * but setting the timestamp can race with tasks waiting for the signaling. This
- * helper busy waits for the correct timestamp to appear.
+ * Return:
+ * The fence's timestamp if the fence is already signaled, the current time
+ * otherwise.
  */
 static inline ktime_t dma_fence_timestamp(struct dma_fence *fence)
 {
-	/*
-	 * The test_bit_acquire() calls order against the
-	 * smp_mb__before_atomic() in dma_fence_signal_timestamp_locked().
-	 */
-	if (WARN_ON(!test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)))
-		return ktime_get();
+	unsigned long flags;
+	ktime_t ret;
 
-	while (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags))
-		cpu_relax();
+	dma_fence_lock_irqsave(fence, flags);
+	if (WARN_ON(!test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)))

include/linux/dma-fence.h static inline void dma_fence_set_error(struct dma_fence *fence, · line 728

Quoted 10 lines
include/linux/dma-fence.h +5 -1
+		ret = ktime_get();
+	else
+		ret = fence->timestamp;
+	dma_fence_unlock_irqrestore(fence, flags);
 
-	return fence->timestamp;
+	return ret;
 }
 
 signed long dma_fence_wait_timeout(struct dma_fence *,

[Severity: High]
Can dma_fence_timestamp() read fence->cb_list.next instead of a valid timestamp on i915 request fences?

In struct dma_fence, cb_list and timestamp share an anonymous union. In drivers/gpu/drm/i915/gt/intel_breadcrumbs.c, irq_signal_request() and the first loop of signal_irq_work() call __dma_fence_signal(&rq->fence), which sets DMA_FENCE_FLAG_SIGNALED_BIT without holding rq->lock (the fence's extern_lock) and before replacing rq->fence.cb_list or writing rq->fence.timestamp:

CPU0 CPU1
irq_signal_request()
__dma_fence_signal(&rq->fence)
test_and_set_bit(SIGNALED_BIT)
irq_work_queue(&b->irq_work)

                                  sync_fill_fence_info()
                                    dma_fence_is_signaled() -> true
                                    dma_fence_timestamp(&rq->fence)
                                      dma_fence_lock_irqsave()
                                      ret = fence->timestamp
                                      /* reads fence->cb_list.next */
                                      dma_fence_unlock_irqrestore()

signal_irq_work()
spin_lock(&rq->lock)
list_replace(&rq->fence.cb_list, ...)
__dma_fence_signal__timestamp()
spin_unlock(&rq->lock)

Without the wait on DMA_FENCE_FLAG_TIMESTAMP_BIT, a caller running between __dma_fence_signal() and the locked section in signal_irq_work() sees DMA_FENCE_FLAG_SIGNALED_BIT set under rq->lock and reads rq->fence.cb_list.next as the timestamp, corrupting merged fence timestamp comparisons in __dma_fence_unwrap_merge() and copying a raw kernel heap pointer to userspace via info->timestamp_ns in SYNC_IOC_FILE_INFO.

[Severity: High]
Does locking dma_fence_spinlock(fence) in dma_fence_timestamp() cause a use-after-free on fence->extern_lock when the lock's owner frees it after signaling?

The dma-fence lifetime rules in include/linux/dma-fence.h ("DOC: Safe external access to driver provided object members") state that fence->extern_lock must not be accessed after the fence has been signaled because drivers may free the lock after an RCU grace period. Unlike helpers that check dma_fence_test_signaled_flag() before touching fence->extern_lock, dma_fence_timestamp() is called on already-signaled fences, such as in __dma_fence_unwrap_merge() during SYNC_IOC_MERGE.

For exporters where the structure holding extern_lock does not outlive every reference to the signaled fence, such as ffs_dmabuf_release() freeing priv (which holds the priv->lock passed to dma_fence_init() in ffs_dmabuf_transfer()) or xe_hw_fence_irq_finish() freeing irq->lock after synchronize_rcu(), dma_fence_lock_irqsave() in dma_fence_timestamp() writes to freed memory.

[Severity: Medium]
Could taking dma_fence_lock_irqsave() on every dma_fence_timestamp() call add unnecessary lock contention and irqsave overhead on hot paths?

Previously, dma_fence_timestamp() only performed read-only bit tests and a timestamp load, keeping signaled fences in a shared cacheline state. Acquiring and releasing the spinlock with local interrupts disabled dirties the lock cacheline on every query. In drm_sched_free_job_work(), dma_fence_timestamp() is called multiple times per completed job (including twice back-to-back on s_fence->scheduled and s_fence->finished in drm_sched_entity_stats_job_add_gpu_time(), which share s_fence->lock). In __dma_fence_unwrap_merge(), every signaled fence in an unwrapped fence array or chain now takes its spinlock in both passes, contending on the global dma_fence_stub.inline_lock or on shared driver ring and IRQ locks.

[Severity: Medium]
Will dma_fence_timestamp() deadlock if called while the fence's spinlock is already held?

dma_fence_timestamp() now acquires dma_fence_spinlock(fence) internally, without documenting that callers must not hold the fence lock or providing a dma_fence_timestamp_locked() helper. Callers that already hold the fence lock, such as fence completion callbacks invoked from dma_fence_signal_timestamp_locked() or sync_print_fence() in drivers/dma-buf/sync_debug.c (which runs under spin_lock(&obj->lock), the extern_lock passed to dma_fence_init() in sync_pt_create(), and is converted to call dma_fence_timestamp() in commit "dma-buf: sync_debug:
don't use TIMESTAMP bit" later in this series), will recursively deadlock on the same spinlock:

sync_print_obj()
spin_lock(&obj->lock)
sync_print_fence(s, &pt->base, false)

    dma_fence_timestamp(&pt->base)
      dma_fence_lock_irqsave(&pt->base, flags)  <-- spins forever
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#5 lore raw

RFC PATCH 4/8 dma-buf: dma-fence: Improve dma_fence_timestamp()

In reply to Philipp Stanner

dma_fence_timestamp() can be made a more robust and useful function by having it return an error code that indicates whether the fence was signaled or not. Only if it's signaled, returning a timestamp makes sense, otherwise the user should choose what value to interpret as a replacement.

Have dma_fence_timestamp() return an integer status code. Return the timestamp via a pointer.

To be able to port drm_sched, move its hack for overwriting functions to a temporary function for now.

---
 drivers/dma-buf/dma-fence-unwrap.c       | 20 +++++++++-----
 drivers/dma-buf/sync_file.c              |  8 +++---
 drivers/gpu/drm/scheduler/sched_entity.c |  4 +--
 drivers/gpu/drm/scheduler/sched_main.c   | 34 +++++++++++++++---------
 include/linux/dma-fence.h                | 20 ++++++++------
 5 files changed, 53 insertions(+), 33 deletions(-)
drivers/dma-buf/dma-fence-unwrap.c +14 -6
index 120fe0c2a75a..a1e9b1ee2c32 100644
@@ -136,10 +136,14 @@ struct dma_fence *__dma_fence_unwrap_merge(size_t num_fences,
 				unsignaled = dma_fence_get(tmp);
 				++count;
 			} else {
-				ktime_t t = dma_fence_timestamp(tmp);
+				ktime_t fence_ts = ktime_get();
+				/* Leaves fence_ts unchanged if fence is not yet
+				 * signaled.
+				 */
+				dma_fence_timestamp(tmp, &fence_ts);
 
-				if (ktime_after(t, timestamp))
-					timestamp = t;
+				if (ktime_after(fence_ts, timestamp))
+					timestamp = fence_ts;
 			}
 		}
 	}
@@ -168,10 +172,14 @@ struct dma_fence *__dma_fence_unwrap_merge(size_t num_fences,
 			if (!dma_fence_is_signaled(tmp)) {
 				array[count++] = dma_fence_get(tmp);
 			} else {
-				ktime_t t = dma_fence_timestamp(tmp);
+				ktime_t fence_ts = ktime_get();
+				/* Leaves fence_ts unchanged if fence is not yet
+				 * signaled.
+				 */
+				dma_fence_timestamp(tmp, &fence_ts);
 
-				if (ktime_after(t, timestamp))
-					timestamp = t;
+				if (ktime_after(fence_ts, timestamp))
+					timestamp = fence_ts;
 			}
 		}
 	}
drivers/dma-buf/sync_file.c +4 -4
index 2166bbdf7e4a..54ef230bcc4b 100644
@@ -268,6 +268,7 @@ static long sync_file_ioctl_merge(struct sync_file *sync_file,
 static int sync_fill_fence_info(struct dma_fence *fence,
 				 struct sync_fence_info *info)
 {
+	ktime_t fence_ts = ktime_set(0, 0);
 	const char __rcu *timeline;
 	const char __rcu *driver;
 
@@ -282,10 +283,9 @@ static int sync_fill_fence_info(struct dma_fence *fence,
 		sizeof(info->driver_name));
 
 	info->status = dma_fence_get_status(fence);
-	info->timestamp_ns =
-		dma_fence_is_signaled(fence) ?
-			ktime_to_ns(dma_fence_timestamp(fence)) :
-			ktime_set(0, 0);
+
+	dma_fence_timestamp(fence, &fence_ts);
+	info->timestamp_ns = ktime_to_ns(fence_ts);
 
 	rcu_read_unlock();
 
drivers/gpu/drm/scheduler/sched_entity.c +2 -2
index 03e68b4102d5..5ceffb4d3114 100644
@@ -78,8 +78,8 @@ ktime_t drm_sched_entity_stats_job_add_gpu_time(struct drm_sched_job *job)
 	struct drm_sched_fence *s_fence = job->s_fence;
 	ktime_t start, end, duration;
 
-	start = dma_fence_timestamp(&s_fence->scheduled);
-	end = dma_fence_timestamp(&s_fence->finished);
+	dma_fence_timestamp(&s_fence->scheduled, &start);
+	dma_fence_timestamp(&s_fence->finished, &end);
 	duration = ktime_sub(end, start);
 
 	spin_lock(&stats->lock);
drivers/gpu/drm/scheduler/sched_main.c +21 -13
index 44553db9b04c..e515bfa949b4 100644
@@ -898,6 +898,26 @@ drm_sched_select_entity(struct drm_gpu_scheduler *sched)
 	return IS_ERR(entity) ? NULL : entity;
 }
 
+/*
+ * This is a temporary, hacky function until we can find a canonical solution
+ * for not overwriting fence timestamps.
+ *
+ * FIXME: Remove this hack.
+ */
+static void drm_sched_overwrite_scheduled_ts(struct drm_sched_job *current_job,
+					     struct drm_sched_job *next_job)
+{
+	struct dma_fence *current_fence = &current_job->s_fence->finished;
+	struct dma_fence *next_fence = &next_job->s_fence->scheduled;
+	ktime_t current_finished, next_scheduled;
+
+	if (dma_fence_timestamp(next_fence, &next_scheduled) != 0)
+		return;
+
+	if (dma_fence_timestamp(current_fence, &current_finished) == 0)
+		next_fence->timestamp = current_finished;
+}
+
 /**
  * drm_sched_get_finished_job - fetch the next finished job to be destroyed
  *
@@ -928,19 +948,7 @@ drm_sched_get_finished_job(struct drm_gpu_scheduler *sched)
 		next = list_first_entry_or_null(&sched->pending_list,
 						typeof(*next), list);
 		if (next) {
-			/* Make the scheduled timestamp more accurate.
-			 *
-			 * TODO
-			 * The test_bit_acquire() is a hotfix against timestamp
-			 * misordering. Replace it with something better.
-			 *
-			 * The counter-part of the barrier is located in
-			 * dma_fence_signal_timestamp_locked().
-			 */
-			if (test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT,
-				     &next->s_fence->scheduled.flags))
-				next->s_fence->scheduled.timestamp =
-					dma_fence_timestamp(&job->s_fence->finished);
+			drm_sched_overwrite_scheduled_ts(job, next);
 
 			/* start TO timer for next job */
 			drm_sched_start_timeout(sched);
include/linux/dma-fence.h +12 -8
index 1c1aa4c7635a..70bb8434ac1a 100644
@@ -679,21 +679,25 @@ static inline void dma_fence_set_error(struct dma_fence *fence,
 /**
  * dma_fence_timestamp - helper to get the completion timestamp of a fence
  * @fence: fence to get the timestamp from.
+ * @ts: a place to store the timestamp to.
+ *
+ * Writes the fences timestamp into @ts if the fence is already signaled.
+ * Leaves @ts unchanged otherwise.
  *
  * Return:
- * The fence's timestamp if the fence is already signaled, the current time
- * otherwise.
+ * 0 if the timestamp was written to @ts, -ENOENT if the fence was not yet
+ * signaled.
  */
-static inline ktime_t dma_fence_timestamp(struct dma_fence *fence)
+static inline int dma_fence_timestamp(struct dma_fence *fence, ktime_t *ts)
 {
 	unsigned long flags;
-	ktime_t ret;
+	int ret = -ENOENT;
 
 	dma_fence_lock_irqsave(fence, flags);
-	if (WARN_ON(!test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)))
-		ret = ktime_get();
-	else
-		ret = fence->timestamp;
+	if (dma_fence_test_signaled_flag(fence)) {
+		*ts = fence->timestamp;
+		ret = 0;
+	}
 	dma_fence_unlock_irqrestore(fence, flags);
 
 	return ret;
Signature · 1 line
2.56.0
#6 lore raw

Re: [RFC PATCH 4/8] dma-buf: dma-fence: Improve dma_fence_timestamp()

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] dma-buf: redundant ktime_get() on signaled fences in __dma_fence_unwrap_merge() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] dma-buf: redundant ktime_get() on signaled fences in __dma_fence_unwrap_merge()
--

commit e022bd65ff0c3c874a861f648d1911f74f6646f1
Author: Philipp Stanner <[email protected]>

dma-buf: dma-fence: Improve dma_fence_timestamp()

This commit changes dma_fence_timestamp() to write the completion timestamp through an output pointer and return an integer status code, updating callers across dma-buf and drm/sched.

Quoted 32 lines
drivers/dma-buf/dma-fence-unwrap.c +9 -8
index 120fe0c2a75af..a1e9b1ee2c325 100644
@@ -136,10 +136,14 @@ struct dma_fence *__dma_fence_unwrap_merge(size_t num_fences,
 				unsignaled = dma_fence_get(tmp);
 				++count;
 			} else {
-				ktime_t t = dma_fence_timestamp(tmp);
-
-				if (ktime_after(t, timestamp))
-					timestamp = t;
+				ktime_t fence_ts = ktime_get();
+				/* Leaves fence_ts unchanged if fence is not yet
+				 * signaled.
+				 */
+				dma_fence_timestamp(tmp, &fence_ts);
+
+				if (ktime_after(fence_ts, timestamp))
+					timestamp = fence_ts;
 			}
 		}
 	}
@@ -168,10 +172,14 @@ struct dma_fence *__dma_fence_unwrap_merge(size_t num_fences,
 			if (!dma_fence_is_signaled(tmp)) {
 				array[count++] = dma_fence_get(tmp);
 			} else {
-				ktime_t t = dma_fence_timestamp(tmp);
-
-				if (ktime_after(t, timestamp))
-					timestamp = t;
+				ktime_t fence_ts = ktime_get();

drivers/dma-buf/dma-fence-unwrap.c struct dma_fence *__dma_fence_unwrap_merge(size_t num_fences, · line 185

Quoted 10 lines
drivers/dma-buf/dma-fence-unwrap.c +7 -0
+				/* Leaves fence_ts unchanged if fence is not yet
+				 * signaled.
+				 */
+				dma_fence_timestamp(tmp, &fence_ts);
+
+				if (ktime_after(fence_ts, timestamp))
+					timestamp = fence_ts;
 			}
 		}
 	}

[Severity: Medium]
Does initializing fence_ts with ktime_get() in both else branches perform an unnecessary clocksource read for every signaled fence?

Both branches only run after dma_fence_is_signaled(tmp) returns true, so DMA_FENCE_FLAG_SIGNALED_BIT is already set on tmp->flags and dma_fence_timestamp(tmp, &fence_ts) will always overwrite fence_ts with tmp->timestamp. Before this change, ktime_get() was only called on the unsignaled fallback path inside dma_fence_timestamp().

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

RFC PATCH 5/8 drm/amdgpu: Stop using dma_fence internals

In reply to Philipp Stanner

amdgpu_ctx_fence_time() directly accesses a fence's internal timestamp, not ensuring memory ordering.

Make the code more robust and readable by using the (now improved) dma_fence_timestamp() function.

---
I think this should, contrary to my previous statements, be fine since the lock taken is the s_fence lock, whereas this function's caller holds a distinct fctx lock.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +6 -5
index 2f0349233695..9d6d92cb9734 100644
@@ -170,6 +170,7 @@ static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
 /* Calculate the time spend on the hw */
 static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
 {
+	ktime_t scheduled_ts, finished_ts;
 	struct drm_sched_fence *s_fence;
 
 	if (!fence)
@@ -177,15 +178,15 @@ static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
 
 	/* When the fence is not even scheduled it can't have spend time */
 	s_fence = to_drm_sched_fence(fence);
-	if (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->scheduled.flags))
+
+	if (dma_fence_timestamp(&s_fence->scheduled, &scheduled_ts) != 0)
 		return ns_to_ktime(0);
 
 	/* When it is still running account how much already spend */
-	if (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->finished.flags))
-		return ktime_sub(ktime_get(), s_fence->scheduled.timestamp);
+	if (dma_fence_timestamp(&s_fence->finished, &finished_ts) != 0)
+		return ktime_sub(ktime_get(), scheduled_ts);
 
-	return ktime_sub(s_fence->finished.timestamp,
-			 s_fence->scheduled.timestamp);
+	return ktime_sub(finished_ts, scheduled_ts);
 }
 
 static ktime_t amdgpu_ctx_entity_time(struct amdgpu_ctx *ctx,
Signature · 1 line
2.56.0
author maintainer
#8 lore raw

RFC PATCH 6/8 dma-buf: sync_debug: don't use TIMESTAMP bit

In reply to Philipp Stanner

dma_fence's TIMESTAMP bit doesn't really serve a purpose and should be removed. Direct accessors should therefore be ported.

Use dma_fence_timestamp() in sync_debug.

---
 drivers/dma-buf/sync_debug.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/dma-buf/sync_debug.c +4 -4
index 9e5d662cd4e8..58c0d00ba5b3 100644
@@ -46,6 +46,8 @@ static void sync_print_fence(struct seq_file *s,
 			     struct dma_fence *fence, bool show)
 {
 	struct sync_timeline *parent = dma_fence_parent(fence);
+	struct timespec64 ts64;
+	ktime_t ts;
 	int status;
 
 	status = dma_fence_get_status_locked(fence);
@@ -55,10 +57,8 @@ static void sync_print_fence(struct seq_file *s,
 		   show ? "_" : "",
 		   sync_status_str(status));
 
-	if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags)) {
-		struct timespec64 ts64 =
-			ktime_to_timespec64(fence->timestamp);
-
+	if (dma_fence_timestamp(fence, &ts) == 0) {
+		ts64 = ktime_to_timespec64(ts);
 		seq_printf(s, "@%ptSp", &ts64);
 	}
 
Signature · 1 line
2.56.0
#9 lore raw

Re: [RFC PATCH 6/8] dma-buf: sync_debug: don't use TIMESTAMP bit

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] dma-buf: sync_debug: recursive spinlock deadlock in sync_print_fence() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] dma-buf: sync_debug: recursive spinlock deadlock in sync_print_fence()
--

commit 771cc9b6d800a1a39680e74552adf1782c101ea3
Author: Philipp Stanner <[email protected]>

dma-buf: sync_debug: don't use TIMESTAMP bit

This commit replaces the direct DMA_FENCE_FLAG_TIMESTAMP_BIT check in sync_print_fence() with a call to dma_fence_timestamp().

Quoted 15 lines
drivers/dma-buf/sync_debug.c +2 -0
index 9e5d662cd4e84..58c0d00ba5b3c 100644
@@ -46,6 +46,8 @@ static void sync_print_fence(struct seq_file *s,
 			     struct dma_fence *fence, bool show)
 {
 	struct sync_timeline *parent = dma_fence_parent(fence);
+	struct timespec64 ts64;
+	ktime_t ts;
 	int status;
 
 	status = dma_fence_get_status_locked(fence);
@@ -55,10 +57,8 @@ static void sync_print_fence(struct seq_file *s,
 		   show ? "_" : "",

drivers/dma-buf/sync_debug.c static void sync_print_fence(struct seq_file *s, · line 63

Quoted 10 lines
drivers/dma-buf/sync_debug.c +2 -4
 		   sync_status_str(status));
 
-	if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags)) {
-		struct timespec64 ts64 =
-			ktime_to_timespec64(fence->timestamp);
-
+	if (dma_fence_timestamp(fence, &ts) == 0) {
+		ts64 = ktime_to_timespec64(ts);
 		seq_printf(s, "@%ptSp", &ts64);
 	}

[Severity: High]
Does calling dma_fence_timestamp() here self-deadlock on obj->lock?

sync_pt_create() initializes each sync_pt fence with &obj->lock as its external fence spinlock, and sync_print_obj() already holds obj->lock when it calls sync_print_fence() (which is why dma_fence_get_status_locked() is used above):

sync_info_debugfs_show()
spin_lock_irq(&sync_timeline_list_lock)
sync_print_obj()

    spin_lock(&obj->lock)
    sync_print_fence()
      dma_fence_timestamp()
        dma_fence_lock_irqsave()  <-- spins forever on &obj->lock

Reading /sys/kernel/debug/sync/info while any sync_timeline has a sync_pt on obj->pt_list will deadlock the CPU with interrupts disabled.

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

RFC PATCH 7/8 drm/i915: Remove TIMESTAMP bit

In reply to Philipp Stanner

i915 seems to have built its own half-copy of parts of the dma_buf subsystem. This includes interferences with dma_fences' timestamp bit, which does not provide memory ordering and which does not seem to serve a clear purpose in i915.

Remove the set_bit().

---
 drivers/gpu/drm/i915/gt/intel_breadcrumbs.c | 1 -
 1 file changed, 1 deletion(-)
drivers/gpu/drm/i915/gt/intel_breadcrumbs.c +0 -1
index c10ac0ab3bfa..a43d774ba779 100644
@@ -138,7 +138,6 @@ static void
 __dma_fence_signal__timestamp(struct dma_fence *fence, ktime_t timestamp)
 {
 	fence->timestamp = timestamp;
-	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
 	trace_dma_fence_signaled(fence);
 }
 
Signature · 1 line
2.56.0
#11 lore raw

Re: [RFC PATCH 7/8] drm/i915: Remove TIMESTAMP bit

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] drm/i915: race in __dma_fence_signal__timestamp() leaks cb_list as timestamp --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] drm/i915: race in __dma_fence_signal__timestamp() leaks cb_list as timestamp
--

commit 2eef29a2b337dc954527ca9b1dc02ace1dc68145
Author: Philipp Stanner <[email protected]>

drm/i915: Remove TIMESTAMP bit

This commit removes the set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags) call from __dma_fence_signal__timestamp() in the i915 breadcrumb signaler.

drivers/gpu/drm/i915/gt/intel_breadcrumbs.c static void · line 142

Quoted 11 lines
drivers/gpu/drm/i915/gt/intel_breadcrumbs.c +0 -1
index c10ac0ab3bfa8..a43d774ba7793 100644
@@ -138,7 +138,6 @@ static void
 __dma_fence_signal__timestamp(struct dma_fence *fence, ktime_t timestamp)
 {
 	fence->timestamp = timestamp;
-	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
 	trace_dma_fence_signaled(fence);
 }

[Severity: Medium]
Can removing DMA_FENCE_FLAG_TIMESTAMP_BIT let dma_fence_timestamp() read rq->fence.cb_list.next as the timestamp while the fence is being signaled?

In struct dma_fence, cb_list and timestamp share an anonymous union. Unlike dma_fence_signal_timestamp_locked(), i915 splits signaling across an unlocked window: __dma_fence_signal() sets DMA_FENCE_FLAG_SIGNALED_BIT without holding rq->lock, and signal_irq_work() only takes rq->lock later to detach cb_list and write fence->timestamp:

CPU0 CPU1
irq_signal_request()
__dma_fence_signal(&rq->fence)
test_and_set_bit(SIGNALED_BIT)
irq_work_queue(&b->irq_work)

                                      sync_file_ioctl(SYNC_IOC_FILE_INFO)
                                        ...
                                          dma_fence_timestamp(&rq->fence)
                                            spin_lock(&rq->lock)
                                            test_bit(SIGNALED_BIT) -> true
                                            *ts = fence->timestamp
                                              <-- reads cb_list.next
                                            spin_unlock(&rq->lock)

signal_irq_work()
spin_lock(&rq->lock)
list_replace(&rq->fence.cb_list, ...)
__dma_fence_signal__timestamp()

    fence->timestamp = timestamp

spin_unlock(&rq->lock)

Waiters polling an i915 out-fence with SYNC_IOC_FILE_INFO or merging fences during that window will receive a raw kernel pointer from cb_list.next as the timestamp instead of waiting or getting a valid ktime_t.

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

RFC PATCH 8/8 dma-buf: dma-fence: Remove TIMESTAMP bit

In reply to Philipp Stanner

All users of DMA_FENCE_FLAG_TIMESTAMP_BIT have been removed. Remove the bit now, too.

---
 drivers/dma-buf/dma-fence.c | 2 --
 include/linux/dma-fence.h   | 2 --
 2 files changed, 4 deletions(-)
drivers/dma-buf/dma-fence.c +0 -2
index ab02afdb0f18..58faee7166ae 100644
@@ -376,9 +376,7 @@ void dma_fence_signal_timestamp_locked(struct dma_fence *fence,
 
 	/* Stash the cb_list before replacing it with the timestamp */
 	list_replace(&fence->cb_list, &cb_list);
-
 	fence->timestamp = timestamp;
-	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
 
 	list_for_each_entry_safe(cur, tmp, &cb_list, node) {
 		INIT_LIST_HEAD(&cur->node);
include/linux/dma-fence.h +0 -2
index 70bb8434ac1a..bab0aa339e05 100644
@@ -52,7 +52,6 @@ struct seq_file;
  * DMA_FENCE_FLAG_INITIALIZED_BIT - fence was initialized
  * DMA_FENCE_FLAG_INLINE_LOCK_BIT - use inline spinlock instead of external one
  * DMA_FENCE_FLAG_SIGNALED_BIT - fence is already signaled
- * DMA_FENCE_FLAG_TIMESTAMP_BIT - timestamp recorded for fence signaling
  * DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT - enable_signaling might have been called
  * DMA_FENCE_FLAG_USER_BITS - start of the unused bits, can be used by the
  * implementer of the fence for its own purposes. Can be used in different
@@ -114,7 +113,6 @@ enum dma_fence_flag_bits {
 	DMA_FENCE_FLAG_INLINE_LOCK_BIT,
 	DMA_FENCE_FLAG_SEQNO64_BIT,
 	DMA_FENCE_FLAG_SIGNALED_BIT,
-	DMA_FENCE_FLAG_TIMESTAMP_BIT,
 	DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
 
 	DMA_FENCE_FLAG_USER_BITS, /* must always be last member */
Signature · 1 line
2.56.0
#13 lore raw

Re: [RFC PATCH 8/8] dma-buf: dma-fence: Remove TIMESTAMP bit

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] dma-buf: sync_debug: recursive spinlock deadlock in sync_print_fence() - [Medium] dma-buf…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] dma-buf: sync_debug: recursive spinlock deadlock in sync_print_fence()
- [Medium] dma-buf: dma-fence: race in dma_fence_timestamp() with i915 fence signaling
- [Medium] drm/sched: unlocked timestamp write in drm_sched_overwrite_scheduled_ts()
--

commit c345425f67e4cc845c145d7cb57df4a3a2b40256
Author: Philipp Stanner <[email protected]>

dma-buf: dma-fence: Remove TIMESTAMP bit

This commit removes DMA_FENCE_FLAG_TIMESTAMP_BIT from enum dma_fence_flag_bits and stops setting it in dma_fence_signal_timestamp_locked().

Quoted 5 lines
drivers/dma-buf/dma-fence.c +0 -0
index 0776ca7c795e8..64d3ac4f0b8fa 100644

drivers/dma-buf/dma-fence.c void dma_fence_signal_timestamp_locked(struct dma_fence *fence, · line 382

Quoted 9 lines
drivers/dma-buf/dma-fence.c +0 -2
@@ -376,9 +376,7 @@ void dma_fence_signal_timestamp_locked(struct dma_fence *fence,
 
 	/* Stash the cb_list before replacing it with the timestamp */
 	list_replace(&fence->cb_list, &cb_list);
-
 	fence->timestamp = timestamp;
-	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
 
 	list_for_each_entry_safe(cur, tmp, &cb_list, node) {
 		INIT_LIST_HEAD(&cur->node);

[Severity: Medium]
Does removing DMA_FENCE_FLAG_TIMESTAMP_BIT allow dma_fence_timestamp() to read rq->fence.cb_list.next as the timestamp on i915 request fences?

In struct dma_fence, cb_list and timestamp share a union. i915 sets DMA_FENCE_FLAG_SIGNALED_BIT via __dma_fence_signal() before acquiring rq->lock to replace cb_list and write rq->fence.timestamp:

CPU0 CPU1
irq_signal_request()
__dma_fence_signal(&rq->fence)

    test_and_set_bit(SIGNALED_BIT,
                     &fence->flags)
                                  sync_file_ioctl_fence_info()
                                    sync_fill_fence_info()
                                      dma_fence_timestamp(&rq->fence, &ts)
                                        dma_fence_lock_irqsave(...)
                                        if (dma_fence_test_signaled_flag())
                                          *ts = fence->timestamp;
                                          <-- reads fence->cb_list.next
                                        dma_fence_unlock_irqrestore(...)

irq_work_queue(&b->irq_work)
...
signal_irq_work()
spin_lock(&rq->lock)
list_replace(&rq->fence.cb_list, ...)
__dma_fence_signal__timestamp(...)
spin_unlock(&rq->lock)

Because dma_fence_timestamp() now only checks DMA_FENCE_FLAG_SIGNALED_BIT under the fence lock, a concurrent call during this window reads the raw kernel pointer in cb_list.next as the timestamp and copies it to userspace in struct sync_fence_info.timestamp_ns via SYNC_IOC_FILE_INFO.

Quoted 4 lines
include/linux/dma-fence.h +0 -0
index 0a7ffda6a4cfe..7fd9393e60035 100644

[ ... ]

include/linux/dma-fence.h enum dma_fence_flag_bits { · line 118

Quoted 8 lines
include/linux/dma-fence.h +0 -1
@@ -114,7 +113,6 @@ enum dma_fence_flag_bits {
 	DMA_FENCE_FLAG_INLINE_LOCK_BIT,
 	DMA_FENCE_FLAG_SEQNO64_BIT,
 	DMA_FENCE_FLAG_SIGNALED_BIT,
-	DMA_FENCE_FLAG_TIMESTAMP_BIT,
 	DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
 
 	DMA_FENCE_FLAG_USER_BITS, /* must always be last member */

[Severity: High]
Does replacing the DMA_FENCE_FLAG_TIMESTAMP_BIT check with spinlock serialization in dma_fence_timestamp() cause a recursive spinlock deadlock in sync_print_obj() -> sync_print_fence()?

In drivers/dma-buf/sw_sync.c, sync_pt_create() initializes each pt->base with &obj->lock as its fence spinlock. When /sys/kernel/debug/sync/info is read, sync_print_obj() already holds &obj->lock when it calls sync_print_fence():

sync_info_debugfs_show()
sync_print_obj()

    spin_lock(&obj->lock)
    sync_print_fence(&pt->base)
      dma_fence_timestamp(&pt->base, &ts)
        dma_fence_lock_irqsave(fence, flags)  <-- deadlocks on &obj->lock

[Severity: Medium]
With fence->timestamp now synchronized by the fence spinlock instead of DMA_FENCE_FLAG_TIMESTAMP_BIT, is the unlocked write in drm_sched_overwrite_scheduled_ts() a data race?

drivers/gpu/drm/scheduler/sched_main.c:drm_sched_overwrite_scheduled_ts() {
    ...
	if (dma_fence_timestamp(current_fence, &current_finished) == 0)
		next_fence->timestamp = current_finished;
}

drm_sched_overwrite_scheduled_ts() only holds sched->job_list_lock when overwriting next_fence->timestamp, racing with concurrent readers such as amdgpu_ctx_fence_time() calling dma_fence_timestamp(&s_fence->scheduled, &scheduled_ts) under the fence spinlock and risking torn 64-bit ktime_t reads on 32-bit architectures.

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

✓ i915.CI.BAT: success for dma-fence: Remove TIMESTAMP bit

In reply to Philipp Stanner
== Series Details ==

== Series Details ==

Series: dma-fence: Remove TIMESTAMP bit
URL : https://patchwork.freedesktop.org/series/179859/
State : success

== Summary ==

CI Bug Log - changes from CI_DRM_19622 -> Patchwork_179859v1
====================================================

Summary
-------

**SUCCESS**

No regressions found.

External URL: https://intel-gfx-ci.01.org/tree/drm-tip/Patchwork_179859v1/index.html

Participating hosts (39 -> 38)
------------------------------

Missing (1): bat-dg2-13

Known issues
------------

Here are the changes found in Patchwork_179859v1 that come from known issues:

### IGT changes ###

#### Issues hit ####

* igt@kms_pm_rpm@basic-pci-d3-state:
- bat-rpls-4: [PASS][1] -> [DMESG-WARN][2] ([i915#13400])
[1]: https://intel-gfx-ci.01.org/tree/drm-tip/CI_DRM_19622/bat-rpls-4/igt@[email protected]
[2]: https://intel-gfx-ci.01.org/tree/drm-tip/Patchwork_179859v1/bat-rpls-4/igt@[email protected]

#### Possible fixes ####

* igt@core_hotunplug@unbind-rebind:
- bat-rpls-4: [DMESG-WARN][3] ([i915#13400]) -> [PASS][4]
[3]: https://intel-gfx-ci.01.org/tree/drm-tip/CI_DRM_19622/bat-rpls-4/igt@[email protected]
[4]: https://intel-gfx-ci.01.org/tree/drm-tip/Patchwork_179859v1/bat-rpls-4/igt@[email protected]

[i915#13400]: https://gitlab.freedesktop.org/drm/i915/kernel/-/issues/13400

Build changes
-------------

* Linux: CI_DRM_19622 -> Patchwork_179859v1

CI-20190529: 20190529
CI_DRM_19622: 2167aae7e27a3c224f220ce01eea87498ff3724d @ git://anongit.freedesktop.org/gfx-ci/linux
IGT_9206: 9206
Patchwork_179859v1: 2167aae7e27a3c224f220ce01eea87498ff3724d @ git://anongit.freedesktop.org/gfx-ci/linux

== Logs ==

For more details see: https://intel-gfx-ci.01.org/tree/drm-tip/Patchwork_179859v1/index.html