Skip to contentSkip to conversation

drm/sched: Track sched fence scheduled and finished time directly

PATCH In review Tvrtko Ursulin 2 participants 3 messages Dec 3 – Dec 4

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

PATCH v4 1/1 drm/sched: Track sched fence scheduled and finished time directly

Philipp reports the current usage of overwriting the dma-fence timestamp from the free_job worker is racy and unsafe due missing memory ordering and especially with drivers which use own unordered submit workqueue for the scheduler. Consider also that the timestamp field is the union in the dma-fence object.

On top of these serious issues, there is also a smaller problem where the said race can cause GPU time overaccounting.

Lets try and solve all issues in one swoop by stopping messing with dma-fence internals and just track what we want in our own derived fence object.

We care about fence submit and finish times and by adding a dedicated lock to manage them we can safely access both and adjust the former without any races, and without needing to overwrite the internal dma-fence timestamp field.

References: https://lore.kernel.org/dri-devel/[email protected]/
References: https://lore.kernel.org/dri-devel/[email protected]/
Cc: Christian König <[email protected]>
Cc: Danilo Krummrich <[email protected]>
Cc: Matthew Brost <[email protected]>
Cc: Philipp Stanner <[email protected]>
Cc: [email protected]
---
v2:
* Fix kerneldoc copy and paste.
* Grab timestamps after obtaing locks.
* Prevent negative job durations on canceled/timedout jobs.

v3:
* Do not miss timestamp adjustment when multiple jobs complete.

v4:
* Rebase for upstream changes.
* More consolidate advance timestamp helper with a better kerneldoc.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c    | 15 ++++----
 drivers/gpu/drm/scheduler/sched_entity.c   |  6 ++--
 drivers/gpu/drm/scheduler/sched_fence.c    | 21 +++++++++--
 drivers/gpu/drm/scheduler/sched_internal.h | 41 ++++++++++++++++++++++
 drivers/gpu/drm/scheduler/sched_main.c     | 19 ++--------
 include/drm/gpu_scheduler.h                | 39 ++++++++++++++++++++
 6 files changed, 113 insertions(+), 28 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +7 -8
index 415f23aa08a0..1a6985283acc 100644
@@ -171,21 +171,20 @@ static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
 static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
 {
 	struct drm_sched_fence *s_fence;
+	ktime_t start, end;
 
 	if (!fence)
 		return ns_to_ktime(0);
 
-	/* When the fence is not even scheduled it can't have spend time */
 	s_fence = to_drm_sched_fence(fence);
-	if (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->scheduled.flags))
-		return ns_to_ktime(0);
+	drm_sched_fence_get_times(s_fence, &start, &end);
+
+	/* When the fence is not even scheduled it can't have spend time */
+	if (!start)
+		return start;
 
 	/* When it is still running account how much already spend */
-	if (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->finished.flags))
-		return ktime_sub(ktime_get(), s_fence->scheduled.timestamp);
-
-	return ktime_sub(s_fence->finished.timestamp,
-			 s_fence->scheduled.timestamp);
+	return ktime_sub(end ?: ktime_get(), start);
 }
 
 static ktime_t amdgpu_ctx_entity_time(struct amdgpu_ctx *ctx,
drivers/gpu/drm/scheduler/sched_entity.c +4 -2
index bc5141c85fbc..fd59844cb989 100644
@@ -78,8 +78,10 @@ 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);
+	drm_sched_fence_get_times(s_fence, &start, &end);
+	if (WARN_ON_ONCE(!start || !end || ktime_after(start, end)))
+		return ns_to_ktime(0);
+
 	duration = ktime_sub(end, start);
 
 	spin_lock(&stats->lock);
