2 * Copyright 2015 Advanced Micro Devices, Inc.
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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.
27 * The GPU scheduler provides entities which allow userspace to push jobs
28 * into software queues which are then scheduled on a hardware run queue.
29 * The software queues have a priority among them. The scheduler selects the entities
30 * from the run queue using a FIFO. The scheduler provides dependency handling
31 * features among jobs. The driver is supposed to provide callback functions for
32 * backend operations to the scheduler like submitting a job to hardware run queue,
33 * returning the dependencies of a job etc.
35 * The organisation of the scheduler is the following:
37 * 1. Each hw run queue has one scheduler
38 * 2. Each scheduler has multiple run queues with different priorities
39 * (e.g., HIGH_HW,HIGH_SW, KERNEL, NORMAL)
40 * 3. Each scheduler run queue has a queue of entities to schedule
41 * 4. Entities themselves maintain a queue of jobs that will be scheduled on
44 * The jobs in a entity are always scheduled in the order that they were pushed.
46 * Note that once a job was taken from the entities queue and pushed to the
47 * hardware, i.e. the pending queue, the entity must not be referenced anymore
48 * through the jobs entity pointer.
54 * The DRM GPU scheduler provides a flow control mechanism to regulate the rate
55 * in which the jobs fetched from scheduler entities are executed.
57 * In this context the &drm_gpu_scheduler keeps track of a driver specified
58 * credit limit representing the capacity of this scheduler and a credit count;
59 * every &drm_sched_job carries a driver specified number of credits.
61 * Once a job is executed (but not yet finished), the job's credits contribute
62 * to the scheduler's credit count until the job is finished. If by executing
63 * one more job the scheduler's credit count would exceed the scheduler's
64 * credit limit, the job won't be executed. Instead, the scheduler will wait
65 * until the credit count has decreased enough to not overflow its credit limit.
66 * This implies waiting for previously executed jobs.
68 * Optionally, drivers may register a callback (update_job_credits) provided by
69 * struct drm_sched_backend_ops to update the job's credits dynamically. The
70 * scheduler executes this callback every time the scheduler considers a job for
71 * execution and subsequently checks whether the job fits the scheduler's credit
75 #include <linux/wait.h>
76 #include <linux/sched.h>
77 #include <linux/completion.h>
78 #include <linux/dma-resv.h>
79 #include <uapi/linux/sched/types.h>
81 #include <drm/drm_print.h>
82 #include <drm/drm_gem.h>
83 #include <drm/drm_syncobj.h>
84 #include <drm/gpu_scheduler.h>
85 #include <drm/spsc_queue.h>
87 #define CREATE_TRACE_POINTS
88 #include "gpu_scheduler_trace.h"
90 #define to_drm_sched_job(sched_job) \
91 container_of((sched_job), struct drm_sched_job, queue_node)
93 int drm_sched_policy = DRM_SCHED_POLICY_FIFO;
96 * DOC: sched_policy (int)
97 * Used to override default entities scheduling policy in a run queue.
99 MODULE_PARM_DESC(sched_policy, "Specify the scheduling policy for entities on a run-queue, " __stringify(DRM_SCHED_POLICY_RR) " = Round Robin, " __stringify(DRM_SCHED_POLICY_FIFO) " = FIFO (default).");
100 module_param_named(sched_policy, drm_sched_policy, int, 0444);
102 static u32 drm_sched_available_credits(struct drm_gpu_scheduler *sched)
106 drm_WARN_ON(sched, check_sub_overflow(sched->credit_limit,
107 atomic_read(&sched->credit_count),
114 * drm_sched_can_queue -- Can we queue more to the hardware?
115 * @sched: scheduler instance
116 * @entity: the scheduler entity
118 * Return true if we can push at least one more job from @entity, false
121 static bool drm_sched_can_queue(struct drm_gpu_scheduler *sched,
122 struct drm_sched_entity *entity)
124 struct drm_sched_job *s_job;
126 s_job = to_drm_sched_job(spsc_queue_peek(&entity->job_queue));
130 if (sched->ops->update_job_credits) {
131 s_job->credits = sched->ops->update_job_credits(s_job);
133 drm_WARN(sched, !s_job->credits,
134 "Jobs with zero credits bypass job-flow control.\n");
137 /* If a job exceeds the credit limit, truncate it to the credit limit
138 * itself to guarantee forward progress.
140 if (drm_WARN(sched, s_job->credits > sched->credit_limit,
141 "Jobs may not exceed the credit limit, truncate.\n"))
142 s_job->credits = sched->credit_limit;
144 return drm_sched_available_credits(sched) >= s_job->credits;
147 static __always_inline bool drm_sched_entity_compare_before(struct rb_node *a,
148 const struct rb_node *b)
150 struct drm_sched_entity *ent_a = rb_entry((a), struct drm_sched_entity, rb_tree_node);
151 struct drm_sched_entity *ent_b = rb_entry((b), struct drm_sched_entity, rb_tree_node);
153 return ktime_before(ent_a->oldest_job_waiting, ent_b->oldest_job_waiting);
156 static inline void drm_sched_rq_remove_fifo_locked(struct drm_sched_entity *entity)
158 struct drm_sched_rq *rq = entity->rq;
160 if (!RB_EMPTY_NODE(&entity->rb_tree_node)) {
161 rb_erase_cached(&entity->rb_tree_node, &rq->rb_tree_root);
162 RB_CLEAR_NODE(&entity->rb_tree_node);
166 void drm_sched_rq_update_fifo(struct drm_sched_entity *entity, ktime_t ts)
169 * Both locks need to be grabbed, one to protect from entity->rq change
170 * for entity from within concurrent drm_sched_entity_select_rq and the
171 * other to update the rb tree structure.
173 spin_lock(&entity->rq_lock);
174 spin_lock(&entity->rq->lock);
176 drm_sched_rq_remove_fifo_locked(entity);
178 entity->oldest_job_waiting = ts;
180 rb_add_cached(&entity->rb_tree_node, &entity->rq->rb_tree_root,
181 drm_sched_entity_compare_before);
183 spin_unlock(&entity->rq->lock);
184 spin_unlock(&entity->rq_lock);
188 * drm_sched_rq_init - initialize a given run queue struct
190 * @sched: scheduler instance to associate with this run queue
191 * @rq: scheduler run queue
193 * Initializes a scheduler runqueue.
195 static void drm_sched_rq_init(struct drm_gpu_scheduler *sched,
196 struct drm_sched_rq *rq)
198 spin_lock_init(&rq->lock);
199 INIT_LIST_HEAD(&rq->entities);
200 rq->rb_tree_root = RB_ROOT_CACHED;
201 rq->current_entity = NULL;
206 * drm_sched_rq_add_entity - add an entity
208 * @rq: scheduler run queue
209 * @entity: scheduler entity
211 * Adds a scheduler entity to the run queue.
213 void drm_sched_rq_add_entity(struct drm_sched_rq *rq,
214 struct drm_sched_entity *entity)
216 if (!list_empty(&entity->list))
219 spin_lock(&rq->lock);
221 atomic_inc(rq->sched->score);
222 list_add_tail(&entity->list, &rq->entities);
224 spin_unlock(&rq->lock);
228 * drm_sched_rq_remove_entity - remove an entity
230 * @rq: scheduler run queue
231 * @entity: scheduler entity
233 * Removes a scheduler entity from the run queue.
235 void drm_sched_rq_remove_entity(struct drm_sched_rq *rq,
236 struct drm_sched_entity *entity)
238 if (list_empty(&entity->list))
241 spin_lock(&rq->lock);
243 atomic_dec(rq->sched->score);
244 list_del_init(&entity->list);
246 if (rq->current_entity == entity)
247 rq->current_entity = NULL;
249 if (drm_sched_policy == DRM_SCHED_POLICY_FIFO)
250 drm_sched_rq_remove_fifo_locked(entity);
252 spin_unlock(&rq->lock);
256 * drm_sched_rq_select_entity_rr - Select an entity which could provide a job to run
258 * @sched: the gpu scheduler
259 * @rq: scheduler run queue to check.
261 * Try to find the next ready entity.
263 * Return an entity if one is found; return an error-pointer (!NULL) if an
264 * entity was ready, but the scheduler had insufficient credits to accommodate
265 * its job; return NULL, if no ready entity was found.
267 static struct drm_sched_entity *
268 drm_sched_rq_select_entity_rr(struct drm_gpu_scheduler *sched,
269 struct drm_sched_rq *rq)
271 struct drm_sched_entity *entity;
273 spin_lock(&rq->lock);
275 entity = rq->current_entity;
277 list_for_each_entry_continue(entity, &rq->entities, list) {
278 if (drm_sched_entity_is_ready(entity)) {
279 /* If we can't queue yet, preserve the current
280 * entity in terms of fairness.
282 if (!drm_sched_can_queue(sched, entity)) {
283 spin_unlock(&rq->lock);
284 return ERR_PTR(-ENOSPC);
287 rq->current_entity = entity;
288 reinit_completion(&entity->entity_idle);
289 spin_unlock(&rq->lock);
295 list_for_each_entry(entity, &rq->entities, list) {
296 if (drm_sched_entity_is_ready(entity)) {
297 /* If we can't queue yet, preserve the current entity in
300 if (!drm_sched_can_queue(sched, entity)) {
301 spin_unlock(&rq->lock);
302 return ERR_PTR(-ENOSPC);
305 rq->current_entity = entity;
306 reinit_completion(&entity->entity_idle);
307 spin_unlock(&rq->lock);
311 if (entity == rq->current_entity)
315 spin_unlock(&rq->lock);
321 * drm_sched_rq_select_entity_fifo - Select an entity which provides a job to run
323 * @sched: the gpu scheduler
324 * @rq: scheduler run queue to check.
326 * Find oldest waiting ready entity.
328 * Return an entity if one is found; return an error-pointer (!NULL) if an
329 * entity was ready, but the scheduler had insufficient credits to accommodate
330 * its job; return NULL, if no ready entity was found.
332 static struct drm_sched_entity *
333 drm_sched_rq_select_entity_fifo(struct drm_gpu_scheduler *sched,
334 struct drm_sched_rq *rq)
338 spin_lock(&rq->lock);
339 for (rb = rb_first_cached(&rq->rb_tree_root); rb; rb = rb_next(rb)) {
340 struct drm_sched_entity *entity;
342 entity = rb_entry(rb, struct drm_sched_entity, rb_tree_node);
343 if (drm_sched_entity_is_ready(entity)) {
344 /* If we can't queue yet, preserve the current entity in
347 if (!drm_sched_can_queue(sched, entity)) {
348 spin_unlock(&rq->lock);
349 return ERR_PTR(-ENOSPC);
352 rq->current_entity = entity;
353 reinit_completion(&entity->entity_idle);
357 spin_unlock(&rq->lock);
359 return rb ? rb_entry(rb, struct drm_sched_entity, rb_tree_node) : NULL;
363 * drm_sched_run_job_queue - enqueue run-job work
364 * @sched: scheduler instance
366 static void drm_sched_run_job_queue(struct drm_gpu_scheduler *sched)
368 if (!READ_ONCE(sched->pause_submit))
369 queue_work(sched->submit_wq, &sched->work_run_job);
373 * __drm_sched_run_free_queue - enqueue free-job work
374 * @sched: scheduler instance
376 static void __drm_sched_run_free_queue(struct drm_gpu_scheduler *sched)
378 if (!READ_ONCE(sched->pause_submit))
379 queue_work(sched->submit_wq, &sched->work_free_job);
383 * drm_sched_run_free_queue - enqueue free-job work if ready
384 * @sched: scheduler instance
386 static void drm_sched_run_free_queue(struct drm_gpu_scheduler *sched)
388 struct drm_sched_job *job;
390 spin_lock(&sched->job_list_lock);
391 job = list_first_entry_or_null(&sched->pending_list,
392 struct drm_sched_job, list);
393 if (job && dma_fence_is_signaled(&job->s_fence->finished))
394 __drm_sched_run_free_queue(sched);
395 spin_unlock(&sched->job_list_lock);
399 * drm_sched_job_done - complete a job
400 * @s_job: pointer to the job which is done
402 * Finish the job's fence and wake up the worker thread.
404 static void drm_sched_job_done(struct drm_sched_job *s_job, int result)
406 struct drm_sched_fence *s_fence = s_job->s_fence;
407 struct drm_gpu_scheduler *sched = s_fence->sched;
409 atomic_sub(s_job->credits, &sched->credit_count);
410 atomic_dec(sched->score);
412 trace_drm_sched_process_job(s_fence);
414 dma_fence_get(&s_fence->finished);
415 drm_sched_fence_finished(s_fence, result);
416 dma_fence_put(&s_fence->finished);
417 __drm_sched_run_free_queue(sched);
421 * drm_sched_job_done_cb - the callback for a done job
423 * @cb: fence callbacks
425 static void drm_sched_job_done_cb(struct dma_fence *f, struct dma_fence_cb *cb)
427 struct drm_sched_job *s_job = container_of(cb, struct drm_sched_job, cb);
429 drm_sched_job_done(s_job, f->error);
433 * drm_sched_start_timeout - start timeout for reset worker
435 * @sched: scheduler instance to start the worker for
437 * Start the timeout for the given scheduler.
439 static void drm_sched_start_timeout(struct drm_gpu_scheduler *sched)
441 lockdep_assert_held(&sched->job_list_lock);
443 if (sched->timeout != MAX_SCHEDULE_TIMEOUT &&
444 !list_empty(&sched->pending_list))
445 mod_delayed_work(sched->timeout_wq, &sched->work_tdr, sched->timeout);
448 static void drm_sched_start_timeout_unlocked(struct drm_gpu_scheduler *sched)
450 spin_lock(&sched->job_list_lock);
451 drm_sched_start_timeout(sched);
452 spin_unlock(&sched->job_list_lock);
456 * drm_sched_tdr_queue_imm: - immediately start job timeout handler
458 * @sched: scheduler for which the timeout handling should be started.
460 * Start timeout handling immediately for the named scheduler.
462 void drm_sched_tdr_queue_imm(struct drm_gpu_scheduler *sched)
464 spin_lock(&sched->job_list_lock);
466 drm_sched_start_timeout(sched);
467 spin_unlock(&sched->job_list_lock);
469 EXPORT_SYMBOL(drm_sched_tdr_queue_imm);
472 * drm_sched_fault - immediately start timeout handler
474 * @sched: scheduler where the timeout handling should be started.
476 * Start timeout handling immediately when the driver detects a hardware fault.
478 void drm_sched_fault(struct drm_gpu_scheduler *sched)
480 if (sched->timeout_wq)
481 mod_delayed_work(sched->timeout_wq, &sched->work_tdr, 0);
483 EXPORT_SYMBOL(drm_sched_fault);
486 * drm_sched_suspend_timeout - Suspend scheduler job timeout
488 * @sched: scheduler instance for which to suspend the timeout
490 * Suspend the delayed work timeout for the scheduler. This is done by
491 * modifying the delayed work timeout to an arbitrary large value,
492 * MAX_SCHEDULE_TIMEOUT in this case.
494 * Returns the timeout remaining
497 unsigned long drm_sched_suspend_timeout(struct drm_gpu_scheduler *sched)
499 unsigned long sched_timeout, now = jiffies;
501 sched_timeout = sched->work_tdr.timer.expires;
504 * Modify the timeout to an arbitrarily large value. This also prevents
505 * the timeout to be restarted when new submissions arrive
507 if (mod_delayed_work(sched->timeout_wq, &sched->work_tdr, MAX_SCHEDULE_TIMEOUT)
508 && time_after(sched_timeout, now))
509 return sched_timeout - now;
511 return sched->timeout;
513 EXPORT_SYMBOL(drm_sched_suspend_timeout);
516 * drm_sched_resume_timeout - Resume scheduler job timeout
518 * @sched: scheduler instance for which to resume the timeout
519 * @remaining: remaining timeout
521 * Resume the delayed work timeout for the scheduler.
523 void drm_sched_resume_timeout(struct drm_gpu_scheduler *sched,
524 unsigned long remaining)
526 spin_lock(&sched->job_list_lock);
528 if (list_empty(&sched->pending_list))
529 cancel_delayed_work(&sched->work_tdr);
531 mod_delayed_work(sched->timeout_wq, &sched->work_tdr, remaining);
533 spin_unlock(&sched->job_list_lock);
535 EXPORT_SYMBOL(drm_sched_resume_timeout);
537 static void drm_sched_job_begin(struct drm_sched_job *s_job)
539 struct drm_gpu_scheduler *sched = s_job->sched;
541 spin_lock(&sched->job_list_lock);
542 list_add_tail(&s_job->list, &sched->pending_list);
543 drm_sched_start_timeout(sched);
544 spin_unlock(&sched->job_list_lock);
547 static void drm_sched_job_timedout(struct work_struct *work)
549 struct drm_gpu_scheduler *sched;
550 struct drm_sched_job *job;
551 enum drm_gpu_sched_stat status = DRM_GPU_SCHED_STAT_NOMINAL;
553 sched = container_of(work, struct drm_gpu_scheduler, work_tdr.work);
555 /* Protects against concurrent deletion in drm_sched_get_finished_job */
556 spin_lock(&sched->job_list_lock);
557 job = list_first_entry_or_null(&sched->pending_list,
558 struct drm_sched_job, list);
562 * Remove the bad job so it cannot be freed by concurrent
563 * drm_sched_cleanup_jobs. It will be reinserted back after sched->thread
564 * is parked at which point it's safe.
566 list_del_init(&job->list);
567 spin_unlock(&sched->job_list_lock);
569 status = job->sched->ops->timedout_job(job);
572 * Guilty job did complete and hence needs to be manually removed
573 * See drm_sched_stop doc.
575 if (sched->free_guilty) {
576 job->sched->ops->free_job(job);
577 sched->free_guilty = false;
580 spin_unlock(&sched->job_list_lock);
583 if (status != DRM_GPU_SCHED_STAT_ENODEV)
584 drm_sched_start_timeout_unlocked(sched);
588 * drm_sched_stop - stop the scheduler
590 * @sched: scheduler instance
591 * @bad: job which caused the time out
593 * Stop the scheduler and also removes and frees all completed jobs.
594 * Note: bad job will not be freed as it might be used later and so it's
595 * callers responsibility to release it manually if it's not part of the
596 * pending list any more.
599 void drm_sched_stop(struct drm_gpu_scheduler *sched, struct drm_sched_job *bad)
601 struct drm_sched_job *s_job, *tmp;
603 drm_sched_wqueue_stop(sched);
606 * Reinsert back the bad job here - now it's safe as
607 * drm_sched_get_finished_job cannot race against us and release the
608 * bad job at this point - we parked (waited for) any in progress
609 * (earlier) cleanups and drm_sched_get_finished_job will not be called
610 * now until the scheduler thread is unparked.
612 if (bad && bad->sched == sched)
614 * Add at the head of the queue to reflect it was the earliest
617 list_add(&bad->list, &sched->pending_list);
620 * Iterate the job list from later to earlier one and either deactive
621 * their HW callbacks or remove them from pending list if they already
623 * This iteration is thread safe as sched thread is stopped.
625 list_for_each_entry_safe_reverse(s_job, tmp, &sched->pending_list,
627 if (s_job->s_fence->parent &&
628 dma_fence_remove_callback(s_job->s_fence->parent,
630 dma_fence_put(s_job->s_fence->parent);
631 s_job->s_fence->parent = NULL;
632 atomic_sub(s_job->credits, &sched->credit_count);
635 * remove job from pending_list.
636 * Locking here is for concurrent resume timeout
638 spin_lock(&sched->job_list_lock);
639 list_del_init(&s_job->list);
640 spin_unlock(&sched->job_list_lock);
643 * Wait for job's HW fence callback to finish using s_job
644 * before releasing it.
646 * Job is still alive so fence refcount at least 1
648 dma_fence_wait(&s_job->s_fence->finished, false);
651 * We must keep bad job alive for later use during
652 * recovery by some of the drivers but leave a hint
653 * that the guilty job must be released.
656 sched->ops->free_job(s_job);
658 sched->free_guilty = true;
663 * Stop pending timer in flight as we rearm it in drm_sched_start. This
664 * avoids the pending timeout work in progress to fire right away after
665 * this TDR finished and before the newly restarted jobs had a
666 * chance to complete.
668 cancel_delayed_work(&sched->work_tdr);
671 EXPORT_SYMBOL(drm_sched_stop);
674 * drm_sched_start - recover jobs after a reset
676 * @sched: scheduler instance
679 void drm_sched_start(struct drm_gpu_scheduler *sched)
681 struct drm_sched_job *s_job, *tmp;
684 * Locking the list is not required here as the sched thread is parked
685 * so no new jobs are being inserted or removed. Also concurrent
686 * GPU recovers can't run in parallel.
688 list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
689 struct dma_fence *fence = s_job->s_fence->parent;
691 atomic_add(s_job->credits, &sched->credit_count);
694 drm_sched_job_done(s_job, -ECANCELED);
698 if (dma_fence_add_callback(fence, &s_job->cb,
699 drm_sched_job_done_cb))
700 drm_sched_job_done(s_job, fence->error);
703 drm_sched_start_timeout_unlocked(sched);
704 drm_sched_wqueue_start(sched);
706 EXPORT_SYMBOL(drm_sched_start);
709 * drm_sched_resubmit_jobs - Deprecated, don't use in new code!
711 * @sched: scheduler instance
713 * Re-submitting jobs was a concept AMD came up as cheap way to implement
714 * recovery after a job timeout.
716 * This turned out to be not working very well. First of all there are many
717 * problem with the dma_fence implementation and requirements. Either the
718 * implementation is risking deadlocks with core memory management or violating
719 * documented implementation details of the dma_fence object.
721 * Drivers can still save and restore their state for recovery operations, but
722 * we shouldn't make this a general scheduler feature around the dma_fence
725 void drm_sched_resubmit_jobs(struct drm_gpu_scheduler *sched)
727 struct drm_sched_job *s_job, *tmp;
728 uint64_t guilty_context;
729 bool found_guilty = false;
730 struct dma_fence *fence;
732 list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
733 struct drm_sched_fence *s_fence = s_job->s_fence;
735 if (!found_guilty && atomic_read(&s_job->karma) > sched->hang_limit) {
737 guilty_context = s_job->s_fence->scheduled.context;
740 if (found_guilty && s_job->s_fence->scheduled.context == guilty_context)
741 dma_fence_set_error(&s_fence->finished, -ECANCELED);
743 fence = sched->ops->run_job(s_job);
745 if (IS_ERR_OR_NULL(fence)) {
747 dma_fence_set_error(&s_fence->finished, PTR_ERR(fence));
749 s_job->s_fence->parent = NULL;
752 s_job->s_fence->parent = dma_fence_get(fence);
754 /* Drop for orignal kref_init */
755 dma_fence_put(fence);
759 EXPORT_SYMBOL(drm_sched_resubmit_jobs);
762 * drm_sched_job_init - init a scheduler job
763 * @job: scheduler job to init
764 * @entity: scheduler entity to use
765 * @credits: the number of credits this job contributes to the schedulers
767 * @owner: job owner for debugging
769 * Refer to drm_sched_entity_push_job() documentation
770 * for locking considerations.
772 * Drivers must make sure drm_sched_job_cleanup() if this function returns
773 * successfully, even when @job is aborted before drm_sched_job_arm() is called.
775 * WARNING: amdgpu abuses &drm_sched.ready to signal when the hardware
776 * has died, which can mean that there's no valid runqueue for a @entity.
777 * This function returns -ENOENT in this case (which probably should be -EIO as
778 * a more meanigful return value).
780 * Returns 0 for success, negative error code otherwise.
782 int drm_sched_job_init(struct drm_sched_job *job,
783 struct drm_sched_entity *entity,
784 u32 credits, void *owner)
787 /* This will most likely be followed by missing frames
788 * or worse--a blank screen--leave a trail in the
789 * logs, so this can be debugged easier.
791 drm_err(job->sched, "%s: entity has no rq!\n", __func__);
795 if (unlikely(!credits)) {
796 pr_err("*ERROR* %s: credits cannot be 0!\n", __func__);
800 job->entity = entity;
801 job->credits = credits;
802 job->s_fence = drm_sched_fence_alloc(entity, owner);
806 INIT_LIST_HEAD(&job->list);
808 xa_init_flags(&job->dependencies, XA_FLAGS_ALLOC);
812 EXPORT_SYMBOL(drm_sched_job_init);
815 * drm_sched_job_arm - arm a scheduler job for execution
816 * @job: scheduler job to arm
818 * This arms a scheduler job for execution. Specifically it initializes the
819 * &drm_sched_job.s_fence of @job, so that it can be attached to struct dma_resv
820 * or other places that need to track the completion of this job.
822 * Refer to drm_sched_entity_push_job() documentation for locking
825 * This can only be called if drm_sched_job_init() succeeded.
827 void drm_sched_job_arm(struct drm_sched_job *job)
829 struct drm_gpu_scheduler *sched;
830 struct drm_sched_entity *entity = job->entity;
833 drm_sched_entity_select_rq(entity);
834 sched = entity->rq->sched;
837 job->s_priority = entity->priority;
838 job->id = atomic64_inc_return(&sched->job_id_count);
840 drm_sched_fence_init(job->s_fence, job->entity);
842 EXPORT_SYMBOL(drm_sched_job_arm);
845 * drm_sched_job_add_dependency - adds the fence as a job dependency
846 * @job: scheduler job to add the dependencies to
847 * @fence: the dma_fence to add to the list of dependencies.
849 * Note that @fence is consumed in both the success and error cases.
852 * 0 on success, or an error on failing to expand the array.
854 int drm_sched_job_add_dependency(struct drm_sched_job *job,
855 struct dma_fence *fence)
857 struct dma_fence *entry;
865 /* Deduplicate if we already depend on a fence from the same context.
866 * This lets the size of the array of deps scale with the number of
867 * engines involved, rather than the number of BOs.
869 xa_for_each(&job->dependencies, index, entry) {
870 if (entry->context != fence->context)
873 if (dma_fence_is_later(fence, entry)) {
874 dma_fence_put(entry);
875 xa_store(&job->dependencies, index, fence, GFP_KERNEL);
877 dma_fence_put(fence);
882 ret = xa_alloc(&job->dependencies, &id, fence, xa_limit_32b, GFP_KERNEL);
884 dma_fence_put(fence);
888 EXPORT_SYMBOL(drm_sched_job_add_dependency);
891 * drm_sched_job_add_syncobj_dependency - adds a syncobj's fence as a job dependency
892 * @job: scheduler job to add the dependencies to
893 * @file: drm file private pointer
894 * @handle: syncobj handle to lookup
895 * @point: timeline point
897 * This adds the fence matching the given syncobj to @job.
900 * 0 on success, or an error on failing to expand the array.
902 int drm_sched_job_add_syncobj_dependency(struct drm_sched_job *job,
903 struct drm_file *file,
907 struct dma_fence *fence;
910 ret = drm_syncobj_find_fence(file, handle, point, 0, &fence);
914 return drm_sched_job_add_dependency(job, fence);
916 EXPORT_SYMBOL(drm_sched_job_add_syncobj_dependency);
919 * drm_sched_job_add_resv_dependencies - add all fences from the resv to the job
920 * @job: scheduler job to add the dependencies to
921 * @resv: the dma_resv object to get the fences from
922 * @usage: the dma_resv_usage to use to filter the fences
924 * This adds all fences matching the given usage from @resv to @job.
925 * Must be called with the @resv lock held.
928 * 0 on success, or an error on failing to expand the array.
930 int drm_sched_job_add_resv_dependencies(struct drm_sched_job *job,
931 struct dma_resv *resv,
932 enum dma_resv_usage usage)
934 struct dma_resv_iter cursor;
935 struct dma_fence *fence;
938 dma_resv_assert_held(resv);
940 dma_resv_for_each_fence(&cursor, resv, usage, fence) {
941 /* Make sure to grab an additional ref on the added fence */
942 dma_fence_get(fence);
943 ret = drm_sched_job_add_dependency(job, fence);
945 dma_fence_put(fence);
951 EXPORT_SYMBOL(drm_sched_job_add_resv_dependencies);
954 * drm_sched_job_add_implicit_dependencies - adds implicit dependencies as job
956 * @job: scheduler job to add the dependencies to
957 * @obj: the gem object to add new dependencies from.
958 * @write: whether the job might write the object (so we need to depend on
959 * shared fences in the reservation object).
961 * This should be called after drm_gem_lock_reservations() on your array of
962 * GEM objects used in the job but before updating the reservations with your
966 * 0 on success, or an error on failing to expand the array.
968 int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job,
969 struct drm_gem_object *obj,
972 return drm_sched_job_add_resv_dependencies(job, obj->resv,
973 dma_resv_usage_rw(write));
975 EXPORT_SYMBOL(drm_sched_job_add_implicit_dependencies);
978 * drm_sched_job_cleanup - clean up scheduler job resources
979 * @job: scheduler job to clean up
981 * Cleans up the resources allocated with drm_sched_job_init().
983 * Drivers should call this from their error unwind code if @job is aborted
984 * before drm_sched_job_arm() is called.
986 * After that point of no return @job is committed to be executed by the
987 * scheduler, and this function should be called from the
988 * &drm_sched_backend_ops.free_job callback.
990 void drm_sched_job_cleanup(struct drm_sched_job *job)
992 struct dma_fence *fence;
995 if (kref_read(&job->s_fence->finished.refcount)) {
996 /* drm_sched_job_arm() has been called */
997 dma_fence_put(&job->s_fence->finished);
999 /* aborted job before committing to run it */
1000 drm_sched_fence_free(job->s_fence);
1003 job->s_fence = NULL;
1005 xa_for_each(&job->dependencies, index, fence) {
1006 dma_fence_put(fence);
1008 xa_destroy(&job->dependencies);
1011 EXPORT_SYMBOL(drm_sched_job_cleanup);
1014 * drm_sched_wakeup - Wake up the scheduler if it is ready to queue
1015 * @sched: scheduler instance
1016 * @entity: the scheduler entity
1018 * Wake up the scheduler if we can queue jobs.
1020 void drm_sched_wakeup(struct drm_gpu_scheduler *sched,
1021 struct drm_sched_entity *entity)
1023 if (drm_sched_can_queue(sched, entity))
1024 drm_sched_run_job_queue(sched);
1028 * drm_sched_select_entity - Select next entity to process
1030 * @sched: scheduler instance
1032 * Return an entity to process or NULL if none are found.
1034 * Note, that we break out of the for-loop when "entity" is non-null, which can
1035 * also be an error-pointer--this assures we don't process lower priority
1036 * run-queues. See comments in the respectively called functions.
1038 static struct drm_sched_entity *
1039 drm_sched_select_entity(struct drm_gpu_scheduler *sched)
1041 struct drm_sched_entity *entity;
1044 /* Start with the highest priority.
1046 for (i = DRM_SCHED_PRIORITY_KERNEL; i < sched->num_rqs; i++) {
1047 entity = drm_sched_policy == DRM_SCHED_POLICY_FIFO ?
1048 drm_sched_rq_select_entity_fifo(sched, sched->sched_rq[i]) :
1049 drm_sched_rq_select_entity_rr(sched, sched->sched_rq[i]);
1054 return IS_ERR(entity) ? NULL : entity;
1058 * drm_sched_get_finished_job - fetch the next finished job to be destroyed
1060 * @sched: scheduler instance
1062 * Returns the next finished job from the pending list (if there is one)
1063 * ready for it to be destroyed.
1065 static struct drm_sched_job *
1066 drm_sched_get_finished_job(struct drm_gpu_scheduler *sched)
1068 struct drm_sched_job *job, *next;
1070 spin_lock(&sched->job_list_lock);
1072 job = list_first_entry_or_null(&sched->pending_list,
1073 struct drm_sched_job, list);
1075 if (job && dma_fence_is_signaled(&job->s_fence->finished)) {
1076 /* remove job from pending_list */
1077 list_del_init(&job->list);
1079 /* cancel this job's TO timer */
1080 cancel_delayed_work(&sched->work_tdr);
1081 /* make the scheduled timestamp more accurate */
1082 next = list_first_entry_or_null(&sched->pending_list,
1083 typeof(*next), list);
1086 if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT,
1087 &next->s_fence->scheduled.flags))
1088 next->s_fence->scheduled.timestamp =
1089 dma_fence_timestamp(&job->s_fence->finished);
1090 /* start TO timer for next job */
1091 drm_sched_start_timeout(sched);
1097 spin_unlock(&sched->job_list_lock);
1103 * drm_sched_pick_best - Get a drm sched from a sched_list with the least load
1104 * @sched_list: list of drm_gpu_schedulers
1105 * @num_sched_list: number of drm_gpu_schedulers in the sched_list
1107 * Returns pointer of the sched with the least load or NULL if none of the
1108 * drm_gpu_schedulers are ready
1110 struct drm_gpu_scheduler *
1111 drm_sched_pick_best(struct drm_gpu_scheduler **sched_list,
1112 unsigned int num_sched_list)
1114 struct drm_gpu_scheduler *sched, *picked_sched = NULL;
1116 unsigned int min_score = UINT_MAX, num_score;
1118 for (i = 0; i < num_sched_list; ++i) {
1119 sched = sched_list[i];
1121 if (!sched->ready) {
1122 DRM_WARN("scheduler %s is not ready, skipping",
1127 num_score = atomic_read(sched->score);
1128 if (num_score < min_score) {
1129 min_score = num_score;
1130 picked_sched = sched;
1134 return picked_sched;
1136 EXPORT_SYMBOL(drm_sched_pick_best);
1139 * drm_sched_free_job_work - worker to call free_job
1143 static void drm_sched_free_job_work(struct work_struct *w)
1145 struct drm_gpu_scheduler *sched =
1146 container_of(w, struct drm_gpu_scheduler, work_free_job);
1147 struct drm_sched_job *job;
1149 if (READ_ONCE(sched->pause_submit))
1152 job = drm_sched_get_finished_job(sched);
1154 sched->ops->free_job(job);
1156 drm_sched_run_free_queue(sched);
1157 drm_sched_run_job_queue(sched);
1161 * drm_sched_run_job_work - worker to call run_job
1165 static void drm_sched_run_job_work(struct work_struct *w)
1167 struct drm_gpu_scheduler *sched =
1168 container_of(w, struct drm_gpu_scheduler, work_run_job);
1169 struct drm_sched_entity *entity;
1170 struct dma_fence *fence;
1171 struct drm_sched_fence *s_fence;
1172 struct drm_sched_job *sched_job;
1175 if (READ_ONCE(sched->pause_submit))
1178 /* Find entity with a ready job */
1179 entity = drm_sched_select_entity(sched);
1181 return; /* No more work */
1183 sched_job = drm_sched_entity_pop_job(entity);
1185 complete_all(&entity->entity_idle);
1186 drm_sched_run_job_queue(sched);
1190 s_fence = sched_job->s_fence;
1192 atomic_add(sched_job->credits, &sched->credit_count);
1193 drm_sched_job_begin(sched_job);
1195 trace_drm_run_job(sched_job, entity);
1196 fence = sched->ops->run_job(sched_job);
1197 complete_all(&entity->entity_idle);
1198 drm_sched_fence_scheduled(s_fence, fence);
1200 if (!IS_ERR_OR_NULL(fence)) {
1201 /* Drop for original kref_init of the fence */
1202 dma_fence_put(fence);
1204 r = dma_fence_add_callback(fence, &sched_job->cb,
1205 drm_sched_job_done_cb);
1207 drm_sched_job_done(sched_job, fence->error);
1209 DRM_DEV_ERROR(sched->dev, "fence add callback failed (%d)\n", r);
1211 drm_sched_job_done(sched_job, IS_ERR(fence) ?
1212 PTR_ERR(fence) : 0);
1215 wake_up(&sched->job_scheduled);
1216 drm_sched_run_job_queue(sched);
1220 * drm_sched_init - Init a gpu scheduler instance
1222 * @sched: scheduler instance
1223 * @ops: backend operations for this scheduler
1224 * @submit_wq: workqueue to use for submission. If NULL, an ordered wq is
1225 * allocated and used
1226 * @num_rqs: number of runqueues, one for each priority, up to DRM_SCHED_PRIORITY_COUNT
1227 * @credit_limit: the number of credits this scheduler can hold from all jobs
1228 * @hang_limit: number of times to allow a job to hang before dropping it
1229 * @timeout: timeout value in jiffies for the scheduler
1230 * @timeout_wq: workqueue to use for timeout work. If NULL, the system_wq is
1232 * @score: optional score atomic shared with other schedulers
1233 * @name: name used for debugging
1234 * @dev: target &struct device
1236 * Return 0 on success, otherwise error code.
1238 int drm_sched_init(struct drm_gpu_scheduler *sched,
1239 const struct drm_sched_backend_ops *ops,
1240 struct workqueue_struct *submit_wq,
1241 u32 num_rqs, u32 credit_limit, unsigned int hang_limit,
1242 long timeout, struct workqueue_struct *timeout_wq,
1243 atomic_t *score, const char *name, struct device *dev)
1248 sched->credit_limit = credit_limit;
1250 sched->timeout = timeout;
1251 sched->timeout_wq = timeout_wq ? : system_wq;
1252 sched->hang_limit = hang_limit;
1253 sched->score = score ? score : &sched->_score;
1256 if (num_rqs > DRM_SCHED_PRIORITY_COUNT) {
1257 /* This is a gross violation--tell drivers what the problem is.
1259 drm_err(sched, "%s: num_rqs cannot be greater than DRM_SCHED_PRIORITY_COUNT\n",
1262 } else if (sched->sched_rq) {
1263 /* Not an error, but warn anyway so drivers can
1264 * fine-tune their DRM calling order, and return all
1267 drm_warn(sched, "%s: scheduler already initialized!\n", __func__);
1272 sched->submit_wq = submit_wq;
1273 sched->own_submit_wq = false;
1275 sched->submit_wq = alloc_ordered_workqueue(name, 0);
1276 if (!sched->submit_wq)
1279 sched->own_submit_wq = true;
1282 sched->sched_rq = kmalloc_array(num_rqs, sizeof(*sched->sched_rq),
1283 GFP_KERNEL | __GFP_ZERO);
1284 if (!sched->sched_rq)
1286 sched->num_rqs = num_rqs;
1287 for (i = DRM_SCHED_PRIORITY_KERNEL; i < sched->num_rqs; i++) {
1288 sched->sched_rq[i] = kzalloc(sizeof(*sched->sched_rq[i]), GFP_KERNEL);
1289 if (!sched->sched_rq[i])
1291 drm_sched_rq_init(sched, sched->sched_rq[i]);
1294 init_waitqueue_head(&sched->job_scheduled);
1295 INIT_LIST_HEAD(&sched->pending_list);
1296 spin_lock_init(&sched->job_list_lock);
1297 atomic_set(&sched->credit_count, 0);
1298 INIT_DELAYED_WORK(&sched->work_tdr, drm_sched_job_timedout);
1299 INIT_WORK(&sched->work_run_job, drm_sched_run_job_work);
1300 INIT_WORK(&sched->work_free_job, drm_sched_free_job_work);
1301 atomic_set(&sched->_score, 0);
1302 atomic64_set(&sched->job_id_count, 0);
1303 sched->pause_submit = false;
1305 sched->ready = true;
1308 for (--i ; i >= DRM_SCHED_PRIORITY_KERNEL; i--)
1309 kfree(sched->sched_rq[i]);
1311 kfree(sched->sched_rq);
1312 sched->sched_rq = NULL;
1314 if (sched->own_submit_wq)
1315 destroy_workqueue(sched->submit_wq);
1316 drm_err(sched, "%s: Failed to setup GPU scheduler--out of memory\n", __func__);
1319 EXPORT_SYMBOL(drm_sched_init);
1322 * drm_sched_fini - Destroy a gpu scheduler
1324 * @sched: scheduler instance
1326 * Tears down and cleans up the scheduler.
1328 void drm_sched_fini(struct drm_gpu_scheduler *sched)
1330 struct drm_sched_entity *s_entity;
1333 drm_sched_wqueue_stop(sched);
1335 for (i = DRM_SCHED_PRIORITY_KERNEL; i < sched->num_rqs; i++) {
1336 struct drm_sched_rq *rq = sched->sched_rq[i];
1338 spin_lock(&rq->lock);
1339 list_for_each_entry(s_entity, &rq->entities, list)
1341 * Prevents reinsertion and marks job_queue as idle,
1342 * it will removed from rq in drm_sched_entity_fini
1345 s_entity->stopped = true;
1346 spin_unlock(&rq->lock);
1347 kfree(sched->sched_rq[i]);
1350 /* Wakeup everyone stuck in drm_sched_entity_flush for this scheduler */
1351 wake_up_all(&sched->job_scheduled);
1353 /* Confirm no work left behind accessing device structures */
1354 cancel_delayed_work_sync(&sched->work_tdr);
1356 if (sched->own_submit_wq)
1357 destroy_workqueue(sched->submit_wq);
1358 sched->ready = false;
1359 kfree(sched->sched_rq);
1360 sched->sched_rq = NULL;
1362 EXPORT_SYMBOL(drm_sched_fini);
1365 * drm_sched_increase_karma - Update sched_entity guilty flag
1367 * @bad: The job guilty of time out
1369 * Increment on every hang caused by the 'bad' job. If this exceeds the hang
1370 * limit of the scheduler then the respective sched entity is marked guilty and
1371 * jobs from it will not be scheduled further
1373 void drm_sched_increase_karma(struct drm_sched_job *bad)
1376 struct drm_sched_entity *tmp;
1377 struct drm_sched_entity *entity;
1378 struct drm_gpu_scheduler *sched = bad->sched;
1380 /* don't change @bad's karma if it's from KERNEL RQ,
1381 * because sometimes GPU hang would cause kernel jobs (like VM updating jobs)
1382 * corrupt but keep in mind that kernel jobs always considered good.
1384 if (bad->s_priority != DRM_SCHED_PRIORITY_KERNEL) {
1385 atomic_inc(&bad->karma);
1387 for (i = DRM_SCHED_PRIORITY_HIGH; i < sched->num_rqs; i++) {
1388 struct drm_sched_rq *rq = sched->sched_rq[i];
1390 spin_lock(&rq->lock);
1391 list_for_each_entry_safe(entity, tmp, &rq->entities, list) {
1392 if (bad->s_fence->scheduled.context ==
1393 entity->fence_context) {
1395 atomic_set(entity->guilty, 1);
1399 spin_unlock(&rq->lock);
1400 if (&entity->list != &rq->entities)
1405 EXPORT_SYMBOL(drm_sched_increase_karma);
1408 * drm_sched_wqueue_ready - Is the scheduler ready for submission
1410 * @sched: scheduler instance
1412 * Returns true if submission is ready
1414 bool drm_sched_wqueue_ready(struct drm_gpu_scheduler *sched)
1416 return sched->ready;
1418 EXPORT_SYMBOL(drm_sched_wqueue_ready);
1421 * drm_sched_wqueue_stop - stop scheduler submission
1423 * @sched: scheduler instance
1425 void drm_sched_wqueue_stop(struct drm_gpu_scheduler *sched)
1427 WRITE_ONCE(sched->pause_submit, true);
1428 cancel_work_sync(&sched->work_run_job);
1429 cancel_work_sync(&sched->work_free_job);
1431 EXPORT_SYMBOL(drm_sched_wqueue_stop);
1434 * drm_sched_wqueue_start - start scheduler submission
1436 * @sched: scheduler instance
1438 void drm_sched_wqueue_start(struct drm_gpu_scheduler *sched)
1440 WRITE_ONCE(sched->pause_submit, false);
1441 queue_work(sched->submit_wq, &sched->work_run_job);
1442 queue_work(sched->submit_wq, &sched->work_free_job);
1444 EXPORT_SYMBOL(drm_sched_wqueue_start);