xref: /linux/drivers/gpu/drm/scheduler/sched_main.c (revision 878516a9e62cd220379e511d43dcf58df3a6ca9f)
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 /**
25  * DOC: Overview
26  *
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.
34  *
35  * The organisation of the scheduler is the following:
36  *
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
42  *    the hardware.
43  *
44  * The jobs in an entity are always scheduled in the order in which they were pushed.
45  *
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.
49  */
50 
51 /**
52  * DOC: Flow Control
53  *
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.
56  *
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.
60  *
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.
67  */
68 
69 #include <linux/wait.h>
70 #include <linux/sched.h>
71 #include <linux/completion.h>
72 #include <linux/dma-resv.h>
73 #include <uapi/linux/sched/types.h>
74 
75 #include <drm/drm_print.h>
76 #include <drm/drm_gem.h>
77 #include <drm/drm_syncobj.h>
78 #include <drm/gpu_scheduler.h>
79 #include <drm/spsc_queue.h>
80 
81 #include "sched_internal.h"
82 
83 #define CREATE_TRACE_POINTS
84 #include "gpu_scheduler_trace.h"
85 
86 #ifdef CONFIG_LOCKDEP
87 static struct lockdep_map drm_sched_lockdep_map = {
88 	.name = "drm_sched_lockdep_map"
89 };
90 #endif
91 
92 int drm_sched_policy = DRM_SCHED_POLICY_FIFO;
93 
94 /**
95  * DOC: sched_policy (int)
96  * Used to override default entities scheduling policy in a run queue.
97  */
98 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).");
99 module_param_named(sched_policy, drm_sched_policy, int, 0444);
100 
101 static u32 drm_sched_available_credits(struct drm_gpu_scheduler *sched)
102 {
103 	u32 credits;
104 
105 	WARN_ON(check_sub_overflow(sched->credit_limit,
106 				   atomic_read(&sched->credit_count),
107 				   &credits));
108 
109 	return credits;
110 }
111 
112 /**
113  * drm_sched_can_queue -- Can we queue more to the hardware?
114  * @sched: scheduler instance
115  * @entity: the scheduler entity
116  *
117  * Return true if we can push at least one more job from @entity, false
118  * otherwise.
119  */
120 static bool drm_sched_can_queue(struct drm_gpu_scheduler *sched,
121 				struct drm_sched_entity *entity)
122 {
123 	struct drm_sched_job *s_job;
124 
125 	s_job = drm_sched_entity_queue_peek(entity);
126 	if (!s_job)
127 		return false;
128 
129 	/* If a job exceeds the credit limit, truncate it to the credit limit
130 	 * itself to guarantee forward progress.
131 	 */
132 	if (s_job->credits > sched->credit_limit) {
133 		dev_WARN(sched->dev,
134 			 "Jobs may not exceed the credit limit, truncate.\n");
135 		s_job->credits = sched->credit_limit;
136 	}
137 
138 	return drm_sched_available_credits(sched) >= s_job->credits;
139 }
140 
141 static __always_inline bool drm_sched_entity_compare_before(struct rb_node *a,
142 							    const struct rb_node *b)
143 {
144 	struct drm_sched_entity *ent_a =  rb_entry((a), struct drm_sched_entity, rb_tree_node);
145 	struct drm_sched_entity *ent_b =  rb_entry((b), struct drm_sched_entity, rb_tree_node);
146 
147 	return ktime_before(ent_a->oldest_job_waiting, ent_b->oldest_job_waiting);
148 }
149 
150 static void drm_sched_rq_remove_fifo_locked(struct drm_sched_entity *entity,
151 					    struct drm_sched_rq *rq)
152 {
153 	if (!RB_EMPTY_NODE(&entity->rb_tree_node)) {
154 		rb_erase_cached(&entity->rb_tree_node, &rq->rb_tree_root);
155 		RB_CLEAR_NODE(&entity->rb_tree_node);
156 	}
157 }
158 
159 void drm_sched_rq_update_fifo_locked(struct drm_sched_entity *entity,
160 				     struct drm_sched_rq *rq,
161 				     ktime_t ts)
162 {
163 	/*
164 	 * Both locks need to be grabbed, one to protect from entity->rq change
165 	 * for entity from within concurrent drm_sched_entity_select_rq and the
166 	 * other to update the rb tree structure.
167 	 */
168 	lockdep_assert_held(&entity->lock);
169 	lockdep_assert_held(&rq->lock);
170 
171 	drm_sched_rq_remove_fifo_locked(entity, rq);
172 
173 	entity->oldest_job_waiting = ts;
174 
175 	rb_add_cached(&entity->rb_tree_node, &rq->rb_tree_root,
176 		      drm_sched_entity_compare_before);
177 }
178 
179 /**
180  * drm_sched_rq_init - initialize a given run queue struct
181  *
182  * @sched: scheduler instance to associate with this run queue
183  * @rq: scheduler run queue
184  *
185  * Initializes a scheduler runqueue.
186  */
187 static void drm_sched_rq_init(struct drm_gpu_scheduler *sched,
188 			      struct drm_sched_rq *rq)
189 {
190 	spin_lock_init(&rq->lock);
191 	INIT_LIST_HEAD(&rq->entities);
192 	rq->rb_tree_root = RB_ROOT_CACHED;
193 	rq->current_entity = NULL;
194 	rq->sched = sched;
195 }
196 
197 /**
198  * drm_sched_rq_add_entity - add an entity
199  *
200  * @rq: scheduler run queue
201  * @entity: scheduler entity
202  *
203  * Adds a scheduler entity to the run queue.
204  */
205 void drm_sched_rq_add_entity(struct drm_sched_rq *rq,
206 			     struct drm_sched_entity *entity)
207 {
208 	lockdep_assert_held(&entity->lock);
209 	lockdep_assert_held(&rq->lock);
210 
211 	if (!list_empty(&entity->list))
212 		return;
213 
214 	atomic_inc(rq->sched->score);
215 	list_add_tail(&entity->list, &rq->entities);
216 }
217 
218 /**
219  * drm_sched_rq_remove_entity - remove an entity
220  *
221  * @rq: scheduler run queue
222  * @entity: scheduler entity
223  *
224  * Removes a scheduler entity from the run queue.
225  */
226 void drm_sched_rq_remove_entity(struct drm_sched_rq *rq,
227 				struct drm_sched_entity *entity)
228 {
229 	lockdep_assert_held(&entity->lock);
230 
231 	if (list_empty(&entity->list))
232 		return;
233 
234 	spin_lock(&rq->lock);
235 
236 	atomic_dec(rq->sched->score);
237 	list_del_init(&entity->list);
238 
239 	if (rq->current_entity == entity)
240 		rq->current_entity = NULL;
241 
242 	if (drm_sched_policy == DRM_SCHED_POLICY_FIFO)
243 		drm_sched_rq_remove_fifo_locked(entity, rq);
244 
245 	spin_unlock(&rq->lock);
246 }
247 
248 /**
249  * drm_sched_rq_select_entity_rr - Select an entity which could provide a job to run
250  *
251  * @sched: the gpu scheduler
252  * @rq: scheduler run queue to check.
253  *
254  * Try to find the next ready entity.
255  *
256  * Return an entity if one is found; return an error-pointer (!NULL) if an
257  * entity was ready, but the scheduler had insufficient credits to accommodate
258  * its job; return NULL, if no ready entity was found.
259  */
260 static struct drm_sched_entity *
261 drm_sched_rq_select_entity_rr(struct drm_gpu_scheduler *sched,
262 			      struct drm_sched_rq *rq)
263 {
264 	struct drm_sched_entity *entity;
265 
266 	spin_lock(&rq->lock);
267 
268 	entity = rq->current_entity;
269 	if (entity) {
270 		list_for_each_entry_continue(entity, &rq->entities, list) {
271 			if (drm_sched_entity_is_ready(entity)) {
272 				/* If we can't queue yet, preserve the current
273 				 * entity in terms of fairness.
274 				 */
275 				if (!drm_sched_can_queue(sched, entity)) {
276 					spin_unlock(&rq->lock);
277 					return ERR_PTR(-ENOSPC);
278 				}
279 
280 				rq->current_entity = entity;
281 				reinit_completion(&entity->entity_idle);
282 				spin_unlock(&rq->lock);
283 				return entity;
284 			}
285 		}
286 	}
287 
288 	list_for_each_entry(entity, &rq->entities, list) {
289 		if (drm_sched_entity_is_ready(entity)) {
290 			/* If we can't queue yet, preserve the current entity in
291 			 * terms of fairness.
292 			 */
293 			if (!drm_sched_can_queue(sched, entity)) {
294 				spin_unlock(&rq->lock);
295 				return ERR_PTR(-ENOSPC);
296 			}
297 
298 			rq->current_entity = entity;
299 			reinit_completion(&entity->entity_idle);
300 			spin_unlock(&rq->lock);
301 			return entity;
302 		}
303 
304 		if (entity == rq->current_entity)
305 			break;
306 	}
307 
308 	spin_unlock(&rq->lock);
309 
310 	return NULL;
311 }
312 
313 /**
314  * drm_sched_rq_select_entity_fifo - Select an entity which provides a job to run
315  *
316  * @sched: the gpu scheduler
317  * @rq: scheduler run queue to check.
318  *
319  * Find oldest waiting ready entity.
320  *
321  * Return an entity if one is found; return an error-pointer (!NULL) if an
322  * entity was ready, but the scheduler had insufficient credits to accommodate
323  * its job; return NULL, if no ready entity was found.
324  */
325 static struct drm_sched_entity *
326 drm_sched_rq_select_entity_fifo(struct drm_gpu_scheduler *sched,
327 				struct drm_sched_rq *rq)
328 {
329 	struct rb_node *rb;
330 
331 	spin_lock(&rq->lock);
332 	for (rb = rb_first_cached(&rq->rb_tree_root); rb; rb = rb_next(rb)) {
333 		struct drm_sched_entity *entity;
334 
335 		entity = rb_entry(rb, struct drm_sched_entity, rb_tree_node);
336 		if (drm_sched_entity_is_ready(entity)) {
337 			/* If we can't queue yet, preserve the current entity in
338 			 * terms of fairness.
339 			 */
340 			if (!drm_sched_can_queue(sched, entity)) {
341 				spin_unlock(&rq->lock);
342 				return ERR_PTR(-ENOSPC);
343 			}
344 
345 			reinit_completion(&entity->entity_idle);
346 			break;
347 		}
348 	}
349 	spin_unlock(&rq->lock);
350 
351 	return rb ? rb_entry(rb, struct drm_sched_entity, rb_tree_node) : NULL;
352 }
353 
354 /**
355  * drm_sched_run_job_queue - enqueue run-job work
356  * @sched: scheduler instance
357  */
358 static void drm_sched_run_job_queue(struct drm_gpu_scheduler *sched)
359 {
360 	if (!READ_ONCE(sched->pause_submit))
361 		queue_work(sched->submit_wq, &sched->work_run_job);
362 }
363 
364 /**
365  * __drm_sched_run_free_queue - enqueue free-job work
366  * @sched: scheduler instance
367  */
368 static void __drm_sched_run_free_queue(struct drm_gpu_scheduler *sched)
369 {
370 	if (!READ_ONCE(sched->pause_submit))
371 		queue_work(sched->submit_wq, &sched->work_free_job);
372 }
373 
374 /**
375  * drm_sched_run_free_queue - enqueue free-job work if ready
376  * @sched: scheduler instance
377  */
378 static void drm_sched_run_free_queue(struct drm_gpu_scheduler *sched)
379 {
380 	struct drm_sched_job *job;
381 
382 	spin_lock(&sched->job_list_lock);
383 	job = list_first_entry_or_null(&sched->pending_list,
384 				       struct drm_sched_job, list);
385 	if (job && dma_fence_is_signaled(&job->s_fence->finished))
386 		__drm_sched_run_free_queue(sched);
387 	spin_unlock(&sched->job_list_lock);
388 }
389 
390 /**
391  * drm_sched_job_done - complete a job
392  * @s_job: pointer to the job which is done
393  *
394  * Finish the job's fence and wake up the worker thread.
395  */
396 static void drm_sched_job_done(struct drm_sched_job *s_job, int result)
397 {
398 	struct drm_sched_fence *s_fence = s_job->s_fence;
399 	struct drm_gpu_scheduler *sched = s_fence->sched;
400 
401 	atomic_sub(s_job->credits, &sched->credit_count);
402 	atomic_dec(sched->score);
403 
404 	trace_drm_sched_process_job(s_fence);
405 
406 	dma_fence_get(&s_fence->finished);
407 	drm_sched_fence_finished(s_fence, result);
408 	dma_fence_put(&s_fence->finished);
409 	__drm_sched_run_free_queue(sched);
410 }
411 
412 /**
413  * drm_sched_job_done_cb - the callback for a done job
414  * @f: fence
415  * @cb: fence callbacks
416  */
417 static void drm_sched_job_done_cb(struct dma_fence *f, struct dma_fence_cb *cb)
418 {
419 	struct drm_sched_job *s_job = container_of(cb, struct drm_sched_job, cb);
420 
421 	drm_sched_job_done(s_job, f->error);
422 }
423 
424 /**
425  * drm_sched_start_timeout - start timeout for reset worker
426  *
427  * @sched: scheduler instance to start the worker for
428  *
429  * Start the timeout for the given scheduler.
430  */
431 static void drm_sched_start_timeout(struct drm_gpu_scheduler *sched)
432 {
433 	lockdep_assert_held(&sched->job_list_lock);
434 
435 	if (sched->timeout != MAX_SCHEDULE_TIMEOUT &&
436 	    !list_empty(&sched->pending_list))
437 		mod_delayed_work(sched->timeout_wq, &sched->work_tdr, sched->timeout);
438 }
439 
440 static void drm_sched_start_timeout_unlocked(struct drm_gpu_scheduler *sched)
441 {
442 	spin_lock(&sched->job_list_lock);
443 	drm_sched_start_timeout(sched);
444 	spin_unlock(&sched->job_list_lock);
445 }
446 
447 /**
448  * drm_sched_tdr_queue_imm: - immediately start job timeout handler
449  *
450  * @sched: scheduler for which the timeout handling should be started.
451  *
452  * Start timeout handling immediately for the named scheduler.
453  */
454 void drm_sched_tdr_queue_imm(struct drm_gpu_scheduler *sched)
455 {
456 	spin_lock(&sched->job_list_lock);
457 	sched->timeout = 0;
458 	drm_sched_start_timeout(sched);
459 	spin_unlock(&sched->job_list_lock);
460 }
461 EXPORT_SYMBOL(drm_sched_tdr_queue_imm);
462 
463 /**
464  * drm_sched_fault - immediately start timeout handler
465  *
466  * @sched: scheduler where the timeout handling should be started.
467  *
468  * Start timeout handling immediately when the driver detects a hardware fault.
469  */
470 void drm_sched_fault(struct drm_gpu_scheduler *sched)
471 {
472 	if (sched->timeout_wq)
473 		mod_delayed_work(sched->timeout_wq, &sched->work_tdr, 0);
474 }
475 EXPORT_SYMBOL(drm_sched_fault);
476 
477 /**
478  * drm_sched_suspend_timeout - Suspend scheduler job timeout
479  *
480  * @sched: scheduler instance for which to suspend the timeout
481  *
482  * Suspend the delayed work timeout for the scheduler. This is done by
483  * modifying the delayed work timeout to an arbitrary large value,
484  * MAX_SCHEDULE_TIMEOUT in this case.
485  *
486  * Returns the timeout remaining
487  *
488  */
489 unsigned long drm_sched_suspend_timeout(struct drm_gpu_scheduler *sched)
490 {
491 	unsigned long sched_timeout, now = jiffies;
492 
493 	sched_timeout = sched->work_tdr.timer.expires;
494 
495 	/*
496 	 * Modify the timeout to an arbitrarily large value. This also prevents
497 	 * the timeout to be restarted when new submissions arrive
498 	 */
499 	if (mod_delayed_work(sched->timeout_wq, &sched->work_tdr, MAX_SCHEDULE_TIMEOUT)
500 			&& time_after(sched_timeout, now))
501 		return sched_timeout - now;
502 	else
503 		return sched->timeout;
504 }
505 EXPORT_SYMBOL(drm_sched_suspend_timeout);
506 
507 /**
508  * drm_sched_resume_timeout - Resume scheduler job timeout
509  *
510  * @sched: scheduler instance for which to resume the timeout
511  * @remaining: remaining timeout
512  *
513  * Resume the delayed work timeout for the scheduler.
514  */
515 void drm_sched_resume_timeout(struct drm_gpu_scheduler *sched,
516 		unsigned long remaining)
517 {
518 	spin_lock(&sched->job_list_lock);
519 
520 	if (list_empty(&sched->pending_list))
521 		cancel_delayed_work(&sched->work_tdr);
522 	else
523 		mod_delayed_work(sched->timeout_wq, &sched->work_tdr, remaining);
524 
525 	spin_unlock(&sched->job_list_lock);
526 }
527 EXPORT_SYMBOL(drm_sched_resume_timeout);
528 
529 static void drm_sched_job_begin(struct drm_sched_job *s_job)
530 {
531 	struct drm_gpu_scheduler *sched = s_job->sched;
532 
533 	spin_lock(&sched->job_list_lock);
534 	list_add_tail(&s_job->list, &sched->pending_list);
535 	drm_sched_start_timeout(sched);
536 	spin_unlock(&sched->job_list_lock);
537 }
538 
539 static void drm_sched_job_timedout(struct work_struct *work)
540 {
541 	struct drm_gpu_scheduler *sched;
542 	struct drm_sched_job *job;
543 	enum drm_gpu_sched_stat status = DRM_GPU_SCHED_STAT_NOMINAL;
544 
545 	sched = container_of(work, struct drm_gpu_scheduler, work_tdr.work);
546 
547 	/* Protects against concurrent deletion in drm_sched_get_finished_job */
548 	spin_lock(&sched->job_list_lock);
549 	job = list_first_entry_or_null(&sched->pending_list,
550 				       struct drm_sched_job, list);
551 
552 	if (job) {
553 		/*
554 		 * Remove the bad job so it cannot be freed by concurrent
555 		 * drm_sched_cleanup_jobs. It will be reinserted back after sched->thread
556 		 * is parked at which point it's safe.
557 		 */
558 		list_del_init(&job->list);
559 		spin_unlock(&sched->job_list_lock);
560 
561 		status = job->sched->ops->timedout_job(job);
562 
563 		/*
564 		 * Guilty job did complete and hence needs to be manually removed
565 		 * See drm_sched_stop doc.
566 		 */
567 		if (sched->free_guilty) {
568 			job->sched->ops->free_job(job);
569 			sched->free_guilty = false;
570 		}
571 	} else {
572 		spin_unlock(&sched->job_list_lock);
573 	}
574 
575 	if (status != DRM_GPU_SCHED_STAT_ENODEV)
576 		drm_sched_start_timeout_unlocked(sched);
577 }
578 
579 /**
580  * drm_sched_stop - stop the scheduler
581  *
582  * @sched: scheduler instance
583  * @bad: job which caused the time out
584  *
585  * Stop the scheduler and also removes and frees all completed jobs.
586  * Note: bad job will not be freed as it might be used later and so it's
587  * callers responsibility to release it manually if it's not part of the
588  * pending list any more.
589  *
590  * This function is typically used for reset recovery (see the docu of
591  * drm_sched_backend_ops.timedout_job() for details). Do not call it for
592  * scheduler teardown, i.e., before calling drm_sched_fini().
593  */
594 void drm_sched_stop(struct drm_gpu_scheduler *sched, struct drm_sched_job *bad)
595 {
596 	struct drm_sched_job *s_job, *tmp;
597 
598 	drm_sched_wqueue_stop(sched);
599 
600 	/*
601 	 * Reinsert back the bad job here - now it's safe as
602 	 * drm_sched_get_finished_job cannot race against us and release the
603 	 * bad job at this point - we parked (waited for) any in progress
604 	 * (earlier) cleanups and drm_sched_get_finished_job will not be called
605 	 * now until the scheduler thread is unparked.
606 	 */
607 	if (bad && bad->sched == sched)
608 		/*
609 		 * Add at the head of the queue to reflect it was the earliest
610 		 * job extracted.
611 		 */
612 		list_add(&bad->list, &sched->pending_list);
613 
614 	/*
615 	 * Iterate the job list from later to  earlier one and either deactive
616 	 * their HW callbacks or remove them from pending list if they already
617 	 * signaled.
618 	 * This iteration is thread safe as sched thread is stopped.
619 	 */
620 	list_for_each_entry_safe_reverse(s_job, tmp, &sched->pending_list,
621 					 list) {
622 		if (s_job->s_fence->parent &&
623 		    dma_fence_remove_callback(s_job->s_fence->parent,
624 					      &s_job->cb)) {
625 			dma_fence_put(s_job->s_fence->parent);
626 			s_job->s_fence->parent = NULL;
627 			atomic_sub(s_job->credits, &sched->credit_count);
628 		} else {
629 			/*
630 			 * remove job from pending_list.
631 			 * Locking here is for concurrent resume timeout
632 			 */
633 			spin_lock(&sched->job_list_lock);
634 			list_del_init(&s_job->list);
635 			spin_unlock(&sched->job_list_lock);
636 
637 			/*
638 			 * Wait for job's HW fence callback to finish using s_job
639 			 * before releasing it.
640 			 *
641 			 * Job is still alive so fence refcount at least 1
642 			 */
643 			dma_fence_wait(&s_job->s_fence->finished, false);
644 
645 			/*
646 			 * We must keep bad job alive for later use during
647 			 * recovery by some of the drivers but leave a hint
648 			 * that the guilty job must be released.
649 			 */
650 			if (bad != s_job)
651 				sched->ops->free_job(s_job);
652 			else
653 				sched->free_guilty = true;
654 		}
655 	}
656 
657 	/*
658 	 * Stop pending timer in flight as we rearm it in  drm_sched_start. This
659 	 * avoids the pending timeout work in progress to fire right away after
660 	 * this TDR finished and before the newly restarted jobs had a
661 	 * chance to complete.
662 	 */
663 	cancel_delayed_work(&sched->work_tdr);
664 }
665 EXPORT_SYMBOL(drm_sched_stop);
666 
667 /**
668  * drm_sched_start - recover jobs after a reset
669  *
670  * @sched: scheduler instance
671  * @errno: error to set on the pending fences
672  *
673  * This function is typically used for reset recovery (see the docu of
674  * drm_sched_backend_ops.timedout_job() for details). Do not call it for
675  * scheduler startup. The scheduler itself is fully operational after
676  * drm_sched_init() succeeded.
677  */
678 void drm_sched_start(struct drm_gpu_scheduler *sched, int errno)
679 {
680 	struct drm_sched_job *s_job, *tmp;
681 
682 	/*
683 	 * Locking the list is not required here as the sched thread is parked
684 	 * so no new jobs are being inserted or removed. Also concurrent
685 	 * GPU recovers can't run in parallel.
686 	 */
687 	list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
688 		struct dma_fence *fence = s_job->s_fence->parent;
689 
690 		atomic_add(s_job->credits, &sched->credit_count);
691 
692 		if (!fence) {
693 			drm_sched_job_done(s_job, errno ?: -ECANCELED);
694 			continue;
695 		}
696 
697 		if (dma_fence_add_callback(fence, &s_job->cb,
698 					   drm_sched_job_done_cb))
699 			drm_sched_job_done(s_job, fence->error ?: errno);
700 	}
701 
702 	drm_sched_start_timeout_unlocked(sched);
703 	drm_sched_wqueue_start(sched);
704 }
705 EXPORT_SYMBOL(drm_sched_start);
706 
707 /**
708  * drm_sched_resubmit_jobs - Deprecated, don't use in new code!
709  *
710  * @sched: scheduler instance
711  *
712  * Re-submitting jobs was a concept AMD came up as cheap way to implement
713  * recovery after a job timeout.
714  *
715  * This turned out to be not working very well. First of all there are many
716  * problem with the dma_fence implementation and requirements. Either the
717  * implementation is risking deadlocks with core memory management or violating
718  * documented implementation details of the dma_fence object.
719  *
720  * Drivers can still save and restore their state for recovery operations, but
721  * we shouldn't make this a general scheduler feature around the dma_fence
722  * interface.
723  */
724 void drm_sched_resubmit_jobs(struct drm_gpu_scheduler *sched)
725 {
726 	struct drm_sched_job *s_job, *tmp;
727 	uint64_t guilty_context;
728 	bool found_guilty = false;
729 	struct dma_fence *fence;
730 
731 	list_for_each_entry_safe(s_job, tmp, &sched->pending_list, list) {
732 		struct drm_sched_fence *s_fence = s_job->s_fence;
733 
734 		if (!found_guilty && atomic_read(&s_job->karma) > sched->hang_limit) {
735 			found_guilty = true;
736 			guilty_context = s_job->s_fence->scheduled.context;
737 		}
738 
739 		if (found_guilty && s_job->s_fence->scheduled.context == guilty_context)
740 			dma_fence_set_error(&s_fence->finished, -ECANCELED);
741 
742 		fence = sched->ops->run_job(s_job);
743 
744 		if (IS_ERR_OR_NULL(fence)) {
745 			if (IS_ERR(fence))
746 				dma_fence_set_error(&s_fence->finished, PTR_ERR(fence));
747 
748 			s_job->s_fence->parent = NULL;
749 		} else {
750 
751 			s_job->s_fence->parent = dma_fence_get(fence);
752 
753 			/* Drop for orignal kref_init */
754 			dma_fence_put(fence);
755 		}
756 	}
757 }
758 EXPORT_SYMBOL(drm_sched_resubmit_jobs);
759 
760 /**
761  * drm_sched_job_init - init a scheduler job
762  * @job: scheduler job to init
763  * @entity: scheduler entity to use
764  * @credits: the number of credits this job contributes to the schedulers
765  * credit limit
766  * @owner: job owner for debugging
767  *
768  * Refer to drm_sched_entity_push_job() documentation
769  * for locking considerations.
770  *
771  * Drivers must make sure drm_sched_job_cleanup() if this function returns
772  * successfully, even when @job is aborted before drm_sched_job_arm() is called.
773  *
774  * Note that this function does not assign a valid value to each struct member
775  * of struct drm_sched_job. Take a look at that struct's documentation to see
776  * who sets which struct member with what lifetime.
777  *
778  * WARNING: amdgpu abuses &drm_sched.ready to signal when the hardware
779  * has died, which can mean that there's no valid runqueue for a @entity.
780  * This function returns -ENOENT in this case (which probably should be -EIO as
781  * a more meanigful return value).
782  *
783  * Returns 0 for success, negative error code otherwise.
784  */
785 int drm_sched_job_init(struct drm_sched_job *job,
786 		       struct drm_sched_entity *entity,
787 		       u32 credits, void *owner)
788 {
789 	if (!entity->rq) {
790 		/* This will most likely be followed by missing frames
791 		 * or worse--a blank screen--leave a trail in the
792 		 * logs, so this can be debugged easier.
793 		 */
794 		dev_err(job->sched->dev, "%s: entity has no rq!\n", __func__);
795 		return -ENOENT;
796 	}
797 
798 	if (unlikely(!credits)) {
799 		pr_err("*ERROR* %s: credits cannot be 0!\n", __func__);
800 		return -EINVAL;
801 	}
802 
803 	/*
804 	 * We don't know for sure how the user has allocated. Thus, zero the
805 	 * struct so that unallowed (i.e., too early) usage of pointers that
806 	 * this function does not set is guaranteed to lead to a NULL pointer
807 	 * exception instead of UB.
808 	 */
809 	memset(job, 0, sizeof(*job));
810 
811 	job->entity = entity;
812 	job->credits = credits;
813 	job->s_fence = drm_sched_fence_alloc(entity, owner);
814 	if (!job->s_fence)
815 		return -ENOMEM;
816 
817 	INIT_LIST_HEAD(&job->list);
818 
819 	xa_init_flags(&job->dependencies, XA_FLAGS_ALLOC);
820 
821 	return 0;
822 }
823 EXPORT_SYMBOL(drm_sched_job_init);
824 
825 /**
826  * drm_sched_job_arm - arm a scheduler job for execution
827  * @job: scheduler job to arm
828  *
829  * This arms a scheduler job for execution. Specifically it initializes the
830  * &drm_sched_job.s_fence of @job, so that it can be attached to struct dma_resv
831  * or other places that need to track the completion of this job.
832  *
833  * Refer to drm_sched_entity_push_job() documentation for locking
834  * considerations.
835  *
836  * This can only be called if drm_sched_job_init() succeeded.
837  */
838 void drm_sched_job_arm(struct drm_sched_job *job)
839 {
840 	struct drm_gpu_scheduler *sched;
841 	struct drm_sched_entity *entity = job->entity;
842 
843 	BUG_ON(!entity);
844 	drm_sched_entity_select_rq(entity);
845 	sched = entity->rq->sched;
846 
847 	job->sched = sched;
848 	job->s_priority = entity->priority;
849 	job->id = atomic64_inc_return(&sched->job_id_count);
850 
851 	drm_sched_fence_init(job->s_fence, job->entity);
852 }
853 EXPORT_SYMBOL(drm_sched_job_arm);
854 
855 /**
856  * drm_sched_job_add_dependency - adds the fence as a job dependency
857  * @job: scheduler job to add the dependencies to
858  * @fence: the dma_fence to add to the list of dependencies.
859  *
860  * Note that @fence is consumed in both the success and error cases.
861  *
862  * Returns:
863  * 0 on success, or an error on failing to expand the array.
864  */
865 int drm_sched_job_add_dependency(struct drm_sched_job *job,
866 				 struct dma_fence *fence)
867 {
868 	struct dma_fence *entry;
869 	unsigned long index;
870 	u32 id = 0;
871 	int ret;
872 
873 	if (!fence)
874 		return 0;
875 
876 	/* Deduplicate if we already depend on a fence from the same context.
877 	 * This lets the size of the array of deps scale with the number of
878 	 * engines involved, rather than the number of BOs.
879 	 */
880 	xa_for_each(&job->dependencies, index, entry) {
881 		if (entry->context != fence->context)
882 			continue;
883 
884 		if (dma_fence_is_later(fence, entry)) {
885 			dma_fence_put(entry);
886 			xa_store(&job->dependencies, index, fence, GFP_KERNEL);
887 		} else {
888 			dma_fence_put(fence);
889 		}
890 		return 0;
891 	}
892 
893 	ret = xa_alloc(&job->dependencies, &id, fence, xa_limit_32b, GFP_KERNEL);
894 	if (ret != 0)
895 		dma_fence_put(fence);
896 
897 	return ret;
898 }
899 EXPORT_SYMBOL(drm_sched_job_add_dependency);
900 
901 /**
902  * drm_sched_job_add_syncobj_dependency - adds a syncobj's fence as a job dependency
903  * @job: scheduler job to add the dependencies to
904  * @file: drm file private pointer
905  * @handle: syncobj handle to lookup
906  * @point: timeline point
907  *
908  * This adds the fence matching the given syncobj to @job.
909  *
910  * Returns:
911  * 0 on success, or an error on failing to expand the array.
912  */
913 int drm_sched_job_add_syncobj_dependency(struct drm_sched_job *job,
914 					 struct drm_file *file,
915 					 u32 handle,
916 					 u32 point)
917 {
918 	struct dma_fence *fence;
919 	int ret;
920 
921 	ret = drm_syncobj_find_fence(file, handle, point, 0, &fence);
922 	if (ret)
923 		return ret;
924 
925 	return drm_sched_job_add_dependency(job, fence);
926 }
927 EXPORT_SYMBOL(drm_sched_job_add_syncobj_dependency);
928 
929 /**
930  * drm_sched_job_add_resv_dependencies - add all fences from the resv to the job
931  * @job: scheduler job to add the dependencies to
932  * @resv: the dma_resv object to get the fences from
933  * @usage: the dma_resv_usage to use to filter the fences
934  *
935  * This adds all fences matching the given usage from @resv to @job.
936  * Must be called with the @resv lock held.
937  *
938  * Returns:
939  * 0 on success, or an error on failing to expand the array.
940  */
941 int drm_sched_job_add_resv_dependencies(struct drm_sched_job *job,
942 					struct dma_resv *resv,
943 					enum dma_resv_usage usage)
944 {
945 	struct dma_resv_iter cursor;
946 	struct dma_fence *fence;
947 	int ret;
948 
949 	dma_resv_assert_held(resv);
950 
951 	dma_resv_for_each_fence(&cursor, resv, usage, fence) {
952 		/* Make sure to grab an additional ref on the added fence */
953 		dma_fence_get(fence);
954 		ret = drm_sched_job_add_dependency(job, fence);
955 		if (ret) {
956 			dma_fence_put(fence);
957 			return ret;
958 		}
959 	}
960 	return 0;
961 }
962 EXPORT_SYMBOL(drm_sched_job_add_resv_dependencies);
963 
964 /**
965  * drm_sched_job_add_implicit_dependencies - adds implicit dependencies as job
966  *   dependencies
967  * @job: scheduler job to add the dependencies to
968  * @obj: the gem object to add new dependencies from.
969  * @write: whether the job might write the object (so we need to depend on
970  * shared fences in the reservation object).
971  *
972  * This should be called after drm_gem_lock_reservations() on your array of
973  * GEM objects used in the job but before updating the reservations with your
974  * own fences.
975  *
976  * Returns:
977  * 0 on success, or an error on failing to expand the array.
978  */
979 int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job,
980 					    struct drm_gem_object *obj,
981 					    bool write)
982 {
983 	return drm_sched_job_add_resv_dependencies(job, obj->resv,
984 						   dma_resv_usage_rw(write));
985 }
986 EXPORT_SYMBOL(drm_sched_job_add_implicit_dependencies);
987 
988 /**
989  * drm_sched_job_has_dependency - check whether fence is the job's dependency
990  * @job: scheduler job to check
991  * @fence: fence to look for
992  *
993  * Returns:
994  * True if @fence is found within the job's dependencies, or otherwise false.
995  */
996 bool drm_sched_job_has_dependency(struct drm_sched_job *job,
997 				  struct dma_fence *fence)
998 {
999 	struct dma_fence *f;
1000 	unsigned long index;
1001 
1002 	xa_for_each(&job->dependencies, index, f) {
1003 		if (f == fence)
1004 			return true;
1005 	}
1006 
1007 	return false;
1008 }
1009 EXPORT_SYMBOL(drm_sched_job_has_dependency);
1010 
1011 /**
1012  * drm_sched_job_cleanup - clean up scheduler job resources
1013  * @job: scheduler job to clean up
1014  *
1015  * Cleans up the resources allocated with drm_sched_job_init().
1016  *
1017  * Drivers should call this from their error unwind code if @job is aborted
1018  * before drm_sched_job_arm() is called.
1019  *
1020  * After that point of no return @job is committed to be executed by the
1021  * scheduler, and this function should be called from the
1022  * &drm_sched_backend_ops.free_job callback.
1023  */
1024 void drm_sched_job_cleanup(struct drm_sched_job *job)
1025 {
1026 	struct dma_fence *fence;
1027 	unsigned long index;
1028 
1029 	if (kref_read(&job->s_fence->finished.refcount)) {
1030 		/* drm_sched_job_arm() has been called */
1031 		dma_fence_put(&job->s_fence->finished);
1032 	} else {
1033 		/* aborted job before committing to run it */
1034 		drm_sched_fence_free(job->s_fence);
1035 	}
1036 
1037 	job->s_fence = NULL;
1038 
1039 	xa_for_each(&job->dependencies, index, fence) {
1040 		dma_fence_put(fence);
1041 	}
1042 	xa_destroy(&job->dependencies);
1043 
1044 }
1045 EXPORT_SYMBOL(drm_sched_job_cleanup);
1046 
1047 /**
1048  * drm_sched_wakeup - Wake up the scheduler if it is ready to queue
1049  * @sched: scheduler instance
1050  *
1051  * Wake up the scheduler if we can queue jobs.
1052  */
1053 void drm_sched_wakeup(struct drm_gpu_scheduler *sched)
1054 {
1055 	drm_sched_run_job_queue(sched);
1056 }
1057 
1058 /**
1059  * drm_sched_select_entity - Select next entity to process
1060  *
1061  * @sched: scheduler instance
1062  *
1063  * Return an entity to process or NULL if none are found.
1064  *
1065  * Note, that we break out of the for-loop when "entity" is non-null, which can
1066  * also be an error-pointer--this assures we don't process lower priority
1067  * run-queues. See comments in the respectively called functions.
1068  */
1069 static struct drm_sched_entity *
1070 drm_sched_select_entity(struct drm_gpu_scheduler *sched)
1071 {
1072 	struct drm_sched_entity *entity;
1073 	int i;
1074 
1075 	/* Start with the highest priority.
1076 	 */
1077 	for (i = DRM_SCHED_PRIORITY_KERNEL; i < sched->num_rqs; i++) {
1078 		entity = drm_sched_policy == DRM_SCHED_POLICY_FIFO ?
1079 			drm_sched_rq_select_entity_fifo(sched, sched->sched_rq[i]) :
1080 			drm_sched_rq_select_entity_rr(sched, sched->sched_rq[i]);
1081 		if (entity)
1082 			break;
1083 	}
1084 
1085 	return IS_ERR(entity) ? NULL : entity;
1086 }
1087 
1088 /**
1089  * drm_sched_get_finished_job - fetch the next finished job to be destroyed
1090  *
1091  * @sched: scheduler instance
1092  *
1093  * Returns the next finished job from the pending list (if there is one)
1094  * ready for it to be destroyed.
1095  */
1096 static struct drm_sched_job *
1097 drm_sched_get_finished_job(struct drm_gpu_scheduler *sched)
1098 {
1099 	struct drm_sched_job *job, *next;
1100 
1101 	spin_lock(&sched->job_list_lock);
1102 
1103 	job = list_first_entry_or_null(&sched->pending_list,
1104 				       struct drm_sched_job, list);
1105 
1106 	if (job && dma_fence_is_signaled(&job->s_fence->finished)) {
1107 		/* remove job from pending_list */
1108 		list_del_init(&job->list);
1109 
1110 		/* cancel this job's TO timer */
1111 		cancel_delayed_work(&sched->work_tdr);
1112 		/* make the scheduled timestamp more accurate */
1113 		next = list_first_entry_or_null(&sched->pending_list,
1114 						typeof(*next), list);
1115 
1116 		if (next) {
1117 			if (test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT,
1118 				     &next->s_fence->scheduled.flags))
1119 				next->s_fence->scheduled.timestamp =
1120 					dma_fence_timestamp(&job->s_fence->finished);
1121 			/* start TO timer for next job */
1122 			drm_sched_start_timeout(sched);
1123 		}
1124 	} else {
1125 		job = NULL;
1126 	}
1127 
1128 	spin_unlock(&sched->job_list_lock);
1129 
1130 	return job;
1131 }
1132 
1133 /**
1134  * drm_sched_pick_best - Get a drm sched from a sched_list with the least load
1135  * @sched_list: list of drm_gpu_schedulers
1136  * @num_sched_list: number of drm_gpu_schedulers in the sched_list
1137  *
1138  * Returns pointer of the sched with the least load or NULL if none of the
1139  * drm_gpu_schedulers are ready
1140  */
1141 struct drm_gpu_scheduler *
1142 drm_sched_pick_best(struct drm_gpu_scheduler **sched_list,
1143 		     unsigned int num_sched_list)
1144 {
1145 	struct drm_gpu_scheduler *sched, *picked_sched = NULL;
1146 	int i;
1147 	unsigned int min_score = UINT_MAX, num_score;
1148 
1149 	for (i = 0; i < num_sched_list; ++i) {
1150 		sched = sched_list[i];
1151 
1152 		if (!sched->ready) {
1153 			DRM_WARN("scheduler %s is not ready, skipping",
1154 				 sched->name);
1155 			continue;
1156 		}
1157 
1158 		num_score = atomic_read(sched->score);
1159 		if (num_score < min_score) {
1160 			min_score = num_score;
1161 			picked_sched = sched;
1162 		}
1163 	}
1164 
1165 	return picked_sched;
1166 }
1167 EXPORT_SYMBOL(drm_sched_pick_best);
1168 
1169 /**
1170  * drm_sched_free_job_work - worker to call free_job
1171  *
1172  * @w: free job work
1173  */
1174 static void drm_sched_free_job_work(struct work_struct *w)
1175 {
1176 	struct drm_gpu_scheduler *sched =
1177 		container_of(w, struct drm_gpu_scheduler, work_free_job);
1178 	struct drm_sched_job *job;
1179 
1180 	job = drm_sched_get_finished_job(sched);
1181 	if (job)
1182 		sched->ops->free_job(job);
1183 
1184 	drm_sched_run_free_queue(sched);
1185 	drm_sched_run_job_queue(sched);
1186 }
1187 
1188 /**
1189  * drm_sched_run_job_work - worker to call run_job
1190  *
1191  * @w: run job work
1192  */
1193 static void drm_sched_run_job_work(struct work_struct *w)
1194 {
1195 	struct drm_gpu_scheduler *sched =
1196 		container_of(w, struct drm_gpu_scheduler, work_run_job);
1197 	struct drm_sched_entity *entity;
1198 	struct dma_fence *fence;
1199 	struct drm_sched_fence *s_fence;
1200 	struct drm_sched_job *sched_job;
1201 	int r;
1202 
1203 	/* Find entity with a ready job */
1204 	entity = drm_sched_select_entity(sched);
1205 	if (!entity)
1206 		return;	/* No more work */
1207 
1208 	sched_job = drm_sched_entity_pop_job(entity);
1209 	if (!sched_job) {
1210 		complete_all(&entity->entity_idle);
1211 		drm_sched_run_job_queue(sched);
1212 		return;
1213 	}
1214 
1215 	s_fence = sched_job->s_fence;
1216 
1217 	atomic_add(sched_job->credits, &sched->credit_count);
1218 	drm_sched_job_begin(sched_job);
1219 
1220 	trace_drm_run_job(sched_job, entity);
1221 	/*
1222 	 * The run_job() callback must by definition return a fence whose
1223 	 * refcount has been incremented for the scheduler already.
1224 	 */
1225 	fence = sched->ops->run_job(sched_job);
1226 	complete_all(&entity->entity_idle);
1227 	drm_sched_fence_scheduled(s_fence, fence);
1228 
1229 	if (!IS_ERR_OR_NULL(fence)) {
1230 		r = dma_fence_add_callback(fence, &sched_job->cb,
1231 					   drm_sched_job_done_cb);
1232 		if (r == -ENOENT)
1233 			drm_sched_job_done(sched_job, fence->error);
1234 		else if (r)
1235 			DRM_DEV_ERROR(sched->dev, "fence add callback failed (%d)\n", r);
1236 
1237 		dma_fence_put(fence);
1238 	} else {
1239 		drm_sched_job_done(sched_job, IS_ERR(fence) ?
1240 				   PTR_ERR(fence) : 0);
1241 	}
1242 
1243 	wake_up(&sched->job_scheduled);
1244 	drm_sched_run_job_queue(sched);
1245 }
1246 
1247 /**
1248  * drm_sched_init - Init a gpu scheduler instance
1249  *
1250  * @sched: scheduler instance
1251  * @args: scheduler initialization arguments
1252  *
1253  * Return 0 on success, otherwise error code.
1254  */
1255 int drm_sched_init(struct drm_gpu_scheduler *sched, const struct drm_sched_init_args *args)
1256 {
1257 	int i;
1258 
1259 	sched->ops = args->ops;
1260 	sched->credit_limit = args->credit_limit;
1261 	sched->name = args->name;
1262 	sched->timeout = args->timeout;
1263 	sched->hang_limit = args->hang_limit;
1264 	sched->timeout_wq = args->timeout_wq ? args->timeout_wq : system_wq;
1265 	sched->score = args->score ? args->score : &sched->_score;
1266 	sched->dev = args->dev;
1267 
1268 	if (args->num_rqs > DRM_SCHED_PRIORITY_COUNT) {
1269 		/* This is a gross violation--tell drivers what the  problem is.
1270 		 */
1271 		dev_err(sched->dev, "%s: num_rqs cannot be greater than DRM_SCHED_PRIORITY_COUNT\n",
1272 			__func__);
1273 		return -EINVAL;
1274 	} else if (sched->sched_rq) {
1275 		/* Not an error, but warn anyway so drivers can
1276 		 * fine-tune their DRM calling order, and return all
1277 		 * is good.
1278 		 */
1279 		dev_warn(sched->dev, "%s: scheduler already initialized!\n", __func__);
1280 		return 0;
1281 	}
1282 
1283 	if (args->submit_wq) {
1284 		sched->submit_wq = args->submit_wq;
1285 		sched->own_submit_wq = false;
1286 	} else {
1287 #ifdef CONFIG_LOCKDEP
1288 		sched->submit_wq = alloc_ordered_workqueue_lockdep_map(args->name,
1289 								       WQ_MEM_RECLAIM,
1290 								       &drm_sched_lockdep_map);
1291 #else
1292 		sched->submit_wq = alloc_ordered_workqueue(args->name, WQ_MEM_RECLAIM);
1293 #endif
1294 		if (!sched->submit_wq)
1295 			return -ENOMEM;
1296 
1297 		sched->own_submit_wq = true;
1298 	}
1299 
1300 	sched->sched_rq = kmalloc_array(args->num_rqs, sizeof(*sched->sched_rq),
1301 					GFP_KERNEL | __GFP_ZERO);
1302 	if (!sched->sched_rq)
1303 		goto Out_check_own;
1304 	sched->num_rqs = args->num_rqs;
1305 	for (i = DRM_SCHED_PRIORITY_KERNEL; i < sched->num_rqs; i++) {
1306 		sched->sched_rq[i] = kzalloc(sizeof(*sched->sched_rq[i]), GFP_KERNEL);
1307 		if (!sched->sched_rq[i])
1308 			goto Out_unroll;
1309 		drm_sched_rq_init(sched, sched->sched_rq[i]);
1310 	}
1311 
1312 	init_waitqueue_head(&sched->job_scheduled);
1313 	INIT_LIST_HEAD(&sched->pending_list);
1314 	spin_lock_init(&sched->job_list_lock);
1315 	atomic_set(&sched->credit_count, 0);
1316 	INIT_DELAYED_WORK(&sched->work_tdr, drm_sched_job_timedout);
1317 	INIT_WORK(&sched->work_run_job, drm_sched_run_job_work);
1318 	INIT_WORK(&sched->work_free_job, drm_sched_free_job_work);
1319 	atomic_set(&sched->_score, 0);
1320 	atomic64_set(&sched->job_id_count, 0);
1321 	sched->pause_submit = false;
1322 
1323 	sched->ready = true;
1324 	return 0;
1325 Out_unroll:
1326 	for (--i ; i >= DRM_SCHED_PRIORITY_KERNEL; i--)
1327 		kfree(sched->sched_rq[i]);
1328 
1329 	kfree(sched->sched_rq);
1330 	sched->sched_rq = NULL;
1331 Out_check_own:
1332 	if (sched->own_submit_wq)
1333 		destroy_workqueue(sched->submit_wq);
1334 	dev_err(sched->dev, "%s: Failed to setup GPU scheduler--out of memory\n", __func__);
1335 	return -ENOMEM;
1336 }
1337 EXPORT_SYMBOL(drm_sched_init);
1338 
1339 /**
1340  * drm_sched_fini - Destroy a gpu scheduler
1341  *
1342  * @sched: scheduler instance
1343  *
1344  * Tears down and cleans up the scheduler.
1345  *
1346  * This stops submission of new jobs to the hardware through
1347  * drm_sched_backend_ops.run_job(). Consequently, drm_sched_backend_ops.free_job()
1348  * will not be called for all jobs still in drm_gpu_scheduler.pending_list.
1349  * There is no solution for this currently. Thus, it is up to the driver to make
1350  * sure that:
1351  *
1352  *  a) drm_sched_fini() is only called after for all submitted jobs
1353  *     drm_sched_backend_ops.free_job() has been called or that
1354  *  b) the jobs for which drm_sched_backend_ops.free_job() has not been called
1355  *     after drm_sched_fini() ran are freed manually.
1356  *
1357  * FIXME: Take care of the above problem and prevent this function from leaking
1358  * the jobs in drm_gpu_scheduler.pending_list under any circumstances.
1359  */
1360 void drm_sched_fini(struct drm_gpu_scheduler *sched)
1361 {
1362 	struct drm_sched_entity *s_entity;
1363 	int i;
1364 
1365 	drm_sched_wqueue_stop(sched);
1366 
1367 	for (i = DRM_SCHED_PRIORITY_KERNEL; i < sched->num_rqs; i++) {
1368 		struct drm_sched_rq *rq = sched->sched_rq[i];
1369 
1370 		spin_lock(&rq->lock);
1371 		list_for_each_entry(s_entity, &rq->entities, list)
1372 			/*
1373 			 * Prevents reinsertion and marks job_queue as idle,
1374 			 * it will be removed from the rq in drm_sched_entity_fini()
1375 			 * eventually
1376 			 */
1377 			s_entity->stopped = true;
1378 		spin_unlock(&rq->lock);
1379 		kfree(sched->sched_rq[i]);
1380 	}
1381 
1382 	/* Wakeup everyone stuck in drm_sched_entity_flush for this scheduler */
1383 	wake_up_all(&sched->job_scheduled);
1384 
1385 	/* Confirm no work left behind accessing device structures */
1386 	cancel_delayed_work_sync(&sched->work_tdr);
1387 
1388 	if (sched->own_submit_wq)
1389 		destroy_workqueue(sched->submit_wq);
1390 	sched->ready = false;
1391 	kfree(sched->sched_rq);
1392 	sched->sched_rq = NULL;
1393 }
1394 EXPORT_SYMBOL(drm_sched_fini);
1395 
1396 /**
1397  * drm_sched_increase_karma - Update sched_entity guilty flag
1398  *
1399  * @bad: The job guilty of time out
1400  *
1401  * Increment on every hang caused by the 'bad' job. If this exceeds the hang
1402  * limit of the scheduler then the respective sched entity is marked guilty and
1403  * jobs from it will not be scheduled further
1404  */
1405 void drm_sched_increase_karma(struct drm_sched_job *bad)
1406 {
1407 	int i;
1408 	struct drm_sched_entity *tmp;
1409 	struct drm_sched_entity *entity;
1410 	struct drm_gpu_scheduler *sched = bad->sched;
1411 
1412 	/* don't change @bad's karma if it's from KERNEL RQ,
1413 	 * because sometimes GPU hang would cause kernel jobs (like VM updating jobs)
1414 	 * corrupt but keep in mind that kernel jobs always considered good.
1415 	 */
1416 	if (bad->s_priority != DRM_SCHED_PRIORITY_KERNEL) {
1417 		atomic_inc(&bad->karma);
1418 
1419 		for (i = DRM_SCHED_PRIORITY_HIGH; i < sched->num_rqs; i++) {
1420 			struct drm_sched_rq *rq = sched->sched_rq[i];
1421 
1422 			spin_lock(&rq->lock);
1423 			list_for_each_entry_safe(entity, tmp, &rq->entities, list) {
1424 				if (bad->s_fence->scheduled.context ==
1425 				    entity->fence_context) {
1426 					if (entity->guilty)
1427 						atomic_set(entity->guilty, 1);
1428 					break;
1429 				}
1430 			}
1431 			spin_unlock(&rq->lock);
1432 			if (&entity->list != &rq->entities)
1433 				break;
1434 		}
1435 	}
1436 }
1437 EXPORT_SYMBOL(drm_sched_increase_karma);
1438 
1439 /**
1440  * drm_sched_wqueue_ready - Is the scheduler ready for submission
1441  *
1442  * @sched: scheduler instance
1443  *
1444  * Returns true if submission is ready
1445  */
1446 bool drm_sched_wqueue_ready(struct drm_gpu_scheduler *sched)
1447 {
1448 	return sched->ready;
1449 }
1450 EXPORT_SYMBOL(drm_sched_wqueue_ready);
1451 
1452 /**
1453  * drm_sched_wqueue_stop - stop scheduler submission
1454  * @sched: scheduler instance
1455  *
1456  * Stops the scheduler from pulling new jobs from entities. It also stops
1457  * freeing jobs automatically through drm_sched_backend_ops.free_job().
1458  */
1459 void drm_sched_wqueue_stop(struct drm_gpu_scheduler *sched)
1460 {
1461 	WRITE_ONCE(sched->pause_submit, true);
1462 	cancel_work_sync(&sched->work_run_job);
1463 	cancel_work_sync(&sched->work_free_job);
1464 }
1465 EXPORT_SYMBOL(drm_sched_wqueue_stop);
1466 
1467 /**
1468  * drm_sched_wqueue_start - start scheduler submission
1469  * @sched: scheduler instance
1470  *
1471  * Restarts the scheduler after drm_sched_wqueue_stop() has stopped it.
1472  *
1473  * This function is not necessary for 'conventional' startup. The scheduler is
1474  * fully operational after drm_sched_init() succeeded.
1475  */
1476 void drm_sched_wqueue_start(struct drm_gpu_scheduler *sched)
1477 {
1478 	WRITE_ONCE(sched->pause_submit, false);
1479 	queue_work(sched->submit_wq, &sched->work_run_job);
1480 	queue_work(sched->submit_wq, &sched->work_free_job);
1481 }
1482 EXPORT_SYMBOL(drm_sched_wqueue_start);
1483