drivers/gpu/drm/scheduler/sched_fence.c +19 -2
index 9f938f5a7e55..181790ebf369 100644
@@ -65,6 +65,8 @@ static void drm_sched_fence_set_parent(struct drm_sched_fence *s_fence,
 void drm_sched_fence_scheduled(struct drm_sched_fence *fence,
 			       struct dma_fence *parent)
 {
+	ktime_t now;
+
 	/* Set the parent before signaling the scheduled fence, such that,
 	 * any waiter expecting the parent to be filled after the job has
 	 * been scheduled (which is the case for drivers delegating waits
@@ -74,14 +76,28 @@ void drm_sched_fence_scheduled(struct drm_sched_fence *fence,
 	if (!IS_ERR_OR_NULL(parent))
 		drm_sched_fence_set_parent(fence, parent);
 
-	dma_fence_signal(&fence->scheduled);
+	spin_lock_irq(&fence->ts_lock);
+	now = ktime_get();
+	fence->start_ts = now;
+	spin_unlock_irq(&fence->ts_lock);
+
+	dma_fence_signal_timestamp(&fence->scheduled, now);
 }
 
 void drm_sched_fence_finished(struct drm_sched_fence *fence, int result)
 {
+	unsigned long flags;
+	ktime_t now;
+
 	if (result)
 		dma_fence_set_error(&fence->finished, result);
-	dma_fence_signal(&fence->finished);
+
+	spin_lock_irqsave(&fence->ts_lock, flags);
+	now = ktime_get();
+	fence->finished_ts = now;
+	spin_unlock_irqrestore(&fence->ts_lock, flags);
+
+	dma_fence_signal_timestamp(&fence->finished, now);
 }
 
 static const char *drm_sched_fence_get_driver_name(struct dma_fence *fence)
@@ -217,6 +233,7 @@ struct drm_sched_fence *drm_sched_fence_alloc(void *owner,
 	fence->owner = owner;
 	fence->drm_client_id = drm_client_id;
 	spin_lock_init(&fence->lock);
+	spin_lock_init(&fence->ts_lock);
 
 	return fence;
 }
drivers/gpu/drm/scheduler/sched_internal.h +41 -0

47 lines not on this page · raw message

drivers/gpu/drm/scheduler/sched_main.c +3 -16
index dfd7d4702f0b..8025f5abb855 100644
@@ -952,22 +952,9 @@ 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:
-			 * Stop overwriting a fence's timestamp.
-			 *
-			 * test_bit_acquire() ensures ordering so that only
-			 * timestamps that are actually present already get
-			 * overwritten (timestamp is a union).
-			 *
-			 * 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);
+			/* make the scheduled timestamp more accurate */
+			drm_sched_fence_advance_start_time(next->s_fence,
+							   job->s_fence);
 
 			/* start TO timer for next job */
 			drm_sched_start_timeout(sched);
include/drm/gpu_scheduler.h +39 -0
index 748a93f5a0a4..8fbe527feced 100644
@@ -308,6 +308,25 @@ struct drm_sched_fence {
          */
 	struct dma_fence		finished;
 
+	/**
+	 * @ts_lock: Lock used for @start_ts and @finished_ts.
+	 */
+	spinlock_t			ts_lock;
+
+	/**
+	 * @start_ts: ktime of fence GPU execution start or 0 is not started.
+	 *
+	 * Must be accessed via helpers.
+	 */
+	ktime_t				start_ts;
+
+	/**
+	 * @finished_ts: ktime of fence GPU execution end or 0 if not finished.
+	 *
+	 * Must be accessed via helpers.
+	 */
+	ktime_t				finished_ts;
+
 	/**
 	 * @deadline: deadline set on &drm_sched_fence.finished which
 	 * potentially needs to be propagated to &drm_sched_fence.parent
@@ -344,6 +363,26 @@ struct drm_sched_fence {
 
 struct drm_sched_fence *to_drm_sched_fence(struct dma_fence *f);
 
+/**
+ * drm_sched_fence_get_times() - Get scheduler fence start and finished times
+ * @fence: Scheduler fence
+ * @scheduled: Pointer to scheduled time storage
+ * @finished: Pointer to finished time storage
+ *
+ * Obtains scheduler fence scheduled and finished times.
+ */
+static inline void
+drm_sched_fence_get_times(struct drm_sched_fence *fence,
+			  ktime_t *scheduled, ktime_t *finished)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&fence->ts_lock, flags);
+	*scheduled = fence->start_ts;
+	*finished = fence->finished_ts;
+	spin_unlock_irqrestore(&fence->ts_lock, flags);
+}
+
 /**
  * struct drm_sched_job - A job to be run by an entity.
  *
Signature · 1 line
2.56.0
#1 lore raw
Quoted 5 lines · Tvrtko Ursulin

Philipp reports the current usage of overwriting the dma-fence timestamp from the free_job worker is racy and unsafe due missing memory ordering and especially with drivers which use own unordered submit workqueue for the scheduler. Consider also that the timestamp field is the union in the dma-fence object.

I *think* this should de jure be fixed by my series being in misc- fixes:

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

Nevertheless, your patch here is desirable. Do we agree that it should end up in misc-next as a general improvement?

Quoted 3 lines

On top of these serious issues, there is also a smaller problem where the said race can cause GPU time overaccounting.

Which race, you mean the unordered worker?

Quoted 3 lines

Lets try and solve all issues in one swoop by stopping messing with dma-fence internals and just track what we want in our own derived fence object.

We'd have to agree on what purpose this patch should have. Either we backmerge the ordering fixes into misc-next, then this patch here would just be an improvement for better timestamp accuracy, but not a fix of UB.

Or we don't backmerge, this patch is rebased onto misc-next and also fixes the undefined behavior, but independently from misc-fixes.

I think the former is better? Opinions?

Quoted 4 lines

We care about fence submit and finish times and by adding a dedicated lock to manage them we can safely access both and adjust the former without any races, and without needing to overwrite the internal dma-fence timestamp field.

How's it determinend whether a timestamp is not yet set to begin with? IOW, what kind of accesses does the lock synchronize?

drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c

Quoted 34 lines

References: https://lore.kernel.org/dri-devel/[email protected]/
References: https://lore.kernel.org/dri-devel/[email protected]/
Cc: Christian König <[email protected]>
Cc: Danilo Krummrich <[email protected]>
Cc: Matthew Brost <[email protected]>
Cc: Philipp Stanner <[email protected]>
Cc: [email protected]
---
v2:
 * Fix kerneldoc copy and paste.
 * Grab timestamps after obtaing locks.
 * Prevent negative job durations on canceled/timedout jobs.

v3:
 * Do not miss timestamp adjustment when multiple jobs complete.

v4:
 * Rebase for upstream changes.
 * More consolidate advance timestamp helper with a better kerneldoc.
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c    | 15 ++++---- drivers/gpu/drm/scheduler/sched_entity.c   |  6 ++-- drivers/gpu/drm/scheduler/sched_fence.c    | 21 +++++++++-- drivers/gpu/drm/scheduler/sched_internal.h | 41 ++++++++++++++++++++++ drivers/gpu/drm/scheduler/sched_main.c     | 19 ++-------- include/drm/gpu_scheduler.h                | 39 ++++++++++++++++++++

 6 files changed, 113 insertions(+), 28 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +0 -0
index 415f23aa08a0..1a6985283acc 100644

Could or should that be a separate patch? What is the change to amdgpu achieving, exactly?

Quoted 11 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +1 -0
@@ -171,21 +171,20 @@ static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
  static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
  {
  	struct drm_sched_fence *s_fence;
+	ktime_t start, end;


  if (!fence)
  return ns_to_ktime(0);

drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +0 -1
-	/* When the fence is not even scheduled it can't have spend time */

  s_fence = to_drm_sched_fence(fence);

drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip) · line 183

