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