xref: /linux/drivers/gpu/drm/scheduler/sched_entity.c (revision 81aa6f190aa0e9ff752fcd0a9eda676458e23133)
1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 
24 #include <linux/export.h>
25 #include <linux/slab.h>
26 #include <linux/completion.h>
27 
28 #include <drm/drm_print.h>
29 #include <drm/gpu_scheduler.h>
30 
31 #include "sched_internal.h"
32 
33 #include "gpu_scheduler_trace.h"
34 
35 /**
36  * drm_sched_entity_stats_release - Entity stats kref release function
37  * @kref: Entity stats embedded kref pointer
38  */
39 void drm_sched_entity_stats_release(struct kref *kref)
40 {
41 	struct drm_sched_entity_stats *stats =
42 		container_of(kref, typeof(*stats), kref);
43 
44 	kfree(stats);
45 }
46 
47 /**
48  * drm_sched_entity_stats_new - Allocate a new struct drm_sched_entity_stats object
49  *
50  * Return: Pointer to newly allocated struct drm_sched_entity_stats object.
51  */
52 static struct drm_sched_entity_stats *drm_sched_entity_stats_new(void)
53 {
54 	struct drm_sched_entity_stats *stats;
55 
56 	stats = kzalloc_obj(*stats);
57 	if (!stats)
58 		return NULL;
59 
60 	kref_init(&stats->kref);
61 	spin_lock_init(&stats->lock);
62 	ewma_drm_sched_avgtime_init(&stats->avg_job_us);
63 
64 	return stats;
65 }
66 
67 /**
68  * drm_sched_entity_stats_job_add_gpu_time - Account job execution time to entity
69  * @job: Scheduler job to account.
70  *
71  * Accounts the execution time of @job to its respective entity stats object.
72  *
73  * Return: Job's real duration in micro seconds.
74  */
75 ktime_t drm_sched_entity_stats_job_add_gpu_time(struct drm_sched_job *job)
76 {
77 	struct drm_sched_entity_stats *stats = job->entity_stats;
78 	struct drm_sched_fence *s_fence = job->s_fence;
79 	ktime_t start, end, duration;
80 
81 	start = dma_fence_timestamp(&s_fence->scheduled);
82 	end = dma_fence_timestamp(&s_fence->finished);
83 	duration = ktime_sub(end, start);
84 
85 	spin_lock(&stats->lock);
86 	stats->runtime = ktime_add(stats->runtime, duration);
87 	ewma_drm_sched_avgtime_add(&stats->avg_job_us, ktime_to_us(duration));
88 	spin_unlock(&stats->lock);
89 
90 	return duration;
91 }
92 
93 /**
94  * drm_sched_entity_init - Init a context entity used by scheduler when
95  * submit to HW ring.
96  *
97  * @entity: scheduler entity to init
98  * @priority: priority of the entity
99  * @sched_list: the list of drm scheds on which jobs from this
100  *           entity can be submitted
101  * @num_sched_list: number of drm sched in sched_list
102  * @guilty: atomic_t set to 1 when a job on this queue
103  *          is found to be guilty causing a timeout
104  *
105  * Note that the &sched_list must have at least one element to schedule the entity.
106  *
107  * For changing @priority later on at runtime see
108  * drm_sched_entity_set_priority(). For changing the set of schedulers
109  * @sched_list at runtime see drm_sched_entity_modify_sched().
110  *
111  * An entity is cleaned up by calling drm_sched_entity_fini(). See also
112  * drm_sched_entity_destroy().
113  *
114  * Returns 0 on success or a negative error code on failure.
115  */
116 int drm_sched_entity_init(struct drm_sched_entity *entity,
117 			  enum drm_sched_priority priority,
118 			  struct drm_gpu_scheduler **sched_list,
119 			  unsigned int num_sched_list,
120 			  atomic_t *guilty)
121 {
122 	if (!entity || !sched_list || !num_sched_list || !sched_list[0])
123 		return -EINVAL;
124 
125 	memset(entity, 0, sizeof(struct drm_sched_entity));
126 
127 	entity->stats = drm_sched_entity_stats_new();
128 	if (!entity->stats)
129 		return -ENOMEM;
130 
131 	INIT_LIST_HEAD(&entity->list);
132 	entity->guilty = guilty;
133 	entity->priority = priority;
134 	entity->last_user = current->group_leader;
135 	entity->num_sched_list = num_sched_list;
136 	entity->sched_list = num_sched_list > 1 ? sched_list : NULL;
137 	entity->rq = &sched_list[0]->rq;
138 	RCU_INIT_POINTER(entity->last_scheduled, NULL);
139 	RB_CLEAR_NODE(&entity->rb_tree_node);
140 	init_completion(&entity->entity_idle);
141 
142 	/* We start in an idle state. */
143 	complete_all(&entity->entity_idle);
144 
145 	spin_lock_init(&entity->lock);
146 	spsc_queue_init(&entity->job_queue);
147 
148 	atomic_set(&entity->fence_seq, 0);
149 	entity->fence_context = dma_fence_context_alloc(2);
150 
151 	return 0;
152 }
153 EXPORT_SYMBOL(drm_sched_entity_init);
154 
155 /**
156  * drm_sched_entity_modify_sched - Modify sched of an entity
157  * @entity: scheduler entity to init
158  * @sched_list: the list of new drm scheds which will replace
159  *		 existing entity->sched_list
160  * @num_sched_list: number of drm sched in sched_list
161  *
162  * Note that this must be called under the same common lock for @entity as
163  * drm_sched_job_arm() and drm_sched_entity_push_job(), or the driver needs to
164  * guarantee through some other means that this is never called while new jobs
165  * can be pushed to @entity.
166  */
167 void drm_sched_entity_modify_sched(struct drm_sched_entity *entity,
168 				    struct drm_gpu_scheduler **sched_list,
169 				    unsigned int num_sched_list)
170 {
171 	WARN_ON(!num_sched_list || !sched_list);
172 
173 	spin_lock(&entity->lock);
174 	entity->sched_list = sched_list;
175 	entity->num_sched_list = num_sched_list;
176 	spin_unlock(&entity->lock);
177 }
178 EXPORT_SYMBOL(drm_sched_entity_modify_sched);
179 
180 static bool drm_sched_entity_is_idle(struct drm_sched_entity *entity)
181 {
182 	rmb(); /* for list_empty to work without lock */
183 
184 	if (list_empty(&entity->list) ||
185 	    spsc_queue_count(&entity->job_queue) == 0 ||
186 	    entity->stopped)
187 		return true;
188 
189 	return false;
190 }
191 
192 /**
193  * drm_sched_entity_error - return error of last scheduled job
194  * @entity: scheduler entity to check
195  *
196  * Opportunistically return the error of the last scheduled job. Result can
197  * change any time when new jobs are pushed to the hw.
198  */
199 int drm_sched_entity_error(struct drm_sched_entity *entity)
200 {
201 	struct dma_fence *fence;
202 	int r;
203 
204 	rcu_read_lock();
205 	fence = rcu_dereference(entity->last_scheduled);
206 	r = fence ? fence->error : 0;
207 	rcu_read_unlock();
208 
209 	return r;
210 }
211 EXPORT_SYMBOL(drm_sched_entity_error);
212 
213 static void drm_sched_entity_kill_jobs_cb(struct dma_fence *f,
214 					  struct dma_fence_cb *cb);
215 
216 static void drm_sched_entity_kill_jobs_work(struct work_struct *wrk)
217 {
218 	struct drm_sched_job *job = container_of(wrk, typeof(*job), work);
219 	struct dma_fence *f;
220 	unsigned long index;
221 
222 	/* Wait for all dependencies to avoid data corruptions */
223 	xa_for_each(&job->dependencies, index, f) {
224 		struct drm_sched_fence *s_fence = to_drm_sched_fence(f);
225 
226 		if (s_fence && f == &s_fence->scheduled) {
227 			/* The dependencies array had a reference on the scheduled
228 			 * fence, and the finished fence refcount might have
229 			 * dropped to zero. Use dma_fence_get_rcu() so we get
230 			 * a NULL fence in that case.
231 			 */
232 			f = dma_fence_get_rcu(&s_fence->finished);
233 
234 			/* Now that we have a reference on the finished fence,
235 			 * we can release the reference the dependencies array
236 			 * had on the scheduled fence.
237 			 */
238 			dma_fence_put(&s_fence->scheduled);
239 		}
240 
241 		xa_erase(&job->dependencies, index);
242 		if (f && !dma_fence_add_callback(f, &job->finish_cb,
243 						 drm_sched_entity_kill_jobs_cb))
244 			return;
245 
246 		dma_fence_put(f);
247 	}
248 
249 	drm_sched_fence_scheduled(job->s_fence, NULL);
250 	drm_sched_fence_finished(job->s_fence, -ESRCH);
251 	WARN_ON(job->s_fence->parent);
252 	job->sched->ops->free_job(job);
253 }
254 
255 /* Signal the scheduler finished fence when the entity in question is killed. */
256 static void drm_sched_entity_kill_jobs_cb(struct dma_fence *f,
257 					  struct dma_fence_cb *cb)
258 {
259 	struct drm_sched_job *job = container_of(cb, struct drm_sched_job,
260 						 finish_cb);
261 
262 	dma_fence_put(f);
263 
264 	INIT_WORK(&job->work, drm_sched_entity_kill_jobs_work);
265 	schedule_work(&job->work);
266 }
267 
268 /**
269  * drm_sched_entity_kill - kill an entity's pending jobs and remove it
270  * @entity: the entity to remove
271  *
272  * Removes the entity from the scheduler's run queue and kills all pending jobs.
273  *
274  * This function should be used over drm_sched_entity_flush() if it is not
275  * desired to actually wait for all pending jobs to finish.
276  */
277 void drm_sched_entity_kill(struct drm_sched_entity *entity)
278 {
279 	struct drm_sched_job *job;
280 	struct dma_fence *prev;
281 
282 	spin_lock(&entity->lock);
283 	entity->stopped = true;
284 	drm_sched_rq_remove_entity(entity->rq, entity);
285 	spin_unlock(&entity->lock);
286 
287 	/* Make sure this entity is not used by the scheduler at the moment */
288 	wait_for_completion(&entity->entity_idle);
289 
290 	/* The entity is guaranteed to not be used by the scheduler */
291 	prev = rcu_dereference_check(entity->last_scheduled, true);
292 	dma_fence_get(prev);
293 	while ((job = drm_sched_entity_queue_pop(entity))) {
294 		struct drm_sched_fence *s_fence = job->s_fence;
295 
296 		dma_fence_get(&s_fence->finished);
297 		if (!prev ||
298 		    dma_fence_add_callback(prev, &job->finish_cb,
299 					   drm_sched_entity_kill_jobs_cb)) {
300 			/*
301 			 * Adding callback above failed.
302 			 * dma_fence_put() checks for NULL.
303 			 */
304 			dma_fence_put(prev);
305 			drm_sched_entity_kill_jobs_cb(NULL, &job->finish_cb);
306 		}
307 
308 		prev = &s_fence->finished;
309 	}
310 	dma_fence_put(prev);
311 }
312 EXPORT_SYMBOL(drm_sched_entity_kill);
313 
314 /**
315  * drm_sched_entity_flush - Flush a context entity
316  *
317  * @entity: scheduler entity
318  * @timeout: time to wait in for Q to become empty in jiffies.
319  *
320  * Splitting drm_sched_entity_fini() into two functions, The first one does the
321  * waiting, removes the entity from the runqueue and returns an error when the
322  * process was killed.
323  *
324  * Returns the remaining time in jiffies left from the input timeout
325  */
326 long drm_sched_entity_flush(struct drm_sched_entity *entity, long timeout)
327 {
328 	struct drm_gpu_scheduler *sched =
329 		container_of(entity->rq, typeof(*sched), rq);
330 	struct task_struct *last_user;
331 	long ret = timeout;
332 
333 	/*
334 	 * The client will not queue more jobs during this fini - consume
335 	 * existing queued ones, or discard them on SIGKILL.
336 	 */
337 	if (current->flags & PF_EXITING) {
338 		if (timeout)
339 			ret = wait_event_timeout(
340 					sched->job_scheduled,
341 					drm_sched_entity_is_idle(entity),
342 					timeout);
343 	} else {
344 		wait_event_killable(sched->job_scheduled,
345 				    drm_sched_entity_is_idle(entity));
346 	}
347 
348 	/* For a killed process disallow further enqueueing of jobs. */
349 	last_user = cmpxchg(&entity->last_user, current->group_leader, NULL);
350 	if (last_user == current->group_leader &&
351 	    (current->flags & PF_EXITING) && (current->exit_code == SIGKILL))
352 		drm_sched_entity_kill(entity);
353 
354 	return ret;
355 }
356 EXPORT_SYMBOL(drm_sched_entity_flush);
357 
358 /**
359  * drm_sched_entity_fini - Destroy a context entity
360  *
361  * @entity: scheduler entity
362  *
363  * Cleanups up @entity which has been initialized by drm_sched_entity_init().
364  *
365  * If there are potentially job still in flight or getting newly queued
366  * drm_sched_entity_flush() must be called first. This function then goes over
367  * the entity and signals all jobs with an error code if the process was killed.
368  */
369 void drm_sched_entity_fini(struct drm_sched_entity *entity)
370 {
371 	/*
372 	 * If consumption of existing jobs wasn't completed forcefully remove
373 	 * them. Also makes sure that the scheduler won't touch this entity any
374 	 * more.
375 	 */
376 	drm_sched_entity_kill(entity);
377 
378 	if (entity->dependency) {
379 		dma_fence_remove_callback(entity->dependency, &entity->cb);
380 		dma_fence_put(entity->dependency);
381 		entity->dependency = NULL;
382 	}
383 
384 	dma_fence_put(rcu_dereference_check(entity->last_scheduled, true));
385 	RCU_INIT_POINTER(entity->last_scheduled, NULL);
386 	drm_sched_entity_stats_put(entity->stats);
387 }
388 EXPORT_SYMBOL(drm_sched_entity_fini);
389 
390 /**
391  * drm_sched_entity_destroy - Destroy a context entity
392  * @entity: scheduler entity
393  *
394  * Calls drm_sched_entity_flush() and drm_sched_entity_fini() as a
395  * convenience wrapper.
396  */
397 void drm_sched_entity_destroy(struct drm_sched_entity *entity)
398 {
399 	drm_sched_entity_flush(entity, MAX_WAIT_SCHED_ENTITY_Q_EMPTY);
400 	drm_sched_entity_fini(entity);
401 }
402 EXPORT_SYMBOL(drm_sched_entity_destroy);
403 
404 /*
405  * drm_sched_entity_wakeup - callback to clear the entity's dependency and
406  * wake up the scheduler
407  */
408 static void drm_sched_entity_wakeup(struct dma_fence *f,
409 				    struct dma_fence_cb *cb)
410 {
411 	struct drm_sched_entity *entity =
412 		container_of(cb, struct drm_sched_entity, cb);
413 	struct drm_gpu_scheduler *sched =
414 		container_of(entity->rq, typeof(*sched), rq);
415 
416 	entity->dependency = NULL;
417 	dma_fence_put(f);
418 	drm_sched_wakeup(sched);
419 }
420 
421 /**
422  * drm_sched_entity_set_priority - Sets priority of the entity
423  *
424  * @entity: scheduler entity
425  * @priority: scheduler priority
426  *
427  * Update the priority of runqueues used for the entity.
428  */
429 void drm_sched_entity_set_priority(struct drm_sched_entity *entity,
430 				   enum drm_sched_priority priority)
431 {
432 	spin_lock(&entity->lock);
433 	entity->priority = priority;
434 	spin_unlock(&entity->lock);
435 }
436 EXPORT_SYMBOL(drm_sched_entity_set_priority);
437 
438 /*
439  * Add a callback to the current dependency of the entity to wake up the
440  * scheduler when the entity becomes available.
441  */
442 static bool drm_sched_entity_add_dependency_cb(struct drm_sched_entity *entity,
443 					       struct drm_sched_job *sched_job)
444 {
445 	struct drm_gpu_scheduler *sched =
446 		container_of(entity->rq, typeof(*sched), rq);
447 	struct dma_fence *fence = entity->dependency;
448 	struct drm_sched_fence *s_fence;
449 
450 	if (fence->context == entity->fence_context ||
451 	    fence->context == entity->fence_context + 1) {
452 		/*
453 		 * Fence is a scheduled/finished fence from a job
454 		 * which belongs to the same entity, we can ignore
455 		 * fences from ourself
456 		 */
457 		dma_fence_put(entity->dependency);
458 		return false;
459 	}
460 
461 	s_fence = to_drm_sched_fence(fence);
462 	if (!fence->error && s_fence && s_fence->sched == sched &&
463 	    !test_bit(DRM_SCHED_FENCE_DONT_PIPELINE, &fence->flags)) {
464 
465 		/*
466 		 * Fence is from the same scheduler, only need to wait for
467 		 * it to be scheduled
468 		 */
469 		fence = dma_fence_get(&s_fence->scheduled);
470 		dma_fence_put(entity->dependency);
471 		entity->dependency = fence;
472 	}
473 
474 	if (trace_drm_sched_job_unschedulable_enabled() &&
475 	    !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &entity->dependency->flags))
476 		trace_drm_sched_job_unschedulable(sched_job, entity->dependency);
477 
478 	if (!dma_fence_add_callback(entity->dependency, &entity->cb,
479 				    drm_sched_entity_wakeup))
480 		return true;
481 
482 	dma_fence_put(entity->dependency);
483 	return false;
484 }
485 
486 static struct dma_fence *
487 drm_sched_job_dependency(struct drm_sched_job *job,
488 			 struct drm_sched_entity *entity)
489 {
490 	struct dma_fence *f;
491 
492 	/* We keep the fence around, so we can iterate over all dependencies
493 	 * in drm_sched_entity_kill_jobs_cb() to ensure all deps are signaled
494 	 * before killing the job.
495 	 */
496 	f = xa_load(&job->dependencies, job->last_dependency);
497 	if (f) {
498 		job->last_dependency++;
499 		return dma_fence_get(f);
500 	}
501 
502 	if (job->sched->ops->prepare_job)
503 		return job->sched->ops->prepare_job(job, entity);
504 
505 	return NULL;
506 }
507 
508 struct drm_sched_job *drm_sched_entity_pop_job(struct drm_sched_entity *entity)
509 {
510 	struct drm_sched_job *sched_job;
511 
512 	sched_job = drm_sched_entity_queue_peek(entity);
513 	if (!sched_job)
514 		return NULL;
515 
516 	while ((entity->dependency =
517 			drm_sched_job_dependency(sched_job, entity))) {
518 		if (drm_sched_entity_add_dependency_cb(entity, sched_job))
519 			return NULL;
520 	}
521 
522 	/* skip jobs from entity that marked guilty */
523 	if (entity->guilty && atomic_read(entity->guilty))
524 		dma_fence_set_error(&sched_job->s_fence->finished, -ECANCELED);
525 
526 	dma_fence_put(rcu_dereference_check(entity->last_scheduled, true));
527 	rcu_assign_pointer(entity->last_scheduled,
528 			   dma_fence_get(&sched_job->s_fence->finished));
529 
530 	/*
531 	 * If the queue is empty we allow drm_sched_entity_select_rq() to
532 	 * locklessly access ->last_scheduled. This only works if we set the
533 	 * pointer before we dequeue and if we a write barrier here.
534 	 */
535 	smp_wmb();
536 
537 	spsc_queue_pop(&entity->job_queue);
538 
539 	drm_sched_rq_pop_entity(entity);
540 
541 	/* Jobs and entities might have different lifecycles. Since we're
542 	 * removing the job from the entities queue, set the jobs entity pointer
543 	 * to NULL to prevent any future access of the entity through this job.
544 	 */
545 	sched_job->entity = NULL;
546 
547 	return sched_job;
548 }
549 
550 void drm_sched_entity_select_rq(struct drm_sched_entity *entity)
551 {
552 	struct dma_fence *fence;
553 	struct drm_gpu_scheduler *sched;
554 	struct drm_sched_rq *rq;
555 
556 	/* single possible engine and already selected */
557 	if (!entity->sched_list)
558 		return;
559 
560 	/* queue non-empty, stay on the same engine */
561 	if (spsc_queue_count(&entity->job_queue))
562 		return;
563 
564 	/*
565 	 * Only when the queue is empty are we guaranteed that
566 	 * drm_sched_run_job_work() cannot change entity->last_scheduled. To
567 	 * enforce ordering we need a read barrier here. See
568 	 * drm_sched_entity_pop_job() for the other side.
569 	 */
570 	smp_rmb();
571 
572 	fence = rcu_dereference_check(entity->last_scheduled, true);
573 
574 	/* stay on the same engine if the previous job hasn't finished */
575 	if (fence && !dma_fence_is_signaled(fence))
576 		return;
577 
578 	spin_lock(&entity->lock);
579 	sched = drm_sched_pick_best(entity->sched_list, entity->num_sched_list);
580 	rq = sched ? &sched->rq : NULL;
581 	if (rq != entity->rq) {
582 		drm_sched_rq_remove_entity(entity->rq, entity);
583 		entity->rq = rq;
584 	}
585 
586 	if (entity->num_sched_list == 1)
587 		entity->sched_list = NULL;
588 
589 	spin_unlock(&entity->lock);
590 }
591 
592 /**
593  * drm_sched_entity_push_job - Submit a job to the entity's job queue
594  * @sched_job: job to submit
595  *
596  * Note: To guarantee that the order of insertion to queue matches the job's
597  * fence sequence number this function should be called with drm_sched_job_arm()
598  * under common lock for the struct drm_sched_entity that was set up for
599  * @sched_job in drm_sched_job_init().
600  */
601 void drm_sched_entity_push_job(struct drm_sched_job *sched_job)
602 {
603 	struct drm_sched_entity *entity = sched_job->entity;
604 	struct drm_gpu_scheduler *sched =
605 		container_of(entity->rq, typeof(*sched), rq);
606 	bool first;
607 
608 	trace_drm_sched_job_queue(sched_job, entity);
609 
610 	if (trace_drm_sched_job_add_dep_enabled()) {
611 		struct dma_fence *entry;
612 		unsigned long index;
613 
614 		xa_for_each(&sched_job->dependencies, index, entry)
615 			trace_drm_sched_job_add_dep(sched_job, entry);
616 	}
617 	atomic_inc(sched->score);
618 	WRITE_ONCE(entity->last_user, current->group_leader);
619 
620 	/*
621 	 * After the sched_job is pushed into the entity queue, it may be
622 	 * completed and freed up at any time. We can no longer access it.
623 	 */
624 	first = spsc_queue_push(&entity->job_queue, &sched_job->queue_node);
625 
626 	/* first job wakes up scheduler */
627 	if (first) {
628 		sched = drm_sched_rq_add_entity(entity);
629 		if (sched)
630 			drm_sched_wakeup(sched);
631 	}
632 }
633 EXPORT_SYMBOL(drm_sched_entity_push_job);
634