Quoted 6 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +4 -2
-	if (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->scheduled.flags))
-		return ns_to_ktime(0);
+	drm_sched_fence_get_times(s_fence, &start, &end);
+
+	/* When the fence is not even scheduled it can't have spend time */
+	if (!start)

Is it common to evaluate a ktime_t like that? The readability IMO decreases because before you at least saw "timestamp is now set, you can read it", whereas now you check whether a time is != 0.

I currently have another patch that modifies dma_fence_timestamp() like so:

/**
* bla bla
*
* Return: -EAGAIN if there's no timestamp yet.
*/
int dma_fence_timestamp(struct dma_fence *fence, ktime_t *ts);

An API like that feels far more robust and intuitive to me.

Can it make sense to split your accessor function into two, get_start_timestamp() and get_end_timestamp()?

Quoted 20 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +1 -0
+		return start;


  /* When it is still running account how much already spend */

drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +1 -5
-	if (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->finished.flags))
-		return ktime_sub(ktime_get(), s_fence->scheduled.timestamp);
-
-	return ktime_sub(s_fence->finished.timestamp,
-			 s_fence->scheduled.timestamp);
+	return ktime_sub(end ?: ktime_get(), start);

 }

 static ktime_t amdgpu_ctx_entity_time(struct amdgpu_ctx *ctx,

drivers/gpu/drm/scheduler/sched_entity.c +0 -0
index bc5141c85fbc..fd59844cb989 100644
@@ -78,8 +78,10 @@ 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;

drivers/gpu/drm/scheduler/sched_entity.c ktime_t drm_sched_entity_stats_job_add_gpu_time(struct drm_sched_job *job) · line 82

Quoted 4 lines
drivers/gpu/drm/scheduler/sched_entity.c +2 -2
-	start = dma_fence_timestamp(&s_fence->scheduled);
-	end = dma_fence_timestamp(&s_fence->finished);
+	drm_sched_fence_get_times(s_fence, &start, &end);
+	if (WARN_ON_ONCE(!start || !end || ktime_after(start, end)))

The WARN is new. Can this now suddenly occur?

Quoted 15 lines


 void drm_sched_fence_finished(struct drm_sched_fence *fence, int result) {

drivers/gpu/drm/scheduler/sched_entity.c +3 -0
+	unsigned long flags;
+	ktime_t now;
+

  if (result) dma_fence_set_error(&fence->finished, result);

drivers/gpu/drm/scheduler/sched_entity.c +5 -1
-	dma_fence_signal(&fence->finished);
+
+	spin_lock_irqsave(&fence->ts_lock, flags);
+	now = ktime_get();
+	fence->finished_ts = now;
+	spin_unlock_irqrestore(&fence->ts_lock, flags);

[…]

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 6 lines
drivers/gpu/drm/scheduler/sched_entity.c +6 -0
+static inline void
+drm_sched_fence_advance_start_time(struct drm_sched_fence *next,
+				   struct drm_sched_fence *prev)
+{
+	spin_lock_irq(&prev->ts_lock);
+	spin_lock_nested(&next->ts_lock, SINGLE_DEPTH_NESTING); /* Timeline order */

What's the deal with the locking functions here? Why do you lock with irqsave above, and here with _irq?

What's _nested supposed to achieve?

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 5 lines
drivers/gpu/drm/scheduler/sched_entity.c +5 -0
+	if (next->start_ts &&
+	    ktime_after(prev->finished_ts, next->start_ts) &&
+	    (!next->finished_ts ||
+	     !ktime_after(prev->finished_ts, next->finished_ts)))
+		next->start_ts = prev->finished_ts;

Hard to read logic. Can that be made more readable with goto unlock?

Quoted 4 lines
drivers/gpu/drm/scheduler/sched_entity.c +4 -0
+	spin_unlock(&next->ts_lock);
+	spin_unlock_irq(&prev->ts_lock);
+}
+

[…]

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 2 lines
drivers/gpu/drm/scheduler/sched_entity.c +2 -0
+	/**
+	 * @ts_lock: Lock used for @start_ts and @finished_ts.

nit s/used for/protecting

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 12 lines
drivers/gpu/drm/scheduler/sched_entity.c +12 -0
+	 */
+	spinlock_t			ts_lock;
+
+	/**
+	 * @start_ts: ktime of fence GPU execution start or 0 is not started.
+	 *
+	 * Must be accessed via helpers.
+	 */
+	ktime_t				start_ts;
+
+	/**
+	 * @finished_ts: ktime of fence GPU execution end or 0 if not finished.

GPU execution of whom? ;)

This gets me thinking. So it's the GPU execution time of a … well, job. Not the fences, but they are supposed to track the execution status of a job.

Now with sched_fence, we have this weird situation that it's an API object, mostly entrenched into amdgpu to do container_of on just one fence and then obtain things like the scheduled status.

Still, struct drm_sched_job annoyingly also contains the job->submit_ts

So I am afraid that our API is about to drift further apart regarding consistency, because the job tracks when it was submitted, but the sched_fence when it was scheduled and when it was finished.

I'm not sure how to set this straight, but if we have so many related timestamps it sounds as if there should be a distinct job_times object for that. But who would access that when and why? That question mostly boils down to amdgpu's desire to obtain these timestamps (why does it even need that, btw? Is that related to your scheduling granularity? drm_sched does the scheduling, so why does amdgpu need *exact* timestamps other than the fence timestamps?)

We also now have the scheduling stats time object, but I guess that's fine since it's distinct and just accumulates job-times. But hence my question, if the scheduler does the scheduling, then why does an external party need the super-duper-exact timestamps?

Quoted 13 lines
drivers/gpu/drm/scheduler/sched_entity.c +5 -0
+	 *
+	 * Must be accessed via helpers.
+	 */
+	ktime_t				finished_ts;
+

  /**
  * @deadline: deadline set on &drm_sched_fence.finished which
  * potentially needs to be propagated to &drm_sched_fence.parent

drivers/gpu/drm/scheduler/sched_entity.c +0 -0
@@ -344,6 +363,26 @@ struct drm_sched_fence {


 struct drm_sched_fence *to_drm_sched_fence(struct dma_fence *f);

drivers/gpu/drm/scheduler/sched_entity.c +1 -0
+/**

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 10 lines
drivers/gpu/drm/scheduler/sched_entity.c +10 -0
+ * drm_sched_fence_get_times() - Get scheduler fence start and finished times
+ * @fence: Scheduler fence
+ * @scheduled: Pointer to scheduled time storage
+ * @finished: Pointer to finished time storage
+ *
+ * Obtains scheduler fence scheduled and finished times.
+ */
+static inline void
+drm_sched_fence_get_times(struct drm_sched_fence *fence,
+			  ktime_t *scheduled, ktime_t *finished)

Yeah, I think two functions are the right thing really, because then you can return "not yet available".

*if* anyone really needs only the scheduled without the finished time. See my question above.

P.

#2 lore raw
Quoted 11 lines · Philipp Stanner
Quoted 5 lines · Tvrtko Ursulin

Philipp reports the current usage of overwriting the dma-fence timestamp from the free_job worker is racy and unsafe due missing memory ordering and especially with drivers which use own unordered submit workqueue for the scheduler. Consider also that the timestamp field is the union in the dma-fence object.

I *think* this should de jure be fixed by my series being in misc- fixes:

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

Not quite! :) My fix is on top of yours, applicable even to strongly ordered platforms.

Quoted 2 lines

Nevertheless, your patch here is desirable. Do we agree that it should end up in misc-next as a general improvement?

Yes, and I did not tag it as as fix because over accounting currently only affects fdinfo (not so important) and the fair policy (not default yet).

Quoted 4 lines
Quoted 2 lines

On top of these serious issues, there is also a smaller problem where the said race can cause GPU time overaccounting.

Which race, you mean the unordered worker?

No, the one linked as a reference below ;)

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

"""
Currently the starting timestamp of the next job on the timeline is adjusted to the end of a preceding job. This works if the next job has been submitted while the preceding job was still executing, but not if it was submitted in the window between it finishing and free job work running the timestamp adjustment.

This can happen because the run job and free job work items share the same ordered workqueue and run job can easily submit the next job before the free job gets a chance to run. This over accounting window is present especially with single credit schedulers, but not limited too.

Fix it by only adjusting the starting timestamp if it is not already after the finish time of the preceding job.
"""

Quoted 9 lines
Quoted 3 lines

Lets try and solve all issues in one swoop by stopping messing with dma-fence internals and just track what we want in our own derived fence object.

We'd have to agree on what purpose this patch should have. Either we backmerge the ordering fixes into misc-next, then this patch here would just be an improvement for better timestamp accuracy, but not a fix of UB.

Quoted 4 lines

Or we don't backmerge, this patch is rebased onto misc-next and also fixes the undefined behavior, but independently from misc-fixes.

I think the former is better? Opinions?

I lost you here a bit. Backmerge will happen sooner or later and at that point this patch could go to drm-misc-next and would be solving the remaining race.

Alternative fix, if we wouldn't want to adding tracking inside drm_sched_fence, would have to work in this area of the code:

drm_sched_get_finished_job()
{
...

	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);

Key thing is to guard the assignment with a time_after, at which point we would have to read next->s_fence->scheduled.timestamp, not just overwrite it.

Quoted 7 lines
Quoted 4 lines

We care about fence submit and finish times and by adding a dedicated lock to manage them we can safely access both and adjust the former without any races, and without needing to overwrite the internal dma-fence timestamp field.

How's it determinend whether a timestamp is not yet set to begin with? IOW, what kind of accesses does the lock synchronize?

Not set is zero. Lock protects both read and write of the new drm_sched_fence timestamps.

Quoted 29 lines
Quoted 29 lines

References: https://lore.kernel.org/dri-devel/[email protected]/
References: https://lore.kernel.org/dri-devel/[email protected]/
Cc: Christian König <[email protected]>
Cc: Danilo Krummrich <[email protected]>
Cc: Matthew Brost <[email protected]>
Cc: Philipp Stanner <[email protected]>
Cc: [email protected]
---
v2:
 * Fix kerneldoc copy and paste.
 * Grab timestamps after obtaing locks.
 * Prevent negative job durations on canceled/timedout jobs.

v3:
 * Do not miss timestamp adjustment when multiple jobs complete.

v4:
 * Rebase for upstream changes.
 * More consolidate advance timestamp helper with a better kerneldoc.

---
  drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c    | 15 ++++----
  drivers/gpu/drm/scheduler/sched_entity.c   |  6 ++--
  drivers/gpu/drm/scheduler/sched_fence.c    | 21 +++++++++--
  drivers/gpu/drm/scheduler/sched_internal.h | 41 ++++++++++++++++++++++
  drivers/gpu/drm/scheduler/sched_main.c     | 19 ++--------
  include/drm/gpu_scheduler.h                | 39 ++++++++++++++++++++
  6 files changed, 113 insertions(+), 28 deletions(-)
Quoted 7 lines

drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +0 -0
index 415f23aa08a0..1a6985283acc 100644

Could or should that be a separate patch? What is the change to amdgpu achieving, exactly?

Removes direct acces to dma-fence bits and timestamp. I don't see that it is worth splitting.

Quoted 9 lines
Quoted 9 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +1 -0
@@ -171,21 +171,20 @@ static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
  static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
  {
  	struct drm_sched_fence *s_fence;
+	ktime_t start, end;
 
  	if (!fence)
  		return ns_to_ktime(0);
 
Quoted 12 lines

drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip) · line 183

Quoted 8 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +4 -3
-	/* When the fence is not even scheduled it can't have spend time */
  	s_fence = to_drm_sched_fence(fence);
-	if (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->scheduled.flags))
-		return ns_to_ktime(0);
+	drm_sched_fence_get_times(s_fence, &start, &end);
+
+	/* When the fence is not even scheduled it can't have spend time */
+	if (!start)

Is it common to evaluate a ktime_t like that? The readability IMO decreases because before you at least saw "timestamp is now set, you can read it", whereas now you check whether a time is != 0.

As long as kerneldoc explains the API I think it's fine. I can add a sentence to drm_sched_fence_get_times kerneldoc.

Quoted 11 lines

I currently have another patch that modifies dma_fence_timestamp() like so:

/**
* bla bla
*
* Return: -EAGAIN if there's no timestamp yet.
*/
int dma_fence_timestamp(struct dma_fence *fence, ktime_t *ts);

Quoted 1 line

An API like that feels far more robust and intuitive to me.

It will hinge on whether we decide to go with the drm_sched_fence_timestamps or not. If we do, then any further changes to dma_fence_timestamp() are irrelevant for the scheduler and amdgpu.

Quoted 2 lines

Can it make sense to split your accessor function into two, get_start_timestamp() and get_end_timestamp()?

I don't think so. Like it is one lock cycle gets the atomic view.

Quoted 21 lines
Quoted 21 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c +2 -5
+		return start;
 
  	/* When it is still running account how much already spend */
-	if (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->finished.flags))
-		return ktime_sub(ktime_get(), s_fence->scheduled.timestamp);
-
-	return ktime_sub(s_fence->finished.timestamp,
-			 s_fence->scheduled.timestamp);
+	return ktime_sub(end ?: ktime_get(), start);
  }
 
  static ktime_t amdgpu_ctx_entity_time(struct amdgpu_ctx *ctx,
drivers/gpu/drm/scheduler/sched_entity.c +0 -0
index bc5141c85fbc..fd59844cb989 100644
@@ -78,8 +78,10 @@ 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;
 
Quoted 6 lines

drivers/gpu/drm/scheduler/sched_entity.c ktime_t drm_sched_entity_stats_job_add_gpu_time(struct drm_sched_job *job) · line 82

Quoted 4 lines
drivers/gpu/drm/scheduler/sched_entity.c +2 -2
-	start = dma_fence_timestamp(&s_fence->scheduled);
-	end = dma_fence_timestamp(&s_fence->finished);
+	drm_sched_fence_get_times(s_fence, &start, &end);
+	if (WARN_ON_ONCE(!start || !end || ktime_after(start, end)))

The WARN is new. Can this now suddenly occur?

It shouldn't unless the logic in drm_sched_fence_advance_start_time() missed some corner case.

Quoted 16 lines
Quoted 13 lines
drivers/gpu/drm/scheduler/sched_entity.c +8 -1
  void drm_sched_fence_finished(struct drm_sched_fence *fence, int result)
  {
+	unsigned long flags;
+	ktime_t now;
+
  	if (result)
  		dma_fence_set_error(&fence->finished, result);
-	dma_fence_signal(&fence->finished);
+
+	spin_lock_irqsave(&fence->ts_lock, flags);
+	now = ktime_get();
+	fence->finished_ts = now;
+	spin_unlock_irqrestore(&fence->ts_lock, flags);

[…]

Quoted 9 lines

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 6 lines
drivers/gpu/drm/scheduler/sched_entity.c +6 -0
+static inline void
+drm_sched_fence_advance_start_time(struct drm_sched_fence *next,
+				   struct drm_sched_fence *prev)
+{
+	spin_lock_irq(&prev->ts_lock);
+	spin_lock_nested(&next->ts_lock, SINGLE_DEPTH_NESTING); /* Timeline order */

What's the deal with the locking functions here? Why do you lock with irqsave above, and here with _irq?

drm_sched_fence_finished has two callers, one is a dma-fence callback, which taints the whole lock to be irq save. One caller is sometimes already irq off, sometimes not (irqsave), while the other we know it's always the worker context (plain irq).

Quoted 1 line

What's _nested supposed to achieve?

We take the same lock class twice which would upset lockdep without the nested annotation. As this is the only place which does it, and we also have a stable nesting order by the schedule/retire timeline, it is completely fine.

Quoted 7 lines

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 5 lines
drivers/gpu/drm/scheduler/sched_entity.c +5 -0
+	if (next->start_ts &&
+	    ktime_after(prev->finished_ts, next->start_ts) &&
+	    (!next->finished_ts ||
+	     !ktime_after(prev->finished_ts, next->finished_ts)))
+		next->start_ts = prev->finished_ts;

Hard to read logic. Can that be made more readable with goto unlock?

Could do but I am not sure what is more readable. Currently the conditions are explained in the comment above as s consolidated story.

Quoted 12 lines
Quoted 4 lines
drivers/gpu/drm/scheduler/sched_entity.c +4 -0
+	spin_unlock(&next->ts_lock);
+	spin_unlock_irq(&prev->ts_lock);
+}
+

[…]

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 2 lines
drivers/gpu/drm/scheduler/sched_entity.c +2 -0
+	/**
+	 * @ts_lock: Lock used for @start_ts and @finished_ts.

nit s/used for/protecting

Quoted 14 lines

drivers/gpu/drm/scheduler/sched_entity.c

Quoted 12 lines
drivers/gpu/drm/scheduler/sched_entity.c +12 -0
+	 */
+	spinlock_t			ts_lock;
+
+	/**
+	 * @start_ts: ktime of fence GPU execution start or 0 is not started.
+	 *
+	 * Must be accessed via helpers.
+	 */
+	ktime_t				start_ts;
+
+	/**
+	 * @finished_ts: ktime of fence GPU execution end or 0 if not finished.

GPU execution of whom? ;)

The fence this field sits.

Quoted 8 lines

This gets me thinking. So it's the GPU execution time of a … well, job. Not the fences, but they are supposed to track the execution status of a job.

Now with sched_fence, we have this weird situation that it's an API object, mostly entrenched into amdgpu to do container_of on just one fence and then obtain things like the scheduled status.

Quoted 5 lines

Still, struct drm_sched_job annoyingly also contains the job->submit_ts

So I am afraid that our API is about to drift further apart regarding consistency, because the job tracks when it was submitted, but the sched_fence when it was scheduled and when it was finished.

job->submit_ts is only used by the FIFO policy. Wink wink. ;)

Quoted 8 lines

I'm not sure how to set this straight, but if we have so many related timestamps it sounds as if there should be a distinct job_times object for that. But who would access that when and why? That question mostly boils down to amdgpu's desire to obtain these timestamps (why does it even need that, btw? Is that related to your scheduling granularity? drm_sched does the scheduling, so why does amdgpu need *exact* timestamps other than the fence timestamps?)

Quoted 4 lines

We also now have the scheduling stats time object, but I guess that's fine since it's distinct and just accumulates job-times. But hence my question, if the scheduler does the scheduling, then why does an external party need the super-duper-exact timestamps?

External parties currently only need it for gputop.

Perhaps if we merge that patch which exports entity runtime we could also extend it to account for the currently running but not finished, and make amdgpu use that. Then drm_sched_fence_get_times() could become internal function. That would be something to brainstorm if it would be possible. I am not sure we should mandate it comes in a package with this though. This one fixes an overaccounting race, that one would potentially simplify amdgpu entity GPU usage tracking and improve it for other drivers too.

Quoted 12 lines
Quoted 12 lines
drivers/gpu/drm/scheduler/sched_entity.c +5 -0
+	 *
+	 * Must be accessed via helpers.
+	 */
+	ktime_t				finished_ts;
+
  	/**
  	 * @deadline: deadline set on &drm_sched_fence.finished which
  	 * potentially needs to be propagated to &drm_sched_fence.parent
@@ -344,6 +363,26 @@ struct drm_sched_fence {
 
  struct drm_sched_fence *to_drm_sched_fence(struct dma_fence *f);
 
Quoted 14 lines

drivers/gpu/drm/scheduler/sched_entity.c struct drm_sched_fence { · line 376

Quoted 11 lines
drivers/gpu/drm/scheduler/sched_entity.c +11 -0
+/**
+ * drm_sched_fence_get_times() - Get scheduler fence start and finished times
+ * @fence: Scheduler fence
+ * @scheduled: Pointer to scheduled time storage
+ * @finished: Pointer to finished time storage
+ *
+ * Obtains scheduler fence scheduled and finished times.
+ */
+static inline void
+drm_sched_fence_get_times(struct drm_sched_fence *fence,
+			  ktime_t *scheduled, ktime_t *finished)

Yeah, I think two functions are the right thing really, because then you can return "not yet available".

Both callers need both start and end so why force them to cycle the lock twice. I don't see the point.

Regards,

Tvrtko

Quoted 6 lines

*if* anyone really needs only the scheduled without the finished time. See my question above.

P.